Menu ▼


<< < 1 2 > >>

To take backup of dll in GAC follow the below setps.

  • Open Windows Run
  • Type C:\Windows\assembly\GAC_MSIL and click enter
  • All the GAC MSIL dll's will be opened
  • You can take backup of what ever dll you want

Read More...
Submited By : mrkraju On 14 Jul 2016

This example shows you how to write C# extension method and how to convert DataSet to JSON using JavaScriptSerializer.

By default DataSet doesnot have GetJSON method to get JOSN string from DataSet. So in this example I have written an extension method to add GetJSON method to DataSet and it will return JSON String as output.

    public static class DataSetExt
    {
        public static string GetJSON(this DataSet ds)
        {

            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            ArrayList root = new ArrayList();
            List<Dictionary<string, object>> table;
            Dictionary<string, object> data;

            foreach (DataTable dt in ds.Tables)
            {
                table = new List<Dictionary<string, object>>();
                foreach (DataRow dr in dt.Rows)
                {
                    data = new Dictionary<string, object>();
                    foreach (DataColumn col in dt.Columns)
                    {
                        data.Add(col.ColumnName, dr[col]);
                    }
                    table.Add(data);
                }
                root.Add(table);
            }
            
            return serializer.Serialize(root);
        }
    }

Steps to write GetJSON extension method.

  • Class should be declared as static
  • Method name should be declared as static
  • Method parameter should be starts with "this" keyword and the Object(DataSet) and variable name(ds).
  • Using System.Web.Script.Serialization.JavaScriptSerializer we converted the DataSet to JSON using Dictionary and ArrayList.

Example
C# extension method

CS Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data;
using System.Text;
using System.Collections;

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

        protected void btnGetJSON_Click(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            dt.Columns.Add("Employee Name", typeof(string));
            dt.Columns.Add("Salary", typeof(decimal));
            dt.Columns.Add("Department", typeof(string));
            dt.Rows.Add("John", 5000.00, "Marketing");
            dt.Rows.Add("Smith", 4000.00, "IT");
            dt.Rows.Add("Williams", 6000.00, "Sales");
            dt.Rows.Add("Vijay", 6500.00, "IT");
            ds.Tables.Add(dt);
            dt = new DataTable();
            dt.Columns.Add("StudentID", typeof(int));
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Marks", typeof(int));
            dt.Columns.Add("Grade", typeof(string));
            dt.Rows.Add(1, "Suresh", 950, "A+");
            dt.Rows.Add(1, "Rama", 900, "A+");
            dt.Rows.Add(1, "Kishore", 750, "B");
            ds.Tables.Add(dt);
            divOutput.InnerHtml = ds.GetJSON();


        }

    }


    public static class DataSetExt
    {
        public static string GetJSON(this DataSet ds)
        {

            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            ArrayList root = new ArrayList();
            List<Dictionary<string, object>> table;
            Dictionary<string, object> data;

            foreach (DataTable dt in ds.Tables)
            {
                table = new List<Dictionary<string, object>>();
                foreach (DataRow dr in dt.Rows)
                {
                    data = new Dictionary<string, object>();
                    foreach (DataColumn col in dt.Columns)
                    {
                        data.Add(col.ColumnName, dr[col]);
                    }
                    table.Add(data);
                }
                root.Add(table);
            }
            
            return serializer.Serialize(root);
        }
    }
}

ASPX Page

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Sample.aspx.cs" Inherits="WebApp.Sample" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Button ID="btnGetJSON" runat="server" Text="Get JSON" OnClick="btnGetJSON_Click" />
    <br /><br />
    <div id="divOutput" runat="server">
        
    </div>
    </form>
</body>
</html>

Read More...
Submited By : mrkraju On 17 Jun 2016

This example shows you how to export datatable or dataset data to excel in asp.net and c#. By using EPPlus.dll we can easily export datatable or dataset data to excel. You can merge cells, give background color and can format the cell text in excel using EPPlus.dll in c# and asp.net

In the below example we have a dataset contains student details and product details. By using EPPlus.dll we will export the data to excel. Datatable1 (students) data will be exported to students sheet and Datatable2 (products) data will be exported to products sheet in the same excel. And we can dynamically merge the heading of the sheet and can give the border for dynamic data.

Example
Export Datatable or Dataset data to excel

C# code

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

