Monday, December 31, 2012

Overview about Assemblies


Assembly

    Assemblies are the building blocks of .NET Framework applications;
    they form the fundamental unit of deployment, version control,
    reuse, activation scoping, and security permissions.
   
    An assembly is a collection of types and resources
    that are built to work together and form a logical
    unit of functionality. An assembly provides
    the common language runtime with the information
    it needs to be aware of type implementations.
    To the runtime, a type does not exist outside
    the context of an assembly.


Assembly Benefits

    Assemblies are designed to simplify application deployment
    and to solve versioning problems that can occur with component-based applications.
    End users and developers are familiar with versioning
    and deployment issues that arise from todays component-based systems.
    Some end users have experienced the frustration of installing a new
    application on their computer, only to find that an existing application
    has suddenly stopped working. Many developers have spent countless hours trying to keep
    all necessary registry entries consistent in order to activate a COM class.
    Many deployment problems have been solved by the use of assemblies in the .NET Framework.
    Because they are self-describing components that have no dependencies 
    on registry entries, assemblies enable zero-impact application installation.
    They also simplify uninstalling and replicating applications.


Versioning Problems

Currently two versioning problems occur with Win32 applications:

a.
    Versioning rules cannot be expressed between pieces of an application
    and enforced by the operating system. The current approach relies 
    on backward compatibility, which is often difficult to guarantee.
    Interface definitions must be static, once published, and a single
    piece of code must maintain backward compatibility with previous versions.
    Furthermore, code is typically designed so that
    only a single version of it can be present and executing on a computer at any given time.

b.
    There is no way to maintain consistency between sets of components 
    that are built together and the set that is present at run time.

    These two versioning problems combine to create DLL conflicts,
    where installing one application can inadvertently break an existing
    application because a certain software component or DLL was installed
    that was not fully backward compatible with a previous version.
    Once this situation occurs, there is no support in the system for
    diagnosing and fixing the problem.

The Assembly Solution
   
    To solve versioning problems, as well as the remaining problems that
    lead to DLL conflicts, the runtime uses assemblies to do the following:
    Enable developers to specify version rules between different software components.
    Provide the infrastructure to enforce versioning rules.
    Provide the infrastructure to allow multiple versions
    of a component to be run simultaneously (called side-by-side execution).


Assembly Contents

Tuesday, September 11, 2012

Drop down list binding with selected index true during row editing of grid view / Data grid

<asp:TemplateColumn HeaderText="Role">
<ItemStyle Wrap="False" BorderWidth="1px"></ItemStyle>
<ItemTemplate>
<asp:Label ID="lblRoleName" runat="server" Text='<%# Eval("RoleName") %>'></asp:Label>
</ItemTemplate>
<FooterStyle HorizontalAlign="Center"></FooterStyle>
<FooterTemplate>
<asp:DropDownList ID="add_RoleName" runat="server" DataSource='<%# getdata("PR_SelectRoleMaster") %>'
DataTextField="RoleName" DataValueField="RoleId">
</asp:DropDownList>
<font size="1" color="red">*</font>
</FooterTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlRoleName" runat="server" OnPreRender="SetDropDownIndex"
DataSource='<%# getdata("PR_SelectRoleMaster") %>' DataTextField="RoleName" DataValueField="RoleId">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateColumn>

string strMemberRoleName = string.Empty, strRemarkFrequency = string.Empty, strRemarksSelectionType = string.Empty;
    string strRemarksClassName = string.Empty;


In CS page

  public void SetDropDownIndex(object sender, System.EventArgs e)
    {
        System.Web.UI.WebControls.DropDownList ed;
        ed = (System.Web.UI.WebControls.DropDownList)sender;
        ed.SelectedIndex = -1;
        ed.SelectedIndex = ed.Items.IndexOf(ed.Items.FindByText(strMemberRoleName));
    }


  protected void DataGridRemarkMaster_EditCommand(object source, DataGridCommandEventArgs e)
    {
        lblRemarkMasterMsg.Text = "";
        DataGridRemarkMaster.ShowFooter = false;
        DataGridRemarkMaster.EditItemIndex = e.Item.ItemIndex;

        strMemberRoleName = ((Label)e.Item.FindControl("lblRoleName")).Text.Trim();
        strRemarkFrequency = ((Label)e.Item.FindControl("lblRemarkFrequency")).Text.Trim();
        strRemarksSelectionType = ((Label)e.Item.FindControl("lblRemarkType")).Text.Trim();
        strRemarksClassName = ((Label)e.Item.FindControl("lblClassName")).Text.Trim();

 }


Friday, September 7, 2012

How to check checkbox in gridview in asp.net using jquery

<asp:GridView runat="server" CssClass="dataGridId" ID="gvCategorySms" DataKeyNames="MemberId"
                AutoGenerateColumns="false" CellPadding="3">
                <AlternatingRowStyle CssClass="dataGridItemId" />
                <HeaderStyle Wrap="False" HorizontalAlign="Left" CssClass="dataGridHeaderId" />
                <FooterStyle HorizontalAlign="Justify" CssClass="dataGridFooterId" />
                <RowStyle CssClass="dataGridAlternatingItemId" />
                <Columns>
                    <asp:TemplateField HeaderText="S.No">
                        <ItemTemplate>
                            <%#Container.DataItemIndex+1 %>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Student Name">
                        <ItemStyle Wrap="false" />
                        <ItemTemplate>
                            <asp:HiddenField Value='<%#Eval("MemberId")%>' runat="server" ID="hfMemberId" />
                            <asp:Label runat="server" ID="lblFullName" Text='<%#Eval("FullName") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Class Name">
                        <ItemStyle Wrap="false" />
                        <ItemTemplate>
                            <asp:Label runat="server" ID="lblFullClassName" Text='<%#Eval("FullClassName") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Roll Number">
                        <ItemStyle Wrap="false" />
                        <ItemTemplate>
                            <asp:Label runat="server" ID="lblRollNumber" Text='<%#Eval("RollNumber") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Mobile Number">
                        <ItemStyle Wrap="false" />
                        <ItemTemplate>
                            <asp:Label runat="server" ID="lblMobileNumber" Text='<%#Eval("MobileNumber") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField ItemStyle-HorizontalAlign="Center">
                        <HeaderTemplate>
                            Select All
                            <input id="chkSelAll" type="checkbox" runat="server" /></HeaderTemplate>
                        <ItemTemplate>
                            <asp:CheckBox ID="chkSel" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
                <AlternatingRowStyle BackColor="#E8E8E8 " ForeColor="#333333" />
            </asp:GridView>



<script type="text/javascript" src="../../Resources/JQuery/jquery-1.4.1.min.js"></script>


<script language="javascript" type="text/javascript">
         $(document).ready(function() {
           
            
             //gridview checkbox
            var chkBox = $("input[id$='gvCategorySms_ctl01_chkSelAll']");
            chkBox.click(function() {
                $("#gvCategorySms INPUT[type='checkbox']").attr('checked', chkBox.is(':checked'));
            });

            // To deselect CheckAll when a GridView CheckBox is unchecked
            $("#gvCategorySms INPUT[type='checkbox']").click(function(e) {
                if (!$(this)[0].checked) {
                    chkBox.attr("checked", false);
                   
                }
            });
                      
           
             $("#btnSubmit").click(function() {
             // Check for text box is Blank or not
             if ($("#txtDetails").val()=="")
             {
                 alert('Please enter sms content');
                 return false;
             }
            
             var countCheckBox=0
              $("#gvCategorySms INPUT[type='checkbox']").each(function(){
               if ($(this)[0].checked)
                 {
                    countCheckBox=1;
                 }
                
              });
             
               if(countCheckBox==0)
               {
                  alert("Please check at least one or more record(s)");
                return false;
                }
             });
           

           
                var textMaxLength = 200;
       // Start checking sms content
            $("#txtDetails").keyup(function(e) {
            $("#lblDetailsMax").text("[" + (textMaxLength-($(this).val().length)) + " characters left]");
                if ($(this).val().length > textMaxLength) {
                     alert('SMS Content '+ textMaxLength + " characters")
                    $(this).focus();
                    return false;
                    }
                });
        });
</script>

Wednesday, August 15, 2012

What is the maximum number of Index per table?

What is the maximum number of Index per table? 

For SQL Server 2005:
1 Clustered Index + 249 Nonclustered Index = 250 Index
http://msdn.microsoft.com/en-us/library/ms143432(SQL.90).aspx

For SQL Server 2008:
1 Clustered Index + 999 Nonclustered Index = 1000 Index
http://msdn.microsoft.com/en-us/library/ms143432.aspx  



The following table specifies the maximum sizes and numbers of various objects defined in SQL Server 2005 databases or referenced in Transact-SQL statements. The table does not include SQL Server Windows CE Edition.
SQL Server 2005 Database Engine object Maximum sizes/numbers SQL Server 2005 (32-bit) Maximum sizes/numbers SQL Server 2005 (64-bit)
Batch size1
65,536 * Network Packet Size
65,536 * Network Packet Size
Bytes per short string column
8,000
8,000
Bytes per GROUP BY, ORDER BY
8,060
8,060
Bytes per index key2
900
900
Bytes per foreign key
900
900
Bytes per primary key
900
900
Bytes per row8
8,060
8,060
Bytes per varchar(max), varbinary(max), xml, text, or image column
2^31-1
2^31-1
Characters per ntext or nvarchar(max) column
2^30-1
2^30-1
Clustered indexes per table
1
1
Columns in GROUP BY, ORDER BY
Limited only by number of bytes
Limited only by number of bytes
Columns or expressions in a GROUP BY WITH CUBE or WITH ROLLUP statement
10
10
Columns per index key7
16
16
Columns per foreign key
16
16
Columns per primary key
16
16
Columns per base table
1,024
1,024
Columns per SELECT statement
4,096
4,096
Columns per INSERT statement
1,024
1,024
Connections per client
Maximum value of configured connections
Maximum value of configured connections
Database size
524,258 terabytes
524,258 terabytes
Databases per instance of SQL Server
32,767
32,767
Filegroups per database
32,767
32,767
Files per database
32,767
32,767
File size (data)
16 terabytes
16 terabytes
File size (log)
2 terabytes
2 terabytes
Foreign key table references per table4
253
253
Identifier length (in characters)
128
128
Instances per computer
50 instances on a stand-alone server for all SQL Server 2005 editions except for Workgroup Edition. Workgroup Edition supports a maximum of 16 instances.
SQL Server 2005 supports 25 instances on a failover cluster.
50 instances on a stand-alone server.
25 instances on a failover cluster.
Length of a string containing SQL statements (batch size)1
65,536 * Network packet size
65,536 * Network packet size
Locks per connection
Maximum locks per server
Maximum locks per server
Locks per instance of SQL Server5
Up to 2,147,483,647
Limited only by memory
Nested stored procedure levels6
32
32
Nested subqueries
32
32
Nested trigger levels
32
32
Nonclustered indexes per table
249
249
Parameters per stored procedure
2,100
2,100
Parameters per user-defined function
2,100
2,100
REFERENCES per table
253
253
Rows per table
Limited by available storage
Limited by available storage
Tables per database3
Limited by number of objects in a database
Limited by number of objects in a database
Partitions per partitioned table or index
1,000
1,000
Statistics on non-indexed columns
2,000
2,000
Tables per SELECT statement
256
256
Triggers per table3
Limited by number of objects in a database
Limited by number of objects in a database
UNIQUE indexes or constraints per table
249 nonclustered and 1 clustered
249 nonclustered and 1 clustered
User connections
32,767
32,767
XML indexes
249
249



Thanks 
Alok Kumar sharm

Monday, July 23, 2012

SQL Functions – STUFF() and REPLACE()


SQL Functions – STUFF() and REPLACE()

STUFF() can be used to stuff a string into another string. It inserts the string at a given position, and deletes the number of characters specified from the original string.





DECLARE @string1 VARCHAR(20) = 'Microsoft Server'

DECLARE @string2 VARCHAR(20) = 'SQL Server 2005'



SELECT      @string1 + ' -> ' + STUFF(@string1, 11, 0, 'SQL ')

            AS 'String 1',

            @string2 + ' -> ' + STUFF(@string2, 15, 1, '8 R2')

            AS 'String 2'

Result Set:

String 1                                 String 2

—————————————- ————————————-

Microsoft Server -> Microsoft SQL Server SQL Server 2005 -> SQL Server 2008 R2



(1 row(s) affected)

In the first string it inserts 'SQL ' at specified position – 11, the third argument 0 indicated the number of characters to be deleted before inserting the new string.

For second string, we have deleted one (1) character starting from position 15, which deletes '5', and then it inserts the new string at position 15 – '8 R2'.



REPLACE():

REPLACE() replaces all the specified characters with new characters.

DECLARE @string3 VARCHAR(35) = 'sql 2005, sql 2008, sql 2008 r2'



SELECT @string3, REPLACE(@string3,'sql','SQL')

Result Set:

———————————–      ———————————–

sql 2005, sql 2008, sql 2008 r2   SQL 2005, SQL 2008, SQL 2008 r2



(1 row(s) affected)

However, it is not limited to same number of characters:

DECLARE @string3 VARCHAR(35) = '2008 R2'



SELECT @string3, REPLACE(@string3,'20','SQL Server 2')

Result Set:

————–       ————————

2008 R2              SQL Server 208 R2



(1 row(s) affected)

Hope This Helps!

Saturday, July 7, 2012

SYSDATETIME versus GETDATE

In SQL Server 2005 (and previous versions) one would use GETDATE() to get the current date and time. In SQL Server 2008 this is still possible, but one can also use SYSDATETIME(). So what is exactly the difference?

The function GETDATE() returns the seconds part of the time in three fractions. The function SYSDATETIME() however returns the seconds part of the time in seven fractions. This is demonstrated in the following example:


select 'The current date and time is: ' , GETDATE()

select 'The current date and time is: ' , SYSDATETIME()

The current date and time is:  2008-08-21 16:28:50.340
The current date and time is:  2008-08-21 16:28:50.3406250
 
Thanks 
Alok Kumar Sharma 
 

DATETIME2 vs DATETIME in SQL Server 2008


