Pages

Dec 8, 2011

How to set html link visible false depending on Eval function in grid view

Below is the html link in the grid view item template that sets visibility depending on the IsOnline values.

<a href = "www.google.com" style='<%# Eval("IsOnline").ToString() == "True" ? "display:block" : "display:none" %>' >link</a>

Dec 7, 2011

How to convert DateTime to Date in Linq to Entity + C#

Use EntityFunction to truncate the time part from a DateTime String.

grid.DataSource = (from user in context.Users where ISActive = True select new
                                          {
                                              user.UserId,
                                              user.UserName,
                                              FirstName = (user.FirstName + " " + user.LastName),                                           
                                              CreatedDate = System.Data.Objects.EntityFunctions.TruncateTime(user.CreatedDate)                                           
                                          }).ToList();)

Jun 19, 2011

Clipboard operations in javascript


Copy TO and Copy FROM CLIPBOARD :


<body>
    <textarea id='clipText'>
Enter Text And Click Button To Copy Text To ClipBoard</textarea><br />
    <input type="button" id='bt' onclick="clipboardData.setData('Text',document.getElementById('clipText').value);"
        value="Copy" />
    <input type="button" onclick="clipboardData.clearData('Text');" value="Clear" />
    <input type="button" onclick="alert(clipboardData.getData('Text'));" value="Paste" />
</body>

May 26, 2011

How to insert a Guid or UniqueIdentifier and return it as a OUTPUT parameter + StoredProcedure. + SQL


CREATE PROCEDURE [test]
    @name as varchar(50),
    @id as uniqueidentifier OUTPUTAS
BEGIN
    declare @returnid table (id uniqueidentifier)

    INSERT INTO test(
        name
    )
    output inserted.id into @returnid
    VALUES(
        @name
    )

    select @id = r.id from @returnid rEND
Above SP returns the newly inserted GUID as the OUT parameter.

May 20, 2011

How to use double coute in string + C#

This usage of double coutes in a string can be easily done using @.
For eg:
To show the below text 
 "This is a "Test"


Code:
TextBox1.text = @"""This is a " + @"""Test""";


The logic is that if you use @ in front of the sting variable then using e double coute(""") 
throughout the string will give you one double coute(").

How to create a text file and save it on client machine using Save File Dialog + Asp.Net + C#

Method to Create text file:
Using System.IO;
Using SystemsText;

private void CreatetxtFile()
{
StringBuilder sb = new StringBuilder();

sb.AppendLine("test");
sb.AppendLine("= = = = = =");
sb.AppendLine();
sb.Append("test2");
sb.AppendLine();
sb.AppendLine();

using (StreamWriter outfile = new StreamWriter("c:" + @"\AllTxtFiles.txt"))
{
outfile.Write(sb.ToString());
}

}
Code to Save the file as dialog :
Response.ContentType = "text/plain";
Response.AppendHeader("Content-Disposition", "attachment; filename=AllTxtFiles.txt");
// specify the path of the file that has to be saved in client machine.
Response.TransmitFile("c://AllTxtFiles.txt");
Response.End();
The above code will show a save file dialog to save the file.

Apr 25, 2011

How to update data from excel sheet to the sql data base. + How to compare two date time columns and find the later values

// Copies the excel sheet values to the table sTemp.
SELECT * INTO dbo.sTemp
FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\test.xls;IMEX=1',
'SELECT * FROM [Sheet_Name2$]')

GO

// Compares two columns of the excel and updates the table with the later values.
UPDATE INV
SET
INV.EndDate = TMP.
RecentDate 
FROM
dbo.Inventory as INV
INNER JOIN
(
SELECT
Inventoryid,
CASE
WHEN ISNULL([WEDate],'') >= ISNULL([MEDate],'')
THEN
[WEDate]
ELSE
[MEDate]
END
AS MostRecentDate,
[WEDate],
[MEDate]
FROM sTemp
) TMP
ON
TMP.TestID = INV.TestID

GO

DROP TAble stemp

GO

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!