Showing posts with label Web page. Show all posts
Showing posts with label Web page. Show all posts

Tuesday, January 3, 2012

Delete All Store Procedures in SQL SERVER

While working on SQL Server 2008, there was a situation when I had to delete one Store Procedure at a time :(.
After doing some research to delete all store procedures with some query, I succeeded to save 2-3 hours or labour work :P

To delete all store procedures in single we can use following code in SQL Query.

DECLARE @procedureName varchar(500)
DECLARE cur CURSOR
      FOR SELECT [name] FROM sys.objects WHERE type = 'p'
      OPEN cur

      FETCH NEXT FROM cur INTO @procedureName
      WHILE @@fetch_status = 0
      BEGIN
            EXEC('DROP PROCEDURE ' + @procedureName)
            FETCH NEXT FROM cur INTO @procedureName
      END
      CLOSE cur
      DEALLOCATE cur
This will surely save time, required to Delete All Store Procedures in SQL SERVER Database
Submit this story to DotNetKicks

Read more...

Tuesday, November 8, 2011

Use Membership for user management - Basics

In this article we shall discuss the membership feature in ASP.NET applications. Asp.net has reduced the development drastically by introducing this. Membership feature of Asp.Net drastically reduces the amount of code we have to write to authenticate users at our Web site. In this article we are going to develop User Management system membership class, and SqlMembershipProvider.

Membership feature of Asp.net provides a membership API that simplifies the task of validating user credentials. SqlMembershipProvider uses SQL Database for storing membership details.

Step1: Install Membership Database for SQLMembershipProvider.
To install Membership Database we have to log on to our server with an account that has authority to administer SQL server. After this open Visual Studio 2010 Command prompt.


Run following command
aspnet_regsql.exe -E -S localhost -A m

Where:
    -E indicates authenticate using the Windows credentials of the currently logged on user.
    -S (server) indicates the name of the server where the database will be installed or is already installed.
    -A m indicates add membership support. This creates the tables and stored procedures required by the membership provider.

Above command mainly generates database naming "aspnetdb" with following  schema structure and related stored procedures


* Please Note that Related stored procedures also get created with above command. These stored procedures get called internally from Membership provider. 

Step2: Configure Forms Authentication
Set following authentication mode in Web.config file
<authentication mode="Forms">
    <forms loginUrl="Login.aspx" 
           protection="All" 
           timeout="30" 
           name="AppNameCookie" 
           path="/FormsAuth" 
           requireSSL="false" 
           slidingExpiration="true" 
           defaultUrl="default.aspx"
           cookieless="UseCookies"
           enableCrossAppRedirects="false"/>
</authentication>

If so many options are not required we can simply use following Tag for authentication

<authentication mode="Forms">
      <forms loginUrl="Login.aspx" timeout="2880" />
    </authentication>

Add the following <authorization> element after the element. This will allow only authenticated users to access the application. The previously established loginUrl attribute of the <authentication> element will redirect unauthenticated requests to the Login.aspx page.


<authorization> 
   <deny users="?" />
   <allow users="*" />
</authorization>
  
Step 3: Configuring SQLMembership Provider
In Step 1, we created SQL Database for Membership Provider, in this step we will configure SQLMembership Provider in Web.config file.


<connectionStrings>
  <add name="MyConnectionString" connectionString="Data Source=MySqlServer;Initial Catalog=aspnetdb;Integrated Security=SSPI;" />
</connectionStrings>
<system.web>
...
  <membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
    <providers>
      <clear />
      <add 
        name="SqlProvider" 
        type="System.Web.Security.SqlMembershipProvider" 
        connectionStringName="MyConnectionString"
        applicationName="/"
        enablePasswordRetrieval="false"
        enablePasswordReset="true"
        requiresQuestionAndAnswer="true"
        requiresUniqueEmail="true"
        passwordFormat="Hashed" />
    </providers>
  </membership>

Default passwordFormat is "Hashed", if we remove it from Configuration then by default Passwords are stored in Hashed format. We can change passwordFormat to Encrypted. (This is not the scope of this Article; I shall put another article for it.)

Step 4: Start using Membership class
Upto step 3 we were only doing configuration for using Membership class. After we done with step 3; whenever we use Membership class, if by default uses Database structure generated in Step 1. It internally manages all the Database calls.
e.g.
Membership.CreateUser("UserName","Password");
//This will create user in Database.
Check out following Membership APIs for user management in Asp.net.
MethodParametersNotes
CreateUserstring username–User name to create.

string password–Password for new user


string email–E-mail for new user.

string passwordQuestion

string passwordAnswer

bool IsApproved

object providerUserKey
Used to create a new user.
DeleteUserstring username–User to delete.

bool removeAllRelatedData
Used to immediately remove a user identified by the supplied username. Returns true if the user was deleted or false if not found.
FindUsersByNamestring usernameToMatch

int pageIndex

int pageSize
Returns a collection of users where the string parameter passed matches part of the username.

Wildcard support depends on how each data store handles characters such as "*", "%" and "_".
FindUsersByEmailstring emailToMatch

int pageIndex

int pageSize
Returns a collection of users whose e-mail addreses matches any part of the string parameter passed.

Wildcard support depends on how each data store handles characters such as "*", "%" and "_"
GeneratePasswordint length

Int numberOfNonAlpha

NumericCharacters
Returns a password of the specified length that contains the specified number of non-alphanumeric characters.
GetAllUsersint pageIndex

int pageSize
Returns a subset of users from the collection of all users. The subset is based on the pageIndex and pageSize methods.
GetNumberOfUsersOnlineNoneReturns a count of all the users who are currently online

The Active Directory provider does not implement this functionality
GetUsernameByEmailstring email–Email of user to lookup.Return a member's username.
UpdateUserMembershipUser user–Membership user to updateUpdates a member's properties; for example, an e-mail address.
ValidateUserstring username–User name to validate.

string password–User password to validate.
Validates a user's credentials. Returns true if the credentials are valid and false if they are not.


With Active Directory, regardless of the configured connection credentials, the provider connects to the directory with the username and password parameter as the connection credentials.
(Note: Above table is picked up from MSDN)

This is how we can use Membership class for User management in Asp.net using SQLMembershipProvider.

Submit this story to DotNetKicks

Read more...

Thursday, May 5, 2011

Disable Text Selection using Javascript

In the web development cycle, at times we come to a requirement where we need to disable text selection for some HTML Tags i.e. "Do not allow to select text present in some particular Div tag, or span tag or text present in some table" in that case we can use following function. Actually this JavaScript function can be used to Disable Text selection for whole body of the HTML.

function disableSelection(target) {
        if (typeof target.onselectstart != "undefined") //IE route
            target.onselectstart = function () { return false }
        else if (typeof target.style.MozUserSelect != "undefined") //Firefox route
            target.style.MozUserSelect = "none"
        else //All other route (ie: Opera)
            target.onmousedown = function () { return false }
        target.style.cursor = "default"
    }


Define above function in HEAD tag and call this function either on some form event or directly at the bottom of the HTML page.

//disableSelection(document.body) //Disable text selection on entire body

disableSelection(document.getElementById("mydiv")) //Disable text selection on element with id="mydiv"

This is very small function but it was very useful for one of my project.
Submit this story to DotNetKicks

Read more...

Saturday, April 30, 2011

Add Update Delete in Gridview Asp.net

This article is about simple way to Add Update and Delete records using asp.net GridView using Dataset or Datatable. We shall update the database table naming (Download Demo)

"UserTable".

Schema for UserTable is as follows
Note:I have used SqlServer 2008
For this article we are going to fill GridView by data from database.
We are going to make perform following operations on data using GridView
  1. Add New record into database; here data will directly be added into database table
  2. Update Records into database, using edit link.
  3. Delete Records using delete link
To make Add Update Delete in Gridview more user friendly; make sure your website is Ajax Enabled and Gridview is put under UpdatePanel. This will avoid unnecessary

postback and Gridview control will look smart.

Before we develop GridView, lets work out main functions for database operations. Create a Class File naming "ManageUsers" and add following functions one by one

Fetch Data from Database.
public DataTable Fetch()
    {
        string sql = "Select * From UserTable";
        SqlDataAdapter da = new SqlDataAdapter(sql, cnstr);
        DataTable dt = new DataTable();
        da.Fill(dt);
        return dt;
        // Write your own Logic for fetching data, this method should return a DataTable
    }


Update Data into Database
public void Update(int id, string FirstName, string LastName, string EmailAddress, string LoginId, string Password, string StartDate, string EndDate)
    {
        string sql = "UPDATE UserTable SET [First Name] = '"+ FirstName + "',[Last Name] = '" + LastName + "',[Login Id] = '" + LoginId +"' ,[Password] = '" + Password 

+ "'";
             sql += ",[Start Date] = '" + StartDate +"',[End Date] = '" + EndDate +"',[Email Address] = '" + EmailAddress + "' WHERE Id=" + id;

        SqlConnection conn = new SqlConnection(cnstr);
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.ExecuteNonQuery();
        conn.Close();
        conn.Dispose();

    }


Insert new records into Database
public void Insert(string FirstName, string LastName, string EmailAddress, string LoginId, string Password, string StartDate, string EndDate)
    {
       string sql = "INSERT INTO UserTable ([First Name],[Last Name],[Login Id],[Password],[Start Date],[End Date],[Email Address]) ";
       sql +=" VALUES ('"+ FirstName +"','" + LastName + "','" + LoginId +"','" + Password + "','" + StartDate + "','" + EndDate + "','" + EmailAddress + "')";
           
        SqlConnection conn = new SqlConnection(cnstr);
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.ExecuteNonQuery();
        conn.Close();
        conn.Dispose();
    }

Delete records from Database

public void Delete(int id)
    {
        string sql = "DELETE FROM UserTable WHERE Id=" + id;
        SqlConnection conn = new SqlConnection(cnstr);
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.ExecuteNonQuery();
        conn.Close();
        conn.Dispose();
        // Write your own Delete statement blocks.
    }

In above code cnstr is the connection string for our

database.

Now we shall make changes in GridView (Note: Make sure GridView is added on page and under updatepanel) (Download Demo)

Once we add gridview inside updatepanel, do following things
  1. set AutoGenerateColumns as False.
  2. Change the ShowFooter Flag to True
  3. set the DataKeyNames your column name for Id. (This field can have multiple values depending on requirement, we are going to use Id, as it is primary key of our datatable. These values are available in GridView events. We can access them using. GridView.DataKeys[e.RowIndex].Values[0]
  4. Smart Navigation Tag of the GridView control, choose Add New Column
    Now add 8 BoundField columns with DataField values as "Id","First Name","Last Name","Email Address", "Login Id", "Password", "Start Date", "End Date"; also add 2 CommandField columns with one for Edit/Update and another for Delete functions. Now we can see our Grid View control is ready. Above data fields are column names of the DataTable we are using. (To bind correct columns, our datatable column names and gridview bound column's "DataField" should match.
  5. We shall also give facility to add new records, for that we will put controls in Footer row. To do this we need to convert all above BoundField columns to template field columns. Click on the Smart Navigation Tag on the GridView choose Edit Columns, the Field’s property window will open.  Select column by column from Id, include also Edit column, and select ‘Convert this field into a TemplateField’
    Except "delete" column all the BoundField columns are converted in to Template Field Column.
  6. Now one by one we will controls to Footer of the GridView. Right click on the GridView control, select Edit Template.
    Column[0] – Id: select Edit Template, choose column[0] – Id, you can view a label placed in the ItemTemplate section and a TextBox placed in the EditItemTemplate section (Id is our Primary key and it should not be editable). In edit Item Section template, put Label. Do not add anything in Footer Template.

    Column[1] - First Name
    Now again select Edit Template, choose column[1] - First Name, Add another TextBox in the FooterTemplate section and name it as NewFirstName. 

    Column[2] - Last Name
    Choose column[2] - Last Name, Add another TextBox in the FooterTemplate section and name it as NewLastName. 

    Column[3] - Email Address
    Choose column[3] - Email Address, Add another TextBox in the FooterTemplate section and name it as NewEmailAddress. 

    Column[4] - Login Id
    Choose column[4] - Login Id, Add another TextBox in the FooterTemplate section and name it as NewLoginId. 

    Column[5] - Password
    Choose column[5] - Password, Add another TextBox in the FooterTemplate section and name it as NewPassword. 

    Column[6] - Start Date
    Choose column[6] - Start Date, Add another TextBox in the FooterTemplate section and name it as NewStartDate. (Check following source view, we have added, Calender Extender of Ajax Toolkit)

    Column[7] - End Date
    Choose column[7] - End Date, Add another TextBox in the FooterTemplate section and name it as NewEndDate.  (Check following source view, we have added, Calender Extender of Ajax Toolkit)

    Column[8] - Edit
    Just add a link button into the FooterTemplate section, specify its CommandName property as ‘AddNew’.

  7. Source of the Gridview control changes to following, check we have added Calender Extender for date selection. (Download Demo)

    
            
                
                    
                        
                    
                    
                        
                    
                
                
                    
                        
                    
                    
                        
                    
                    
                        
                    
                
                
                    
                        
                    
                    
                        
                    
                    
                        
                    
                
                
                    
                        
                    
                    
                        
                    
                    
                        
                    
                
                
                    
                        
                    
                    
                        
                    
                    
                        
                    
                
                
                    
                        
                    
                    
                        
                    
                    
                        
                    
                
                
                    
                        
                        
                    
                    
                        
                        
                    
                    
                        
                    
                
                
                    
                        
                        
                    
                    
                        
                        
                    
                    
                        
                    
                
                
                    
                        
                         
                    
                    
                        Add New
                    
                    
                        
                    
                
                
            
            
    
  8. Now we shall develop code in code behind of web page i.e. in C#. We have already developed ManageUsers Class in start. We will develop code for handing Edit,Update and Insert operations of GridView. Add events as shown in following image.


    Now check out following code for each event we have added for GridView.

    Create object of the Class "ManageUsers"; and write function to Bind Customer details to the GridView.
    private void BindCustomers()
        {
            DataTable CustomerTable = customer.Fetch();
    
            if (CustomerTable.Rows.Count > 0)
            {
                gridUserManagement.DataSource = CustomerTable;
                gridUserManagement.DataBind();
            }
            else
            {
                CustomerTable.Rows.Add(CustomerTable.NewRow());
                gridUserManagement.DataSource = CustomerTable;
                gridUserManagement.DataBind();
    
                int TotalColumns = gridUserManagement.Rows[0].Cells.Count;
                gridUserManagement.Rows[0].Cells.Clear();
                gridUserManagement.Rows[0].Cells.Add(new TableCell());
                gridUserManagement.Rows[0].Cells[0].ColumnSpan = TotalColumns;
                gridUserManagement.Rows[0].Cells[0].Text = "No Record Found";
            }
        }
    

    Initializing the GridView control on Page load:
    protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindCustomers();
            }
        }
    

    GridView RowEditing Event
    protected void gridUserManagement_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gridUserManagement.EditIndex = e.NewEditIndex;
            BindCustomers(); 
        }
    

    GridView RowCancelingEdit Event
    protected void gridUserManagement_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gridUserManagement.EditIndex = -1;
            BindCustomers(); 
        }
    

    Updating Records (GridView RowUpdating Event): Update the data to the UserTable, by adding the following lines of code in the GridView’s RowUpdating event
    protected void gridUserManagement_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            TextBox txtNewFirstName = (TextBox)gridUserManagement.Rows[e.RowIndex].FindControl("TextBox2");
            TextBox txtNewLastName = (TextBox)gridUserManagement.Rows[e.RowIndex].FindControl("TextBox3");
            TextBox txtNewEmailAddress = (TextBox)gridUserManagement.Rows[e.RowIndex].FindControl("TextBox4");
            TextBox txtNewLoginId = (TextBox)gridUserManagement.Rows[e.RowIndex].FindControl("TextBox5");
            TextBox txtNewPassword = (TextBox)gridUserManagement.Rows[e.RowIndex].FindControl("TextBox6");
            TextBox txtNewStartDate = (TextBox)gridUserManagement.Rows[e.RowIndex].FindControl("TextBox8");
            TextBox txtNewEndDate = (TextBox)gridUserManagement.Rows[e.RowIndex].FindControl("TextBox9");
    
            customer.Update(Convert.ToInt32(gridUserManagement.DataKeys[e.RowIndex].Values[0].ToString()), txtNewFirstName.Text, txtNewLastName.Text, txtNewEmailAddress.Text, txtNewLoginId.Text, txtNewPassword.Text, txtNewStartDate.Text, txtNewEndDate.Text);
            gridUserManagement.EditIndex = -1;
            BindCustomers(); 
        }
    
    The above block of codes in RowUpdating event, finds the control in the GridView, takes those values in pass it to the ManageUsers class Update method. The first parameter GridView1.DataKeys[e.RowIndex].Values[0].ToString() will return the Id of the Customer. That is the unique id for each customer to perform update function.

    Delete In GridView:
    protected void gridUserManagement_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            customer.Delete(Convert.ToInt32(gridUserManagement.DataKeys[e.RowIndex].Values[0].ToString()));
            BindCustomers(); 
        }
    

    Add New Records from GridView control

    protected void gridUserManagement_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("AddNew"))
            {
                TextBox txtNewFirstName = (TextBox)gridUserManagement.FooterRow.FindControl("NewFirstName");
                TextBox txtNewLastName = (TextBox)gridUserManagement.FooterRow.FindControl("NewLastName");
                TextBox txtNewEmailAddress = (TextBox)gridUserManagement.FooterRow.FindControl("NewEmailAddress");
                TextBox txtNewLoginId = (TextBox)gridUserManagement.FooterRow.FindControl("NewLoginId");
                TextBox txtNewPassword = (TextBox)gridUserManagement.FooterRow.FindControl("NewPassword");
                TextBox txtNewStartDate = (TextBox)gridUserManagement.FooterRow.FindControl("NewStartDate");
                TextBox txtNewEndDate = (TextBox)gridUserManagement.FooterRow.FindControl("NewEndDate");
    
                customer.Insert(txtNewFirstName.Text, txtNewLastName.Text, txtNewEmailAddress.Text, txtNewLoginId.Text, txtNewPassword.Text, txtNewStartDate.Text, txtNewEndDate.Text);
                BindCustomers();
            } 
        }
    


