Thursday, October 25, 2012

How can I convert Datatable to Generic List and vice versa in C#?

Problem: I need to convert Generic list to Datatable and Data table to Generic list. How can I do this in C#?

 Solution: You may often require to convert your Datatable to Generic list of your Generic list to Datatable. Following code snippet use extension method for the conversion:




using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Text;

/// <summary>
/// Summary description for GenericListExtensionMethod
/// </summary>
public static class GenericListExtensionMethod
{
    public static DataTable GetDataTable<T>(this List<T> obj)
    {
        DataTable dt = new DataTable();
        //special handling for value types and string
        if (typeof(T).IsValueType || typeof(T).Equals(typeof(string)))
        {
            DataColumn dc = new DataColumn("Value");
            dt.Columns.Add(dc);
            foreach (T item in obj)
            {
                DataRow dr = dt.NewRow();
                dr[0] = item;
                dt.Rows.Add(dr);
            }
        }

        else//for reference types other than  string
        {

            //find all the public properties of this Type using reflection
            PropertyInfo[] piT = typeof(T).GetProperties();
            foreach (PropertyInfo pi in piT)
            {
                //create a datacolumn for each property
                if (pi.PropertyType.Name.Contains("Nullable"))
                {
                    DataColumn dc = new DataColumn(pi.Name, typeof(string));
                    dt.Columns.Add(dc);
                }
                else
                {
                    DataColumn dc = new DataColumn(pi.Name, pi.PropertyType);
                    dt.Columns.Add(dc);
                }
            }

            //now we iterate through all the items in current instance, take the corresponding values and add a new row in dt
            for (int item = 0; item < obj.Count; item++)
            {
                DataRow dr = dt.NewRow();

                for (int property = 0; property < dt.Columns.Count; property++)
                {
                    dr[property] = piT[property].GetValue(obj[item], null);
                }

                dt.Rows.Add(dr);
            }
        }

        return dt;
    }

    public static List<T> ToCollection<T>(this DataTable dt)
    {
        List<T> lst = new List<T>();
        Type tClass = typeof(T);
        PropertyInfo[] pClass = tClass.GetProperties();
        List<DataColumn> dc = dt.Columns.Cast<DataColumn>().ToList();
        T cn;
        foreach (DataRow item in dt.Rows)
        {
            cn = (T)Activator.CreateInstance(tClass);
            foreach (PropertyInfo pc in pClass)
            {
                string ptp = pc.PropertyType.Name;
               
                DataColumn d = dc.Find(c => c.ColumnName == pc.Name);
                if (d != null && item[pc.Name] != null && item[pc.Name] != DBNull.Value)
                {
                    string tt = d.DataType.Name;
                    switch (tt)
                    {
                        case "String":
                                pc.SetValue(cn, Convert.ToString(item[pc.Name]), null);
                            break;
                        case "Int16":
                            pc.SetValue(cn, Convert.ToInt16(item[pc.Name]), null);
                            break;
                        case "Int32":
                            pc.SetValue(cn, Convert.ToInt32(item[pc.Name]), null);
                            break;
                        case "Decimal":
                            pc.SetValue(cn, Convert.ToDecimal(item[pc.Name]), null);
                            break;
                        case "DateTime":
                            pc.SetValue(cn, Convert.ToDateTime(item[pc.Name]), null);
                            break;
                        default:
                            pc.SetValue(cn, Convert.ToString(item[pc.Name]), null);
                            break;
                    }
                   
                }
            }
            lst.Add(cn);
        }
        return lst;
    }

}

And here is how you can use these methods (in Ext.Net):

protected void btnExport_Click(object sender, DirectEventArgs e)
    {
        string json = e.ExtraParams["AllValues"];
        if (string.IsNullOrEmpty(json))
        {
            return;
        }
        List<dividend> lst = JSON.Deserialize<List<dividend>>(json);
        if (lst == null)
        {
            return;
        }
        try
        {
            DataTable dt = new DataTable();
            dt = lst.GetDataTable();

            string exportAs = "BankReturn" + CurrentDateString() + ".xlsx";


            List<string> columnNames = new List<string>() { "dividendyear", "declareid", "wno", "boid", "name", "bankcorr", "branch", "accno", "StatusName", "LastAction", "remarks" };
            Export(dt, columnNames, exportAs);

                    }
        catch (Exception ex)
        {
            X.Msg.Alert("Message", string.Format("{0}", ex.ToString())).Show();
            return;
        }
    }


protected void fuImport_FileSelected(object sender, DirectEventArgs e)
    {
        string json = e.ExtraParams["AllValues"];
        if (string.IsNullOrEmpty(json))
        {
            X.Msg.Alert("Message", string.Format("{0}", "Please search some data first to update on import")).Show();
            return;
        }

        List<dividend> lst = JSON.Deserialize<List<dividend>>(json);

        DataSet ds = ImportExcelXLS(fuImport.PostedFile, true);

        List<dividend> impLst = ds.Tables[0].ToCollection<dividend>();

        gpBoInfoStore.DataSource = lst;
        gpBoInfoStore.DataBind();
    }











Tuesday, September 18, 2012

How to solve error: 404.2 The page you are requesting cannot be served

Problem: 
I get the error while trying to visit home page of a deployed asp.net 4 application in IIS7: 404.2 The page you are requesting cannot be served because of the ISAPI and CGI Restriction list settings on the Web server.

How can I solve this issue?

 Solution:
This error occurs because the requested ISAP(Internet Server API) and/or CGI(Common Gateway Interface) resource is restricted on the computer that is running IIS 7. After installing .NET Framework 4.0 on a machine there is a few configuration changes you need to do to IIS in order to get a ASP.NET 4.0 page running.

To resolve this issue you have to follow steps mentioned below:

1. Open IIS and Click on the sever name.
2. In Feature View Double click "ISAPI and CGI Restrictions"

3. Select ASP.Net V4 and click Allow in action panel. It will be set to Allowed.

Now your application should run.


Tuesday, September 4, 2012

How to call server side a direct method from ext.net gridpanel?


In ext.net you can call server side direct method from your client side code. This is an excellent way to doing jobs on server side from client side java script function and grid panel, button or other controls. Here we will see how we can do this job done in a grid panel.
In the following code snippet will call a direct method against an action in a grid panel action column. Also we will pass some arguments from our grid to direct method that we require for data manipulation on server side.
Let see code for grid panel:
<ext:GridPanel ID="gpList" runat="server" StripeRows="true" Title="BO List" AutoExpandColumn="name"
                                    Collapsible="true" AnchorHorizontal="100%" Height="350">
                                    <Store>
                                        <ext:Store ID="gpListStore" runat="server" OnRefreshData="gpListStore_RefreshData"
                                            OnSubmitData="gpListStore_SubmitData">
                                            <Reader>
                                                <ext:JsonReader IDProperty="cno">
                                                    <Fields>
                                                        <ext:RecordField Name="dividendyear" />
                                                        <ext:RecordField Name="declareid" />
                                                        <ext:RecordField Name="wno" />
                                                        <ext:RecordField Name="name" />
                                                        <ext:RecordField Name="boid" />
                                                        <ext:RecordField Name="shares" />
                                                        <ext:RecordField Name="dividendM" />
                                                        <ext:RecordField Name="taxrate" />
                                                        <ext:RecordField Name="taxamt" />
                                                        <ext:RecordField Name="netamt" />
                                                        <ext:RecordField Name="actionid" />
                                                        <ext:RecordField Name="status" />
                                                    </Fields>
                                                </ext:JsonReader>
                                            </Reader>
                                        </ext:Store>
                                    </Store>
                                    <ColumnModel ID="ColumnModel1" runat="server">
                                        <Columns>
                                            <ext:RowNumbererColumn />
                                            <ext:Column ColumnID="cdeclareid" Header="Declare Id" DataIndex="declareid" Width="70" />
                                            <ext:Column ColumnID="cdividendyear" Header="Year" DataIndex="dividendyear" Width="50">
                                            </ext:Column>
                                            <ext:Column ColumnID="cBoid" Header="Boid" DataIndex="boid" Width="130" />
                                            <ext:Column ColumnID="cname" Header="Name" DataIndex="name" />
                                            <ext:Column ColumnID="cshares" Header="Shares" DataIndex="shares" Width="50" />
                                            <ext:Column ColumnID="cdividendM" Header="Dividend" DataIndex="dividendM" Width="50" />
                                            <ext:Column ColumnID="ctaxrate" Header="Tax Rate" DataIndex="taxrate" Width="50" />
                                            <ext:Column ColumnID="ctaxamt" Header="Tax Amt" DataIndex="taxamt" Width="50" />
                                            <ext:Column ColumnID="cnetamt" Header="Net Amt" DataIndex="netamt" Width="50" />
                                            <ext:Column ColumnID="cStatus" Header="Status" DataIndex="status" />
                                            <ext:CommandColumn Header="Action" Width="90">
                                                <Commands>
                                                    <ext:GridCommand Icon="ApplicationViewDetail" CommandName="ViewDetail">
                                                        <ToolTip Text="View Detail" />
                                                    </ext:GridCommand>
                                                    <ext:CommandSeparator />
                                                    <ext:GridCommand Icon="AsteriskRed" CommandName="Action">
                                                        <ToolTip Text="Action" />
                                                    </ext:GridCommand>
                                                    <ext:CommandSeparator />
                                                    <ext:GridCommand Icon="Connect" CommandName="Communication">
                                                        <ToolTip Text="Communication with people." />
                                                    </ext:GridCommand>
                                                </Commands>
                                            </ext:CommandColumn>
                                        </Columns>
                                    </ColumnModel>
                                    <SelectionModel>
                                        <ext:CheckboxSelectionModel ID="CheckboxSelectionModel1" runat="server" />
                                    </SelectionModel>
                                    <BottomBar>
                                        <ext:PagingToolbar ID="PagingToolBar1" runat="server" PageSize="10" />
                                    </BottomBar>
                                    <Listeners>
                                        <Command Handler="Ext.net.DirectMethods.ExecuteActionCommand(command, record.data.wno, record.data.declareid, record.data.boid);" />
                                    </Listeners>
                                    <DirectEvents>
                                        <AfterEdit OnEvent="gpList_AfterEdit">
                                            <EventMask ShowMask="true" Target="This" />
                                            <ExtraParams>
                                                <ext:Parameter Name="field" Value="e.field" Mode="Raw" />
                                                <ext:Parameter Name="id" Value="e.record.id" Mode="Raw" />
                                                <ext:Parameter Name="record" Value="e.record.data" Mode="Raw" Encode="true" />
                                            </ExtraParams>
                                        </AfterEdit>
                                    </DirectEvents>
                                </ext:GridPanel>


Direct method is called using listener in ext.net which always woks at client side.
<Listeners>
          <Command Handler="Ext.net.DirectMethods.ExecuteActionCommand(command, record.data.wno, record.data.declareid, record.data.boid);" />
</Listeners>


Here in Action column we have three action commands:
1.  ViewDetail
2.  Action
3.  Communication
These commands will pass to parameter command and on server side we will decide which action actually performed. Server side code is here:

[DirectMethod]
    public void ExecuteActionCommand(string command, string wno,  string declareid, string boid)
    {
        if (command == "ViewDetail")
        {
            //Display bo holder detail info
            var win = new Window
            {
                ID = "BOWindow",
                Title = "Bo Detail",
                Width = Unit.Pixel(800),
                Height = Unit.Pixel(380),
                Modal = true,
                Collapsible = true,
                Maximizable = false,
                Hidden = false,

            };

            win.AutoLoad.Url = "~/BoMasterDetails.aspx?boid=" + boid + "&declareid=" + declareid;
            win.AutoLoad.Mode = LoadMode.IFrame;

            win.Render(this.Form); win.Dispose();
        }
        else if (command == "Action")
        {
            var win = new Window
            {
                ID = "ActionWindow",
                Title = "Corporate Action",
                Width = Unit.Pixel(800),
                Height = Unit.Pixel(550),
                Modal = true,
                Collapsible = true,
                Maximizable = false,
                Hidden = false,

            };

            win.AutoLoad.Url = "~/ActionLogEntryPopup.aspx?wno=" + wno + "&boid=" + boid + "&declareid=" + declareid;
            win.AutoLoad.Mode = LoadMode.IFrame;

            win.Render(this.Form); win.Dispose();
        }
        else if (command == "Communication")
        {
            dividend div = new dividendBLL().dividend_GetAll_By_wno(wno).FirstOrDefault();
            var win = new Window
            {
                ID = "CommWindow",
                Title = "Communication",
                Width = Unit.Pixel(800),
                Height = Unit.Pixel(550),
                Modal = true,
                Collapsible = true,
                Maximizable = false,
                Hidden = false,

            };

            win.AutoLoad.Url = "~/CommunicationLogEntryPopup.aspx?wno=" + wno + "&boid=" + boid + "&declareid=" + declareid;
            win.AutoLoad.Mode = LoadMode.IFrame;

            win.Render(this.Form); win.Dispose();
        }
    }