public partial class _Default : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnExport_Click(object sender, EventArgs e)
    {
        CreateExcelFile();
    }

    DataSet GetData()
    {
        DataTable dt = new DataTable("Students");
        dt.Columns.Add("StudentID", typeof(int));
        dt.Columns.Add("StudentName", typeof(string));
        dt.Columns.Add("RollNumber", typeof(int));
        dt.Columns.Add("TotalMarks", typeof(int));
        dt.Rows.Add(1, "Jame's", 101, 900);
        dt.Rows.Add(2, "Steave, Smith", 105, 820);
        dt.Rows.Add(3, "Mark\"Waugh", 109, 850);
        dt.Rows.Add(4, "Steave,\"Waugh", 110, 950);
        dt.Rows.Add(5, "Smith", 111, 910);
        dt.Rows.Add(6, "Williams", 115, 864);
        DataSet ds = new DataSet("Example-DotnetLearners");
        ds.Tables.Add(dt);

        dt = new DataTable("Prodcuts");
        dt.Columns.Add("ProductID", typeof(int));
        dt.Columns.Add("ProductName", typeof(string));
        dt.Columns.Add("UnitPrice", typeof(decimal));
        for (int i = 1; i <= 100; i++)
            dt.Rows.Add(i, "Product - " + i.ToString(), i * 1.123);
        ds.Tables.Add(dt);
        return ds;
    }

    void CreateExcelFile()
    {
        try
        {
            using (DataSet ds = GetData())
            {
                if (ds != null && ds.Tables.Count > 0)
                {
                    using (ExcelPackage xp = new ExcelPackage())
                    {
                        foreach (DataTable dt in ds.Tables)
                        {
                            ExcelWorksheet ws = xp.Workbook.Worksheets.Add(dt.TableName);

                            int rowstart = 2;
                            int colstart = 2;
                            int rowend = rowstart;
                            int colend = colstart + dt.Columns.Count;

                            ws.Cells[rowstart, colstart, rowend, colend].Merge = true;
                            ws.Cells[rowstart, colstart, rowend, colend].Value = dt.TableName;
                            ws.Cells[rowstart, colstart, rowend, colend].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                            ws.Cells[rowstart, colstart, rowend, colend].Style.Font.Bold = true;
                            ws.Cells[rowstart, colstart, rowend, colend].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                            ws.Cells[rowstart, colstart, rowend, colend].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);

                            rowstart += 2;
                            rowend = rowstart + dt.Rows.Count;
                            ws.Cells[rowstart, colstart].LoadFromDataTable(dt, true);
                            int i = 1;
                            foreach (DataColumn dc in dt.Columns)
                            {
                                i++;
                                if (dc.DataType == typeof(decimal))
                                    ws.Column(i).Style.Numberformat.Format = "#0.00";
                            }
                            ws.Cells[ws.Dimension.Address].AutoFitColumns();



                            ws.Cells[rowstart, colstart, rowend, colend].Style.Border.Top.Style =
                               ws.Cells[rowstart, colstart, rowend, colend].Style.Border.Bottom.Style =
                               ws.Cells[rowstart, colstart, rowend, colend].Style.Border.Left.Style =
                               ws.Cells[rowstart, colstart, rowend, colend].Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;

                        }
                        Response.AddHeader("content-disposition", "attachment;filename=" + ds.DataSetName + ".xlsx");
                        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                        Response.BinaryWrite(xp.GetAsByteArray());
                        Response.End();
                    }
                }
            }
        }
        catch
        {
            throw;
        }
    }
}

ASPX Page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnExport" runat="server" Text="Export" OnClick="btnExport_Click" />
    </div>
    </form>
</body>
</html>

Read More...
Submited By : mrkraju On 17 Dec 2015

This example shows you how to create a csv file in c# and how to export datatable or dataset to csv file in c#. While writing csv file if input data contains double quote(") or comma(,) then csv file will not be generated properly. To overcome this issue we have written a custom method "FormatCSV" in the below example.

Datatable

Output