This is how we can develop a simple GridView control in Asp.Net with Add Update Delete functionality.

Download Demo Code here --> Add Update Delete in Gridview Asp.net
Submit this story to DotNetKicks

Read more...

Wednesday, March 16, 2011

Active Directory Authentication Asp.net

Very offen in web development, we come across a requirement where we need to use Active Directory Authentication in Asp.net; i .e. we need to use Active Directory to Authenticate user. The flow for the same can be assumed as following point. In this case we shall not have User table in Database unless required, we can verify the Authenticity of user with Active Directory.
  1. User logs in with Active Directoyl Login and Password.
  2. System verifies Login and Password with Active Directory
  3. If we get Success we will proceed the login else will display error.

We shall use following C# class naming AuthenticateUser to implement ActiveDirectory Authentication in Asp.net

public class AuthenticateUser
{
    public AuthenticateUser()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    private string _path;
    private string _filterAttribute;

    public AuthenticateUser(string path)
    {
        _path = path;
    }

    public bool IsAuthenticated(string domain, string username, string pwd)
    {
        string domainAndUsername = domain + @"\" + username;
        DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);

        try
        {
            //Bind to the native AdsObject to force authentication.
            object obj = entry.NativeObject;

            DirectorySearcher search = new DirectorySearcher(entry);

            search.Filter = "(SAMAccountName=" + username + ")";
            search.PropertiesToLoad.Add("cn");
            SearchResult result = search.FindOne();

            if (null == result)
            {
                return false;
            }

            //Update the new path to the user in the directory.
            _path = result.Path;
            _filterAttribute = (string)result.Properties["cn"][0];
        }
        catch (Exception ex)
        {
            throw new Exception("Error authenticating user. " + ex.Message);
        }

        return true;
    }


}

Remeber we have added "System.DirectoryServices" name space.

We can simply use following code to Authenticate user using ActiveDirectory in asp.net

Note: In following code we use Authentication on Page Load event, you can implement this on Login Page.

protected void Page_Load(object sender, EventArgs e)
    {
        AuthenticateUser cls = new AuthenticateUser("LDAP://YourActiveDirectoryPath"); //Set Active Directory Path
        bool flag = cls.IsAuthenticated("ZESTORMTPL", "UserLoginID", "Password");
        //Put your UserLoginID and Password
    }
Active Directory Authentication Asp.net is as simple as copy pasting above code and use it as it is.
Submit this story to DotNetKicks

Read more...

Tuesday, January 11, 2011

Asp.Net Reading File From Url

In this article is about Reading file from URL specially Text of CSV files, which we can directly read for the source and convert them into table. By doing this we generally avoid file handling, saving the file and then reading it again. WebRequest class of System.Net library is used to read remotely hosted text file or csv file.

We simply need to use following function which will read remote file and put it in a string format. String is named as output string.

WebRequest req = WebRequest.Create(YOURURL);
        WebResponse result = req.GetResponse();
        Stream ReceiveStream = result.GetResponseStream();
        Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
        StreamReader sr = new StreamReader(ReceiveStream, encode);
        string output = string.Empty;
        Char[] read = new Char[256];
        int count = sr.Read(read, 0, read.Length);
        while (count > 0)
        {
            String str = new String(read, 0, count);
            output += str;
            count = sr.Read(read, 0, read.Length);
        }