DATETIME2 vs DATETIME in SQL Server 2008
The DATETIME2 is a new data type in SQL Server 2008.
We all know of the existence of the DATETIME.

So, what is the difference between these two data types?

Let's try to compare them with some examples.

--Comparison 1: Notice the date - Both data types work fine
select cast('1753-01-01 18:00:00.123' as DATETIME) as [datetime]
Result (Success): 1753-01-01 18:00:00.123

select cast('1753-01-01 18:00:00.123' as DATETIME2) as [datetime2]
Result (Success): 1753-01-01 18:00:00.1230000

Comments: Please note the precision of the DATETIME2. It provides support up to nanoseconds!


--Comparison 2: Notice the time precision
select cast('1753-01-01 18:00:00.1234' as DATETIME) as [datetime]
Result (Error): Conversion failed when converting date and/or time from character string

select cast('1753-01-01 18:00:00.1234' as DATETIME2) as [datetime2]
Result (Success): 1753-01-01 18:00:00.1234000

Comments: DATΕTIME does not support time precision more than milliseconds and that's why the above conversion fails. Though, the DATETIME2 supports up to nanoseconds and the conversion works.


--Comparison 3: Notice the date values
select cast('1653-01-01 18:00:00.123' as DATETIME) as [datetime]
Result (Error): The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

select cast('1653-01-01 18:00:00.123' as DATETIME2) as [datetime]
Result (Success): 1653-01-01 18:00:00.1230000

Comments: DATΕTIME does not support date values before the year 1753 and that's why the conversion fails. Though, DATETIME2 supports until back to year 0001 and so the conversion works.

Conclusions: The DATETIME2 offers support for larger date ranges and larger time precision.


DATETIME: Date and Time Ranges
------------------------------------
The supported date range is:1753-01-01 through 9999-12-31 (January 1, 1753, AD through December 31, 9999 AD)

The supported time range is: 00:00:00 through 23:59:59.997


DATETIME2: Date and Time Ranges
-------------------------------------
The supported date range is: 0001-01-01 through 9999-12-31 (January 1,1 AD through December 31, 9999 AD)

The Supported time range is: 00:00:00 through 23:59:59.9999999


Thanks
Alok Kumar Sharma

Getting Age in Text or Date Difference in text format

/*----------------------------------------------------------------------------------------------------------------------------
  Author     :-    Alok Kumar Sharma
  Purpose    :-    To find the datediff/age in text format (eg. 1 year(s), 10 month(s), 10 day(s)).              
  DATE        :-   07-July-2012
  DATABASE    :-     SQL

----------------------------------------------------------------------------------------------------------------------------*/
IF (Select COUNT(*) From Sysobjects Where [name] like 'FN_GETDATEDIFFTEXT') > 0
BEGIN
    DROP FUNCTION FN_GETDATEDIFFTEXT
END
GO
CREATE FUNCTION FN_GETDATEDIFFTEXT(@FromDate DateTime, @ToDate DateTime)
RETURNS NVARCHAR(50)
AS
BEGIN  

    Declare @daysDiff Int
    Declare @monthDiff Int
    Declare @yearDiff Int

    --Select @daysDiff = DATEDIFF(DAY, @FromDate, @ToDate)
    Set @monthDiff = ABS(DATEDIFF(MONTH, @FromDate, @ToDate)%12)
    Set @yearDiff = ABS(DATEDIFF(YYYY, @FromDate, @ToDate))

    -- If the From date month is greater than the month of the To date and the year difference is greater than zero
    -- then the year should the deducted by one
    IF DATEPART(MONTH,@FromDate) > DATEPART(MONTH,@ToDate) AND @yearDiff > 0
    BEGIN
        Set @yearDiff = @yearDiff - 1
    END

    IF DATEPART(DAY,@FromDate) > DATEPART(DAY, @ToDate)
    Begin
        --Get last date of the month of the FromDate
        Declare @lastDateOfMonth DateTime = DATEADD(MONTH, 1, @FromDate)  
        Set @lastDateOfMonth = '01-' + DATENAME(MONTH,@lastDateOfMonth) + '-'+DATENAME(YEAR,@lastDateOfMonth)
        Set @lastDateOfMonth = DATEADD(DAY, -1, @lastDateOfMonth)
      
        Set @daysDiff = DATEDIFF(DAY, @FromDate, @lastDateOfMonth)
        Set @daysDiff = @daysDiff + DATEPART(DAY, @ToDate)
        Set @monthDiff = @monthDiff - 1
    End
    ELSE
    BEGIN
        Set @daysDiff = DATEPART(DAY, @ToDate) - DATEPART(DAY, @FromDate)
    END

    -- Select @yearDiff Yr, @monthDiff Mn, @daysDiff Dy
    RETURN
        CAST(@yearDiff as nvarchar) + ' year(s), ' +
        CAST(@monthDiff as  nvarchar) + ' month(s), ' +
        CAST(@daysDiff as nvarchar) + ' day(s)'
END
GO

-- Select DBO.FN_GETDATEDIFFTEXT('30-Dec-2010', '31-Jan-2011')
-- Select DBO.FN_GETDATEDIFFTEXT('01-Jan-1990', Getdate())

Check IsAlphaNumeric In SQL Server

CREATE FUNCTION dbo.IsAlphaNumeric
(@input varchar(100))
RETURNS bit
AS
BEGIN

declare @i int, @max int, @c varchar(1), @asc int

declare @isAN bit

set @max = LEN(@input)

set @isAN= 1
set @i = 0
while @i < @max begin
    set @i = @i + 1
    set @c = SUBSTRING(@input,@i,1)
    set @asc = ascii(@c)
    set @isAN =
        case when @asc between 48 and 57 then 1 -- 0 9
        when @asc between 65 and 90 then 1 -- A Z
        when @asc between 97 and 122 then 1 -- a z
        when @asc = 32 then 1 --space
        else 0
        end
        
    if @isAN = 0 begin
        return @isAN --not alpha
    end


end
return @isAN -- is alpha

END

Friday, July 6, 2012

Selecting item from ASP.NET listbox using jquery

 $("#btnSave").click(function() {

 var varClassID="";
                $('#ddlChildClass :selected').each(function(i, selected){
               if(varClassID=="")
                    varClassID=$(selected).val();
               else
                    varClassID=varClassID+","+$(selected).val();
                 });

}

====================================


<asp:ListBox ID="ddlChildClass" runat="server" SelectionMode="Multiple">
                    </asp:ListBox>


<input id="btnSave" type="button" value="Save" class="buttonId" runat="server" />

Thursday, May 17, 2012

ASP.NET Application and Page Life Cycle

The Two Step Process

From 30,000 feet level, ASP.NET request processing is a 2 step process as shown below. User sends a request to the IIS:
  • ASP.NET creates an environment which can process the request. In other words, it creates the application object, request, response and context objects to process the request.
  • Once the environment is created, the request is processed through a series of events which is processed by using modules, handlers and page objects. To keep it short, let's name this step as MHPM (Module, handler, page and Module event), we will come to details later.





In the coming sections, we will understand both these main steps in more detail.

Creation of ASP.NET Environment

Step 1: The user sends a request to IIS. IIS first checks which ISAPI extension can serve this request. Depending on file extension the request is processed. For instance, if the page is an ‘.ASPX page’, then it will be passed to ‘aspnet_isapi.dll’ for processing.

Step 2: If this is the first request to the website, then a class called as ‘ApplicationManager’ creates an application domain where the website can run. As we all know, the application domain creates isolation between two web applications hosted on the same IIS. So in case there is an issue in one app domain, it does not affect the other app domain.

Step 3: The newly created application domain creates hosting environment, i.e. the ‘HttpRuntime’ object. Once the hosting environment is created, the necessary core ASP.NET objects like ‘HttpContext’ , ‘HttpRequest’ and ‘HttpResponse’ objects are created.

Step 4: Once all the core ASP.NET objects are created, ‘HttpApplication’ object is created to serve the request. In case you have a ‘global.asax’ file in your system, then the object of the ‘global.asax’ file will be created. Please note global.asax file inherits from ‘HttpApplication’ class.
Note: The first time an ASP.NET page is attached to an application, a new instance of ‘HttpApplication’ is created. Said and done to maximize performance, HttpApplication instances might be reused for multiple requests.

Step 5: The HttpApplication object is then assigned to the core ASP.NET objects to process the page.

Step 6: HttpApplication then starts processing the request by HTTP module events, handlers and page events. It fires the MHPM event for request processing.


The below image explains how the internal object model looks like for an ASP.NET request. At the top level is the ASP.NET runtime which creates an ‘Appdomain’ which in turn has ‘HttpRuntime’ with ‘request’, ‘response’ and ‘context’ objects.

Process Request using MHPM Events Fired

Once ‘HttpApplication’ is created, it starts processing requests. It goes through 3 different sections ‘HttpModule’ , ‘Page’ and ‘HttpHandler’. As it moves through these sections, it invokes different events which the developer can extend and add customize logic to the same.
Before we move ahead, let's understand what are ‘HttpModule’ and ‘HttpHandlers’. They help us to inject custom logic before and after the ASP.NET page is processed. The main differences between both of them are:
  • If you want to inject logic based in file extensions like ‘.ASPX’, ‘.HTML’, then you use ‘HttpHandler’. In other words, ‘HttpHandler’ is an extension based processor.
  • If you want to inject logic in the events of ASP.NET pipleline, then you use ‘HttpModule’. ASP.NET. In other words, ‘HttpModule’ is an event based processor.
You can read more about the differences from here.
Below is the logical flow of how the request is processed. There are 4 important steps MHPM as explained below:

Step 1(M: HttpModule): Client request processing starts. Before the ASP.NET engine goes and creates the ASP.NET HttpModule emits events which can be used to inject customized logic. There are 6 important events which you can utilize before your page object is created BeginRequest, AuthenticateRequest, AuthorizeRequest, ResolveRequestCache, AcquireRequestState and PreRequestHandlerExecute.

Step 2 (H: ‘HttpHandler’): Once the above 6 events are fired, ASP.NET engine will invoke ProcessRequest event if you have implemented HttpHandler in your project.

Step 3 (P: ASP.NET page): Once the HttpHandler logic executes, the ASP.NET page object is created. While the ASP.NET page object is created, many events are fired which can help us to write our custom logic inside those page events. There are 6 important events which provides us placeholder to write logic inside ASP.NET pages Init, Load, validate, event, render and unload. You can remember the word SILVER to remember the events S – Start (does not signify anything as such just forms the word) , I – (Init) , L (Load) , V (Validate), E (Event) and R (Render).

Step4 (M: HttpModule): Once the page object is executed and unloaded from memory, HttpModule provides post page execution events which can be used to inject custom post-processing logic. There are 4 important post-processing events PostRequestHandlerExecute, ReleaserequestState, UpdateRequestCache and EndRequest.
The below figure shows the same in a pictorial format.

In What Event Should We Do What?

The million dollar question is in which events should we do what? Below is the table which shows in which event what kind of logic or code can go.
Section Event Description
HttpModule BeginRequest This event signals a new request; it is guaranteed to be raised on each request.
HttpModule AuthenticateRequest This event signals that ASP.NET runtime is ready to authenticate the user. Any authentication code can be injected here.
HttpModule AuthorizeRequest This event signals that ASP.NET runtime is ready to authorize the user. Any authorization code can be injected here.
HttpModule ResolveRequestCache In ASP.NET, we normally use outputcache directive to do caching. In this event, ASP.NET runtime determines if the page can be served from the cache rather than loading the patch from scratch. Any caching specific activity can be injected here.
HttpModule AcquireRequestState This event signals that ASP.NET runtime is ready to acquire session variables. Any processing you would like to do on session variables.
HttpModule PreRequestHandlerExecute This event is raised just prior to handling control to the HttpHandler. Before you want the control to be handed over to the handler any pre-processing you would like to do.
HttpHandler ProcessRequest Httphandler logic is executed. In this section, we will write logic which needs to be executed as per page extensions.
Page Init This event happens in the ASP.NET page and can be used for:
  • Creating controls dynamically, in case you have controls to be created on runtime.
  • Any setting initialization.
  • Master pages and the settings.
In this section, we do not have access to viewstate, postedvalues and neither the controls are initialized.
Page Load In this section, the ASP.NET controls are fully loaded and you write UI manipulation logic or any other logic over here.
Page Validate If you have valuators on your page, you would like to check the same here.

Render It’s now time to send the output to the browser. If you would like to make some changes to the final HTML which is going out to the browser, you can enter your HTML logic here.
Page Unload Page object is unloaded from the memory.
HttpModule PostRequestHandlerExecute Any logic you would like to inject after the handlers are executed.
HttpModule ReleaserequestState If you would like to save update some state variables like session variables.
HttpModule UpdateRequestCache Before you end, if you want to update your cache.
HttpModule EndRequest This is the last stage before your output is sent to the client browser.

A Sample Code for Demonstration

With this article, we have attached a sample code which shows how the events actually fire. In this code, we have created a ‘HttpModule’ and ‘Httphandler’ in this project and we have displayed a simple response write in all events, below is how the output looks like.
Below is the class for ‘HttpModule’ which tracks all events and adds it to a global collection.
public class clsHttpModule : IHttpModule
{
...... 
void OnUpdateRequestCache(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnUpdateRequestCache");
}
void OnReleaseRequestState(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnReleaseRequestState");
}
void OnPostRequestHandlerExecute(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnPostRequestHandlerExecute");
}
void OnPreRequestHandlerExecute(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnPreRequestHandlerExecute");
}
void OnAcquireRequestState(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnAcquireRequestState");
}
void OnResolveRequestCache(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnResolveRequestCache");
}
void OnAuthorization(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnAuthorization");
}
void OnAuthentication(object sender, EventArgs a)
{

objArrayList.Add("httpModule:AuthenticateRequest");
}
void OnBeginrequest(object sender, EventArgs a)
{

objArrayList.Add("httpModule:BeginRequest");
}
void OnEndRequest(object sender, EventArgs a)
{
objArrayList.Add("httpModule:EndRequest");
objArrayList.Add("<hr>");
foreach (string str in objArrayList)
{
httpApp.Context.Response.Write(str + "<br>") ;
}
} 
}
Below is the code snippet for ‘HttpHandler’ which tracks ‘ProcessRequest’ event.
public class clsHttpHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
clsHttpModule.objArrayList.Add("HttpHandler:ProcessRequest");
context.Response.Redirect("Default.aspx");
}
}
We are also tracking all the events from the ASP.NET page.
public partial class _Default : System.Web.UI.Page 
{
protected void Page_init(object sender, EventArgs e)
{

clsHttpModule.objArrayList.Add("Page:Init");
}
protected void Page_Load(object sender, EventArgs e)
{
clsHttpModule.objArrayList.Add("Page:Load");
}
public override void Validate() 
{
clsHttpModule.objArrayList.Add("Page:Validate");
}
protected void Button1_Click(object sender, EventArgs e)
{
clsHttpModule.objArrayList.Add("Page:Event");
}
protected override void Render(HtmlTextWriter output) 
{
clsHttpModule.objArrayList.Add("Page:Render");
base.Render(output);
}
protected void Page_Unload(object sender, EventArgs e)
{
clsHttpModule.objArrayList.Add("Page:UnLoad");
}}
Below is how the display looks like with all events as per the sequence discussed in the previous section.

Zooming ASP.NET Page Events

In the above section, we have seen the overall flow of events for an ASP.NET page request. One of the most important sections is the ASP.NET page, we have not discussed the same in detail. So let’s take some luxury to describe the ASP.NET page events in more detail in this section.
Any ASP.NET page has 2 parts, one is the page which is displayed on the browser which has HTML tags, hidden values in form of viewstate and data on the HTML inputs. When the page is posted, these HTML tags are created in to ASP.NET controls with viewstate and form data tied up together on the server. Once you get these full server controls on the behind code, you can execute and write your own login on the same and render the page back to the browser.

Now between these HTML controls coming live on the server as ASP.NET controls, the ASP.NET page emits out lot of events which can be consumed to inject logic. Depending on what task / logic you want to perform, we need to put this logic appropriately in those events.
Note: Most of the developers directly use the page_load method for everything, which is not a good thought. So it’s either populating the controls, setting view state, applying themes, etc., everything happens on the page load. So if we can put logic in proper events as per the nature of the logic, that would really make your code clean.
Seq Events Controls Initialized View state
Available
Form data
Available
What Logic can be written here?
1 Init No No No Note: You can access form data etc. by using ASP.NET request objects but not by Server controls.Creating controls dynamically, in case you have controls to be created on runtime. Any setting initialization.Master pages and them settings. In this section, we do not have access to viewstate , posted values and neither the controls are initialized.
2 Load view state Not guaranteed Yes Not guaranteed You can access view state and any synch logic where you want viewstate to be pushed to behind code variables can be done here.
3 PostBackdata Not guaranteed Yes Yes You can access form data. Any logic where you want the form data to be pushed to behind code variables can be done here.
4 Load Yes Yes Yes This is the place where you will put any logic you want to operate on the controls. Like flourishing a combobox from the database, sorting data on a grid, etc. In this event, we get access to all controls, viewstate and their posted values.
5 Validate Yes Yes Yes If your page has validators or you want to execute validation for your page, this is the right place to the same.
6 Event Yes Yes Yes If this is a post back by a button click or a dropdown change, then the relative events will be fired. Any kind of logic which is related to that event can be executed here.
7 Pre-render Yes Yes Yes If you want to make final changes to the UI objects like changing tree structure or property values, before these controls are saved in to view state.
8 Save view state Yes Yes Yes Once all changes to server controls are done, this event can be an opportunity to save control data in to view state.
9 Render Yes Yes Yes If you want to add some custom HTML to the output this is the place you can.
10 Unload Yes Yes Yes Any kind of clean up you would like to do here.


 Thanks
Alok Kumar sharma

What’ is the sequence in which ASP.NET events are processed?

PreInit
    Use this event for the following:
    *Check the IsPostBack property to determine whether this is the first time the page is being processed.
    *Create or re-create dynamic controls.
    *Set a master page dynamically.
    *Set the Theme property dynamically.
  
    Read or set profile property values.
    NoteNote
    If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.

Init
    Raised after all controls have been initialized and any skin settings have been applied. Use this event to read or initialize control properties.

InitComplete
    Raised by the Page object. Use this event for processing tasks that require all initialization be complete.
PreLoad
    Use this event if you need to perform processing on your page or control before the Load event.
    After the Page raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.

Load
    The Page calls the OnLoad event method on the Page, then recursively does the same for each child control, which does the same for each of its child controls until the page and all controls are loaded.
    Use the OnLoad event method to set properties in controls and establish database connections.

Control events
    Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.
    NoteNote
    In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.
LoadComplete
    Use this event for tasks that require that all other controls on the page be loaded.
PreRender
    Before this event occurs:
        *The Page object calls EnsureChildControls for each control and for the page.
        *Each data bound control whose DataSourceID property is set calls its DataBind method. For more information, see Data Binding Events for Data-Bound Controls below.
    The PreRender event occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls.
SaveStateComplete
    Before this event occurs, ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored.
    Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.
Render
    This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control's markup that is sent to the browser.
    If you create a custom control, you typically override this method to output the control's markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method. For more information, see Developing Custom ASP.NET Server Controls.
    A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.
Unload
    This event occurs for each control and then for the page. In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.
    For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.
NoteNote
    During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.

Monday, May 14, 2012

Find Control within GridView

#region chkSelect_SelectedIndexChanged
    protected void chkSelect_SelectedIndexChanged(object sender, EventArgs e)
    {
        RadioButtonList rb2Action = (RadioButtonList)sender;
        rb2Action.NamingContainer.FindControl("chkSelect");
        GridViewRow gvr1 = (GridViewRow)rb2Action.Parent.Parent;
        string strFilePath = string.Empty;
        string strSendToIndividuals = string.Empty;
        string strMessageBody = string.Empty;
        string strContentSubject = string.Empty;
        string strMemberName = GetMemberName(Session["UserID"].ToString());
        string[] strkeyID = ((LinkButton)(gvr1.FindControl("lbTitle"))).CommandArgument.Trim().Split(';');
        if (strkeyID.Length > 0)
        {
            strFilePath = strkeyID[0].ToString();
            strSendToIndividuals = strkeyID[2].ToString();
            strMessageBody = "Your shared " + strkeyID[5].ToString() + " on date Request for Sharing " + Convert.ToDateTime(strkeyID[4]).ToString("dd/MM/yyyy") + " for class  " + gvr1.Cells[0].Text.ToString() + gvr1.Cells[1].Text.ToString() + ((LinkButton)(gvr1.FindControl("lbTitle"))).Text;
        }
        if (rb2Action.SelectedValue.Trim().Equals("Approve"))
        {
            strContentSubject = "Content Feedback -(Approval)";
            strMessageBody = strMessageBody + " has been approved by " + strMemberName + " on Date " + DateTime.Now.ToString("dd/MM/yyyy");
            ((TextBox)gvr1.FindControl("txtRemarks")).Text = "";
        }
        else
        {
            strContentSubject = " Content Feedback -(Rejection) ";
            strMessageBody = strMessageBody + " has been rejected  by " + strMemberName + " on Date " + DateTime.Now.ToString("dd/MM/yyyy") + " due to the following reason(s): " + ((TextBox)gvr1.FindControl("txtRemarks")).Text;
            ((TextBox)gvr1.FindControl("txtRemarks")).Text = "due to the following reason(s): ";
        }
    }

    #endregion

Friday, April 13, 2012

XML

1 What is XML?
Ans:
     XML stands for EXtensible Markup Language.
    XML is a markup language much like HTML.
    XML was designed to carry data, not to display data.
    XML tags are not predefined. You must define your own tags.
    XML is designed to be self-descriptive.


2 What is the version information in XML?
3 What is ROOT element in XML?
Ans :
    XML documents must contain one element that is the parent of all other elements. This element is called the root element.
    <root>
      <child>
        <subchild>.....</subchild>
      </child>
    </root>

4 If XML does not have closing tag will it work?

5 Is XML case sensitive?
Ans:Yes, XML tags are case sensitive.Opening and closing tags must be written with the same case:
       eg
    <Menu>Home</Menu>

6 What is the difference between XML and HTML?
Ans:
    • XML was designed to transport and store data, with focus on what data is.
    • HTML was designed to display data, with focus on how data looks.
   •  HTML was designed to display data with focus on how data looks while XML was designed to be a software and hardware independent tool used to transport and store data, with focus on what data is.
   • HTML is a markup language itself while XML provides a framework for defining markup languages.
   • HTML is a presentation language while XML is neither a programming language nor a presentation language.
   • HTML is case insensitive while XML is case sensitive.
   • HTML is used for designing a web-page to be rendered on the client side while XML is used basically to transport data between the application and the database.
   • HTML has it own predefined tags while what makes XML flexible is that custom tags can be defined and the tags are invented by the author of the XML document.
   • HTML is not strict if the user does not use the closing tags but XML makes it mandatory for the user the close each tag that has been used.
   • HTML does not preserve white space while XML does.
   • HTML is about displaying data,hence static but XML is about carrying information,hence dynamic


7 Is XML meant to replace HTML?
8 Can you explain why your project needed XML?
9 What is DTD (Document Type Definition)?
10 What is well formed XML?
11 What is a valid XML?
12 What is CDATA section in XML?
13 What is CSS?
14 What is XSL?
15 What is element and attributes in XML?
16 Which are the namespaces in .NET used for XML?
17 What are the standard ways of parsing XML document?
18 In What scenarios will you use a DOM parser and SAX parser?
19 How was XML handled during COM times?
20 What is the main difference between MSML and .NET Framework XML classes?
21 What are the core functionalities in XML .NET framework? Can you explain in detail
22 those functionalities?
23 What is XSLT?
24 Define XPATH?
25 What is the concept of XPOINTER?
26 What is an XMLReader Class?
27 What is XMLTextReader?
28 How do we access attributes using “XmlReader”?
29 Explain simple Walk through of XmlReader.
30 What does XmlValidatingReader class do?

 Localization/Globalization

1 What is Unicode & Why was it introduced?
2 Does .NET support UNICODE and how do you know it supports?
3 What is the difference between localization and globalization?
4 What architecture decisions you should consider while planning for international software’s?
5 How do we get the current culture of the environment in windows and ASP.NET?
6 Which are the important namespaces during localization and globalization?
7 What are resource files and how do we generate resource files?
8 Can resource file be in any other format other than resx extensions?
9 How is resource files actually used in project?
10 How can we use Culture Auto in project?
11 What are satellite assemblies?
12 How do we generate Satellite assemblies?
13 What is AL.EXE and RESGEN.EXE? 275
14 What is the use of resource manager class?
15 What precautions do we need to take while deploying satellite assemblies?
16 Can we get a strongly typed resource class rather than using resource manager?
17 Can you explain the fundamentals of “GetGlobalResourceObject” and
18 “GetLocalResourceObject” functions?
19 Can we sign a satellite assembly?
20 Can you explain collation sequence in sql server?
21 How do we define collation sequence for database and tables?
22 Can we change the order in a select query with a specified collation sequence?
23 Can you list best practices for globalization and localization?
24 Why is the culture set to the current thread?

Thanks & Regards
Alok Kumar Sharma

NET Architecture

1 What are design patterns?
2 What is the difference between Factory and Abstract Factory Patterns?
3 What is MVC pattern?
4 How can we implement singleton pattern in .NET?
5 How do you implement prototype pattern in .NET?
6 What are the situations you will use a Web Service and Remoting in projects?
7 Can you give a practical implementation of FAÇADE patterns?
8 How can we implement observer pattern in .NET?
9 What is three-tier architecture?
10 Have you ever worked with Microsoft Application Blocks, if yes then which?
11 What is Service Oriented architecture?
12 What are different ways you can pass data between tiers?
13 What is Windows DNA architecture?
14 What is aspect oriented programming?

Thanks & Regards
Alok Kumar Sharma
 

ASP.NET

1 What’ is the sequence in which ASP.NET events are processed?
2 In which event are the controls fully loaded?
3 How can we identify that the Page is Post Back?
4 How does ASP.NET maintain state in between subsequent request?
5 What is event bubbling?
6 How do we assign page specific attributes?
7 How do we ensure viewstate is not tampered?
8 What is the use of @ Register directives?
9 What is the use of Smart Navigation property?
10 What is AppSetting Section in “Web.Config” file?
11 Where is View State information stored?
12 what is the use of @ Output Cache directive in ASP.NET.
13 How can we create custom controls in ASP.NET?
14 How many types of validation controls are provided by ASP.NET?
15 Can you explain “AutoPostBack”?
16 How can you enable automatic paging in Data Grid?
17 What is the use of “GLOBAL.ASAX” file?
18 What is the difference between “Web.config” and “Machine.Config”?
19 What is a SESSION and APPLICATION object?
20 What is the difference between ‘Server.Transfer’ and ‘response. Redirect’ ?
21 What is the difference between Authentication and authorization?
22 what is impersonation in ASP.NET?
23 Can you explain in brief how the ASP.NET authentication process works?
24 What are the various ways of authentication techniques in ASP.NET?
25 How does authorization work in ASP.NET?
26 What is difference between Data grid, Datalist, and repeater?
27 From performance point of view, how do they rate?
28 What is the method to customize columns in Data Grid?
29 How can we format data inside Data Grid?
30 How to decide on the design consideration to take a Data grid, data list, or repeater?
31 Difference between ASP and ASP.NET?
32 What are major events in GLOBAL.ASAX file?
33 What order they are triggered?
34 Do session use cookies?
35 How can we force all the validation control to run?
36 How can we check if all the validation control are valid and proper?
37 If client side validation is enabled in your Web page, does that mean server side code  is not run.
38 Which JavaScript file is referenced for validating the validators at the client side?
39 How to disable client side script in validators?
40 How can I show the entire validation error message in a message box on the client side ?
41 You find that one of your validations is very complicated and does not fit in any of the validators, what will you do?
42 What exactly happens when ASPX page is requested from a browser?
43 How can we kill a user session?
44 How do you upload a file in ASP.NET?
45 How do I send email message from ASP.NET?
46 What are different IIS isolation levels?
47 ASP used STA threading model, what is the threading model used for ASP.NET.
48 What is the use of <%@ page aspcompat=true %> attribute?
49 Explain the differences between Server-side and Client-side code?
50 Can you explain Forms authentication in detail?
51 How do I sign out in forms authentication?
52 If cookies are not enabled at browser end does form Authentication work?
53 How to use a checkbox in a data grid?
54 What are the steps to create a windows service in VB.NET?
55 What is the difference between “Web farms” and “Web garden”?
56 How do we configure “Web Garden”?
57 What is the main difference between Grid layout and Flow Layout?
58 What’s the difference between trace and debug in ASP.NET?
59 How do you enable tracing in on an ASP.NET page?
60 Which namespace is needed to implement debug and trace ?
61 Can you explain the concept of trace listener?
62 What are trace switches?



Thanks & Regards

Alok Kumar Sharma

OOPs

1 What is Object Oriented Programming?
2 What is a Class?
3 What is an Object?
4 What is the relation between Classes and Objects?
5 What are different properties provided by Object-oriented systems?
6 How can we achieve inheritance in VB.NET?
7 what are abstract classes?
8 What is a Interface?
9 What is difference between abstract classes and interfaces?
10 What is a delegate?
11 What are Events?
12 Do events have return type.
13 Can events have access modifiers?
14 Can we have shared events?
15 what is shadowing?
16 What is the difference between Shadowing and Overriding?
17 what is the difference between delegate and events?
18 If we inherit a class do the private variables also get inherited?
19 What is the different accessibility levels defined in .NET?
20 Can you prevent a class from overriding?
21 what is the use of “Must inherit” keyword in VB.NET?
22 Do interface have accessibility modifier.
23 What are similarities between Class and structure?
24 What is the difference between Class and structure’s?
25 What does virtual keyword mean?
26 What are shared (VB.NET)/Static(C#) variables?
27 What is Dispose method in .NET?
28 What is the use of “Overrides” and “Overridable” keywords?
29 Where are all .NET Collection classes located?
30 What is ArrayList?
31 What is a HashTable?
32 What are queues and stacks?
33 What is ENUM?
34 What is nested Classes?
35 What is Operator overloading in .NET?
36 For the below code which constructor will fire first?
37 What is the significance of Finalize method in .NET?
38 How can we suppress a finalize method?
39 What is the use of DISPOSE method?
40 How do I force the Dispose method to be called automatically, as clients can forget to call Dispose method?
41 In what instances you will declare a constructor to be private?
42 Can we have different access modifiers on get/set methods of a property ?
43 If we write a goto or a return statement in try and catch block will the finally block execute?
44 What is Indexer?
45 Can we have static indexer in C#?
46 Can two catch blocks be executed?
47 What is the difference between System.String and System.StringBuilder classes?

Caching Concepts

1 What is an application object?
2 what is the difference between Cache object and application object?
3 How can get access to cache object?
4 What are dependencies in cache and types of dependencies?
5 Can you show a simple code showing file dependency in cache?
6 What is Cache Callback in Cache?
7 What is scavenging?
8 What are different types of caching using cache object of ASP.NET?
9 How can you cache different version of same page using ASP.NET cache object?
10 How will implement Page Fragment Caching?
11 Can you compare ASP.NET sessions with classic ASP?
12 Which are the various modes of storing ASP.NET session?
13 Is Session_End event supported in all session modes?
14 What are the steps to configure StateServer Mode?
15 What are the steps to configure SQLServer mode?
16 Where do you specify session state mode in ASP.NET?
17 What are the other ways you can maintain state?
18 What are benefits and Limitation of using Hidden fields?
19 What is ViewState?
20 Does the performance for viewstate vary according to User controls?
21 What are benefits and Limitation of using Viewstate for state management?
22 How can you use Hidden frames to cache client data ?
23 What are benefits and limitations of using Hidden frames?
24 What are benefits and limitations of using Cookies?
25 What is Query String and What are benefits and limitations of using Query Strings?
26 What is Absolute and Sliding expiration?
27 What is cross page posting? 93
28 How do we access viewstate value of this page in the next page ?
29 Can we post and access view state in another application?
30 What is SQL Cache Dependency in ASP.NET 2.0?
31 How do we enable SQL Cache Dependency in ASP.NET 2.0?
32 What is Post Cache substitution?
33 Why do we need methods to be static for Post Cache substitution?

Thanks & Regards

Alok Kumar Sharma

NET Interoperability Questions

NET Interoperability
1 How can we use COM Components in .NET?
2 We have developed the COM wrapper do we have to still register the COM?
3 How can we use .NET components in COM?
4 How can we make Windows API calls in .NET?
5 When we use windows API in .NET is it managed or unmanaged code?
6 What is COM?
7 What is Reference counting in COM?
8 Can you describe IUKNOWN interface in short?
9 Can you explain what DCOM is?
10 How do we create DCOM object in VB6?
11 How to implement DTC in .NET?
12 How many types of Transactions are there in COM + .NET?
13 How do you do object pooling in .NET?
14 What are types of compatibility in VB6?
15 What is equivalent for regsvr32 exe in .NET?

Thanks & Regards

Alok Kumar Sharma

.NET Interview Questions

Basic .NET Framework
1 What is an IL?
2 What is a CLR?
3 What is CTS?
4 What is a CLS (Common Language Specification)?
5 What is a Managed Code?
6 What is a Assembly?
7 What are the different types of Assembly?
8 What is NameSpace?
9 What is Difference between NameSpace and Assembly?
10 If you want to view an Assembly how do you go about it?
11 What is Manifest?
12 Where is version information stored of an assembly?
13 Is versioning applicable to private assemblies?
14 What is GAC?
15 what is the concept of strong names?
16 How to add and remove an assembly from GAC?
17 What is Delay signing?
18 What is garbage collection?
19 Can we force garbage collector to run?
20 What is reflection?
21 What are different types of JIT?
22 What are Value types and Reference types?
23 What is concept of Boxing and Unboxing ?
24 What is the difference between VB.NET and C#?
25 what is the difference between System exceptions and Application exceptions?
26 What is CODE Access security?
27 What is a satellite assembly?
28 How to prevent my .NET DLL to be decompiled?
29 what is the difference between Convert.toString and .toString () method?
30 What is Native Image Generator (Ngen.exe)?
31 If we have two version of same assembly in GAC how do we make a choice?
32 What is CodeDom?

   Threading


1 What is Multi-tasking?
2 What is Multi-threading?
3 What is a Thread?
4 Did VB6 support multi-threading?
5 Can we have multiple threads in one App domain?
6 Which namespace has threading?
7 What does Address Of operator do in background?
8 How can you reference current thread of the method?
9 what is Thread.Sleep () in threading?
10 How can we make a thread sleep for infinite period?
11 What is Suspend and Resume in Threading?
12 What the way to stop a long running thread?
13 How do I debug thread?
14 What is Thread.Join () in threading?
15 What are Daemon threads and how can a thread be created as Daemon?
16 How is shared data managed in threading?
17 Can we use events with threading?
18 How can we know a state of a thread?
19 What is use of Interlocked class ?
20 What is a monitor object?
21 What are wait handles?
22 What is ManualResetEvent and AutoResetEvent?
23 What is Reader Writer Locks?
24 How can you avoid deadlock in threading?
25 What is the difference between thread and process?

 Remoting and Webservices

1 What is .NET Remoting?
2 Which class does the remote object has to inherit?
3 what are two different types of remote object creation mode in .NET ?
4 Describe in detail Basic of SAO architecture of Remoting?
5 What are the situations you will use singleton architecture in remoting?
6 What is fundamental of published or precreated objects in Remoting?
7 What are the ways in which client can create object on server in CAO model?
8 Are CAO stateful in nature?
9 To create objects in CAO with ‘new’ keyword what should be done?
10 Is it a good design practice to distribute the implementation to Remoting Client?

11 What are LeaseTime, SponsorshipTime, RenewonCallTime and  LeaseManagerPollTime?
Ans:

In normal .NET environment objects garbage collector manages lifetime. However, in remoting environment remote clients can access objects, which are out of control of garbage collector. Garbage collector boundary is limited to a single PC on which framework is running; any remote client across physical PC is out of control of GC (Garbage Collector).

This constraint of garbage collector leads to a new way of handling lifetime for remoting objects, by using concept called as “LeaseTime”. Every server side object is assigned by default a “LeaseTime” of five minutes. This lease time is decreased at certain intervals. Again, for every method call a default of two minutes is assigned. When i say method call means every call made from client. This is called as “RenewalOnCallTime”.

    Let’s put the whole thing in equation to make the concept more clear.

    Total Remoting object life time = LeaseTime + (Number of method calls) X (RenewalTime).

    Then default Remote Object Life Time = 5 + (1) X 2 = 10 minutes (Everything is in minutes)


When total object lifetime is reduced to zero, then it queries the sponsor that should the object be destroyed. Sponsor is an object, which decides should object Lifetime be renewed. So it queries any registered sponsors with the object, if does not find any then the object is marked for garbage collection. After this garbage, collection has whole control on the object lifetime. If we do not foresee how long a object will be needed specify the “Sponsorship Timeout” value. Sponsorship Timeout is time unit a call to a sponsor is timed out.

    “LeaseManagerPollTime” defines the time the sponsor has to return a lease time extension.

13 Which config file has all the supported channels/protocol?
14 How can you specify remoting parameters using Config files?
15 Can Non-Default constructors be used with Single Call SAO?
16 How can we call methods in remoting asynchronously?
17 What is Asynchronous One-Way Calls?
18 What is marshalling and what are different kinds of marshalling?
19 What is ObjRef object in remoting?
20 What is a Web Service?
21 What is UDDI?
22 What is DISCO?
23 What is WSDL?
24 What the different phase/steps of acquiring a proxy object in Web service?
25 What the different phase/steps of acquiring a proxy object in Web service?
26 What is file extension of Web services?
27 Which attribute is used in order that the method can be used as WebService?
28 What are the steps to create a web service and consume it?
29 Do webservice have state?

Thanks & Regards

Alok Kumar Sharma

Monday, April 9, 2012

nchar and nvarchar (Transact-SQL)


Character data types that are either fixed-length, nchar, or variable-length, nvarchar, Unicode data and use the UNICODE UCS-2 character set.

nchar [ ( n ) ]

    Fixed-length Unicode string data. n defines the string length and must be a value from 1 through 4,000. The storage size is two times n bytes. When the collation code page uses double-byte characters, the storage size is still n bytes. Depending on the string, the storage size of n bytes can be less than the value specified for n. The ISO synonyms for nchar are national char and national character..
nvarchar [ ( n | max ) ]

    Variable-length Unicode string data. n defines the string length and can be a value from 1 through 4,000. max indicates that the maximum storage size is 2^31-1 bytes (2 GB). Example [@MemberFName varchar(Max)] The storage size, in bytes, is two times the actual length of data entered + 2 bytes. The ISO synonyms for nvarchar are national char varying and national character varying.

Remarks
Remarks


When n is not specified in a data definition or variable declaration statement, the default length is 1. When n is not specified with the CAST function, the default length is 30.
Example cast(@MemberFirstName as Varchar) then the size of  "@MemberFirstName" only 30 charachers.

Use nchar when the sizes of the column data entries are probably going to be similar.

Use nvarchar when the sizes of the column data entries are probably going to vary considerably.

sysname is a system-supplied user-defined data type that is functionally equivalent to nvarchar(128), except that it is not nullable. sysname is used to reference database object names.

Objects that use nchar or nvarchar are assigned the default collation of the database unless a specific collation is assigned using the COLLATE clause.

SET ANSI_PADDING is always ON for nchar and nvarchar. SET ANSI_PADDING OFF does not apply to the nchar or nvarchar data types.

Thanks
Alok Kumar Sharma
 

Saturday, April 7, 2012

SQL SERVER – Find out the Duplicate Records

SELECT AccNo, COUNT(*) TotalCount
FROM SRLibData
GROUP BY AccNo
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC

Thanks
Alok Kumar Sharma

Wednesday, February 15, 2012

Operation is not valid due to the current state of the object.


Server Error in '/' Application.
________________________________________
Operation is not valid due to the current state of the object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: Operation is not valid due to the current state of the object.

Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[InvalidOperationException: Operation is not valid due to the current state of the object.]
System.Web.HttpRequest.FillInFormCollection() +11091695
System.Web.HttpRequest.get_Form() +119
System.Web.HttpRequest.get_HasForm() +11085399
System.Web.UI.Page.GetCollectionBasedOnMethod(Boolean dontReturnNull) +124
System.Web.UI.Page.DeterminePostBackMode() +83
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +270

________________________________________
Version Information: Microsoft .NET Framework Version:2.0.50727.3625; ASP.NET Version:2.0.50727.3634


Reasons:

You installed the Windows Update recently: Microsoft Security Bulletin MS11-100.
The bulletin fixes the DOS attack vector by providing a limit to the number of variables that can be submitted for a single HTTP POST request. The default limit is 500.

Resolution:

This problem can be resolved in two ways:
  1. Reconfiguring Image Uploader and server-side script to send all files in upload list into multiple packages (FilesPerPackage property should be set to some small value (e.g. 1-10))*.
  2. Modifying applicationHost.config file. Go to C:\Windows\System32\inetsrv\config\applicationHost.config and add the following section to the config file, like it is shown in this code:
    Code:
    ?
    1
    2
    3
    <appSettings>
        <add key="aspnet:MaxHttpCollectionKeys" value="10000" />
    </appSettings>

    It will allow increasing the number of variables that can be sent in a single HTTP POST request.
    ________
    * - The second way still has limitation. If you send all files in a single request, number of variables posted in a request depends on number of files. This way, increasing the value in config will give a temporary solution. Anyway it can be found amount of files causing this exception again. To eliminate even a chance of this problem you need to consider the first way.
 

Add This key in Web.config file.
added this key to the <appsettings> and it fixed the problem.






<appSettings>
    <add key="aspnet:MaxHttpCollectionKeys" value="10000" />

 </appSettings>