Pages

Oct 4, 2010

How to find First non repeated character in a string + c#

This is really a mind twisting question. But if you dint give a try to solve this , you may think that its so simple.
This was asked in one of my interview.
now lets see how to solve this
Method call : GetFirstNonRepeatedChar("abcdab");

private char GetFirstNonRepeatedChar(string value)
        {
           // declare a character array.
            char[] cArr = null;
            try
            {
                // load the string to char array.
                cArr = value.ToCharArray();


                for (int i = 0; i < cArr.Length; i++)
           { 
                   // count to track all comparison has over              
                   int count = 0;
for (int j = 0; j < cArr.Length; j++)
                    {
                        // avoids to comparison for same character
                        if (i != j)
                        {
                            // if repeated then come out of the inner loop
                            if (cArr[i] == cArr[j])
                            {                                
                                break;
                            }
                            else
                            {
                                // increament the count for each non repeatable comparison
                                count = count + 1;
                                // if the count reaches the char array length - 1
                                // and you are inside the for loop then the current value
                                // is the first non repeated character.
                                if (count == cArr.Length -1)
                                {
                                    return cArr[i];
                                }
                            }
                        }                        
                    }
       }
                return '0'; // if no non repeated char is fount
            }
            catch (Exception)
            {
                
                throw;
            }            
        }


Answer : c

Oct 2, 2010

Difference between exec and sp_executesql + SQL SERVER

If we are using Direct T-SQL (not dynamic) in stored procedure, SQL Server reuses execution plan from the cache. i.e. SQL Server will not compile the Stored Procedure again.

If we are using dynamic sql in stored procedure, SQL Server may not use the execution plan. It will recreate the execution plan every time with different string of SQL.So, we have to think about the performance while using dynamic sql.

To execute the dynamic SQL in stored procedure, we have to use the following way.

1. EXEC (Non- parameterized)
2. sp_executesql (Parameterized)


There will be performance difference between above two.

Execution plan will not be created until you execute the dynamic sql. If you execute the dynamic sql using EXEC, execution plan will be created for every execution even values only changing. If you use sp_executesql, SQL Server Optimizer will try to use same execution plan. Because dynamic sql string will be the same, values only going to change. So it will be treated as Stored Procedure having input parameters.

Sep 30, 2010

Stored Procedure(SP) Vs User Defined Functions(UDF) + SQL SERVER

Differences: 
1. Procedure can return zero or n values whereas function can return one value which is mandatory.
2. Procedures can have input,output parameters for it whereas functions can have only input parameters.
3. Procedure allow select as well as DML statement in it whereas function allow only select statement in it.
4. Functions can be called from procedure whereas procedures cannot be called from function.
5. Exception can be handled by try-catch block in a procedure whereas try-catch block cannot be used in a function.
6. We can go for transaction management in procedure whereas we can't go in function.
7. Procedures can not be utilized in a select statement whereas function can be embedded in a select statement.

Sep 9, 2010

How to specify table name dynamically in a SQL statement + SQL SERVER 2008

Dynamic SQL :
Using a dynamic sql is quite comman in sql statement. I had a situation where
i have to pass the table file as a argument to a Stored Procudure and depending 
upon the argument i have to execute the Select statement.


Say for eg.
argument @Table = dbo.Customers
then
SELECT * FROM @Table
But this doesnt work.
So when you are in a need to specify any of the objects like table or column etc
we need to use dynamic SQL using exec method. Below is an example

DECLARE @TableName varchar(50)
SET @TableName ='dbo.Customers'
DECLARE @SQL varchar(max)
SET @SQL = 'SELECT * FROM ' +@TableName // dynamic table name
EXEC(@SQL)

Sep 8, 2010

How to find the intersected rows of a spatial Index using POLYGON object + Spatial Queries

Below is the sample stored procedure used to find the 
rows that are intersected with the POLYGON object
[Created using Coordinates list].


CREATE PROCEDURE [dbo].[GetIntersectingRows] 
-- Add the parameters for the stored procedure here
@Coordinates varchar(max)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;


Declare @AOIPolygon geography
set @AOIPolygon = geography::STPolyFromText('POLYGON(('+@Coordinates+'))', 4326);


SELECT ID,Quad_Name,State from dbo.USCollared250K_Index 
WITH (INDEX(geom_sidx)) WHERE
@AOIPolygon.STIntersects(geom) = 1;
END


Note:
@Coordinates - comma separated pairs of coordinates like
eg. -104.864472 39.764004,-104.864472 39.853945,-105.057976 39.853945,
-105.057976 39.764004,-104.864472 39.764004

How to open a pop up window with specified properties[height,width,position and no menubar,no resizable]. + Javascript

Below is the javascript method that opens a popup without scrolbar or menubar or resizable etc


function openQuadPopup(val) {           
            var width = screen.width - 100;
            var height = screen.height - 100;
            var leftPos = (screen.width - width - 30) / 2;
            var topPos = (screen.height - height - 30) / 2;
            myWindow = window.open('TestPage.aspx?ImagePath=' + val, 'NameForPopup', 'menubar=0,resizable=0,width=' + width + ',height=' + height + "'");


            myWindow.moveTo(leftPos, topPos);          
        }


To include scroll bars use


window.open('TestPage.aspx', '','scrollbars=yes,width=300,height=300')

Aug 26, 2010

How to find Country's Name using IP Address in Asp.Net

Use the below free web-service to get the country name using IP Address.
 http://www.webservicex.net/geoipservice.asmx?wsdl


Add the service to your web or windows application and name the service
as say for eg. locationFinder
Now access it in your code as
// Create instance for the service

LocationFinder.GeoIPService service = new LocationFinder.GeoIPService();
// Gets the country name.
string country = service.GetGeoIP("216.241.xxx.xx").CountryName;


To get the ipAddress of the Client machine use
String ipAddress = Request.UserHostAddress.ToString();

Aug 11, 2010

Simple login page using Forms's Authentication + Asp.Net + C#

Login Page Implementation[Forms Authentication] :
Login page implementation is a basic need in most applications.
Now lets see a simple implementation of the Login Page in asp.net.
Create a page named Login.aspx  and add a table like

Login:

<table align="center">    
      <tr>
        <td>
          UserName :</td>
        <td>&nbsp;
          <asp:TextBox ID="txtUserName" runat="server" /></td>
        <td>
          <asp:RequiredFieldValidator ID="RequiredFieldValidator1" 
            ControlToValidate="txtUserName"
            Display="Dynamic" 
            ErrorMessage="Please Enter User Name" 
            runat="server" />
        </td>
      </tr>
      <tr>
        <td>
          Password  :</td>
        <td>
          <asp:TextBox ID="txtPassword" TextMode="Password" 
             runat="server" />
        </td>
        <td>
          <asp:RequiredFieldValidator ID="RequiredFieldValidator2" 
            ControlToValidate="txtPassword"
            ErrorMessage="Please Enter Password." 
            runat="server" />
        </td>
        </tr>   
          <tr>
          <td colspan="3" align="left">
            <asp:Button ID="Submit1" OnClick="Logon_Click" Text="Log On" 
                runat="server" />
            </td>
          </tr>  
          <tr>
            <td colspan="3">
                <p>
                  <asp:Label ID="Msg" ForeColor="red" runat="server" />
                </p>
            </td>
          </tr> 
    </table>

Now add the code-behind for login page like

     // if you have more users then store the username and
     // password in back-end database and perform the check

     if ((txtUserName.Text == "mukunda") && (txtPassword.Text == "easyone1"))
        {
            // This statement will redirect to start page automatically.
            FormsAuthentication.RedirectFromLoginPage
               (txtUserName.Text, false);
        }
        else
        {
            // to show error message for invalid login.
            Msg.Text = "Invalid credentials. Please try again.";
        }

To make the above code work we need to add the following to web config

        <authentication mode="Forms">
      <forms loginUrl="Login.aspx" name=".ASPXFORMSAUTH">
  </forms>
  </authentication>
  <authorization>
<deny users="?"/>
  </authorization>
      inside <system.web> tag.

And in the Main page you can access the logged user name and
show it in a label like
lblEmpID.Text = Context.User.Identity.Name;

LogOut :
To log out the current user you need to add a link button in main page
<asp:LinkButton ID="Submit1" runat="server" 
OnClick="Signout_Click">Sign Out</asp:LinkButton>    
    
Code-Behind:

    /// <summary>
    /// event for signingout the current page & redirect to Login page
    /// </summary>    
    protected void Signout_Click(object sender, EventArgs e)
    {
        FormsAuthentication.SignOut();
        Response.Redirect("Login.aspx");
    }
  
Now a simple login implementation using Forms Authentication is done!

Aug 10, 2010

Simple Add,Edit,Update and Delete operations in GridView + Asp.net 3.5

Lets first create a table in MSAccess like below named Customer

Customer Table















Aspx Page:

Drag a gridview and fields and event as given below


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
                DataKeyNames="ID" onrowcommand="GridView1_RowCommand"
                onrowdeleting="GridView1_RowDeleting"
                onrowediting="GridView1_RowEditing"
                onrowdatabound="GridView1_RowDataBound"
                onrowupdating="GridView1_RowUpdating">
                <Columns>
                    <asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="true"/>
                    <asp:TemplateField HeaderText="Name">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtTName" runat="server"
                             Text='<%# Bind("Name") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'>
                            </asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Age">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtTAge" runat="server"
                            Text='<%# Bind("Age") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label2" runat="server" Text='<%# Bind("Age") %>'>
                           </asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:CommandField ShowDeleteButton="True" />
                    <asp:CommandField ShowEditButton="True" />
                </Columns>
            </asp:GridView>

.cs page:
// Create a connection to Access Database.
OleDbConnection aConnection = new OleDbConnection
 ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\CustomerInfo.mdb");

// Binds grid on page load.

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            bindGrid();
        }
    }


// Method to bind grid

private void bindGrid()
    {
        string query = string.Empty;
        OleDbCommand cmd = null;
        OleDbDataAdapter adap = null;
        DataSet ds = new DataSet();
        try
        {
            aConnection.Open();
            query = "SELECT * FROM Customer";
            cmd = new OleDbCommand(query, aConnection);
            adap = new OleDbDataAdapter(cmd);
            adap.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
        catch (Exception)
        {
          
            throw;
        }
        finally
        {
            aConnection.Close();
        }

// To make the grid editable when edit button clicked

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bindGrid();
    }

// Performs Delete and Update operations

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int cusID = 0;
        GridView gv = (GridView)sender;
       // to find the Current ID selected.
        cusID = Convert.ToInt32(
        gv.Rows[Convert.ToInt32(e.CommandArgument)].Cells[0].Text);
        if (e.CommandName == "Delete")
        {
            DeleteCustomer(cusID);
        }
        if (e.CommandName == "Update")
        {
           // to find the edit text box  value.
           TextBox txtname = GridView1.Rows[Convert.ToInt32(e.CommandArgument)]
            .FindControl("txtTName") as TextBox;
           TextBox txtage = GridView1.Rows[Convert.ToInt32(e.CommandArgument)].
            FindControl("txtTAge") as TextBox;
            updateCustomer(txtname.Text, txtage.Text, cusID);
        }
    }

//To create an Alert before deleting the row in gridview.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        foreach (Control control in e.Row.Cells[3].Controls)
        {
            LinkButton DeleteButton = control as LinkButton;
            if (DeleteButton != null && DeleteButton.Text == "Delete")
            {
                DeleteButton.OnClientClick =
                 "return(confirm('Are you sure you want to delete this record?'))";
            }
        }
    }

// Method to Delete Customer Information

private void DeleteCustomer(int ID)
    {
        string query = string.Empty;
        OleDbCommand cmd = null;
        try
        {
            query = "DELETE FROM Customer WHERE ID=" + ID;
            cmd = new OleDbCommand(query, aConnection);
            aConnection.Open();
            cmd.ExecuteNonQuery();
            aConnection.Close();
            bindGrid();
          
        }
        catch (Exception)
        {

            throw;
        }
        finally
        {
          
        }
    }

// Method to update customer with edit values.

private void updateCustomer(string name, string age, int ID)
    {
        string query = string.Empty;
        OleDbCommand cmd = null;
        try
        {
            query = "UPDATE Customer SET Name='" + name + "',Age='" +
                         age + "' WHERE ID=" + ID;
            cmd = new OleDbCommand(query, aConnection);
            aConnection.Open();
            cmd.ExecuteNonQuery();
            aConnection.Close();
            GridView1.EditIndex = -1;
            bindGrid();
        }
        catch (Exception)
        {

            throw;
        }
    }

Above given is the code used to perform Edit,Update
and delete operations in a gridview.

Aug 6, 2010

How to open Visual Studio 2010 project in Visual Studio 2008

Steps to Open VS2010 project using VS2008:

· Open the .sln file corresponding to the Project to be converted with Notepad
· Locate the following line: Microsoft Visual Studio Solution File, Format Version 11.00
· Replace 11.00 with 10.00
· Locate the following line: # Visual Studio 10
· Replace 10 with 2008
· Save the File
· Delete the .cache files existing in the following paths:
o obj/debug
o obj/release
· Open the project with Visual Studio 2008
· Build the project with Visual Studio 2008

Reference: http://dougortiz.blogspot.com/2009/05/converting-visual-studio-2010-project.html

Aug 5, 2010

How to use dynamic column name in update query + SQL SERVER

This is a General Requirement that we may be in a need to update 
the table using a dynamic column name.
Say for Eg:
Here my case is ,
I need to update a table, when user reaches different stage of the Ordering Proces.
So i have columns as name, age, stage1,stage2,stage3 etc upto 8 stages.
When user enter each stage i will be calling this procedure with stage 
as parameter like 1,2,3 etc.. up to 8.

CREATE PROCEDURE [dbo].[UserTracking_usp]
(       
      @TrackID int
      @Stage varchar(10)
)
AS

BEGIN
            // to store dynamic column name
            DECLARE @CurrentStage varchar(50)
            DECLARE @UpdateSQL varchar(200)

            SET @CurrentStage =
            CASE 
                  WHEN @Stage='2'  THEN  'Stage2'
                  WHEN @Stage='3'  THEN  'Stage3'
                  WHEN @Stage='4'  THEN  'Stage4'
                  WHEN @Stage='5'  THEN  'Stage5'
                  WHEN @Stage='6'  THEN  'Stage6'
                  WHEN @Stage='7'  THEN  'Stage7'
                  WHEN @Stage='8'  THEN  'Stage8'
            END
       SET  @UpdateSQL = 
       'UPDATE User_Tracking SET ' + convert(varchar, @CurrentStage) + '= 1   
       WHERE
       User_Tracking_ID = ' + convert(varchar, @TrackID);
       EXEC (@UpdateSQL)
       END    


So this procedure will examine which column name should be updated
using a case statement and substitute as a dynamic column name for 
update query as shown above.


In the same way one can use for select,delete statements etc..

Jul 12, 2010

How to show date alone in GridView BoundField when using DateTime as DataType in DataBase.


DateTime Formatting in GridView:
Usually we create a field with DataType DateTime in Database 
say for eg. MSAccess database.
Now when you show this in the GridView it shows Date along with 
time like 7/6/2010 8:10:12 PM
But you may be in situation to show only the Date alone.
like 7/6/2010
To do so, simple specify the format in the GridView BoundField like

<Columns>
    <asp:BoundField 
              DataField="Date1" 
              HeaderText="Date" 
              DataFormatString="{0:d}" />
</Columns>

Refer the below link for different other formats
http://msdn.microsoft.com/en-us/library/
system.web.ui.webcontrols.boundfield.dataformatstring.aspx

Jul 10, 2010

How to show a alert message or confirmation when deleting row from GridView without postback + Asp.Net

This is a basic logic needed in Grid-view while deleting a data. By mistake people may click
on the delete button and if there is no alert or confirmation, some valuable data may be lost.
Let's go for implementation, below is the grid-view


<asp:GridView ID="GridView2" runat="server"  AutoGenerateSelectButton="true"
            DataKeyNames="ID"  AutoGenerateDeleteButton="true"
            onrowdatabound="GridView2_RowDataBound" >
      <Columns>
                <asp:BoundField DataField="ID" HeaderText="SL.No" Visible="false"/>
                <asp:BoundField DataField="Project" HeaderText="Project" Visible="false"/>
      </Columns>
</asp:GridView>

In the above grid the two properties namely AutoGenerateSelectButton,
and AutoGenerateDeleteButton let you show the Select and
Delete button on the GridView.
Now on onrowdatabound event of the GridView we implement the logic like


  protected void GridView2_RowDataBound(object sender,
                                                            GridViewRowEventArgs e)
    {
        // Gets the Delete command column, which is the first column
        foreach (Control control in e.Row.Cells[0].Controls)
        {
            // Gets the Delete link button
            LinkButton DeleteButton = control as LinkButton;
            if (DeleteButton != null && DeleteButton.Text == "Delete")
            {
               DeleteButton.OnClientClick =
               "return(confirm('Are you sure you want to delete this record?'))";
            }
        }
    }
The above code will show you an alert message before deleting a row.

How to access ServerSide method from GridView's ItemTemplate

Calling a CodeBehind Method From GridView's ItemTemplate:


While working with GridView, there may be a case where 
we actually need to do some operations in serverside for 
which we may be in a need to call a server side
method from ItemTemplate of a GridView.


Say for example, 
I had a situation where i need to call a server side 
method (which return a string value) from ItemTemplate.
So i used a label in the ItemTemplate like 



<asp:TemplateField HeaderText="Testing">
<ItemTemplate>
<asp:Label ID="lblCustomerAge" Text='<%# GetCategory() %>' runat="server">
</asp:Label>
</ItemTemplate>
</asp:TemplateField>


Here GetCategory is the server side method.Code-behind is given below

  protected string GetCategory()
    {
       // Do whatever you want here
        return "TestCategory"; // For eg. passing a string
    }

Jul 6, 2010

How to split a sentence into word using C# + Regular Expressions


using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string[] w = SplitWords("This is a Sample, Test");
        foreach (string s in w)
        {
            Console.WriteLine(s);
        }
        Console.ReadLine();
    }

    /// <summary>
    /// Get all the words in the input string and separate them.
    /// </summary>
    static string[] SplitWords(string s)
    {
        //
        // Split on all non-word characters.
        // ... Returns an array of all the words.
        //
        return Regex.Split(s, @"\W+");
        // @      special verbatim string syntax
        // \W+    one or more non-word characters together
    }
}
Output:
This
is
a
Sample
Test

Jul 3, 2010

How to find the System Name in C#

Lets make use of the Namespace 
using System.Security.Principal; to find the System name.


Below is the code:
lblSysNo.Text = WindowsIdentity.GetCurrent().Name.ToString();

Jul 1, 2010

How to pass double couted paramaters to Command line utilities programatically + c#

Invoking a Command Line Utility From C#:


For eg. let's consider FWTools which has a command line utility named 
ogr2ogr for converting tab to kml
Below is the code to invoke the command line utility ogr2ogr

Invoking Command Line without parameters:

// Create an instance for System.Diagnostic.Process
Process proc = new Process();
// Provide the utility name with location
proc.StartInfo.FileName = @"C:\FWTools2.4.7\bin\ogr2ogr.exe";
// Start the process
proc.Start();

Invoking Command Line with normal parameters:
Note: -f, KML, sourcepath, destpath are arguments separted by space
Process proc = new Process(); 
string driver = @"-f KML C:\FWTools2.4.7\bin\zeeee.kml 
C:\FWTools2.4.7\bin\Morocco.tab"
proc.StartInfo.FileName = @"C:\FWTools2.4.7\bin\ogr2ogr.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.Arguments = driver; 
proc.Start();
proc.WaitForExit(); // use if you want your  program to wait for the process to complete.
proc.Close();

Invoking Command Line with Double couted parameters:

Usually space in the arguments list denote that each are separate
argument separated by space.

In the above code KML is the name of the driver used to convert 
Tab to KML.

And to convert ESRI's shape file to MapInfo's Tab file the driver 
used is "MapInfo File", which itself has a space

so by default command line arguments will consider it as a
two parameter one is "MapInfo" and other is "File"
so the program goes wrong.

Below is the solution, how to pass the double couted paremeter

string driver = "-f " + @"""" + "MapInfo File" + @"""" +
 @" C:\FWTools2.4.7\bin\test.tab C:\FWTools2.4.7\bin\test.shp";

By using this methodology, we can pass "MapInfo File" as a 
single argument to a command line utility.