CS Page Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Text;
using System.Globalization;
using System.IO;

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            DataTable dt = GetData();
            foreach (DataRow dr in dt.Rows)
            {
                foreach (DataColumn dc in dt.Columns)
                    sb.Append(FormatCSV(dr[dc.ColumnName].ToString()) + ",");
                sb.Remove(sb.Length - 1, 1);
                sb.AppendLine();
            }
            File.WriteAllText("E:\\Sample\\SampleCSV.csv", sb.ToString());
        }

        DataTable GetData()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("StudentID", typeof(int));
            dt.Columns.Add("StudentName", typeof(string));
            dt.Columns.Add("RollNumber", typeof(int));
            dt.Columns.Add("TotalMarks", typeof(int));
            dt.Rows.Add(1, "Jame's", 101, 900);
            dt.Rows.Add(2, "Steave, Smith", 105, 820);
            dt.Rows.Add(3, "Mark\"Waugh", 109, 850);
            dt.Rows.Add(4, "Steave,\"Waugh", 110, 950);
            dt.Rows.Add(5, "Smith", 111, 910);
            dt.Rows.Add(6, "Williams", 115, 864);
            return dt;
        }

        public static string FormatCSV(string input)
        {
            try
            {
                if (input == null)
                    return string.Empty;

                bool containsQuote = false;
                bool containsComma = false;
                int len = input.Length;
                for (int i = 0; i < len && (containsComma == false || containsQuote == false); i++)
                {
                    char ch = input[i];
                    if (ch == '"')
                        containsQuote = true;
                    else if (ch == ',')
                        containsComma = true;
                }

                if (containsQuote && containsComma)
                    input = input.Replace("\"", "\"\"");

                if (containsComma)
                    return "\"" + input + "\"";
                else
                    return input;
            }
            catch
            {
                throw;
            }
        }

    }

}

Read More...
Submited By : mrkraju On 07 Dec 2015

We can format numbers using String.Format method in c#, it will returns a formatted result string.

Example Add leading zeros to number(Fixed length)
You can specify the minimum length of the digits for the input number along with the standard format string "D" it will add the leading zeros for the remaining digits.

In the below example we have mentioned D10 and input value we have given as 7658 so the String.Format will add 6 leading zeros to the input value.

Or you can specify the string format as 10 zeros {0:0000000000} will give you the same output.

int intVal = 7658;
string strMessage = string.Format(String.Format("{0:D10}", intVal));
spnMessage.InnerText = strMessage;

    OR
    
int intVal = 7658;
string strMessage = string.Format(String.Format("{0:0000000000}", intVal));
spnMessage.InnerText = strMessage;

Output
0000007658


More examples

{0,10:000000}
It will add the leading zeros up to 6 digits and adds 4 spaces.

int intVal = 7658;
string strMessage = string.Format(String.Format("{0,10:000000}", intVal));
spnMessage.InnerText = strMessage;
Output
007658


{0,0000000000.0000}
It will add the leading zeros up to 10 digits and adds 4 decimal digits.
int intVal = 7658;
string strMessage = string.Format(String.Format("{0:0000000000.0000}", intVal));
spnMessage.InnerText = strMessage;
Output
0000007658.0000


{0:N2}
It will format number with thousand separator along with 2 decimal digits.
int intVal = 7658;
string strMessage = string.Format(String.Format("{0:N2}", intVal));
spnMessage.InnerText = strMessage;
Output
7,658.00


{0:C}
It will format number with currency along with 2 decimal digits.
int intVal = 7658;
string strMessage = string.Format(String.Format("{0:C}", intVal));
spnMessage.InnerText = strMessage;
Output
$7,658.00

Read More...
Submited By : mrkraju On 24 Nov 2015

String.Format will returns a formatted result string. It converts the value of objects to string based on the format specified. In this example we will see how to format strings using String.Format

Example 1: Format string

string strMessage = string.Format("Hello {0} {1}. Welcome to DotnetLearners.com", txtFirstName.Text, txtLastName.Text);

Where "Hello {0} {1}. Welcome to DotnetLearners.com" is format and txtFirstName.Text, txtLastName.Text are string parameters.

The {} in the format string is format item. and 0, 1 indecates the index of the object whose string value will be inserted at that position.
Output
Hello Will Smith. Welcome to DotnetLearners.com


Example 2: Padding(Adding spaces) string

string strMessage = string.Format("Hello {0, 10} {1, -20}. Welcome to DotnetLearners.com", txtFirstName.Text, txtLastName.Text);

{0, 10} -> indicates 10 characters string (including input string) and the input string will be right aligned, that is spaces will be added left to the string.
{1, -20} -> indicates 20 characters string (including input string) and the input string will be left aligned, that is spaces will be added right to the string.
Output
Hello Will Smith . Welcome to DotnetLearners.com

Read More...
Submited By : mrkraju On 24 Nov 2015

C# DateTime method DateTime.DaysInMonth(year, month) will give you the number of days in the given month of the year. you have to pass the year and month of the given date to the method. Below example shows you how to use the DateTime.DaysInMonth method to get the number of days in a give date / month.

Example
number of days in a month

CS Page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Text;
using System.Globalization;

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

        }

        protected void btnGetDays_Click(object sender, EventArgs e)
        {
            DateTime dt = DateTime.ParseExact(txtDate.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture);
            int numberOfDays = DateTime.DaysInMonth(dt.Year, dt.Month);
            lblMessage.Text = "Number of days in the month " + dt.ToString("MMM-yyyy") + " is: <span style='color:red;'>" + numberOfDays + "</span>";
        }
    }
}