We are following simple steps in Asp.net for Reading file from URL.
  1. Identify the URL and create WebRequest Object
  2. Get the Response Stream 
  3. Encoding it in Appropriate Unicode format
  4. Reading the Data Stream.
  5. Finally getting the whole text string in one string variable i.e. "output" in this case.
It is very easy to in Asp.net to Read file from Url, as we have seen in above code. We can write our logic to manipulate the string. Submit this story to DotNetKicks

Read more...

Monday, December 20, 2010

Get Excel Sheet Names In Asp.net

In Previous article named Reading Excel File in Asp.net , we discussed about Uploading excel file with One sheet, where we assumed that we know the name of the sheet i.e. Reading from "Sheet1" of uploaded excel file.(Demo Code)

In this article we will discuss to read data from excel file where are not sure about the number of Sheets present in Excel file and name of those excel sheet. This is very common requirement for developers who are playing with Excel Data. We will keep logic of Uploading file similar to previous article. In this article we assume that we have uploaded the file and saved it at predefined location. Now we will only consider reading from excel file which contains number of excel sheets with names not known to us.


Just check out following code, where we consume excel file and read all Sheet names as Table names in one Data Table, and then display all Excel sheets one by one.

public DataSet GetExcelData(string ExcelFilePath)
    {
        string OledbConnectionString = string.Empty;
        OleDbConnection objConn = null;
        OledbConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0;";
        objConn = new OleDbConnection(OledbConnectionString);

        if (objConn.State == ConnectionState.Closed)
        {
            objConn.Open();
        }
        DataSet objDataset = new DataSet();

        DataTable dtName = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        
        for (int _rowCount = 0; _rowCount < dtName.Rows.Count; _rowCount++)
        {
            Response.Write(dtName.Rows[_rowCount]["TABLE_NAME"].ToString() + "
");

            OleDbCommand objCmdSelect = new OleDbCommand("Select * from [" + dtName.Rows[_rowCount]["TABLE_NAME"].ToString() + "]", objConn);
            OleDbDataAdapter objAdapter = new OleDbDataAdapter();
            objAdapter.SelectCommand = objCmdSelect;
            objAdapter.Fill(objDataset, dtName.Rows[_rowCount]["TABLE_NAME"].ToString());
            objAdapter.Dispose();
            objCmdSelect.Dispose();
        }

        objConn.Close();
        return objDataset;

    }

We are simply reading all excel sheets present in the Excel file and adding them in Data Set.
Check out Demo code for the reference. Getting Excel sheet Names in Asp.net is an easy task. We can simply bind this data to grids and display it or push this data directly to database.

We need to note one thing, that sheet names in Excel are read as "SheetName + $", where "$" does not belong to sheet name.

If we need to do operations related to Range of Excel sheet Cells, refer my previous article

Download Demo Code here --> GetExcelSheetNamesInAsp.zip Submit this story to DotNetKicks

Read more...

Monday, November 22, 2010

Google Charts API for ASP.NET

Google Visualization has provided a powerful set of JavaScripts which allows us to develop various graphs and charts. I think if we are developing something like dashboard or something like Google Analytic dashboard, then using Google Visualizations is amazing idea. In case of Asp.net we can simply develop a logic to use DataTables as input and Graph will be generated automatically. Again we can capture the click events for the graph and display alerts or run some JavaScript as per our logic (DemoCode).

In this article we will simply check out different graphs and its integration with asp.net. Check out following Screen shots.





Google Charts API can be implemented effectively in Asp.net, this is just a small part of actual assignment I did for the development of a dashboard.
Step 1: Understanding Table structure of Google API.Google Charts API accepts table as input and generate graphs accordingly. It takes Table in Following format. (for more information check out  Google References )


We should be careful while generating Table in HTML, i.e. while adding Rows and Columns in Google DataTable. Google Data Table creation looks as follows

var data = new google.visualization.DataTable();
        data.addColumn('string', 'Name');
        data.addColumn('number', 'Salary');
        data.addRows(4);
There are many things we can do with Google Table which I am not including in this article.

Check out following JavaScript code for creating Google Table and Adding data in it
var data = new google.visualization.DataTable();
   function setDataforGraph()
        {
         // Create and populate the data table.
       var raw_data =  [['INFOSYS', 3077.15, 3081.65, 3015.9, 3059.80, 3082.65, 3054.65, 2997.85, 3030.05, 2970.95, 3003.95]];
            var xAxis = ['05-Nov-10', '08-Nov-10', '09-Nov-10', '10-Nov-10', '11-Nov-10', '12-Nov-10', '15-Nov-10', '16-Nov-10', '18-Nov-10','19-Nov-10'];

            data.addColumn('string', 'Date');
            for (var i = 0; i < raw_data.length; ++i) {
                data.addColumn('number', raw_data[i][0]);
            }
            
            data.addRows(xAxis.length);
            for (var j = 0; j < xAxis.length; ++j) {
                data.setValue(j, 0, xAxis[j].toString());
            }
            for (var i = 0; i < raw_data.length; ++i) {
                for (var j = 1; j < raw_data[i].length; ++j) {
                    data.setValue(j - 1, i + 1, raw_data[i][j]);
                }
            }
          
        }

We also need to include JavaScript sources, there are some packages Google Provides, as we are going to use this for Charts we include coreCharts
Add script file "http://www.google.com/jsapi"


Once we done with DataTable creation we go for the logic to display Charts. We need to call Google Function

function drawVisualization(Type) {

            // Create and draw the visualization.
            var targetDiv = document.getElementById('visualization');
            var chart;
            if(Type == "ColumnChart") chart = new google.visualization.ColumnChart(targetDiv);
            else if(Type == "PieChart") chart = new google.visualization.PieChart(targetDiv);
            else if (Type == "AreaChart") chart = new google.visualization.AreaChart(targetDiv);
            else if (Type == "BarChart") chart = new google.visualization.BarChart(targetDiv);
            else if(Type == "LineChart") chart = new google.visualization.LineChart(targetDiv);
            chart.draw(data);
            new google.visualization.events.addListener(chart, 'select', selectionHandler);

            function selectionHandler(e) {
                selection = chart.getSelection();
                for (var i = 0; i < selection.length; i++) {
                    var item = selection[i]; 
                    alert(data.getValue(item.row, 1));
                }
            }
        }

Above function can be called on any event. Which will generate Chart of Particular Type. Refer Demo Code. We can add selectionHandler to capture events on click of chart. Above function will give us value of the Item i.e. Data. Check out following image.


HTML Structure of form is something like below, where we have Div tag for Google Visualization.

At this point we are done with the Google Charts API usage in HTML. Now to make Google Charts work in asp.net we simply need to develop a logic in code behind which will enable us to Create GoogleDataTable.

To generate data in code behind we use string elements which we can simple get in JavaScript on page render.

public string x_Axis = string.Empty;
    public string graphTable = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            graphTable = getGoogleVisualizationStr(DemoDataTable);
            x_Axis = "'05-Nov-10', '08-Nov-10', '09-Nov-10', '10-Nov-10', '11-Nov-10', '12-Nov-10', '15-Nov-10', '16-Nov-10', '18-Nov-10','19-Nov-10'";
        }
    }

We keep Demo Table in c# code, with same data values used in above table.
private DataTable DemoDataTable
    {
        get
        {
            DataTable DT = new DataTable();
            DT.TableName = "GENERAL";
            DT.Columns.Add(new DataColumn("Name", typeof(string)));
            DT.Columns.Add(new DataColumn("Data1", typeof(long)));
            DT.Columns.Add(new DataColumn("Data2", typeof(long)));
            DT.Columns.Add(new DataColumn("Data3", typeof(long)));
            DT.Columns.Add(new DataColumn("Data4", typeof(long)));
            DT.Columns.Add(new DataColumn("Data5", typeof(long)));
            DT.Columns.Add(new DataColumn("Data6", typeof(long)));
            DT.Columns.Add(new DataColumn("Data7", typeof(long)));
            DT.Columns.Add(new DataColumn("Data8", typeof(long)));
            DT.Columns.Add(new DataColumn("Data9", typeof(long)));
            DT.Columns.Add(new DataColumn("Data10", typeof(long)));
            DT.Rows.Add(new object[] { "INFOSYS", 3077.15, 3081.65, 3015.9, 3059.80, 3082.65, 3054.65, 2997.85, 3030.05, 2970.95, 3003.95 });
            return DT;
        }
    }

We write a simple code to generate rowData used in above lines of code.

private string getGoogleVisualizationStr(DataTable DT)
    {
        string googleVisualTable = string.Empty;
        googleVisualTable = "[";
        for (int i = 0; i < DT.Rows.Count; i++)
        {
            for (int j = 0; j < DT.Columns.Count; j++)
            {
                if (j == 0)
                {
                    googleVisualTable += "[ '" + DT.Rows[i][j] + "'";
                }
                else if (j == DT.Columns.Count - 1) googleVisualTable += "," + DT.Rows[i][j] + "]";
                else googleVisualTable += "," + DT.Rows[i][j];

            }
            if (i != DT.Rows.Count - 1) googleVisualTable += ",";
        }
        googleVisualTable += "]";
        return googleVisualTable;
    }
We replace our JavaScript code with
var raw_data = <%= graphTable %>
var xAxis = [<%=x_Axis %>];

Thats it we are done with development of Google Charts API for ASP.NET. Above code used data of only one company to keep things simple. To add more companies simply add it in data table. So that our graphs will look like




Download Democode for reference --> GoogleVisualizationDemo.zip Submit this story to DotNetKicks

Read more...

Wednesday, November 3, 2010

Generate captcha image in asp.net - simple way

When it comes to captcha images simple question pops in i.e. how to generate captcha images?
This article is about generating Captcha image in asp.net, this is very simple logic which can be implemented immediately for any website. You can directly Download Demo and use it.
We have used following simple steps to Generate Captcha Image in asp.net
  1. Create Captcha Image from random numbers and store that number in session variable, we have used Captcha.aspx page for the same.
  2. Use Captcha.aspx as source for the captcha image in Default.aspx page, i.e. for image tag give Captcha.aspx as SRC.
  3. On Submit click simply verify captcha entered by user and captcha in session. 
Our folder structure is very simple, check out following image


To understand the way we have checked captcha, have look on HTML of Default.aspx page (Check out DemoCode, for better understanding.)


Catptcha Text



Check out the way we have used Captcha.aspx page in image source.

On submit click we simply checks whether Captcha entered in "txtCaptcha" is valid or not, we have following code for submit button clicked.

protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (Session["Captcha"] != null)
        {
            if (txtCaptcha.Text == Session["Captcha"].ToString())
            {
                Response.Redirect("RedirectPage.aspx");
            }
            else
            {
                Response.Write("Please Enter Valid Captcha code");
                txtCaptcha.Text = "";
            }
        }
        else
        {
            Response.Write("Session Expired, please re-enter Captcha.");
        }
    }

Now what remains is the logic for Generate captcha image, we don't have any HTML tags on captcha.aspx, we simply write following code for Binary Image Generation and write it. We have used Random number; but we can have our different logic for the same.

protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "text/plain";
        Random random = new Random(DateTime.Now.Millisecond);

        int number = random.Next(100000);

        Session.Add("Captcha",number.ToString());

        System.Drawing.Bitmap bmpOut = new Bitmap(100, 50);

        Graphics graphics = Graphics.FromImage(bmpOut);

        graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;

        graphics.FillRectangle(Brushes.Aquamarine, 0, 0, 100, 50);

        graphics.DrawString(number.ToString(), new Font("TimesNewRoman", 20), new SolidBrush(Color.Coral), 0, 0);

        MemoryStream memorystream = new MemoryStream();

        bmpOut.Save(memorystream, System.Drawing.Imaging.ImageFormat.Png);

        byte[] bmpBytes = memorystream.GetBuffer();

        bmpOut.Dispose();

        memorystream.Close();

        Response.BinaryWrite(bmpBytes);

        Response.End();

    }

Thats it we are done with our Generate captcha image in asp.net. Very simple code to use, download democode and use it directly in your web application.

Download Democode here---> CaptchaInAsp.net.zip Submit this story to DotNetKicks

Read more...

Wednesday, September 15, 2010

Url Rewriting Made Easy - Article 3

After implementing URL Rewriting there are certain issues which we need to tackle, so that URL rewriting logic will not affect web application. This is I am talking with reference to URL Rewriting for Search Engine Optimization, where we are preferring hackable URLs.
This article is continuation of my previous articles on URL Rewriting.
  1. Url Rewriting Made Easy- Article 1 (Demo Code)
  2. Url Rewriting Made Easy- Article 2 (Demo Code)
Basic things which I considered while developing logic was, Url Rewriting should be very simple to understand and implement. And it should be considered while developing the web application and not after completing the development.
What happens when we do URL Rewriting? On the client side i.e. on Browser we display URL which is hackable (i.e. Easy to understand and can be remembered easily, which also directly or indirectly displays directory structure.). On server side page get redirected to some other page using query string and rest of the operations can be performed in normal way. But There is one serious thing which we need to consider, normally when we Use Images and JavaScript files in HTML logic we tend to give relative path; and this path is picked by browsers to display images and include JavaScript files in HTML code.
In case of URL Rewriting we have discussed in Article 1 and Article 2, we need to keep work around for images and JavaScripts. As per the logic Raw Urls (i.e. Hackable URL) is being displayed and used by the browser, but for displaying Images which belongs to different folder we need to use fully qualified urls.
USE FULLY QUALIFIED URLS FOR IMAGES AS WELL AS TO INCLUDE JAVA SCRIPT FILES, SO THAT URL REWRITING CAN WORK. You can always go for Image Handlers or manipulate Image Urls by making Images server side controls. for including JavaScripts you can either Manipulate the Head Section Dynamically or use your own logic. Submit this story to DotNetKicks

Read more...

Tuesday, August 10, 2010

Different ways of web page Redirect in Asp.Net

As a website developer many times we come across situation where we need to redirect pages, as there are many ways to redirect pages in asp.net and in HTML as well; one should know the difference between various web page redirect methods.
In this article we will discuss various web page redirecting methods we can use in asp.net

  1. Hyperlink: This is a traditional way of web page redirect which can use with HTML TAG i.e "A" tag. This is a static link on a page, which can be used as a tag with various style attributes. Also we can put data in opening and closing tag of "A". Asp.Net provides Hyper Link control, which is a class inherited from Webcontrol class. This control needs user to click explicitly on link for web page redirect.
    
     

    There are many attributes and events which are associated with hyperlink control, which can be used for many purposes.

    Hyperlink has following characteristics
    • New request is performed on Target Page.
    • Current page information doesn't get passed. Need to use query string to pass parameters
    • User Need to Initiate the web page transfer request.
    • Redirects to any page, not only restricted to current domain.
    When to Use
    • For navigation without any processing, e.g. Menu's list Items
    • When user should control the navigation.
  2. CrossPagePostBacks :By default, buttons in an ASP.NET Web page post the page to itself. i.e. it simply acts as a submit button of HTML. Where as Cross-page posting enables us to change the style of submitting the page, we can configure a button on an ASP.NET Web page to post the current page to a different page. Typically in multi-page forms, we can use such buttons on the page to move to the next and previous pages of the form.

    Though cross page posting is similar to hyperlinks, in cross page posting, the target page is invoked using an HTTP post command, which sends the values of controls on the source page to the target page. In addition if source and target page are in the same web application then the target page can access public properties of the source page. You can check out the article on cross page post by, click on CROSS PAGE POSTBACK
    Hyperlink has following characteristics
    • Post current Page Information into Target Page.
    • Makes Post information available into target page.
    • User Need to Initiate the cross page postback request.
    • Redirects to any page, not only restricted to current domain.
    • Enables the target page to read public properties of the source page if the pages are in the same Web application.
    When to Use
    • To pass current page information to the target page (as in multi-page forms).
    • When user should control the navigation.
  3. Response.Redirect: This is simple HTTP redirection we can directly use in code behind. very simple to use  When we use Response.Redirect the browser issues a new request to the target server in the form of an HTTP GET request. Response.Redirect is same as form submit in HTML, it does exactly same, actually in HTML response.redirect come as submit only. This method passes the server elements using query string. We can always use this method in code behind with our logic to redirect to other page(s).
    Hyperlink has following characteristics



    • Performs a new HTTP GET request on the target page.
    • Passes the query string (if any) to the target page. In Internet Explorer, the size of the query string is limited to 2,048 characters.
    • Provides programmatic and dynamic control over the target URL and query string.
    • Enables you to redirect to any page, not just pages in the same Web application.
    • Enables you to share information between source and target pages using session state.

    When to Use
    • For conditional navigation, when you want to control the target URL and control when navigation takes place. For example, use this option if the application must determine which page to navigate to based on data provided by the user.
  4. Server.Transfer: In case of Server.Transfer, server simple transfers the current source page context to the target page. The target page then renders in place of the source page. To use Server.Transfer, source page and target page should be in the same web application. When we use transfer method target page can read control values and public property values from the source page. Transfer between source and target pages happens on the server, because of this the browser has no information about the changes page, and it retains all information about the original i.e. source URL. Browser history doesn't get update to reflect the transfer. This is the best strategy to keep URL hidden, if user refresh the page he/she will be redirected to source page rather than new transferred page.
    Server.Transfer has following characteristics
    • Instead of source page control is transfered to new page which get renders in place of source
    • Redirects only to target pages that are in the same Web application as the source page.
    • Enables us to read values and public properties from source page.
    • Browser information Does not update with information about the target page. Pressing the refresh or back buttons in the browser can result in unexpected behavior.
    When to Use
    • For conditional navigation, when you want to control when navigation takes place and you want access to the context of the source page.
    • Best used in situations where the URL is hidden from the user.
Submit this story to DotNetKicks

Read more...

Sunday, July 25, 2010

XMLHTTPJSClass - JSON Class for Ajax Operations

In the development of Ajax application many times we may come across following issues.
  • Need to update multiple text boxes simultaneously.
  • Fill more that one dropdown lists.
  • Combination of text boxes, dropdown lists and div tags.
  • Calling different web pages and different webservices

Means one event may lead to updating of many html elements. In such cases we will have to send Ajax request in a loop. Again for each request we will have to take care of timeouts and request failures. Here if data is static we can keep it on HTML page and using JavaScript can directly hide and show the contents. But if we have to use real time data and also choices of display vary according to choices of the user, in such case looping of Ajax request may not be a good idea.

In this article we will discuss about XMLHTTPRequest object and JavaScript. We will develop a JavaScript class in which we can vary our choices and also be able to update multiple HTML contents. Also this class can be extended as per the requirements.

We will first talk about class in JavaScript, there is no keyword called class in JavaScript but we can use function as a class.

Checkout following code



In above script if we remove obj.Msg = "HI"; we will get an alert with text Hello.


Now step by step we will start developing our JavaScript class.
1.Include JS file and write following


In this step we have created XMLHTTPRequest object and simply send call to the server. By default method is GET (this.Method = "GET") and calling type is Ascynchronous (this.Async = true)


2.In this step we will develop simple logic which will allow us to dynamically call Ajax function.

For this in our above Ajax function we will add one JSON (www.json.org) object as follows.



In above script we can set the default values for all. Please reffer demo JS file to understand this better. We will use these values to set response from the server to textboxes,drop down lists,Div tags, td tags etc. Using "CallPage" : "CallPage.aspx" we can define default server page and while calling Ajax function we can reset this value to web method or to any other web page.
As we will proceed in this article we will come to know how can we change all above values and how can we use it for multiple updation.Also we will see that how to extend the class for further customization.

3.As we have seen in 1st step;

this.request.onreadystatechange=this.handleResponse;
In this step we will develop this.handleResponse function also in this function we will use JSON object defined in 2nd step.
Whenever this.handleResponse function gets call script looses the focus of this. To keep trac of this object we will assing it to some variable. i.e



In this function we will be able to receive data from server. Once we get the data we can play with it the way we want.
This function will take care of the responses from web services as well as from web pages.
Difference is, web service returns response in the form of XML where are response from the webpage can be defined by web developer.

The function will be as follows



If there is any problem in understanding please go through above code again.

In the the 1st step we have



While developing Ajax application take care of following point.
  • URL for XMLHTTPRequest object should belong to same domain.
  • Firefox and other browser doesn’t allow cross domain communication.
  • IE will show warning

Thus our


e.g. "http://localhost/Demo/CallPage.aspx?"+this.JSONArray.Querystring;

Also when ever we want to call web methods like above example, we need to set following protocols under in web.config file.



4.Up to this point we have finished with development of Ajax logic which will return us response. And in this point we will develop logic for population HTML controls

In this.handleResponse (step 3) we have seen that we get response in
“data” variable in JavaScript.

So once we got response from the server we will write following logic



self.JSONArray.isEdit[0].textBoxId will contain id of the text box in which we have to fill the response. And data is the response from the server.
In 2nd step we have defined JSON object as follows



And in our above switch we have simply used the elements of JSON object

At this point we will see how to call our Ajax Class, how to initiate the request and how to set Elements of our JSON object.
Simply create object of our AjaxClass().



if obj.JSONArray.dependentType=1 then our switch case will not work for text box, but it will work for dropdown list (check above switch case). Means we will have to set dropdown list of JSON object.



and so on, we can define our own set of HTML controls to be filled.

In the same way we can change all default settings in JSON object of that class.
e.g. obj.JSONArray.Method = "GET";
obj.JSONArray.CallPage = "Mywebservice/webMethod";
obj.JSONArray.Querystring= "My querystring";

For this URL will be



In case of web service we will have to set CallPage element in the same way we did in above example.

Now for multiple textboxes simple trick,
obj.JSONArray.isEdit[0].textBoxId="txt1$txt2$txtn";//$ is a delimiter
While sending data from server send it with the same delimiter,in such a way when we split obj.JSONArray.isEdit[0].textBoxId and response data on $; we will get one to one data and textBoxId.

Now we can have different types like “txtbox(es) + drop down list(s) + div” in such case we can use "misc" option of isEdit element of JSON object.
And we can define our PopulateControls function the way we want.

Just think of the choices for getting Response from AjaxCall; we can develop very critical systems using this logic and keeping code as simple as possible. Also we can integrate our ICallback logic for large data transfer.



Demo JavaScript file is as below ( DOWNLOAD)



Download Demo Code here --> XMLHTTPJSClass.zip

Submit this story to DotNetKicks

Read more...