Archive

Archive for the ‘DotNet’ Category

Create water mark text box in asp.net/C# using javascript within a single step

February 23, 2012 3 comments

How to create a water mark text box in asp.net/C# using javascript 

In some scenario in the project, we need to implement water mark text for each textboxes in the form. It will help user to give right direction to enter proper and valid entries for each textboxes. We can achieve this water mark text boxes easily by using javascript methods.

Javascript method to create water mark text boxes in ASP.Net/C# using javascript

Here we are going to create a small asp.net application to show example of water mark text box creation. In aspx page we are having a textbox for username and a button. In the textbox it will show ‘Enter username’ as water mark style with gray color. When a user click mouse on to the textbox it will hide. Once the user leave the mouse pointer from the textbox without enter any data, it will display water mark text.

ASPX PAGE WITH JAVASCRIPT FOR WATER MARK TEXTBOX

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
 <title>Watermark Textbox Using JavaScript</title>
 <script language="javascript" type="text/javascript">
 function WaterMark(txtName, event) {
 var defaultText = "Enter Username";
 // Condition to check textbox length and event type
 if (txtName.value.length == 0 & event.type == "blur") {
 //if condition true then setting text color 
 //and default text in textbox
 txtName.style.color = "Gray";
 txtName.value = defaultText;
 }
// Condition to check textbox value and event type
 if (txtName.value == defaultText & event.type == "focus") {
 txtName.style.color = "black";
 txtName.value = "";
 }
 }
function WaterMarkPwd(txtName, Password) {
 var defaultText = "Enter Password";
 // Condition to check textbox length and event type
 if (txtName.value.length == 0 & event.type == "blur") {
 //if condition true then setting text color and 
 //default text in textbox
 txtName.style.color = "Gray";
 txtName.value = defaultText;
 }
// Condition to check textbox value and event type
 if (txtName.value == defaultText & event.type == "focus") {
 txtName.style.color = "black";
 txtName.value = "";
 }
 }
 </script>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <b>UserName:</b>
 <asp:TextBox ID="txtUserName" runat="server" Text="Enter Username" ForeColor="Gray"
 onblur="WaterMark(this, event);" onfocus="WaterMark(this, event);" />
 <asp:Button runat="server" ID="btnLogin" Text="Login" />
 </div>
 </form>
</body>
</html>

How to calculate difference between two dates in javascript/jquery

February 16, 2012 1 comment

Simple steps to calculate difference between two date fields using JavaScript/JQuery 

In some scenario, we need to calculate the difference between two dates from the client side. Here we are going to demonstrate all about date fields using javascript such as Javascript date field validation for different format, difference between two dates in days, hours, minutes, seconds, years and weeks

Very strong and simple Javascript validation for date fields for format dd/mm/yyyy 

Following javascript function simply verify and return result for checking valid date from client side itself. It will automatically validate leap year entries and return correct result. That means if we pass ’29/02/2011′ to the function it will be return false. If we are passing ’29/02/2012′ to the function it will return true. So we don’t need to bother about the leap year or other complex things.

function isValidDate(dateStr) {
// Date validation Function
// Checks For the following valid Date formats:
// DD/MM/YYYY
var re = /^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\
d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))
|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]
\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/;
var valid = re.test(dateStr);
if (valid == false) {
alert(dateStr + ' Date is not in a valid format.')
return false;
}
return true;
}

How to calculate the date difference from client side using javascript?

Now we are going to find the difference between two date fields from the client side javascript or jquery. In some of the scenario, we need to find the number of days between two selected dates  like leave applying modules, hotel room booking etc. In this case we can simply calculate the difference between from date and to date using following function in javascript.

Here we are having two date fields for from date and todate. User has to select a from date and to date by using this controls. Todate should be greater than from date. When user select from date or todate we will call javascript function calculate()  and this function finds the difference between two dates and display the difference in the label. Its also validate as todate should be greater than the from date.