ASPX Page

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._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 id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Date :
        <asp:TextBox ID="txtDate" runat="server" Text="11/23/2015"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="btnGetDays" runat="server" Text="Get Number Of Days" OnClick="btnGetDays_Click" />
        <br />
        <br />
        <asp:Label ID="lblMessage" runat="server" Style="color: Green; font-weight: bold;
            font-size: 14px;"></asp:Label>
    </div>
    </form>
</body>
</html>

Read More...
Submited By : mrkraju On 23 Nov 2015

This example shows you how to get the number of days difference between two given dates using C# in asp.net

Using datetime subtract method we can get the timespan between two days, and timespan.TotalDays will give you the total number of days difference between the given days.

Example
days between two days

CS Page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Globalization;

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

    }

    protected void btnDifference_Click(object sender, EventArgs e)
    {
        DateTime dt1 = DateTime.ParseExact(txtDate1.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture);
        DateTime dt2 = DateTime.ParseExact(txtDate2.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture);
        TimeSpan tspan = dt2.Subtract(dt1);
        lblMessage.Text = "Number of days difference is: " + ((int)tspan.TotalDays).ToString();
    }

}

ASPX Page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Date 1:
        <asp:TextBox ID="txtDate1" runat="server" Text="11/09/2015"></asp:TextBox>
        <br />
        <br />
        Date 2:
        <asp:TextBox ID="txtDate2" runat="server" Text="11/22/2015"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="btnDifference" runat="server" Text="Get Difference" OnClick="btnDifference_Click" />
        <br />
        <br />
        <asp:Label ID="lblMessage" runat="server" Style="color: Green; font-weight: bold;"></asp:Label>
    </div>
    </form>
</body>
</html>

Read More...
Submited By : mrkraju On 22 Nov 2015

This example shows you how to verify given input contains only alphabets or not using regular expression in asp.net and c#.

Regular expression to check string contains only alphabets and spaces.
string strRegexpAlphabets = @"^[a-zA-Z ]*$";

Regular expression to check string contains only alphabets & not allow spaces (Remove the space after Z and before ]).
string strRegexpAlphabets = @"^[a-zA-Z]*$";

C# Code

protected void btnValidate_Click(object sender, EventArgs e)
{
    string strRegexpAlphabets = @"^[a-zA-Z ]*$";
    if (System.Text.RegularExpressions.Regex.IsMatch(txtAlphabets.Text, strRegexpAlphabets))
    {
        lblMessage.Text = "String contains only alphabets";
        lblMessage.ForeColor = System.Drawing.Color.Green;
    }
    else
    {
        lblMessage.Text = "String contains other than alphabets";
        lblMessage.ForeColor = System.Drawing.Color.Red;
    }
}

ASPX Page

<div>
    Alphabets<br />
    <asp:TextBox ID="txtAlphabets" runat="server"></asp:TextBox>
    <br />
    <br />
    <asp:Button ID="btnValidate" runat="server" Text="Validate" OnClick="btnValidate_Click" />
    <br />
    <br />
    <asp:Label ID="lblMessage" runat="server"></asp:Label>
</div>

Output
Regular expression to check string contains only numbers

Read More...
Submited By : mrkraju On 13 Nov 2015

This example shows you how to check given input contains only numbers (digits) or not using regular expression in asp.net and c#.

Regular expression
string strRegexpNumber = @"^[0-9 ]*$";

C# Code

protected void btnValidate_Click(object sender, EventArgs e)
{
    string strRegexpNumber = @"^[0-9 ]*$";
    if (Regex.IsMatch(txtNumber.Text, strRegexpNumber))
    {
        lblMessage.Text = "Valid Number";
        lblMessage.ForeColor = System.Drawing.Color.Green;
    }
    else
    {
        lblMessage.Text = "Invalid Number";
        lblMessage.ForeColor = System.Drawing.Color.Red;
    }
}

ASPX Page

<div>
    Number<br />
    <asp:TextBox ID="txtNumber" runat="server"></asp:TextBox>
    <br />
    <br />
    <asp:Button ID="btnValidate" runat="server" Text="Validate" OnClick="btnValidate_Click" />
    <br />
    <br />
    <asp:Label ID="lblMessage" runat="server"></asp:Label>
</div>

Output
number regular expression

Read More...
Submited By : mrkraju On 12 Nov 2015
<< < 1 2 > >>




Search dotnetlearners.com