How to display a popup dynamically in ext.net?


Here I will show you quick tips on how you can create a dynamic popup control in your ext.net application.
Look at the following server side ext.net code snippet:
            var win = new Window
            {
                ID = "CommWindow",
                Title = "Communication",
                Width = Unit.Pixel(800),
                Height = Unit.Pixel(550),
                Modal = true,
                Collapsible = true,
                Maximizable = false,
                Hidden = false,

            };

            win.AutoLoad.Url = "~/CommunicationLogEntryPopup.aspx?wno=" + wno + "&boid=" + boid + "&declareid=" + declareid;
            win.AutoLoad.Mode = LoadMode.IFrame;

            win.Render(this.Form); win.Dispose();

First create a window and define all its properties and load your page into the window and IFrame.
Hope this will help you guys. 

Sunday, August 5, 2012

How to convert a file to byte array and create file from byte array?

Problem:
How to convert a file to byte array? and how can I create the file from byte array?

Solution:

To convert a file to byte array you need to used FileStream class. You have to open instance of the class in read mode and class Read() method to read bytes in byte array.

To retrieve the file from byte array you have to open the instance of the class in create mode with write access and call Write() method to write bytes and create file.

Look at following code example:


string sessionId = Session.SessionID;
        imgDocImage.ImageUrl = string.Empty;
        string fileName = hdfImagePath.Value.ToString();
        string docDtlId = hfDoctDtlId.Value.ToString();
        string tempPath = Server.MapPath("~/Uploads");
        tempPath = tempPath + "\\" + sessionId + "\\" + fileName;
        string newPath = Server.MapPath("~/Uploads");
        newPath = newPath + "\\" + docDtlId;
        if (!System.IO.Directory.Exists(newPath))
        {
            System.IO.Directory.CreateDirectory(newPath);
        }
        newPath = newPath + "\\" + fileName;
        int id = 0;
        if (!System.IO.File.Exists(newPath))
        {
            FileStream fsr = new FileStream(tempPath, FileMode.Open, FileAccess.Read);
            int bytesInFile = (int)fsr.Length;
            byte[] fileContent = new byte[bytesInFile];
            long bytesRead = fsr.Read(fileContent, 0, bytesInFile);
            fsr.Close();

            FileStream fs = new FileStream(newPath, FileMode.Create, FileAccess.Write);
            fs.Write(fileContent, 0, fileContent.Length);
            fs.Close();
        }

Monday, July 30, 2012

My Open source FTP client project


Dev Studio 17 Web-Based FTP Client is now on codeplex.com and is open for learners and professionals and free for commercial use also. This is a complete web base ftp client application that will help in your work.

Project Description
Dev Studio 17 Web-Based FTP Client is a web based ftp application built using asp.net, c#.

Features:
  • Upload files to FTP Server
  • Downloads files from FTP Server
  • Create Directory
  • Remove Directory
  • Delete files
  • Traverse back to upper directory
 To download the application please visit: http://ds17ftp.codeplex.com/

Thanks

How can I save record using jQuery in ASP.Net?

Problem: How can I save record using jQuery in ASP.Net? Please provide me source code for save record using jquery in asp.net.

Solution:

You need to create a web service and add a web method for saving record and call the method from jquery.
Look at the following example:
You need to add a method in your web service which is marked with WebMethod attribute. Similar to following code snipppet:


[WebMethod]
        public bool MarkProjectComplete(long projectID)
        {
            bool result = false;
            EnumStatus status = ProjectFacade.MarkProjectComplete(projectID);
            if (status == EnumStatus.Successfull)
            {
                result = true;
                if (projectID > 0)
                {
                    Project project = null;
                    project = ProjectFacade.GetProjectByID(projectID);
                }
            }
            return result;
        }
 

Then call your method from your jquery function. Look at following code snippet:

function MarkProjectComplete(projectID) {
            if (confirm('Are you sure you would like to mark this project as ‘Mark Project Complete’?')) {
                $.ajax({
                    type: "POST",
                    url: "<%= ApplicationPath %>/WebServices/YourWebService.asmx/MarkProjectComplete",
                    data: "{'projectID' : '" + projectID + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        if (msg.d == true) {
                            alert("Mark Project Complete Successfully");
                            
                        }
                    },
                    error: function () {
                    }
                });
            }
        }

Hope it will be helpful. Thanks.