function calculate() {
var value1 = document.getElementById('<%=txtDateFrom.ClientID%>')
.value.split("/");
var value2 = document.getElementById('<%=txtDateTo.ClientID%>')
.value.split("/");
if (value1 != "" && value2 != "") {
var day1 = parseFloat(value1[0]);
var month1 = parseFloat(value1[1]);
var year1 = parseFloat(value1[2]);
var day2 = parseFloat(value2[0]);
var month2 = parseFloat(value2[1]);
var year2 = parseFloat(value2[2]);

if ((year2 < year1) || (year2 == year1 && month2 < month1) || 
(year2 == year1 && month2 == month1 && day2 < day1)) {
alert('From Date should greater than Date From');
document.getElementById('<%=txtVacationDays.ClientID%>').innerHTML = "0";
return;
}                    
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24
var fromDate = new Date(year1, month1 - 1, day1);
var toDate = new Date(year2, month2 - 1, day2);
// Convert both dates to milliseconds
var dateFrom = fromDate.getTime();
var dateTo = toDate.getTime();
// Calculate the difference in milliseconds
var difference_ms = Math.abs(dateTo - dateFrom)
// Convert back to days and return
var DiffDays = Math.round(difference_ms / ONE_DAY)
document.getElementById('<%=txtVacationDays.ClientID%>').innerHTML 
= parseFloat(DiffDays) + 1;
}
}

In order to call this javascript function on aspx textbox change event, we need to set attributes to the textbox on code behind as follows.

protected void Page_Load(object sender, EventArgs e)
{
    txtFromDate.Attributes.Add("Onchange", "calculate();");
    txtToDate.Attributes.Add("Onchange", "calculate();");
}

ASPX page having two date fields as follows :

<table>
 <tr>
 <td>
 First Date:
 <asp:TextBox runat="server" ID="txtFromDate" />
 (DD/MM/YYYY format)<br />
 Second Date: Date:
 <asp:TextBox runat="server" ID="txtToDate" />
 (DD/MM/YYYY format)<br />
 <center>
 <asp:Button runat="server" ID="btnCheck" Text="Check" 
 OnClientClick="return calculate();" />
 </center>
 </td>
 </tr>
</table>

How to maintain scrollposition after post back?

January 6, 2012 Leave a comment

How to maintain scroll position in ASP.Net Pages

When web pages are posted back to the server, by default user is returned to the top of the page. On a large web page, you might have a requirement to scroll down the user automatically to the last position on the page.

MaintainScrollPositionOnPostBack page property can be used to achieve this  in one of the following ways.

  1. Application level:To set the property by default for all pages in the website, open web.config and add the attribute to the pages node.<pages maintainScrollPositionOnPostBack=”true”>
  2. Page Level:for a particular page, open the aspx and set the property<%@ Page MaintainScrollPositionOnPostback=”true” …
  3. Code level: to set the property programmaticallyPage.MaintainScrollPositionOnPostBack = true;

How to deploy sync framework to windows azure/Deploy sync framework project to windows azure

October 5, 2011 1 comment

Deployment of sync framework workerrole / webrole project into azure environment

The article is going to explain that how we can deploy sync framework worker role or webrole projects created in Visual Studio into azure environment. We have created a worker role application that sync azure databases frequently. We are using Sync Framework 2.1 for sync database in the azure. Once it is completed the application, the challenge was to deploy this sync framework to azure platform. We have to include some dlls and also need to do some configuration settings to deploy project into Windows Azure platform

 Steps to do for deploying Sync Framework Project into Azure

 1.Open your Windows Azure Cloud Service project in Visual Studio >> In the Solution Explorer, right-click the

Web Role project, point to Add, and then click Add Reference.

2.Add references to Microsoft.Synchronization.dll, Microsoft.Synchronization.Data.dll, and Microsoft.Synchronization.Data.SqlServer.dll from Sync Framework 2.1

installation folder most of the time it is C:\Program Files (x86)\Microsoft Sync Framework\2.1.

3.Select all files and take the Properties window, then set the value of Aliases property to global and

Copy Local property to True.

4.Create a class file named activationcontext.cs file with the following content and add the file to

Workerrole/Webrole project.

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Runtime.InteropServices;
using System.IO;

namespace Microsoft.Samples.Synchronization
{
    public class ActivationContext
    {
        // Activation Context API Functions

        [DllImport("Kernel32.dll", SetLastError = true)]
        private extern static IntPtr CreateActCtx(ref ACTCTX actctx);

        // Activation context structure
        private struct ACTCTX
        {
            public int cbSize;
            public uint dwFlags;
            public string lpSource;
            public ushort wProcessorArchitecture;
            public ushort wLangId;
            public string lpAssemblyDirectory;
            public string lpResourceName;
            public string lpApplicationName;
        }

        private const int ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID = 0x004;
        private const int ACTCTX_FLAG_SET_PROCESS_DEFAULT = 0x00000010;
        private IntPtr m_hActCtx = (IntPtr)0;
        public const UInt32 ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET = 14011;

     /// <summary>
     /// Explicitly load a manifest and create the process-default activation
     /// context. It takes effect immediately and stays there until the process exits.
    /// </summary>
        static public void CreateActivationContext()
        {
            string rootFolder = AppDomain.CurrentDomain.BaseDirectory;
            string manifestPath = Path.Combine(rootFolder, "webapp.manifest");
            UInt32 dwError = 0;

            // Build the activation context information structure
            ACTCTX info = new ACTCTX();
            info.cbSize = Marshal.SizeOf(typeof(ACTCTX));
            info.dwFlags = ACTCTX_FLAG_SET_PROCESS_DEFAULT;
            info.lpSource = manifestPath;
            if (null != rootFolder && "" != rootFolder)
            {
                info.lpAssemblyDirectory = rootFolder;
                info.dwFlags |= ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID;
            }

            dwError = 0;

            // Create the activation context
            IntPtr result = CreateActCtx(ref info);
            if (-1 == result.ToInt32())
            {
                dwError = (UInt32)Marshal.GetLastWin32Error();
            }

            if (-1 == result.ToInt32() &&
ActivationContext.ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET != dwError)
            {
                string err = string.Format("Cannot create process-default win32 sxs context,
error={0} manifest={1}", dwError, manifestPath);
                ApplicationException ex = new ApplicationException(err);
                throw ex;
            }
        }
    }
}

5.Add a folder named synchronization.assemblies to the Web Role/ Worker Role project and add the following five files to the folder.

 Microsoft.Synchronization.dll
Microsoft.Synchronization.Data.dll
Microsoft.Synchronization.Data.SqlServer.dll
Synchronization21.dll

 Create a file named synchronization.assemblies.manifest, add the following content, and add the file to this folder.

 <?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>
<assemblyIdentity
type="x64"
name="synchronization.assemblies"
version="2.1.0.0"/>
<file name = "synchronization21.dll">
<comClass clsid="{EC413D66-6221-4ebb-AC55-4900FB321011}"
threadingModel="Both"/>   
</file>
</assembly>

6.Multiple-select all files under synchronization.assemblies folder, right-click, and then click Properties.

Set the value of Build Action property to Content and Copy To Output Directory to Copy Always.

7.Create a file named webapp.manifest, add the following content, and add the file to the Web Role project.

<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity name="webapp" version="8.0.0.0" type="x64"/>
<dependency>
<dependentAssembly>
<assemblyIdentity name="synchronization.assemblies" version="2.1.0.0" type="x64"/>
</dependentAssembly>
</dependency>
</assembly>

 8.Set the value of Build Action property to Content and Copy To Output Directory to Copy Always for the webapp.manifest file using Properties window.

9.Add the following statement to the OnStart method before base.OnStart method call in the WebRole.cs file.

 Microsoft.Samples.Synchronization.ActivationContext.CreateActivationContext();

Import contacts from Gmail using ASP.Net/C# Application

October 3, 2011 17 comments

How to import contacts from GMAIL into ASP.Net/C# application

Some of the application especially social network application needs to have the feature for import contacts from our gmail account. By using this feature we can easily import all contacts from our gmail account and can send bulk mail to all or groups in our gmail account

 Is it possible import contacts from GMAIL account using ASP.Net/C# Application?

Of course, we can access and import our gmail contacts into our ASP.Net/C# application using gmail API. GMAIL itself providing some APIs to access gmail accounts from an external applications like ASP.Net or C#. We can call this API from our application by passing our gmail credentials, then will access our account from the application. Here we are demonstrating how we can use GMAIL API to get contacts in GMAIL account using ASP.Net/C# application.

 Very simple Steps to import GMAIL contacts from ASP.Net/C# application

Step-1:  Download Google data API setup.

 Here is the proper link for downloading particular API.

http://google-gdata.googlecode.com/files/Google%20Data%20API%20Setup%281.4.0.2%29.msi

 In this link GMAIL providing so many APIs for communicating with their different project.

http://code.google.com/p/google-gdata/

 Google.GData.Apps.dll, Google.GData.Client.dll, Google.GData.Contacts.dll, Google.GData.Extensions.dll are the major dll that’s should use for our application.

 Step-2:  Create a very simple ASP.Net application to import contacts from GMAIL. For a simple application, aspx page looks like this

 <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>IMport Gmail Contacts</title>
</head>
<body>
<form id="frmGmailContacts" runat="server">
<div>
<table>
<tr>
<td>
UserName</td>
<td>
<asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Password</td>
<td>
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password">
</asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnImport" runat="server" Text="Import"
onclick="btnImport_Click" />
</td>
</tr>
</table>
</div>
<div>
<asp:GridView ID="gdvContacts" runat="server"></asp:GridView>
</div>
</form>
</body>
</html>
 

Step 3 : In code behind we have to call API for getting contacts on button click event, and assign result set to gridview.

 

public static DataSet GetGmailContacts(string App_Name, string Uname,
string UPassword)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
DataColumn C2 = new DataColumn();
C2.DataType = Type.GetType("System.String");
C2.ColumnName = "EmailID";
dt.Columns.Add(C2);
RequestSettings rs = new RequestSettings(App_Name, Uname, UPassword);
rs.AutoPaging = true;
ContactsRequest cr = new ContactsRequest(rs);
Feed<Contact> f = cr.GetContacts();
foreach (Contact t in f.Entries)
{
foreach (EMail email in t.Emails)
{
DataRow dr1 = dt.NewRow();
dr1["EmailID"] = email.Address.ToString();
dt.Rows.Add(dr1);
}
}
ds.Tables.Add(dt);
return ds;
}
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = GetGmailContacts("Import GMAIL Contacts",
txtUsername.Text, txtPassword.Text);
gdvContacts.DataSource = ds;
gdvContacts.DataBind();
}

Collapsible panel extender samples in ASP.Net indifferent scenario

July 25, 2011 3 comments

How to implement collapsible panel extender in ASP.Net/C#?

Ajax collapsible panel extender is a tool used to collapse and expand each section with content or without content with asynchronous javascript, hence there is no postback happening in the middle of collapse/expand process. Dot Net framework helps to create collapse and expand functionalities within easy steps. Ajax tool kit included a control name Ajax Collapsible Panel Extender allows to implement above mentioned process as very easily.  The CollapsiblePanel is a very flexible extender that allows you to easily add collapsible sections to your web page. This extender targets any ASP.NET Panel control. The page developer specifies which control(s) on the page should be the open/close controller for the panel, or the panel can be set to automatically expand and/or collapse when the mouse cursor moves in or out of it, respectively.

Steps to implement Ajax collapsible panel extender in ASP.Net/C#

