Friday, December 31, 2010

How to get Client IP address using ASP.NET

This is one of the common query asked in many forums and I saw people giving different answer for this query. So I thought I will clarify this here.

I will start with the most common answer we can see for this query,

 string ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
  
 Response.Write("Client machine IP:-"+ipAddress);
  


I wonder people are really checking this code and the output of this code if client is using proxy!!!!
Above code will always give 127.0.0.1 that is the default localhost IP Address.
If you are using proxy then above code will not work.
What we have to do in that case is get the machine name first and find the IP address by passing the machine name like below,

 string strMachineName = System.Net.Dns.GetHostName();
  
 string IPAddress = System.Net.Dns.GetHostAddresses(strMachineName).GetValue(0).ToString();    
  
 Response.Write("Client machine Name"+ strMachineName); 
  
 Response.Write("Client machine IP Address"+ IPAddress);
  

Saturday, October 9, 2010

ASP.NET MVC 3 Beta in LIVE

ASP.NET MVC 3 Beta provides a Model-View-Controller (MVC) framework on top of the existing ASP.NET 4 runtime

You will be able to dowload beta version from Microsoft now, Click Here to download.

ASP.NET MVC 3 is a framework for developing highly testable and maintainable Web applications by leveraging the Model-View-Controller (MVC) pattern.

The framework encourages developers to maintain a clear separation of concerns among the responsibilities of the application – the UI logic using the view, user-input handling using the controller, and the domain logic using the model.

Thursday, September 9, 2010

Query to display all tables in MS SQL containing a particular string.

Below query will display all tables in MS SQL database containing a particular string.

I hope this query will help many who is in project support.

declare @String2Search nvarchar(100)
set @String2Search = 'Type Search string'
 
CREATE TABLE #SearchResults (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @String2Search2 nvarchar(110)
SET @TableName = ''
SET @String2Search2 = QUOTENAME('%' + @String2Search + '%','''')
 WHILE @TableName IS NOT NULL
     BEGIN
            SET @ColumnName = ''
            SET @TableName = 
            (
                 SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
                 FROM      INFORMATION_SCHEMA.TABLES
                 WHERE           TABLE_TYPE = 'BASE TABLE'
                      AND     QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
                      AND     OBJECTPROPERTY(
                                OBJECT_ID(
                                     QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                                      ), 'IsMSShipped'
                                    ) = 0
            )
            WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
            BEGIN
                 SET @ColumnName =
                 (
                      SELECT MIN(QUOTENAME(COLUMN_NAME))
                      FROM      INFORMATION_SCHEMA.COLUMNS
                      WHERE           TABLE_SCHEMA     = PARSENAME(@TableName, 2)
                           AND     TABLE_NAME     = PARSENAME(@TableName, 1)
                           AND     DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
                           AND     QUOTENAME(COLUMN_NAME) > @ColumnName
                 )
                 IF @ColumnName IS NOT NULL
                 BEGIN
                      INSERT INTO #SearchResults
                      EXEC
                      (
                           'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) 
                           FROM ' + @TableName + ' (NOLOCK) ' +
                           ' WHERE ' + @ColumnName + ' LIKE ' + @String2Search2
                      )
                 END
            END     
       END
       SELECT ColumnName, ColumnValue FROM #SearchResults  

Sunday, August 22, 2010

Sync Framework 2.1 Released.

What is Sync Framework?

Sync Framework is a comprehensive synchronization platform that enables collaboration and offline access for applications, services, and devices. Sync Framework features technologies and tools that enable roaming, data sharing, and taking data offline. By using Sync Framework, developers can build synchronization ecosystems that integrate any application with data from any store, by using any protocol over any network.

Sync Framework 2.1

Sync Framework 2.1 includes all the great functionality of 2.0 release, enhanced by several exciting new features and improvements. The most exciting of these lets you synchronize data stored in SQL Server or SQL Server Compact with SQL Azure in the cloud. Microsoft added top customer requests like parameter-based filtering and the ability to remove synchronization scopes and templates from a database, and of course they made many performance enhancements to make synchronization faster and easier.

SQL Azure Synchronization

With Sync Framework 2.1, you can leverage the Windows Azure Platform to extend the reach of your data to anyone that has an internet connection, without making a significant investment in the infrastructure that is typically required. Specifically, Sync Framework 2.1 lets you extend your existing on premises SQL Server database to the cloud and removes the need for customers and business partners to connect directly to your corporate network. After you configure your SQL Azure database for synchronization, users can take the data offline and store it in a client database, such as SQL Server Compact or SQL Server Express, so that your applications operate while disconnected and your customers can stay productive without the need for a reliable network connection. Changes made to data in the field can be synchronized back to the SQL Azure database and ultimately back to the on premises SQL Server database. Sync Framework 2.1 also includes features to interact well with the shared environment of Windows Azure and SQL Azure. These features include performance enhancements, the ability to define the maximum size of a transaction to avoid throttling, and automatic retries of a transaction if it is throttled by Windows Azure. All of this is accomplished by using the same classes you use to synchronize a SQL Server database, such as SqlSyncProvider and SqlSyncScopeProvisioning, so you can use your existing knowledge of Sync Framework to easily synchronize with SQL Azure.

Application of Changes

Sync Framework 2.1 takes advantage of the table-valued parameter feature of SQL Server 2008 and SQL Azure to apply multiple inserts, updates, and deletes by using a single stored procedure call, instead of requiring a stored procedure call to apply each change. This greatly increases performance of these operations and reduces the number of round trips between client and server during change application. Bulk procedures are created by default when a SQL Server 2008 or SQL Azure database is provisioned.

Parameter-based Filtering

Sync Framework 2.1 enables you to create parameter-based filters that control what data is synchronized. Parameter-based filters are particularly useful when users want to filter data based on a field that can have many different values, such as user ID or region, or a combination of two or more fields. Parameter-based filters are created in two steps. First, filter and scope templates are defined. Then, a filtered scope is created that has specific values for the filter parameters. This two-step process has the following advantages: • Easy to set up. A filter template is defined one time. Creating a filter template is the only action that requires permission to create stored procedures in the database server. This step is typically performed by a database administrator. • Easy to subscribe. Clients specify parameter values to create and subscribe to filtered scopes on an as-needed basis. This step requires only permission to insert rows in synchronization tables in the database server. This step can be performed by a user. • Easy to maintain. Even when several parameters are combined and lots of filtered scopes are created, maintenance is simple because a single, parameter-based procedure is used to enumerate changes.

Removing Scopes and Templates

Sync Framework 2.1 adds the SqlSyncScopeDeprovisioning and SqlCeSyncScopeDeprovisioning classes to enable you to easily remove synchronization elements from databases that have been provisioned for synchronization. By using these classes you can remove scopes, filter templates, and the associated metadata tables, triggers, and stored procedures from your databases. SQL Server Compact 3.5 SP2 Compatibility The Sync Framework 2.1 SqlCeSyncProvider database provider object uses SQL Server Compact 3.5 SP2. Existing SQL Server Compact databases are automatically upgraded when Sync Framework connects to them. Among other new features, SQL Server Compact 3.5 SP2 makes available a change tracking API that provides the ability to configure, enable, and disable change tracking on a table, and to access the change tracking data for the table.

For more information about Sync Framework 2.1, including feature comparisons, refer MSDN,
http://msdn.microsoft.com/en-us/library/bb902854(v=SQL.110).aspx"

Tuesday, August 17, 2010

Toggling panel using Jquery

Enter this code just below the <title> tag. File name “jquery-1.2.6.min.js” depends on the jquery file you have downloaded.
<script src="jquery-1.2.6.min.js" type="text/javascript"></script>
Then Add css code to give style to the panels.
   1:  <style type="text/css">
   2:          .Header
   3:          {
   4:              color: white;
   5:              background-color: Black;
   6:              font: bold 13px auto "Trebuchet MS",
                   Verdana;
   7:              font-size: 12px;
   8:              cursor: pointer;
   9:              width:500px;
  10:              height:18px;
  11:              padding: 4px;            
  12:          }
  13:          .Body
  14:          {
  15:              background-color: Cyan;
  16:              font: normal 11px auto Verdana, Arial;
  17:              border: 1px gray;                
  18:              width:500px;
  19:              padding: 4px;
  20:              padding-top: 7px;
  21:          }       
  22:      </style>

Add the jquery code which does the panel toggling
   1:  <script type="text/javascript">
   2:          $(document).ready(function() 
   3:            {
   4:              $('#Panel1').click(function() 
   5:                {
   6:                  $('#Panel2').slideToggle('slow');
   7:                }
   8:               );
   9:             }
  10:           );
  11:      </script>

All the above codes are continuous one after another.
Now it’s the time to add two panels, first panel with a label and second panel with some text in it. On clicking the first panel second panel with text will toggle...
Add this code just after form tag or add it through .NET interface.
<asp:Panel ID="Panel1" runat="server" CssClass="Header">
<asp:Label ID="Label1" runat="server">
What is JQuery {Click here to toggle}</asp:Label></asp:Panel>
                
<asp:Panel ID="Panel2" runat="server" CssClass="Body">
JQuery is a lightweight JavaScript library that emphasizes interaction between JavaScript and HTML. It was released January 2006 at BarCamp NYC by John Resig. Dual licensed under the MIT License and the GNU General Public License, jQuery is free and open source software.
     Both Microsoft and Nokia have announced plans to bundle jQuery[1] on their platforms, Microsoft adopting it initially within Visual Studio[2] and use within Microsoft's ASP.NET AJAX framework and ASP.NET MVC Framework whilst okia will integrate it into their Web Run-Time platform.
</asp:Panel>

This is what JQUERY code less do more….

Saturday, August 14, 2010

Display all Stored Procedures containing a particular string in MS SQL

 
Use below query to display the complete list of Stored Procedures in the database containing a particular string.

SELECT ROUTINE_NAME, ROUTINE_DEFINITION FROM INFORMATION_SCHEMA.ROUTINES 
WHERE ROUTINE_DEFINITION LIKE '%User_ID%' AND ROUTINE_TYPE='PROCEDURE'

Out put of the above query will be the list of Stored Procedures containing the string "User_ID" in your database.

Wednesday, July 7, 2010

Display Outage page in Asp.Net

App_offline.htm file used to display the error/notification message to the users when your site is under maintenance. if you keep this file your root directory no other files/requests will be processed.

Make a simple HTML file by writing "The application is under maintenance. Please try again later." and name it as App_offline.htm

Drop this file in your root directory of your web application folder.

After copying App_offline.htm file try to access your web application link and see the output.

How to find Browser type and version from code behind?

Copy paste below code in your code behind and see the out put!!!!!

string strBrowser= Request.Browser.Browser;//Display the browser type like IE, Mozilla etc.

string strBrowserVersion= Request.Browser.Version;//Display the browser version like IE 8.0,8.2 based on the release.

int intBrowserMajorVersion= Request.Browser.MajorVersion;//Display Browser major version like in IE 6,7,8

double dblBrowserMinorVersion= Request.Browser.MinorVersion;//Display Brwser Minor version like IE 1,2,3 based on the release.

Validate a user has entered a date in correct format such as mm/dd/yyyy format using JavaScript?

You can use below regular expression,

Just copy and paste this expression in your regular expression's ValidExpression property.

(?=\d)^(?:(?!(?:10\D(?:0?[5-9]|1[0-4])\D(?:1602))|(?:0?9\D(?:0?[3-9]|1[0-3])\D(?:1752)))((?:0?[13578]|1[02])|(?:0?[469]|11)(?!\/31)(?!-31)(?!\.31)|(?:0?2(?=.?(?:(?:29.(?!000[04]|(?:(?:1[^0-6]|[2468][^048]|[3579][^26])00))(?:(?:(?:\d\d)(?:[02468][048]|[13579][26])(?!\x20BC))|(?:00(?:42|3[0369]|2[147]|1[258]|09)\x20BC))))))|(?:0?2(?=.(?:(?:\d\D)|(?:[01]\d)|(?:2[0-8])))))([-.\/])(0?[1-9]|[12]\d|3[01])\2(?!0000)((?=(?:00(?:4[0-5]|[0-3]?\d)\x20BC)|(?:\d{4}(?!\x20BC)))\d{4}(?:\x20BC)?)(?:$|(?=\x20\d)\x20))?((?:(?:0?[1-9]|1[012])(?::[0-5]\d){0,2}(?:\x20[aApP][mM]))|(?:[01]\d|2[0-3])(?::[0-5]\d){1,2})?$

Saturday, March 28, 2009

Calendar Using JavaScript with MastePage

Many people using master page might wonder why calendar control is not opening if they are using master page in their normal aspx page., If you add and call the JavaScript cleaner control similar to the normal aspx page calendar won’t be displayed in the page using master page….so I just posting this article to show you how this works….
There is no extra or special coding for this…
First, add JavaScript/CSS reference in MASTER page like below,
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!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>Maste Page</title>
    <script src="\calendar\calendar.js" type="text/javascript"></script>
    <link href="\calendar\Calendar.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
        
        </asp:contentplaceholder>
    </div>
    </form>
</body>
</html>
Then call the JavaScript function to show the calendar based on the JavaScript you are using. Here my function is
showCalendar(<TextBox Name>,<Date Format>)
instead of passing control name we are passing ID of the control. This is the only change you have to remember…
<asp:TextBox ID="txtDateCreated" runat="server"></asp:TextBox><input id="DateCreated" onclick="return showCalendar('ctl00_ContentPlaceHolder1_txtDateCreated', '%m/%d/%Y',true);" type="image" src="calendar/calendar.gif">
Execute the code…see that wonderful calendar.

Monday, March 23, 2009

How to return values from JavaScript function to the C# page load

Add the JavaScript function just below the HTML <title> tag. This function should have __doPostBack to return value.
   1:     <script language="javascript">
   2:          function RetVal()
   3:          {
   4:              var testVar = 'abc'
   5:              __doPostBack('Test',testVar);
   6:          }
   7:      </script>

Add a label to display the values from JavaScript function.
Add a text box to page and set the AutoPostBack property to true. One control with AutoPostBack property set to true is required in the page to get the value from JavaScript function using __doPostBack.
In Page_Load write the following code.
   1:  protected void Page_Load(object sender, EventArgs e)
   2:  {
   3:    if (IsPostBack)
   4:    {
   5:      string arg = Request.Form["__EVENTTARGET"];
   6:      string val = Request.Form["__EVENTARGUMENT"];
   7:      if (arg == "Test")
   8:      {
   9:       Label1.Text = val;
  10:      }
  11:    }
  12:     else
  13:     {
  14:      string script;
  15:      script = @"<SCRIPT language='javascript'> RetVal
           ();" + "</SCRIPT>";
  16:      Page.RegisterStartupScript("Test", script);
  17:     }
  18:    }

Page.RegisterStartupScript: Allows ASP.NET server controls to emit client-side script blocks in the Page, now this method is obsolete, in ASP.NET 2.0 it gives you an error - or more correctly warnings telling you that both functions are obsolete.
'System.Web.UI.Page.IsStartupScriptRegistered(string)' is obsolete: 'The recommended alternative is ClientScript.IsStartupScriptRegistered(string key).
"The __EVENTTARGET hidden variable will tell the server ,which control actually does the server side event firing so that the framework can fire the server side event for that control."
The __ EVENTARGUMENT variable is used to provide additional event information if needed by the application, which can be accessed in the server
Execute the code and see the result…

Tuesday, March 3, 2009

List all the Stored Procedures Associated with a specific Table

DECLARE @TABLENAME VARCHAR(50)
SET @TABLENAME='<table name>'    --Pass the Table Name here
SELECT @TableName as [Table Name],A.Name AS [SP Name],B.Text as [SP Text] from SYSOBJECTS A
INNER JOIN SYSCOMMENTS B
ON A.ID=B.ID 
WHERE B.TEXT LIKE '%'+@TableName+'%'
and A.TYPE='P'
Same way we can use this to find out View, Trigger etc..
V: View
TR: Trigger

See the out put…

SQL query to fetch all the tables and column names from the database

select table_name, column_name, data_type, character_maximum_length, is_nullable 
from information_schema.columns 
where table_name in (select name from sysobjects where xtype='U') order by table_name

Here xtype='U' means user table.

Some of the other options you can use are,
C: Check constraint
D: Default constraint
F: Foreign Key constraint
L: Log
P: Stored procedure
PK: Primary Key constraint
RF: Replication Filter stored procedure
S: System table
TR: Trigger
U: User table
UQ: Unique constraint
V: View
X: Extended stored procedure
Press F5 and see the result!!!!!!

Tuesday, February 24, 2009

How to download file from FTP server using C#

Add below namespaces,
using System.Net;
using System.IO;
using System.Text;

Create a button and add the below code under button click
//fileName = Name of the file to be downloaded from FTP server.
        string fileName = "test.txt";

        //filePath = The full path where the file is to be created. Here i put local system path.
        string filePath = "C:\\FTP";
        
        string ftpServerIP = "<IP Address>";
        string ftpUserID = "<User ID>";
        string ftpPassword = "<Password>";
        FtpWebRequest reqFTP;
        try
        {
            FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileName));
            reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
            reqFTP.UseBinary = true;
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
            Stream ftpStream = response.GetResponseStream();
            long cl = response.ContentLength;
            int bufferSize = 2048;
            int readCount;
            byte[] buffer = new byte[bufferSize];
            readCount = ftpStream.Read(buffer, 0, bufferSize);
            while (readCount > 0)
            {
                outputStream.Write(buffer, 0, readCount);
                readCount = ftpStream.Read(buffer, 0, bufferSize);
            }
            ftpStream.Close();
            outputStream.Close();
            response.Close();
        }
        catch (Exception ex)
        {
           string errMsg= (ex.Message);
        }

Execute the code and see the C:\FTP folder for the file….

Monday, February 23, 2009

How to upload file to FTP server using C#

Add below namespaces,
using System.Net;
using System.IO;

Create a button and add the below code under button click
        string filename = "c:\\test.txt";
        string ftpServerIP = "<IP address>";
        string ftpUserID = "<userid>";
        string ftpPassword = "<Password>";

        FileInfo fileInf = new FileInfo(filename);

     string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;

        FtpWebRequest reqFTP;

        // Create FtpWebRequest object
        reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileInf.Name));

        //Provide ftp userid and password
        reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

        // By default KeepAlive is true, where the control connection is not closed
        // after a command is executed.
        reqFTP.KeepAlive = false;

        //Specify the command to be executed. Here we use upload file command
        reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

        //data transfer type we use here is binary
        reqFTP.UseBinary = true;

        // Notify the server about the size of the uploaded file
        reqFTP.ContentLength = fileInf.Length;

        // The buffer size is set to 2kb
        int buffLength = 2048;

        byte[] buff = new byte[buffLength];

        int contentLen;

        // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
        FileStream fs = fileInf.OpenRead();

        try
        {

            // Stream to which the file to be upload is written
            Stream strm = reqFTP.GetRequestStream();

            // Read from the file stream 2kb at a time
            contentLen = fs.Read(buff, 0, buffLength);

            // Till Stream content ends
            while (contentLen != 0)
            {

                // Write Content from the file stream to the FTP Upload Stream
                strm.Write(buff, 0, contentLen);
                contentLen = fs.Read(buff, 0, buffLength);
            }

            // Close the file stream and the Request Stream
            strm.Close();
            fs.Close();
        }
        catch (Exception ex)
        {
            string ErrMsg = ex.Message;
        }
Execute the code and check the FTP server for the file.