Tuesday, November 29, 2011

Using Try Catch And Exception Handling in Procedures


CREATE PROCEDURE usp_InsertTest            
(                  
 @Name varchar(50),    
 @Add varchar(50),    
 @Sal int ,    
 @ErrMsg varchar(4000) output      
 )                  
AS      
declare @Err varchar(2000)
Begin
 begin try
  begin transaction    
  insert into Tbltest([Name],[Add],Sal) values(@Name,@Add,@Sal)      
  commit transaction  
 end try
 begin catch
  rollback transaction

 end catch  
End

Thursday, November 10, 2011

Difference between Truncate and Delete in SQL

Truncate an Delete both are used to delete data from the table. These both command will only delete data of the specified table, they cannot remove the whole table data structure.Both statements delete the data from the table not the structure of the table.
  • TRUNCATE is a DDL (data definition language) command whereas DELETE is a DML (data manipulation language) command.

  • You can use WHERE clause(conditions) with DELETE but you can't use WHERE clause with TRUNCATE .

  • You cann't rollback data in TRUNCATE but in DELETE you can rollback data.TRUNCATE removes(delete) the record permanently.

  • A trigger doesn’t get fired in case of TRUNCATE whereas Triggers get fired in DELETE command.

  • If tables which are referenced by one or more FOREIGN KEY constraints then TRUNCATE will not work.

  • TRUNCATE resets the Identity counter if there is any identity column present in the table where delete not resets the identity counter.

  • Delete and Truncate both are logged operation.But DELETE is a logged operation on a per row basis and TRUNCATE logs the deallocation of the data pages in which the data exists.

  • TRUNCATE is faster than DELETE.

Difference between Having and Where clause

Where clause can be used with Select, Update and Delete Statement Clause but having clause can be used only with Select statement.
 We can't use aggregate functions in the where clause unless it is in a subquery contained in a HAVING clause whereas we can use aggregate function in Having clause. We can use column name in Having clause but the column must be contained in the group by clause.
Where Clause is used on the individual records whereas Having Clause in conjunction with Group By Clause work on the record sets ( group of records ).
. The WHERE clause selects rows before grouping. The HAVING clause selects rows after grouping.
. The WHERE clause cannot contain aggregate functions. The HAVING clause can contain aggregate functions.

list of differences between SQL Server 2000 , 2005 and 2008

