Sunday 25 August 2013

How to remove DataTable column in c#

We can remove Column in DatatTable by using DataColumnCollection.Remove method as follows.

private void RemoveColumnByName(string columnName)
    {
        // Get the DataColumnCollection from a DataTable
        DataColumnCollection columns =dt.Columns;

        if (columns.Contains(columnName))
            if (columns.CanRemove(columns[columnName]))
                columns.Remove(columnName);
    }

Wednesday 21 August 2013

Creating a simple photo gallery in asp.net by using Ajax HoverMenuExtender control with GridView.

In this tutorial i will show you how to create a simple image gallery with GridView control by using Ajax HoverMenuExtender.

1. Create a new website in VisualStudio.

2. Register AjaxControlToolkit in your page as follows.


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

3. If you are using an Ajax controls in your page you should use ToolkitScriptManager control in your page. 

4. Drag and drop ToolkitScriptManager on to your page.

    <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
    </asp:ToolkitScriptManager>

5. Place GridView inside your page and then assign the following properties to GridView.

     AutoGenerateColumns="False"
     CellPadding="4"
     ForeColor="#333333"
     GridLines="None"
     BorderColor="#8A8A8A"
     BorderStyle="Solid"
     BorderWidth="2px"
     PageSize="4"
     AllowPaging="true"
     PagerSettings-Mode="NextPrevious"
     PagerSettings-NextPageText="Next"
     PagerSettings-PreviousPageText="Prev"
     HeaderStyle-BackColor="#696969"
     HeaderStyle-Font-Bold="True"
     HeaderStyle-ForeColor="White"

6. Add PageIndexChanging event to GridView for paging purpose.
    
    OnPageIndexChanging="GridView1_PageIndexChanging"

7. Add TemplateField to display the images in your grid and place an image control and set the ImageUrl to the binding expression as follows.

    <Columns>
            <asp:TemplateField HeaderText="Gallery">
                <ItemTemplate>
                    <asp:Image runat="server" ID="thumbnailImage" ImageUrl='<%# Container.DataItem %>'
                        Width="100" Height="100" />                
                </ItemTemplate>
            </asp:TemplateField>
    </Columns>

8. To show image preview when the user mouse over on to the image in gridview we will use HoverMenuExtender control.

HoverMenuExtender:
HoverMenu is an ASP.NET AJAX extender that can be attached to any ASP.NET WebControl,and will associate that control with a popup panel do display additional content. 

9. Drag and drop the HoverMenuExtender control inside ItemTemplate and set  the properties, and then add the Panel and place an Image control inside Panel to preview the gridview image and then set the ImageUrl to the binding expression as follows.

    <asp:HoverMenuExtender ID="HoverMenuExtender1" runat="server" PopupControlID="popupImage"
                        TargetControlID="thumbnailImage" OffsetX="10" OffsetY="5" PopupPosition="Right"
                        PopDelay="100" HoverDelay="100">
    </asp:HoverMenuExtender>
    <asp:Panel runat="server" ID="popupImage" BorderColor="#8A8A8A" BorderStyle="Solid"
                        BorderWidth="7px">
                        <asp:Image runat="server" ID="mainImage" ImageUrl='<%# Container.DataItem %>' Style="height: 400px;
                            width: auto;" />
    </asp:Panel>

10. Now add the images to your website create "Images" folder in your website root folder and place images  you want to display inside it.

11. Now go to code behind file add the following code to load the images into GridView.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //Load images to the gridview
            LoadGallery();
        }
    }

    private void LoadGallery()
    {
        //Get application path of the website
        string appPath = HttpContext.Current.Request.ApplicationPath;
        //Get physical path of the website along woth images folder
        string physicalPath = HttpContext.Current.Request.MapPath(appPath) + "\\images";
        //get all files inside images folder
        string[] filePaths = Directory.GetFiles(physicalPath );
        //new array to store files names
        string[] finalFilePaths = new string[filePaths.Length];
        foreach (string str in filePaths)
        {
            //get relative path of the files and store in finalFilePath array
            finalFilePaths[Array.IndexOf(filePaths, str)] = str.Replace(physicalPath, "~/images");
        }
        //assign final paths to the gridview
        GridView1.DataSource = finalFilePaths;
        //Bind the gridview
        GridView1.DataBind();
    }

10. To work the paging in your GridView write the code inside  GridView1_PageIndexChanging event as follows.

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        //assign new page index to gridview
        GridView1.PageIndex = e.NewPageIndex;
        //Rebind the GridView
        LoadGallery();
    }

11. Now build your website and open the page in your browser. GridView will load all the images from the "Images" folder and display's them. So, mouse over on to the images. Image preview will display besides to the image.

So, in this way we can create the simple photo gallery with the GridView.

Tuesday 20 August 2013

How to get the application path in C#.NET

First Get the ASP.NET application's virtual application root path on the server using HttpRequest.ApplicationPath Property.

string appPath = HttpContext.Current.Request.ApplicationPath;

Now map the specified virtual path to a physical path using Request.MapPath() Method.

string physicalPath = HttpContext.Current.Request.MapPath(appPath);

Friday 16 August 2013

SQL Server Data Types and their .NET Framework equivalents

The following table lists Microsoft SQL Server data types, their equivalents in the common language runtime (CLR) for SQL Server in the System.Data.SqlTypes namespace, and their native CLR equivalents in the Microsoft .NET Framework.
SQL Server data type Type
(In System.Data.SqlTypes
or
Microsoft.SqlServer.Types)
CLR data type (.NET Framework)
bigint SqlInt64 Int64, Nullable<Int64>
binary SqlBytes, SqlBinary Byte[]
bit SqlBoolean Boolean, Nullable<Boolean>
char None None
date SqlDateTime DateTime, Nullable<DateTime>
datetime SqlDateTime DateTime, Nullable<DateTime>
datetime2 None DateTime, Nullable<DateTime>
DATETIMEOFFSET None DateTimeOffset, Nullable<DateTimeOffset>
decimal SqlDecimal Decimal, Nullable<Decimal>
float SqlDouble Double, Nullable<Double>
image None None
int SqlInt32 Int32, Nullable<Int32>
money SqlMoney Decimal, Nullable<Decimal>
nchar SqlChars, SqlString String, Char[]
ntext None None
numeric SqlDecimal Decimal, Nullable<Decimal>
nvarchar SqlChars, SqlString String, Char[]
nvarchar(1), nchar(1) SqlChars, SqlString Char, String, Char[], Nullable<char>
real SqlSingle 
(the range of SqlSingle, however, is larger than real)
Single, Nullable<Single>
smallint SqlInt16 Int16, Nullable<Int16>
smallmoney SqlMoney Decimal, Nullable<Decimal>
sql_variant None Object
time None TimeSpan, Nullable<TimeSpan>
timestamp None None
tinyint SqlByte Byte, Nullable<Byte>
uniqueidentifier SqlGuid Guid, Nullable<Guid>
User-defined type(UDT) None The same class that is bound to
The user-defined type in the same
assembly or a dependent assembly.
varbinary SqlBytes, SqlBinary Byte[]
varbinary(1), binary(1) SqlBytes, SqlBinary byte, Byte[], Nullable<byte>
varchar None None
xml SqlXml None

Monday 12 August 2013

Download file inside Ajax UpdatePanel in ASP.NET


In this article I am going to show you how to download the file from UpdatePanel. 

1. Create new ASP.NET Web page in VisualStudio.

2. Before going to add UpdatePanel to your page you must add ScriptManager control to your web page. 

3. Drag and drop ScriptManager control on to the page.
 <ajax:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </ajax:ToolkitScriptManager>

4. Now drag and drop UpdatePanel to the page.
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Always">
            <ContentTemplate>              
            </ContentTemplate>           
</asp:UpdatePanel>

5.  Now add Button inside the UpdatePanel.
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Always">
            <ContentTemplate>
                <asp:Button ID="btnDownloadFile" runat="server" Text="Download File" OnClick="btnDownloadFile_Click" />
            </ContentTemplate>           
</asp:UpdatePanel>

6. To download the file write the following code in button click event.

    protected void btnDownloadFile_Click(object sender, EventArgs e)
    {
        //Send physical path of the file
        DownloadFile("D:\\Test.txt");
    }
    private void DownloadFile(string filePath)
    {
        // Get the physical Path of the file
        string filepath = filePath;
        System.IOFileInfo file = new System.IOFileInfo(filepath);

        if (file.Exists)
        {
            Response.ClearContent();
            // Add the file name and attachment
            Response.AddHeader("Content-Disposition", "attachment; filename=Test.txt");
            // Add the file size into the response header
            Response.AddHeader("Content-Length", file.Length.ToString());
            // Set the ContentType
            Response.ContentType = GetFileExtension(file.Extension.ToLower());
            // Write the file into the response
            Response.TransmitFile(file.FullName);
            Response.End();
        }
    }
    private string GetFileExtension(string fileExtension)
    {
        switch (fileExtension)
        {
            case ".htm":
            case ".html":
            case ".log":
                return "text/HTML";
            case ".txt":
                return "text/plain";
            case ".doc":
                return "application/ms-word";
            case ".tiff":
            case ".tif":
                return "image/tiff";
            case ".asf":
                return "video/x-ms-asf";
            case ".avi":
                return "video/avi";
            case ".zip":
                return "application/zip";
            case ".xls":
            case ".csv":
                return "application/vnd.ms-excel";
            case ".gif":
                return "image/gif";
            case ".jpg":
            case "jpeg":
                return "image/jpeg";
            case ".bmp":
                return "image/bmp";
            case ".wav":
                return "audio/wav";
            case ".mp3":
                return "audio/mpeg3";
            case ".mpg":
            case "mpeg":
                return "video/mpeg";
            case ".rtf":
                return "application/rtf";
            case ".asp":
                return "text/asp";
            case ".pdf":
                return "application/pdf";
            case ".fdf":
                return "application/vnd.fdf";
            case ".ppt":
                return "application/mspowerpoint";
            case ".dwg":
                return "image/vnd.dwg";
            case ".msg":
                return "application/msoutlook";
            case ".xml":
            case ".sdxl":
                return "application/xml";
            case ".xdp":
                return "application/vnd.adobe.xdp+xml";
            default:
                return "application/octet-stream";
        }
    }

7. Now open the web page in browser and click on download file button. The file will not download because UpdatePanel is used for partial page rendering. If you want to download the file you should  postback whole page. To resolve this problem we need to rely upon a standard postback i.e. we need to set the button that is download file to be PostBack trigger. This will initiate a normal postback whenever we click the download file button and it is possible to download the file. So, add the postback trigger to the UpdatePanel as follows.
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Always">
            <ContentTemplate>
                <asp:Button ID="btnDownloadFile" runat="server" Text="Download File" OnClick="btnDownloadFile_Click" />
            </ContentTemplate>
            <Triggers>
                <asp:PostBackTrigger ControlID="btnDownloadFile" />
            </Triggers>
        </asp:UpdatePanel>

8.  Now save and open the page in browser and click on download file button. Now you are able to download the file from the UpdatePanel.


Whole page script: 

<%@ Page Language="C#" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<!DOCTYPE html>
<html>
<script runat="server">
   
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnDownloadFile_Click(object sender, EventArgs e)
    {
        //Send physical path of the file
        DownloadFile("D:\\Test.txt");
    }
    private void DownloadFile(string filePath)
    {
        // Get the physical Path of the file
        string filepath = filePath;
        System.IOFileInfo file = new System.IOFileInfo(filepath);

        if (file.Exists)
        {
            Response.ClearContent();
            // Add the file name and attachment
            Response.AddHeader("Content-Disposition", "attachment; filename=Test.txt");
            // Add the file size into the response header
            Response.AddHeader("Content-Length", file.Length.ToString());
            // Set the ContentType
            Response.ContentType = GetFileExtension(file.Extension.ToLower());
            // Write the file into the response
            Response.TransmitFile(file.FullName);
            Response.End();
        }
    }
    private string GetFileExtension(string fileExtension)
    {
        switch (fileExtension)
        {
            case ".htm":
            case ".html":
            case ".log":
                return "text/HTML";
            case ".txt":
                return "text/plain";
            case ".doc":
                return "application/ms-word";
            case ".tiff":
            case ".tif":
                return "image/tiff";
            case ".asf":
                return "video/x-ms-asf";
            case ".avi":
                return "video/avi";
            case ".zip":
                return "application/zip";
            case ".xls":
            case ".csv":
                return "application/vnd.ms-excel";
            case ".gif":
                return "image/gif";
            case ".jpg":
            case "jpeg":
                return "image/jpeg";
            case ".bmp":
                return "image/bmp";
            case ".wav":
                return "audio/wav";
            case ".mp3":
                return "audio/mpeg3";
            case ".mpg":
            case "mpeg":
                return "video/mpeg";
            case ".rtf":
                return "application/rtf";
            case ".asp":
                return "text/asp";
            case ".pdf":
                return "application/pdf";
            case ".fdf":
                return "application/vnd.fdf";
            case ".ppt":
                return "application/mspowerpoint";
            case ".dwg":
                return "image/vnd.dwg";
            case ".msg":
                return "application/msoutlook";
            case ".xml":
            case ".sdxl":
                return "application/xml";
            case ".xdp":
                return "application/vnd.adobe.xdp+xml";
            default:
                return "application/octet-stream";
        }
    }
</script>
<body>
    <form id="form1" runat="server">
        <ajax:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </ajax:ToolkitScriptManager>
        <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Always">
            <ContentTemplate>
                <asp:Button ID="btnDownloadFile" runat="server" Text="Download File" OnClick="btnDownloadFile_Click" />
            </ContentTemplate>
            <Triggers>
                <asp:PostBackTrigger ControlID="btnDownloadFile" />
            </Triggers>
        </asp:UpdatePanel>
    </form>
</body>
</html>


Saturday 10 August 2013

Stored Procedures in SQL Server 2008

Hi in this video you will get all the information about Stored Procedures in SQL Server 2008.



Thursday 8 August 2013

How to Get the Current Portal ID in DotNetNuke

In DotNetNuke We can get the Current portal ID by using the PortalController class as follows.

In C#.NET:

int portalID = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings().PortalId;

In VB.NET:

Dim portalID As Integer = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings().PortalId

Here in the above code GetCurrentPortalSettings() method returns PortalSettings object.  By using PortalsSettings object we are getting the PortalID.

Wednesday 7 August 2013

How to use the AutoEventWireup attribute in an ASP.NET

We can specify the default value of the AutoEventWireup attribute in the following locations:

1. The Machine.config file.
2. The Web.config file.
3. Individual Web Forms (.aspx files).
4. Web User Controls (.ascx files)

If you make these changes in the Machine.config file, the changes affect all ASP.NET Web Forms on the computer. If you make these changes in the Web.config file, the changes affect only the application that the file belongs to. However, to make changes in the individual Web Form Only, we have to add the AutoEventWireup attribute to the @Page directive.

AutoEventWireup will have a value true or false. By default it is true in C#.NET and false in VB.NET.

Generally when you request a webpage page the page life cycle begins.

AutoEventWireup ="true"

If you set the AutoEventWireup to true VisualStudio will generate the code to bind the events and then page events will call based on their names.

public class EventWireUpFalse : System.Web.UI.Page
    {
      private void Page_Load(object sender, System.EventArgs e)
      {
Response.Write("The Page_Load Event Fired with AutoEventWireup False");
      }
   }
 
In the above code the Page_Load event called directly.

AutoEventWireup = "false"

If you set the AutoEventWireup to false Visual Studio will not be able to generate code to bind the events. In this case, you must define explicit Handles clause or delegate.

public class EventWireUpFalse : System.Web.UI.Page
    {
      private void Page_Load(object sender, System.EventArgs e)
      {
Response.Write("The Page_Load Event Fired with AutoEventWireup False");
      }  
      // adding a new delegate to call the Page_Load event.
      override protected void OnInit(EventArgs e)
      {
         this.Load += new System.EventHandler(this.Page_Load);
      }

   }

In the above code Page_Load method will call through the delegate.

Tuesday 6 August 2013

Difference between || (Logical OR) and | (Conditional OR) operators in C#

Logical OR ||

If one condition is true compiler will return True without checking other conditions.
Ex:
if( A || B || C ) {}
If condition A is true without checking condition B compiler will return True.

Conditional OR |

Compiler will check for all the conditions.
Ex:
if( A | B | C ) {}
If condition A is true compiler  will check for condition B, and condition C if all conditions are True then only the compiler will return True otherwise it will return False.