Here we are going to demonstrate step by step process to implement ajax collapsible panel extender in ASP.Net/C#. In order to implement collapsible panel extender we need to include ajax control toolkit dll as reference to our visual studio.

  1. Register Ajax control toolkit to your aspx page
  2. Drag and drop a <ScriptManager> from the Toolbox to the page
  3. Now add an UpdatePanel to the page. Inside the <ContentTemplate> drag and drop a CollapsiblePanel from the AJAX toolkit. After applying some Css and add properties of the CollapsiblePanel, the mark up will look similar to the following

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit"
TagPrefix="cc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>CollapsiblePanelExtender Tips </title>   
<style type="text/css">
.cpHeader
{
color: white;
background-color: #719DDB;
font: bold 11px auto "Trebuchet MS", Verdana;
font-size: 12px;
cursor: pointer;
width:450px;
height:18px;
padding: 4px;           
}
.cpBody
{
background-color: #DCE4F9;
font: normal 11px auto Verdana, Arial;
border: 1px gray;               
width:450px;
padding: 4px;
padding-top: 7px;
}      
</style>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Panel ID="pHeader" runat="server" CssClass="cpHeader">
<asp:Label ID="lblText" runat="server" />
</asp:Panel>

<asp:Panel ID="pBody" runat="server" CssClass="cpBody">
Here will display our contents or controls
</asp:Panel>

<cc1:CollapsiblePanelExtender ID="CollapsiblePanelExtender1" runat="server"
TargetControlID="pBody" CollapseControlID="pHeader" ExpandControlID="pHeader"
Collapsed="true" TextLabelID="lblText" CollapsedText="Click to Show Content.."
ExpandedText="Click to Hide Content.."
CollapsedSize="0">
</cc1:CollapsiblePanelExtender>

</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>

 

How to Expand/Collapse the ASP.NET AJAX CollapsiblePanel programmatically using JavaScript?

In above example we looked that how we can implement ajax collapsible panel extender within the aspx page. In some scenario we need to call this functionality on some javscript events. In those scenario, we need to study that how we can call collapse and expand functionalities from javascript. Below is the code for calling ajax collapsible panel extender from javascript.

<asp:Button ID="btnClick" OnClientClick="ExpandCollapse()"
runat="server" Text="Expand/Collapse" />
</ContentTemplate>
</asp:UpdatePanel>
Add JavaScript in the <head> tag as shown below:
<script type="text/javascript">

function ExpandCollapse() {           
var collPanel = $find("CollapsiblePanelExtender1");
if (collPanel.get_Collapsed())
collPanel.set_Collapsed(false);
else
collPanel.set_Collapsed(true);
}      

</script>
 

How we can implement ajax collapsible panel extender from code behind in ASP.Net/C#?

We are going to check how we can call expand/collapse ajax collapsible panel extender from code behind in asp.net/c#. In some scenario we need to call expand/collapse functions in Ajax collapsible panel extender dynamically from asp.net/C#. Below mentioned code helps to dynamically call expand/collapse ajax collapsible panel extender from asp.net/c#

protected void btn_Collapse(object sender, EventArgs e)
    {
        // Expand
        this.CollapsiblePanelExtender1.Collapsed = false;
        this.CollapsiblePanelExtender1.ClientState = "false";
        // Collapse
        // Expand
        this.CollapsiblePanelExtender1.Collapsed = true;
        this.CollapsiblePanelExtender1.ClientState = "true";
    }

How to add an Ajax collapsible panel extender dynamically from code behind in ASP.Net/C#

In some scenario we have to create and implement a ajax collapsible panel extender dynamically as per the data from the database in ASP.Net/C#. We can create and implement ajax collapsible panel extender dynamically from code behind in ASP.Net/C# using below mentioned code.

 

using AjaxControlToolkit;

protected void Page_Load(object sender, EventArgs e)
{        
// Create Header Panel
Panel panelHead = new Panel();
panelHead.ID = "pH";
panelHead.CssClass = "cpHeader";
// Add Label inside header panel to display text
Label lblHead = new Label();
lblHead.ID = "lblHeader";
panelHead.Controls.Add(lblHead);

//Create Body Panel
Panel panelBody = new Panel();
panelBody.ID = "pB";
panelBody.CssClass = "cpBody";
// Add Label inside body Panel to display text
Label lblB = new Label();
lblB.ID = "lblBody";
lblB.Text = "This panel was added dynamically";
panelBody.Controls.Add(lblB);

// Create CollapsiblePanelExtender
CollapsiblePanelExtender cpe =
    new CollapsiblePanelExtender();
cpe.TargetControlID = panelBody.ID;
cpe.ExpandControlID = panelHead.ID;
cpe.CollapseControlID = panelHead.ID;
cpe.ScrollContents = false;
cpe.Collapsed = true;
cpe.ExpandDirection =
CollapsiblePanelExpandDirection.Vertical;
cpe.SuppressPostBack = true;
cpe.TextLabelID = lblHead.ID;
cpe.CollapsedText = "Click to Show Content..";
cpe.ExpandedText = "Click to Hide Content..";

this.UpdatePanel1.ContentTemplateContainer.Controls.Add(panelHead);
this.UpdatePanel1.ContentTemplateContainer.Controls.Add(panelBody);
this.UpdatePanel1.ContentTemplateContainer.Controls.Add(cpe);

}

How to get all classes and methods from a dll in ASP.Net C# using Reflection

July 21, 2011 12 comments

Use of reflection in ASP.Net/How to extract dll file in ASP.Net,C#

By using Reflection class we can access all types of objects in a dll file. Now we are going to demonstrate how we can access all list of classes and methods by browsing a dll file. We can also run a particular method from the dll by passing proper parameters. We are using Reflection class to accept all types from a dll file in ASP.Net, C#.  The System.Reflection namespace contains classes and interfaces that provide a managed view of loaded types, methods, and fields, with the ability to dynamically create and invoke types.

What is Reflection in ASP.Net/C#?

  • Reflection is a collection of classes which allow you to query assembly (classes/objects) metadata at runtime. Using reflection you can also create new types and their instances at runtime and invoke methods on these new type instances.
  • Reflection enables you to find out information about types in your assemblies during runtime. Using reflection, you can find out the details of an object’s methods in terms of its access modifier ( private, public etc.), you can discover the name and types of parameters in a methods signature.
  • Reflection is the ability to read metadata at runtime. Using reflection, it is possible to uncover the methods, properties, and events of a type, and to invoke them dynamically. Reflection also allows us to create new types at runtime.
  • Reflection provides objects (of type Type) that encapsulate assemblies, modules and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, Reflection enables you to access them.

How to List all classes in a dll file using Asp.Net,C# using reflection?

The following function accept dll file and extracting dll file using reflection class and return all classes in the dll file. We can call this function by dll file path as parameter then it will return all classes in the dll. In our project we are using a openfiledialog control to browse dll file and once the user select the dll file from local folder it will call below mentioned function with parameter as dll path. Then  it will return all classes in the dll file and we are displaying this list of class names in a list so that user can clearly seen all classes in the dll.

Funtion for listing all classes/types in a dll file in ASP.Net,C#

/// <summary>
/// Return all types loaded from desired DLL
/// </summary>
/// <param name="dllName">The DLL in which to parse and get the types from</param>
/// <returns>A filled ArrayList object containing all types </returns>
public ArrayList GetAllTypesFromDLLstring(string dllName)
{
Assembly _Assemblies = null;
try
{
_Assemblies = Assembly.LoadFrom(dllName);
}
catch (Exception ex)
{
Console.WriteLine("\n\nError - couldn't obtain assemblies from " + dllName);
Console.WriteLine("EXCEPTION OUTPUT\n" + ex.Message + "\n" + ex.InnerException);
ArrayList _Quit = new ArrayList(1);
_Quit.Add("QUIT");
return _Quit;
}

Type[] _AllTypes = _Assemblies.GetTypes();

ArrayList _Temp = new ArrayList();

foreach (Type t in _AllTypes)
{
_Temp.Add(t.ToString());
}

return _Temp;
}
 