SQL SERVER 2008:
1.Both are combined as SSMS(Sql Server management Studio).
2.XML datatype is used.
3.We can create 2(pow(20))-1 databases.
4.Exception Handling
5.Varchar(Max) data type
6.DDL Triggers
7.DataBase Mirroring
8.RowNumber function for paging
9.Table fragmentation
10.Full Text Search
11.Bulk Copy Update
12.Can encrypt the entire database introduced in 2008.
--check it(http://technet.microsoft.com/en-us/library/cc278098(SQL.100).aspx)
(http://www.sqlservercentral.com/articles/Administration/implementing_efs/870/)
(http://www.kodyaz.com/articles/sql-server-2005-database-encryption-step-by-step.aspx)
(http://www.sql-server-performance.com/articles/dev/encryption_2005_1_p1.aspx)
(http://geekswithblogs.net/chrisfalter/archive/2008/05/08/encrypt-documents-with-sql-server.aspx)
13.Can compress tables and indexes.
-http://www.mssqltips.com/tip.asp?tip=1582
14.Date and time are seperately used for date and time datatype,geospatial and timestamp with internal timezone
is used.
15.Varchar(max) and varbinary(max) is used.
16.Table datatype introduced.
17.SSIS avails in this version.
18.Central Management Server(CMS) is Introduced.
-http://msdn.microsoft.com/en-us/library/bb934126.aspx
-http://www.sqlskills.com/BLOGS/KIMBERLY/post/SQL-Server-2008-Central-Management-Servers-have-you-seen-these.aspx
19.Policy based management(PBM) server is Introduced.
-http://www.mssqltips.com/tip.asp?tip=1492
-http://msdn.microsoft.com/en-us/library/bb510667.aspx















SQL SERVER 2005:

1.Both are combined as SSMS(Sql Server management Studio).
2.XML datatype is introduced.
3.We can create 2(pow(20))-1 databases.
4.Exception Handling
5.Varchar(Max) data type
6.DDL Triggers
7.DataBase Mirroring
8.RowNumber function for paging
9.Table fragmentation
10.Full Text Search
11.Bulk Copy Update
12.Cant encrypt
13.Can Compress tables and indexes.(Introduced in 2005 SP2)
14.Datetime is used for both date and time.
15.Varchar(max) and varbinary(max) is used.
16.No table datatype is included.
17.SSIS is started using.
18.CMS is not available.
19.PBM is not available.



 SQL SERVER 2000:
1.Query Analyser and Enterprise manager are separate.
2.No XML datatype is used.
3.We can create maximum of 65,535 databases.
4.Nill
5.Nill
6.Nill
7.Nill
8.Nill
9.Nill
10.Nill
11.Nill
12.Nill
13.cant compress the tables and indexes.
14.Datetime datatype is used for both date and time.
15.No varchar(max) or varbinary(max) is available.
16.No table datatype is included.
17.No SSIS is included.
18.CMS is not available.
19.PBM is not available









 

Thursday, October 20, 2011

Inserting Multiple records in sql using while loop

CREATE proc usp_InsertMultiple

as      

Declare @UserIdNew int     
Declare @CountTo int=0           
 Declare  @char int   
Declare @userIds VARCHAR(MAX)      
SELECT @userIds = COALESCE(@userIds+',' ,'') +CAST(UserId  as varchar(Max)) from TblUsers       
 Set @userIds=@userIds+','   
SELECT @userIds   
 if(@userIds <>'')       
 begin       
 while(CHARINDEX (',',@userIds)>0)       
 begin    
        set  @char=  CHARINDEX (',',@userIds)   
        print @char   
        set @UserIdNew=LTRIM(RTRIM(substring(@userIds,1,CHARINDEX(',',@userIds)-1)))       
        insert into tbl01 (UserId) values(@UserIdNew)    
        set @userIds=SUBSTRING(@userIds,charindex(',',@userIds)+1,LEN(@userIds))       
        set @CountTo=@CountTo+1         
        set @UserIdNew=''     
 end       
end      
       
      
                          

Thursday, October 13, 2011

Split , seprated strings in SQL

CREATE FUNCTION dbo.Split(@String varchar(8000), @Delimiter char(1))        
   returns @temptable TABLE (items varchar(8000))        
 as        
 begin        
     declare @idx int        
    declare @slice varchar(8000)        
         
       select @idx = 1        
          if len(@String)<1 or @String is null  return        
         
     while @idx!= 0        
     begin        
         set @idx = charindex(@Delimiter,@String)        
         if @idx!=0        
             set @slice = left(@String,@idx - 1)        
        else        
             set @slice = @String        
             
          if(len(@slice)>0)   
            insert into @temptable(Items) values(@slice)        
     
          set @String = right(@String,len(@String) - @idx)        
          if len(@String) = 0 break        
       end    
   return        
   end




/*use this as*/

Select testid,testname from tblKG01 where Company_ID= 93 and KGID in ( select  * from dbo.split(@Ids,',')  ) 

watermark textbox using javascript

Using Java script
  <script language="javascript" type="text/javascript">
        function WaterMark(txtName, event) {
            var defaultText = "Enter Username Here";
            // Condition to check textbox length and event type
            if (txtName.value.length == 0 & event.type == "blur") {
                //if condition true then setting text color and default text in textbox
                txtName.style.color = "Gray";
                txtName.value = defaultText;
            }
            // Condition to check textbox value and event type
            if (txtName.value == defaultText & event.type == "focus") {
                txtName.style.color = "black";
                txtName.value = "";
            }
        }
</script>




 <asp:TextBox ID="txtUserName" runat="server" Text="Enter Username Here" ForeColor="Gray"  onblur =  "WaterMark(this, event);" onfocus = "WaterMark(this, event);" />
                                       

 using AJAX Toolkit Control

 <asp:TextBox ID="txtUserName" runat="server"  ForeColor="Gray"   />
 <cc1:TextBoxWatermarkExtender ID="txt" runat="server" WatermarkText="hii enter here"  TargetControlID="txtUserName"></cc1:TextBoxWatermarkExtender>
                                   

Wednesday, October 12, 2011

Createing a alert Class in asp.net

                                  /*AlertBoxes.cs*/

using System.Web;
using System.Web.UI;

/// <summary>
/// Summary description for AlertBoxes
/// </summary>

namespace alert
{
    public class AlertBoxes
    {
        public static void ShowAlertMessage(string error)
        {
            Page page = HttpContext.Current.Handler as Page;
            if (page != null)
            {
                error = error.Replace("'", "\'");
                ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", "alert('" + error + "');", true);
            }
        }
    }
}




/*use like this*/
                alert.AlertBoxes.ShowAlertMessage("alert");

Tuesday, October 11, 2011

Scrolling title using java script

/* Save this file as abc.js */
msg = " the test site   ";  //title

msg = "" + msg;pos = 0;
function scrollMSG() {
document.title = msg.substring(pos, msg.length) + msg.substring(0, pos);
pos++;
if (pos >  msg.length) pos = 0
window.setTimeout("scrollMSG()",200);
}
scrollMSG();



/*use this on aspx page*/

 <script src="js/abc.js" type="text/javascript"></script>

Inserting Data with xml in sql server

DataSet dsCategories = new DataSet();
 dsCategories = objCompany.GetDefaultData();
 string strCategoryDetails = dsCategories.GetXml();



Create PROCEDURE [dbo].[usp_Testingxml]             
 (                          
  @CategoryDetails nText  
 )                          
                           
AS                          
                          
DECLARE @handle int   
Declare @CompanyId int                          
set @CompanyId = 1                         
   
 
  EXEC sp_xml_preparedocument @handle OUTPUT, @CategoryDetails                      
  Insert into tblCmpcategories(CategoryId,CategoryName,CompanyId)
  SELECT  CategoryId, CatName, @CompanyId FROM                          
  OPENXML (@handle, '/NewDataSet/Table',2)  
  WITH (CategoryId int ,CatName VARCHAR(50) ) --xml fields                         
  EXEC sp_xml_removedocument @handle

--http://msdn.microsoft.com/en-us/magazine/cc163782.aspx

Sunday, October 9, 2011

Cursors Example

SQL Server is very good at handling sets of data. For example, you can use a single UPDATE statement to update many rows of data. There are times when you want to loop through a series of rows a perform processing for each row. In this case you can use a cursor. 
      
CREATE PROCEDURE [dbo].[usp_GetUserLeavesSummaryWithoutCarryOverForReport]          
 (                                                            
 @CompanyId int ,                                                  
 @UserID int        
 )                                                            
AS          
declare @ReportTable table(userid int,LeaveTypeId int,LeaveType varchar(50),LeavesTaken float,UnApproved float,LeavesEntitled float,LeavesPending float,Name varchar(50),DepartmentId int )                  
declare @uservalue int      
declare @uservalues cursor      
      
     
      
begin      
set @uservalues=Cursor for  select TblUsers.UserId  from TblUsers where TblUsers.Company_Id=@CompanyId       
open @uservalues       
fetch next      
from @uservalues into @uservalue      
      
while @@FETCH_STATUS=0      
     
insert into @ReportTable(userid,LeaveTypeId,LeaveType,LeavesTaken,UnApproved,LeavesEntitled,LeavesPending,Name,DepartmentId)                                         
 Select UED.User_ID,UED.LeaveType_ID , LM.LeaveType,                     
     isnull(dbo.[getLeavesCountByUserForReport](LM.LeaveTypeID,@uservalue,@CompanyId,@date),0) as LeavesTaken,                    
                        
     ( select FirstName+' '+SurName from tblUsers where UserID=@uservalue) as Name,      
     ( select Department_Id from tblUsers where UserID=@uservalue) as Departmentid                                                      
      from tblLeaveMaster LM    
      inner join                  
      Tbl_UserLeaveEntitlementDetail UED                     
      on                
     UED.LeaveType_ID=LM.LeaveTypeID                    
     where UED.Company_ID=@CompanyId and UED.User_ID=@uservalue and UED.Entitlement <> 0      
fetch next      
from @uservalues into @uservalue      
end      
close @uservalues      
deallocate @uservalues   
 
  
   
      
         

Friday, October 7, 2011

getting File path in window application for reading xml file

string xmlfileName = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\" + "Orders.xml";
 DataSet dsXml = new DataSet();
 dsXml.ReadXml(xmlfileName);

Page Life Cycle in ASP.NET

When a visitor first requests an .aspx page on your server, the server sends it to the HTTP Pipeline. The HTTP Pipeline handles all processes involved in converting all of the application code into HTML to be interpreted by the browser. The first class initiated is called HttpRuntime. This class finds a free HttpApplication object to start processing the request. The HttpApplication object then runs the appropriate handler assigned in the web.config and machine.config files for the requested extension.
The extension .aspx can be handled by the HandlerClass or HandlerFactory class. The HttpApplication objects starts the IHttpHandler interface which begins processing the application code by calling the processRequest() method.
Need help with Windows Dedicated Hosting? Try Server Intellect. I'm a happy customer!
The processRequest() method then calls the FrameworkInitialize() method which begins building the control trees for the requested page. Now the processRequest() method cycles through the page's life cycle in the order listed below.
Methods Description
Page_Init Page Initialization
LoadViewState View State Loading
LoadPostData Postback Data Processing
Page_Load Page Loading
RaisePostDataChangedEvent PostBack Change Notification
RaisePostBackEvent PostBack Event Handling
Page_PreRender Page Pre Rendering Phase
SaveViewState View State Saving
Page_Render Page Rendering
Page_Unload Page Unloading
The first processed method is Page_Init(). Once the control tree has been created, the controls declared in the .aspx file are initialized. The controls can modify some of the settings set in this method to be used later in the page life cycle. Obviously no other information is available to be modified at this time.
The next processed method is LoadViewState(). The Viewstate contains stored information that is set by the page and controls of the page. This is carried to and from every aspx page request per visitor.


The next processed method is LoadPostData(). These are values associated with the HTML form elements the visitor has typed, changed or selected. Now the control has access to this information which can update their stored information pulled from the Viewstate.
The next processed method is Page_Load(). This method should look familiar and is usually the most common used method on the server side application code for an .aspx file. All code inside of this method is executed once at the beginning of the page.
The next processed method is RaisePostDataChangedEvent(). When a visitor completes a form and presses the submit button, an event is triggered. This change in state signals the page to do something.
The next processed method is RaisePostBackEvent(). This method allows the page to know what event has been triggered and which method to call. If the visitor clicks Button1, then Button1_Click is usually called to perform its function.

The next processed method is Page_PreRender(). This method is the last chance for the Viewstate to be changed based on the PostBackEvent before the page is rendered.
The next processed method is SaveViewState(). This method saves the updated Viewstate to be processed on the next page. The final Viewstate is encoded to the _viewstate hidden field on the page during the page render.
The next processed method is Page_Render(). This method renders all of the application code to be outputted on the page. This action is done with the HtmlWriter object. Each control uses the render method and caches the HTML prior to outputting.
The last processed method is Page_Unload(). During this method, data can be released to free up resources on the server for other processes. Once this method is completed, the HTML is sent to the browser for client side processing.
Now you should have a little bit better understanding of the order of methods executed in the request of an .aspx file.

Caching in asp.net

It is a way to store the frequently used data into the server memory which can be retrieved very quickly. And so provides both scalability and performance. For example if user is required to fetch the same data from database frequently then the resultant data can be stored into the server memory and later retrieved in very less time (better performance). And the same time the application can serve more page request in the same time (scalability).

Caching Options in ASP.NET


ASP.NET supports three types of caching for Web-based applications:
  • Page Level Caching (called Output Caching)
  • Page Fragment Caching (often called Partial-Page Output Caching)
  • Programmatic or Data Caching

Thursday, October 6, 2011

Get value from Rad Combo Box using java script

            var combo = $find("<%= radCombobox11.ClientID %>");
            var deptCode = combo.get_value();    //gets selected value
           combo.disable();                                 // disable combo box
           combo.enable();                                // enable combo box

Wednesday, October 5, 2011

Difference between WEB.CONFIG and APP.CONFIG file


Difference between WEB.CONFIG and APP.CONFIG file


web.config is used with web applications. web.config will by default have several configurations required for the web application. You can have a web.config for each folder under your web application.

app.config is used for windows applications. When you build the application in vs.net, it will be automatically renamed to <appname>.exe.config and this file has to be delivered along with your application.


Difference between Web.config and Machine.config

Scope:
Web.config => For particular application in IIS.
Machine.config = > For All the applications in IIS

Created:
Web.config => Created when you create an application
Machine.config => Create when you install Visual Studio
 
Known as:
Web.config => is known as Application Level configuration file
Machine.config => is known as Machine level configuration file
 
Location:
Web.config => In your application Directory
Machine.config => …\Microsoft.NET\Framework\(Version)\ CONFIG

Access Modifiers (C# Programming Guide)

Default Access modifiers in C#

 An enum has default modifier as public

A class has default modifiers as Internal . It can declare members (methods etc) with following access modifiers:
public
internal
private
protected internal

An interface has default modifier as public

A struct has default modifier as Internal and it can declare its members (methods etc) with following access modifiers:
public
internal
private

A methods, fields, and properties has default access modifier as "Private" if no modifier is specified.


http://www.c-sharpcorner.com/UploadFile/puranindia/WhatareAccessModifiersinCsharp08202009024156AM/WhatareAccessModifiersinCsharp.aspx


http://www.dotnetfunda.com/interview/exam425-default-access-modifiers-in-csharp-.aspx

Difference between method overriding and overloading

Overriding is the concept of having functions of same name and signature in different classes. one in the super class can be made virtual and other can override the functionality of virtual one.

Overloading is the concept of having functions of same name, but different signature in same class. They are differentiated by the compiler by their signatures.

Using overloading and overridding, you can acheive the concept of polymorphism.

Polymorphism means "one name, multiple forms". Using one name u can do multiple of actions...

Method overloading is a compile time polymorphism and Method Overridding is a runtime polymorphism...

Compile time polymorphism means compiler knows which object assigned to which class at the compiling time....Runtime polymorphism means compiler didn't know at the compile time, it only knows at a run time...


When overriding, you change the method behavior for a derived class.
e.g Clas A
{
Virtual void hi(int a)
{
}
}

Class B:A
{
public overrid void hi(int a)
{

}
}

Overloading simply involves having a method with the same name within the class.

Example for Over loading

Class A
{
class a()

{

}
class a(int a)
{
}
}






Difference between stored procedure and functions in SQL Server

1. Functions are compiled and executed at run time.
Stored procedures are stored in parsed and compiled format in the database.

2. Functions cannot affect the state of the database which means we cannot perform insert,delete,update and create operations on the database.
Stored Procedures can affect the state of the database by using insert,delete,update and create operations.

3 Functions are basically used to compute values. We passes some parameters to functions as input and then it performs some operations on the parameter and return output.
Stored procedures are basically used to process the task.
 
 
4 Exception can be handled by try-catch block in a procedure whereas try-catch block cannot be used in a function.

5 We can go for transaction management in procedure whereas we can't go in function.

6.A procedure may modify an object where a function can only return a value The RETURN statement immediately completes the execution of a subprogram and returns control to the caller.

7.Function can take only input aurguments, but procedure may take both input and out put parameters.

8 We can call a function from a procedure, but it is not possible to call a procedure from a function

Friday, September 30, 2011

Creating IP Restriction using asp.net


//IPAddress.csv
"IP Address"
"127.0.0.1"





private void GetIPAddressONFile()
    {
        string SystemIpAddress = "";
        string SystemIpName = "";
     
        SystemIpAddress = Request.UserHostAddress;

        SystemIpName = Request.UserHostName;
        SystemIpAddress = Context.Request.ServerVariables["REMOTE_HOST"];
        string path = Server.MapPath("../IPAddress//IPAddress.csv");
        System.IO.FileInfo file = new FileInfo(path);
        DataSet dsCSV = new DataSet();
        dsCSV = ConnectFile(file);

        //DataColumn tableColumn = dsCSV.Tables[0].Columns["IP Address"];
        DataRowCollection tableRows = dsCSV.Tables[0].Rows;
        int count = 0;
        foreach (DataRow row in tableRows)
        {
            if (row["IP Address"].ToString() == SystemIpAddress)
            {
                count += 1;
            }
        }
        if (count < 1)
            Response.Redirect("~/loginsubmit.aspx?Msg=NA");
    }


 private DataSet ConnectFile(FileInfo filetable)
    {
        DataSet ds = new DataSet();
        string str;
        try
        {
            ConnCSV = ConnCSV + filetable.DirectoryName.ToString();
            string sqlSelect;
            OleDbConnection objOleDBConn;
            OleDbDataAdapter objOleDBDa;
            objOleDBConn = new OleDbConnection(ConnCSV);
            objOleDBConn.Open();
            sqlSelect = "select * from [" + filetable.Name.ToString() + "]";
            objOleDBDa = new OleDbDataAdapter(sqlSelect, objOleDBConn);
            objOleDBDa.Fill(ds);
            objOleDBConn.Close();
        }
        catch (Exception ex)
        {
            str = ex.Message;
        }
        return ds;
    }

Read CSV Files into Dataset using asp.net

set in web.config
<appSettings>
  <add key="connxls" value="Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='text;HDR=Yes;FMT=Delimited';Data Source=" />
</appSettings>


In test.aspx.cs
using System.Data.OleDb;
using System.Collections.Specialized;



protected void Page_Load(object sender, EventArgs e)
    {
NameValueCollection config = (NameValueCollection)ConfigurationSettings.GetConfig("appSettings");
        ConnCSV = config["connxls"];
      

    }

protected void UploadButton_Click(object sender, EventArgs e)
    {
string str=strSavedFilePath;
System.IO.FileInfo file11 = new FileInfo(str);
            DataSet dsCSV = new DataSet();
            dsCSV = ConnectFile(file11);

}
  private DataSet ConnectFile(FileInfo filetable)
    {
        DataSet ds = new DataSet();
        string str;
        try
        {
            ConnCSV = ConnCSV + filetable.DirectoryName.ToString();
            string sqlSelect;
            OleDbConnection objOleDBConn;
            OleDbDataAdapter objOleDBDa;
            objOleDBConn = new OleDbConnection(ConnCSV);
            objOleDBConn.Open();
            sqlSelect = "select * from [" + filetable.Name.ToString() + "]";
            objOleDBDa = new OleDbDataAdapter(sqlSelect, objOleDBConn);
            objOleDBDa.Fill(ds);
            objOleDBConn.Close();
        }
        catch (Exception ex)
        {
            str = ex.Message;
        }
        return ds;
    }






For getting Last modified procedures

SELECT name, create_date, modify_date
FROM sys.objects
WHERE type = 'P' order by modify_date desc

Thursday, September 29, 2011

Using CheckBox List Asp.net

In aspx file
 <asp:CheckBoxList ID="chkModuleList" runat="server">
 <asp:ListItem Text="Test 1" Value="1"></asp:ListItem>
 <asp:ListItem Text="Test 2" Value="2"></asp:ListItem>
 <asp:ListItem Text="Test 3" Value="3"></asp:ListItem>
  <asp:ListItem Text="Test 4" Value="4"></asp:ListItem>
  </asp:CheckBoxList>

In aspx.cs file
 for (int i = 0; i <chkModuleList.Items.Count; i++)
        {
string strtest = Convert.ToString(chkModuleList.Items[i].Selected);
//string strtest = Convert.ToString(chkModuleList.Items[i].Value);
//string strtest = Convert.ToString(chkModuleList.Items[i].Text); 
}

Wednesday, September 28, 2011

Check Uncheck radio button with java script

  <script language="javascript" type="text/javascript">
   function CheckUncheckRadio(id) {
            var val;
            var rdo = document.getElementById(id)
            var radio = rdo.getElementsByTagName("input");
            if (radio.checked == true) {

                radio.checked = false;
                val = 0;
            }
            else {

                radio.checked = true;
                val = 1;
            }

            if (val == 0) {
                rdo.checked = false;
            }
            else {
                rdo.checked = true;
            }
        }

    </script>





 <asp:RadioButton ID="rbExpenseCost" runat="server" Text="1" onclick="CheckUncheckRadio('rbExpenseCost');"/>

<asp:RadioButton ID="rbLeaveCost" runat="server"  Text="2" onclick="CheckUncheckRadio('rbLeaveCost');" />
                                                 












Concating two #eval for a label in grid view

  <ItemTemplate>
  <asp:Label ID="totalApprovals" runat="server" ForeColor="#fe9a00" Text='<%#Eval("TotalApprovals")+" "+"Pending"%>'></asp:Label>
  </ItemTemplate>

Tuesday, September 27, 2011

Alert message on hyper link click

 <a href="#" onclick='alert("hiii");return false;'  >Click Here</a>
or
<a href='javascript:alert("hello")'>hello</a>
 
For Confirmation box 
 OnClientClick="return confirm('Are you sure, you want to delete.');"  




Monday, September 26, 2011

Executing .bat files on button click asp.net

 protected void btn_Click(object sender, EventArgs e) 
{
   ProcessStartInfo psi = new ProcessStartInfo(@"C:\bank.bat");
          psi.RedirectStandardOutput = true;
          psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
          psi.UseShellExecute = false;
          System.Diagnostics.Process listFiles;
          listFiles = System.Diagnostics.Process.Start(psi);
          System.IO.StreamReader myOutput = listFiles.StandardOutput;
          listFiles.WaitForExit(2000);
}




//bat file code

@echo off
cd\
c:


start iexplore.exe www.google.com

Binding Grid View,Drop down with in grid view from aspx page

//Drop Down In Item template
//Test .aspx
<asp:DropDownList ID="ddlCreditClient" runat="server" Visible="true" DataSource='<%#BindCreditClient()%>'    DataTextField="CName" DataValueField="ClientId">

//Test.aspx.cs
protected DataTable BindCreditClient()
    {
        DataTable dt = new DataTable();
        //bind data table here
        return dt;
    }


 //Data List  in Item template
//Test.aspx
 <asp:DataList ID="DlInnerWorkFlow" runat="server" RepeatDirection="Horizontal" DataSource='<%#getWorkFlowForm(Convert.ToInt32(Eval("FormId")),(Convert.ToInt32(Eval("DepartmentID"))))%>'>
 <ItemTemplate>
 <asp:Label ID="lblUserName" runat="server" BorderStyle="None" Text='<%#Eval("FirstName")%>'></asp:Label>
</ItemTemplate>
 <SeparatorTemplate>
 <asp:Image ID="imgarrow" runat="server" ImageAlign="Bottom" BorderStyle="None" ImageUrl="~/images/btn-arrow_right_Gray.gif" />
 </SeparatorTemplate>
 </asp:DataList>


//Test.aspx.cs

  public DataTable getWorkFlowForm(int FormId, int DepartmentId)
    {
      
        DataTable dt = new DataTable();
      //bind datatable here
          
        return dt;
    }



Telerik Controls Help Urls

//link for implementing google like filetring in telerik grid view
http://demos.telerik.com/aspnet-ajax/controls/examples/integration/gridandcombo/defaultcs.aspx

//File upload control , Upload / Client-side Validation 

http://demos.telerik.com/aspnet-ajax/upload/examples/clientsidevalidation/defaultcs.aspx?RadUrid=af0a12bf-569e-4359-b73b-4116b5daa247 

//Filtering in ComboBox / Autocomplete 

http://demos.telerik.com/aspnet-ajax/combobox/examples/functionality/autocompleteclientside/defaultcs.aspx

 //Tool tips Help

http://demos.telerik.com/aspnet-ajax/tooltip/examples/waiariasupport/defaultcs.aspx

 //Tabbed grid in telerik

http://demos.telerik.com/aspnet-ajax/grid/examples/hierarchy/nestedviewtemplate/defaultcs.aspx

//Calender Control,ToolTip / RadToolTip for RadCalendar 

http://demos.telerik.com/aspnet-ajax/tooltip/examples/tooltipcalendar/defaultcs.aspx

//BUG: ASyncFileUpload javascript error affects Firefox 4+ with Upate Panel and Update Progress
http://ajaxcontroltoolkit.codeplex.com/workitem/26932

//Tips for avoiding Spam Filters with System.Net.Mail

 http://www.andreas-kraus.net/blog/tips-for-avoiding-spam-filters-with-systemnetmail/








Creating Google Map with multiple way points and draggable directions using asp.net and java script

//This code is for Creating Google Map with multiple way points and draggable directions using asp.net and java script. Please set design according to your css//

<head id="Head1" runat="server">
     <title>Calculate distance</title>
 
    <script src="http://maps.google.com/maps/api/js?sensor=false&amp;key=ABQIAAAAJBjl1Th9QFwMQaJjFDBKahS_UYXK4NsaVm1AC7JD1mYvEQ3NmBRS7MuG9QhvC79P5JUmScpoMMAI8Q"
        type="text/javascript"></script>

    <script type="text/javascript">

        function showInformation() {
            var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
            var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
            document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + location1.address + ' (' + location1.lat + ':' + location1.lon + ')<br /><strong>Address 2: </strong>' + location2.address + ' (' + location2.lat + ':' + location2.lon + ')<br /><strong>Calculate Distance: </strong>' + drivingDistanceMiles + ' miles (or ' + document.getElementById('txtDistance').value + ' kilometers)';
        }

        function showLocation() {
            geocoder.getLocations(document.forms[0].fromAddress.value, function(response) {
                if (!response || response.Status.code != 200) {
                    alert("Sorry, we were unable to geocode the first address");
                }
                else {
                    location1 = { lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address };
                    geocoder.getLocations(document.forms[0].toAddress.value, function(response) {
                        if (!response || response.Status.code != 200) {
                            alert("Sorry, we were unable to geocode the second address");
                        }
                        else {
                            location2 = { lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address };
                            gDir.load('from: ' + location1.address + ' to: ' + location2.address);
                        }
                    });
                }
            });
        }



        var finalToAddress = "";
        var address = 'India'; //Default map location on page load
        var rendererOptions = {
            draggable: true
        };
        var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
        var directionsService = new google.maps.DirectionsService();
        var map;
        var mygc = new google.maps.Geocoder();
        mygc.geocode({ 'address': address },

         function(results, status) {
             var country1 = results[0].geometry.location.lat();
             var country2 = results[0].geometry.location.lng();
             var australia = new google.maps.LatLng(country1, country2);
             initialize(australia);
         }
        );

        function initialize(australia) {
            var myOptions =
    {
        zoom: 7,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: australia
    };
            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            directionsDisplay.setMap(map);
            directionsDisplay.setPanel(document.getElementById("directionsPanel"));
            google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {


                computeTotalDistance(directionsDisplay.directions);
            });
            calcRoute();

        }

        function calcRoute(fromAddress, toAddress) {
            var items = new Array();
            for (var i = 1; i <= textboxes; i++) {
                items[(i - 1)] = document.getElementById(i.toString()).value;
            }
            var waypoints = [];
            var address;
            address = document.getElementById('toAddress').value;

            if (items.length > 0) {
                waypoints.push({
                    location: address,
                    stopover: true
                })
            };

            for (var i = 0; i < items.length - 1; i++) {
                address = items[i];
                if (address !== "") {

                    waypoints.push({
                        location: address,
                        stopover: true
                    });
                }
            }

            var toAddress1 = "";

            if (waypoints.length != 0) {
                toAddress1 = document.getElementById((waypoints.length).toString()).value;
                finalToAddress = document.getElementById((waypoints.length).toString()).value;

            }
            else {
                toAddress1 = document.getElementById('toAddress').value;
                finalToAddress = document.getElementById('toAddress').value;


            }


            var request = {
                origin: fromAddress,
                destination: toAddress1,

                waypoints: waypoints,

                optimizeWaypoints: false,

                travelMode: google.maps.DirectionsTravelMode.DRIVING
            };

            directionsService.route(request, function(response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setDirections(response);
                }
            });
        }

        function computeTotalDistance(result) {
            var total = 0;

            var myroute = result.routes[0];

            for (i = 0; i < myroute.legs.length; i++) {
                total += myroute.legs[i].distance.value;

            }

            total = parseFloat(Math.round((total / 1000) * 100) / 100);
            var measurUnit = 'KM'; //set unit of distance according to you
            if (measurUnit == "KM") {
                document.getElementById('txtDistance').value = total;
                document.getElementById('lblType').innerHTML = "KM";
            }
            else {
                document.getElementById('txtDistance').value = parseFloat(Math.round(((total * 1000) / 1609.344) * 100) / 100);
                document.getElementById('lblType').innerHTML = "Miles";
            }
        }
        function setDirections(fromAddress, toAddress) {
            calcRoute(fromAddress, toAddress);
        }


        /*Functions for adding and removing text boxes*/
        var intTextBox = 0;
        var textboxes = 0;

        function addElement() {
            intTextBox = intTextBox + 1;
            var contentID = document.getElementById('content');
            var newTBDiv = document.createElement('div');
            newTBDiv.setAttribute('id', 'strText' + intTextBox);
            newTBDiv.innerHTML = String.fromCharCode(64 + (intTextBox + 2)) + ' :' + "<input style='margin-top:5px;margin-left:30px;' class='txt3_double' type='text' id='" + intTextBox + "' name='" + intTextBox + "'/>";
            contentID.appendChild(newTBDiv);
            textboxes = intTextBox;
        }


        function removeElement() {
            if (intTextBox != 0) {
                var contentID = document.getElementById('content');
                contentID.removeChild(document.getElementById('strText' + intTextBox));
                intTextBox = intTextBox - 1;
                textboxes = intTextBox;
            }
        }
                
      
        
        
    </script>

</head>
<body onload="initialize()">
    <form id="Form1" runat="server" action="#" onsubmit="setDirections(this.from.value, this.to.value);return false "
    style="margin-left: 20px; text-align: center; overflow: hidden;">
    <div style="min-height: 325px; min-width: 500px; overflow: hidden; vertical-align: middle;">
        <div>
            <div>
                <b>Calculate Distance</b></div>
            <div>
                <div>
                    A :
                    <div>
                        <input type="text" size="25" id="fromAddress" name="from" />
                        <asp:HiddenField ID="hdnDefault" runat="server" />
                    </div>
                </div>
                <div>
                    <div>
                        B :
                        <div>
                            <input type="text" size="25" id="toAddress" name="to" class="txt3_double" />
                        </div>
                        <div>
                        </div>
                        <div id="content">
                        </div>
                    </div>
                    <div>
                        <div>
                            <div>
                                <a href="javascript:addElement();">Add Destination</a> <a href="javascript:removeElement();">
                                    Remove</a>
                            </div>
                        </div>
                        <div>
                            Distance:
                            <div class="nameValueBox fl ">
                                <asp:TextBox ID="txtDistance" runat="server" Enabled="false" CssClass="txt3_double"></asp:TextBox>
                                <asp:Label ID="lblType" runat="server" Text=""></asp:Label>
                            </div>
                        </div>
                        <div>
                            <div>
                                <asp:Button ID="ibtnCalculate" runat="server" Text="Calculate" />
                                <asp:Button ID="ibtnDone" runat="server" Text="Insert" OnClientClick="returnToParent()" />
                            </div>
                        </div>
                        <div>
                            <div id="map_canvas" style="width: 430px; height: 450px; margin-right: 10px;">
                            </div>
                        </div>
                        <div>
                            <p id="results">
                            </p>
                        </div>
                    </div>
                    <div id="directionsPanel" style="text-align: right; vertical-align: top;">
                        <p>
                            <span id="total"></span>
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </form>
    <br />
</body>




Executing a utility using Command Line Mode asp.net

This is the code for executing commands using asp.net
 protected void btn_Click(object sender, EventArgs e)
    {

 ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe");
 processStartInfo.RedirectStandardInput = true;
 processStartInfo.RedirectStandardOutput = true;
 processStartInfo.UseShellExecute = false;
 processStartInfo.RedirectStandardError = true; 
 Process process = Process.Start(processStartInfo);
    if (process != null)
        {
       process.StandardInput.WriteLine("Cd\\");
       //renaming a file
       process.StandardInput.WriteLine("ren data.ofx abc1234.txt");

      //creating directory
      process.StandardInput.WriteLine("mkdir testDir");
   
    //executing utility
   process.StandardInput.WriteLine("bank2csv_pro.exe data.qbo output123.CSV");
     process.StandardInput.Close();
   // display the commands
     string outputString = process.StandardOutput.ReadToEnd();
     Response.Write(outputString);
    // display the errors coming in execution
     string error = process.StandardError.ReadToEnd();
      Response.Write(error);

         }
}





Monday, January 24, 2011

default ADO.net provider

 no default provider

difference between ADO.NET and ADO

difference between ADO.NET and ADO

    * Recordset and Dataset
    * Disconnected Architecture
    * Lock Types

Saturday, January 22, 2011

How to describe view in sql server?

To Describe View Structure:
sp_help   ViewNameByDP




To Describe View Definition:
sp_helptext   ViewNameByDP

Can a page have multiple master pages?

No.



A single page cannot inherit two different master pages, but you can use nested master pages.