Follow by Email

Thursday, August 29, 2013

Allow only decimal and float values in asp.net using asp RegularExpressionValidator control | Regular expression to validate float and decimal values example

Hi in this post i will show how to allow only decimal and float values in asp.net using regular expression.

In Aspx:

<asp:TextBox ID="txtEmpSalary" runat="server"></asp:TextBox>

<asp:RegularExpressionValidator ID="ValidateTotalBillAmount" ErrorMessage="Enter Proper value" ControlToValidate="txtEmpSalary" ValidationExpression="(?<=^|)\d+(\.\d+)?(?=$|)|(?<=^| )\.\d+(?=$|)" runat="server">
</asp:RegularExpressionValidator>


In code-behind:

 if (Page.IsValid = = false)
        {
            return;
        }

if page has any error then it will return.


Wednesday, August 28, 2013

download an excel file from a ftp in c#.net | Download file from ftp example in .net

hi in this post i will show how to download an excel file from a ftp in c#.net.

Below is the code:

    public void Main()
    {
        // FTP URL
        FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://www.yourDomainNameorIP/ExcelFile.xlsx");
        ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;

        // FTP Login
        ftpRequest.Credentials = new NetworkCredential("<UserId>", "<Pwd>");

        FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();

        Stream responseStream = ftpResponse.GetResponseStream();
        long cl = ftpResponse.ContentLength;

        int bufferSize = 2048;
        int readCount;

        byte[] buffer = new byte[bufferSize];

        String FilePath;
        FilePath = Server.MapPath("/Download"); // create a folder called Download in the application root folder to save the file.

        FileStream outputStream = new FileStream(FilePath + "\\" + "filename.xlsx", FileMode.Create);

        readCount = responseStream.Read(buffer, 0, bufferSize);

        while (readCount > 0)
        {
            outputStream.Write(buffer, 0, readCount);
            readCount = responseStream.Read(buffer, 0, bufferSize);
        }

        responseStream.Close();
        outputStream.Close();
        ftpResponse.Close();
    }


After u execute the above code u can see the downloaded file in the download folder created in the root folder of the application.

Monday, August 26, 2013

Implementing Factory design pattern in asp.net using c# | Design Patterns | Example Factory design pattern

hi in this post i will show how to implement the Factory design pattern in asp.net

In Factory design pattern we cannot directly create the object of the class we need to send our requirement to the factory class. This factory class will provide us the required object.

it helps us to create object without exposing the instantiation logic to client.

Example :

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

namespace ConsoleApplication1
{
    interface color
    {
        string GetCarColor();
    }

    class myFactory
    {
        public color GetObj(int type)
        {
            color interfaceObj = null;
            switch (type)
            {
                case 1:
                    interfaceObj = new car1();
                    break;
                case 2:
                    interfaceObj = new car2();
                    break;
                case 3:
                    interfaceObj = new car3();
                    break;
            }
            return interfaceObj;
        }
    }

    class car1 : color
    {
        public string GetCarColor()
        {
            return "Red color car";
        }

    }
    class car2 : color
    {
        public string GetCarColor()
        {
            return "Blue color car";
        }
    }
    class car3 : color
    {
        public string GetCarColor()
        {
            return "White color car";
        }
    }
}

/////Main Class

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            myFactory obj = new myFactory();
            color c = obj.GetObj(2);
            string s = c.GetCarColor();
            Console.WriteLine(s);
            Console.ReadLine();

        }
    }
}

Friday, August 23, 2013

hi in this post i will show how to print a particular <div> section using JavaScript in asp.net.

Example:

<script type="text/javascript">
    function ClickToPrint() {
        docPrint = window.open("", "Print");
        docPrint.document.open();
        docPrint.document.write('<html><head><title>::PRINT SAMPLE::</title>');
        docPrint.document.write('</head><body onLoad="self.print()">');
        docPrint.document.write('<table width="900px" border=0><tr><td width=100%><center><font face="windings">');
        docPrint.document.write(document.getElementById("PrintDiv").innerHTML);
        docPrint.document.write('</font></center></td></tr></table></body></html>');
        docPrint.document.close();
    }

</script>
<html>
<head runat="server">
    <title></title>
</head>
<body>
    <div id="PrintDiv">
        Hello World ! This is Asp.net.
    </div>
    <div id="DoNotPrintDiv">
        Thanks for visiting this website !!
    </div>
    <input id="Button1" onclick="ClickToPrint();" type="button" value="Print" class="button" />