How to access all methods in a dll file in ASP.Net,C# using reflection library

Next we are going to access all methods in a class in the dll file. Here we have to pass dll file patha and class name to list all methods. The output will be the list of all methods in the particular class in the dll file.

Function for listin all methods in a class from dll file using reflection in ASP.Net,C#

/// <summary>
/// Returns all method names from desired DLL/Class
/// </summary>
/// <param name="dllName">The DLL in which to parse for desired class</param>
/// <param name="className">The class in which to parse for all methods</param>
/// <returns>An ArrayList of each method from desired class</returns>
public ArrayList GetAllTypesFromClass(string dllName, string className)
{
Assembly _Assemblies = Assembly.LoadFrom(dllName);

Type _Type = _Assemblies.GetType(className);

ArrayList _Temp = new ArrayList();

try
{
MethodInfo[] _Methods = _Type.GetMethods();

foreach (MethodInfo meth in _Methods)
{
_Temp.Add(meth.ToString());
}
}
catch (Exception ex)
{
Console.WriteLine("\n\nError - couldn't obtain methods from " + dllName);
Console.WriteLine("EXCEPTION OUTPUT\n" + ex.Message + "\n" + ex.InnerException);
_Temp.Clear();
_Temp.Capacity = 1;
_Temp.Add("QUIT");
}

return _Temp;
}

 

Is it possible to run a method in the dll file at run time in ASP.Net,C# using reflection ?

Yes, we can run a particular method in a dll file from our ASP.Net/C# application using reflection library at run time. Let’s see how we can run a method in the assembly file. The below mentioned function demonstrates how we can run a particular method from the asp.net,c# application at run time.

Function to call/run a method/function in a dll file from ASP.Net/C#  using reflection at runtime

/// <summary>
/// Runs target Method from target Class from target DLL.
/// </summary>
/// <param name="dllName">The DLL to load and use parse for methods</param>
/// <param name="className">The class to load from specific DLL</param>
/// <param name="methodName">The method to call from class</param>
public void RunClass(string dllName, string className, string methodName)
{
// Create the assemblies from our current DLL.
Assembly _Assemblies = Assembly.LoadFrom(dllName);

// Get the type that we want from the assemblies.
//  IE: This would be the fully qualified class name (including namespace)
//  Example: "Reflectionism.Examples.Example1" or "Reflectionism.Examples.Example2"
Type _Type = null;
try
{
_Type = _Assemblies.GetType(className);
}
catch (Exception ex)
{
Console.WriteLine("\n\nError - couldn't obtain classrd from " + className);
Console.WriteLine("EXCEPTION OUTPUT\n" + ex.Message + "\n" + ex.InnerException);
return;
}

// Get the desired method we want from the target type.
MethodInfo _MethodInfo = null;
try
{
_MethodInfo = _Type.GetMethod(methodName);
}
catch (Exception ex)
{
Console.WriteLine("\n\nError - couldn't obtain method " +
    methodName + " from " + className);
Console.WriteLine("EXCEPTION OUTPUT\n" + ex.Message + "\n" + ex.InnerException);
return;
}

// The first parameter to pass into the Invoke Method coming up.
Object _InvokeParam1 = Activator.CreateInstance(_Type);

// This calls the target method ("DisplayMyself").
//  NOTE: I'm not passing any arguments down to the method being invoked.
//  Therefore, I'm passing null as my argument, otherwise Invoke takes an
//  array of Objects.
_MethodInfo.Invoke(_InvokeParam1, null);
}
}
}

Hence we have discussed all possibilities regarding reflection in asp.net/c# such as how to access types/classes from dll file, how to get/access methods/functions from dll file/assembly using reflection in asp.net, possible way to call/run a method/function in the dll from asp.net/c# at run time. We hope you got a needful help from this post. Thanks..

%d bloggers like this: