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