</body>
</html>

Tuesday, August 20, 2013

[Resolved]Msg 8111 Cannot define PRIMARY KEY constraint on nullable column in table 'tablename' | SQL Server Add Primary key constraint to table

To Resolve such an error :

Msg 8111
Cannot define PRIMARY KEY constraint on nullable column in table 'tablename'.
Msg 1750
Could not create constraint. See previous errors.

Steps:

1. First Remove all the null values from the column on which primary key has to be created or update such fields with unique values.

2.Then Make that column as not Nullable using this query:

ALTER TABLE tablename ALTER COLUMN columnName NOT NULL

3. Now We can add the primary key constraint for the table.

ALTER TABLE tablename 
ADD CONSTRAINT PK primary key (columnName

Monday, August 12, 2013

[Resolved] Asp.net Http Runtime maxRequestLength exceeded error

hi maxRequestLength  exceeded error can be resolved as below :

Such an error occur when the uploaded data exceeds the limit. Like if the limit is 4MB and file begin uploaded to the server is 5 MB then such an error will occur.

By default the Http Runtime maxRequestLength  is 4MB we can increase this size in the web.config file of the application.

Suppose we want to increase the limit to 8MB then in the web.config file do the following :

<configuration>
    <system.web>
        <httpRuntime maxRequestLength="8192" />
    </system.web>
</configuration>


MaxRequestLength Accept values as KiloBytes.

Thursday, August 8, 2013

using singleton pattern in .net | example of using the singleton patter in .net c# | Design Patterns

Design Pattern : Singleton

Singleton pattern assures that only a single object will be created for any class and the same object will be used in the application.

Example (Adding Numbers ) :

Solution Explorer


Class file (here we will be writing the code for implementing singleton pattern)

public class CommonClass
{
    private static CommonClass _instance;
    protected CommonClass()
    {
    }
    public static CommonClass Instance()
    {
        if (_instance == null) _instance = new CommonClass();
        return _instance;
    }

    public int addNumber(int x, int y)
    {
        return (x + y);
    }

}


ASPX :

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Enter Numbers to Add :<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
        <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />
        <br />

          Result 1: <asp:Label ID="Label1" runat="server" Text=""></asp:Label><br />
          Result 2: <asp:Label ID="Label2" runat="server" Text=""></asp:Label>

        <br />

        <asp:Label ID="lblMsg" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</body>
</html>


Codebehind:

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

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

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    public void Button1_Click(object sender, EventArgs e)
    {
        CommonClass s1 = CommonClass.Instance();
        Label1.Text = s1.addNumber(int.Parse(TextBox1.Text), int.Parse(TextBox2.Text)).ToString();

        CommonClass s2 = CommonClass.Instance();
        Label2.Text = s2.addNumber(int.Parse(TextBox1.Text) + 5, int.Parse(TextBox2.Text) + 5).ToString();

        if (s1 == s2)
        {
            lblMsg.Text = "Same Object Used";
        }
    }

}


Output :



Tuesday, August 6, 2013

[Resolved]The XML parse error near XML text | Msg 6602 Procedure sp_xml_preparedocument, Line 1 The error description is 'Whitespace is not allowed at this location.' | Msg 8179 Could not find prepared statement with handle 0.

hi in this post i show how to resolve the error generated while XML Parsing in SQL.

Example :

DECLARE @INDEX INT
DECLARE @XMLEMPLOYEE NVARCHAR(MAX)

SET @XMLEMPLOYEE = N'<ROOT><EMPLOYEE EMPID="1" EMPNAME="CHANDAN"/>
                            <EMPLOYEE EMPID="2" EMPNAME="CHANDAN & SINGH"/> 
                     </ROOT>'

EXEC SP_XML_PREPAREDOCUMENT @INDEX OUTPUT
 ,@XMLEMPLOYEE

SELECT EMPID
 ,EMPNAME
FROM OPENXML(@INDEX, 'ROOT/EMPLOYEE') WITH (
  EMPID NVARCHAR(50)
  ,EMPNAME NVARCHAR(550)
  )


After Executing this above query, we get the error as below:

