Monday, February 25, 2013

How to create DLL in asp.net(C#)

 

Steps to create DLL (Dynamic Linking Library)

1)Open Visual Studio , Select “New Project

2)From the templates , choose “ClassLibrary” and give a name to it. (say “Calculatordll”)

createdll

3)It creates a namespace named “Claculatordll” and a class by default. Now write the set of code which you want make as DLL. We can have more than one class here.

namespace created

4)For now I will create two classes. One with calculator functionalities ( such as add , sub , mul etc) and the other class with display function.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CalculatorDll
{
    public class CalculatorFuncions
    {
        public int add(int a, int b)
        {
            return (a + b);
        }
        public int sub(int a, int b)
        {
            return (a - b);
        }
        public int multiply(int a, int b)
        {
            return (a * b);
        }
    }
    public class DisplayFunctions
    {
        public string Display(string str)
        {
            return str;
        }
    }
}

5)Now build the project . DLL will be created in the bin folder.

Find the dll in bin folder of the project. ( bin –> Release –> CalculatorDll.dll )

buildproject             bin folder   

 dll created

Now lets see how to use this dll in another project or web application.

It can be done in 3 ways.

1)Right click on the solution and select “add reference” . the following window appears . Browse for the calculator dll created just now and click ok.

add web reference         

browse dll

Sample code which uses the calculatordll

Aspx Code :

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

<!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>USING DLL</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
        <tr>
            <td>
                Enter a:
            </td>
            <td>
                <asp:TextBox ID="txta" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                Enter b:
            </td>
            <td>
                <asp:TextBox ID="txtb" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" />
                <asp:Button ID="btnSub" runat="server" Text="Subtract" OnClick="btnSub_Click" />
                <asp:Button ID="btnMul" runat="server" Text="Multiply" OnClick="btnMul_Click" />
            </td>
        </tr>
        <tr>
            <td>
                Result :
            </td>
            <td>
                <asp:TextBox ID="txtResult" runat="server"></asp:TextBox>
            </td>
        </tr>
        </table>
    </div>
    </form>
</body>
</html>

Code Behind :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UseDLL
{
    public partial class _Default : System.Web.UI.Page
    {
        /*CREATE AN OBJECT FOR THE CLASS IN DLL AND INVOKE FUNCTIONS IN THAT CLASS*/
        CalculatorDll.CalculatorFuncions Calc = new CalculatorDll.CalculatorFuncions();
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            txtResult.Text = Convert.ToString(Calc.add(Int32.Parse(txta.Text), Int32.Parse(txtb.Text)));
        }

        protected void btnSub_Click(object sender, EventArgs e)
        {
            txtResult.Text = Convert.ToString(Calc.sub(Int32.Parse(txta.Text), Int32.Parse(txtb.Text)));
        }

        protected void btnMul_Click(object sender, EventArgs e)
        {
            txtResult.Text = Convert.ToString(Calc.multiply(Int32.Parse(txta.Text), Int32.Parse(txtb.Text)));
        }
    }
}

Output :

op1            op2

2)Add this namespace to Web.config file in your application .

In System.web tag , go to pages tag and the write the following code in “controls” tag to access this dll in your application.

<system.web>
    <pages>
            <controls>
              <add namespace="CalculatorDll" assembly ="CalculatorDll" tagPrefix="CalculatorDll"/>
            </controls>
        </pages>
</system.web>

Now to access this namespace , add “using ClaculatorDll;” to your code behind code.

3) If you want to use it in a single page , then we can register this namespace using @register directive.

Reading from Text File (C#)

 

Sample code to read data from text file : use “System.IO” namespace to work with file Input Output Operations

Aspx Code :

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

<!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>READING TEXT FILE</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table>

              <tr>
            <td colspan="2">
                <asp:Button ID="btnReadFile" runat="server" Text="ReadFile" OnClick="btnReadFile_Click" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:Label ID="lblContents" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label>
                <asp:Label ID="lblFileContents" runat="server" Font-Bold="True" ForeColor="Black"></asp:Label>
            </td>
        </tr>
    </table>
    </div>
    </form>
</body>
</html>

Code Behind :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class Santhakam_SaveTextToFile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected String ReadTextFile()
    {
        String FileContents = string.Empty;
        StreamReader ObjReader;
        try
        {
            ObjReader = File.OpenText("C:\\Test.txt");
            FileContents = ObjReader.ReadToEnd();
            return FileContents;

        }
        catch(Exception ex)
        {
            return "Error";
        }
    }
   protected void btnReadFile_Click(object sender, EventArgs e)
    {
        lblContents.Text = "File Contents : ";
        lblFileContents.Text = ReadTextFile();
    }
}

Output:

ReadTextFile1         ReadTextFile2

Writing to a Text File (C#)

 

To perform file operations , use the namespace “using System.IO” .  StreamWriter class provides functions to write data to file and Stream Reader class provides functions to read data from file and to append data if required.

Sample code to write data to a Text File :

Aspx Code :

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

<!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>SAVING TEXT TO FILE</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table>
        <tr>
            <td>
                Enter Text:
            </td>
            <td>
                <asp:TextBox ID="txtMsg" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <asp:Button ID="btnWriteTextToFile" runat="server" Text ="WriteTextToFile"  OnClick="btnWriteTextToFile_Click" />
            </td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <asp:Label ID="lblMsg" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label>
            </td>
        </tr>
    </table>
    </div>
    </form>
</body>
</html>

Code Behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class Santhakam_SaveTextToFile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void WritetoTextFile()
    {
        //CREATE OBJECT FOR STREAMWRITER CLASS
        StreamWriter obj;
        try
        {
            /*CREATE TEXT FILE*/
            obj = File.CreateText("C:\\Sample.txt");
            /*WRITE DATA TO FILE*/
            obj.WriteLine(txtMsg.Text);
            obj.Flush();
            obj.Close();           
        }
        catch (Exception ex)
        {
            //ErrorPage.ToString();
        }

    }
   protected void btnWriteTextToFile_Click(object sender, EventArgs e)
    {
        WritetoTextFile();
        lblMsg.Text = "File has been created and text is saved to file Successfully";
    }
}

Output :

SaveTexttofile1      Savetexttofile2