The XML parse error 0xc00ce513 occurred on line number 2, near the XML text "<EMPLOYEE EMPID="2" EMPNAME="CHANDAN & SINGH"/>".
Msg 6602, Level 16, State 2, Procedure sp_xml_preparedocument, Line 1
The error description is 'Whitespace is not allowed at this location.'.
Msg 8179, Level 16, State 5, Line 9
Could not find prepared statement with handle 0.


The problem is due to the using of ampersand(&) in the xml document.

Solution:

While creating the XML document replace the ampersand(&) with &amp; and then re-run the query to get the correct output.

DECLARE @INDEX INT
DECLARE @XMLEMPLOYEE NVARCHAR(MAX)

SET @XMLEMPLOYEE = N'<ROOT><EMPLOYEE EMPID="1" EMPNAME="CHANDAN"/>
                            <EMPLOYEE EMPID="2" EMPNAME="CHANDAN &amp; SINGH"/> 
                     </ROOT>'

EXEC SP_XML_PREPAREDOCUMENT @INDEX OUTPUT
 ,@XMLEMPLOYEE

SELECT EMPID
 ,EMPNAME
FROM OPENXML(@INDEX, 'ROOT/EMPLOYEE') WITH (
  EMPID NVARCHAR(50)
  ,EMPNAME NVARCHAR(550)
  )


It will give the ouput as :

EMPID EMPNAME
1 CHANDAN
2 CHANDAN & SINGH

Check Data-length of the all the data in the column in Sql Server | query to check size of all the data present in the column


Taking an Example , Suppose we want to check the data-size of all the data present in a column for a Employee table :

Query :

SELECT DATALENGTH(CUSTOMER_ID) AS EMP_ID_LENGTH ,
       DATALENGTH(EMPLOYEE_NAME) AS EMPLOYEE_LENGTH,
       *
FROM EMPLOYEE_TABLE

Monday, August 5, 2013

changing column size in sql | Query to increase or decrease column length in sql server

Changing Column Size :

Suppose you want to change the size of a column having datatype as NVARCHAR of length 100.
We will increase it length to 200.

Query :

ALTER TABLE CUSTOMER_TABLE
ALTER COLUMN CUSTOMERNAME nvarchar(200)

Thursday, August 1, 2013

Using WebGrid in MVC 4 Razor | Example Binding WebMatrix Grid in Asp.net MVC 4 Razor | Sorting paging Grid in MVC Razor

Hi in this post i will show how to use a webgrid and also how to do paging sorting in it using Asp.net MVC Razor.

Example :

Some times @using webmatrix.data namespace is not accessible so we need to add reference for WebMatrix.Data and WebMatrix.WebData

or

you can directly copy the dll from "C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v2.0\Assemblies" and copy into the bin folder of the application.



Code:

@using WebMatrix.Data;
@{  
    var db = Database.Open("MyNewConnection"); 
    var selectQueryString = "SELECT * FROM Employee"; 
    var data = db.Query(selectQueryString); 
    var grid = new WebGrid(source: data,
                           defaultSort: "employeename",  
                           rowsPerPage: 10); 
    grid.SortDirection = SortDirection.Ascending;
}
<!DOCTYPE html> 
<html> 
    <head> 
        <title>Displaying Data Using the WebGrid</title> 
        <style type="text/css"> 
            .grid { margin: 4px; border-collapse: collapse; width: 600px; } 
            .head { background-color: #E8E8E8; font-weight: bold; color: #FFF; } 
            .grid th, .grid td { border: 1px solid #C0C0C0; padding: 5px; } 
            .alt { background-color: #E8E8E8; color: #000; } 
            .empname { width: 200px; font-weight:bold;} 
        </style> 
    </head> 
    <body> 
        <h1>Employee Details</h1> 
        <div id="grid"> 
            @grid.GetHtml( 
                tableStyle: "grid", 
                headerStyle: "head", 
                alternatingRowStyle: "alt", 
                columns: grid.Columns( 
                    grid.Column("employeename", "Employee Name", style: "empname"), 
                    grid.Column("Location", format:@<i>@item.location</i>), 
                    grid.Column("employeeid"), 
                    grid.Column("Salary", format:@<text>$@item.contact</text>) 
                ) 
            ) 
        </div> 
    </body> 
</html>

In the webconfig file of the application add new connection string:

<connectionStrings>
      <add name="MyNewConnection" connectionString="Data Source=.;Initial Catalog=SampleDB;Integrated Security=True"
           providerName="System.Data.SqlClient" />
</connectionStrings>


Output: