Friday, May 30, 2014

What is the difference between Classic and Integrated pipeline mode in IIS7?

Classic mode is a mode where IIS only works with ISAPI extensions and ISAPI filters directly. In fact, in this mode, ASP.NET is just an ISAPI extension (aspnet_isapi.dll) and an ISAPI filter (aspnet_filter.dll). IIS just treats ASP.NET as an external plugin implemented in ISAPI. When an application pool is in Classic mode, IIS 7.0 handles requests as in IIS 6.0 worker process isolation mode. ASP.NET requests first go through native processing steps in IIS and are then routed to Aspnet_isapi.dll for processing of managed code in the managed runtime. Finally, the request is routed back through IIS to send the response.

This separation of the IIS and ASP.NET request-processing models results in duplication of some processing steps, such as authentication and authorization. Additionally, managed code features, such as forms authentication, are only available to ASP.NET applications or applications for which you have script mapped all requests to be handled by aspnet_isapi.dll.

Integrated mode, on the other hand, is a new mode in IIS7 where IIS pipeline is tightly integrated (i.e. is just the same) as ASP.NET request pipeline. ASP.NET can see every request it wants to and manipulate things along the way. ASP.NET is no longer treated as an external plugin. It's completely blended and integrated in IIS. When an application pool is in Integrated mode, you can take advantage of the integrated request-processing architecture of IIS and ASP.NET. When a worker process in an application pool receives a request, the request passes through an ordered list of events. Each event calls the necessary native and managed modules to process portions of the request and to generate the response.

There are several benefits to running application pools in Integrated mode. First the request-processing models of IIS and ASP.NET are integrated into a unified process model. This model eliminates steps that were previously duplicated in IIS and ASP.NET, such as authentication. Additionally, Integrated mode enables the availability of managed features to all content types.

Thursday, May 29, 2014

How to create MaskedTextBox custom control in Asp.net?

A Masked Textbox is very handy when you want to put a mask for "Phone, SSN or Date" Fields throughout the project. Especially, when you have many places in your project where you have to do masking on textboxes. Masking is useful because it prevents a user from entering wrong inputs. If we create custom control for Masking, it will be easier for us to just drag and drop control and apply masking format like
for U.S. Phone-> (999) 999-9999 where 9 represents digit only. So the question is how to create a custom control... and here it is:

You can do this by JQuery and VB/C# class. You need two files of JQuery:
1. jquery-1.9.1.min.js
2. jquery.maskedinput.min.js
You can download these two files from :
http://jquery.com/
http://digitalbush.com/projects/masked-input-plugin/

And one VB/C# Class file. Following is the VB.net code:

Public Class MaskedTextBox
    Inherits TextBox


    Private _cMast As String
    Public Property cMask() As String
        Get
            Return _cMast
        End Get
        Set(ByVal value As String)
            _cMast = value
        End Set
    End Property


    Private Sub MaskedTextBox_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim scriptText As String



        scriptText = "<script src="jquery-1.9.1.min.js"></script>" _
            + "<script src="jquery.maskedinput.min.js"></script>" _
            + "<script>$(document).ready(function() {" _
            + "$('#" + Me.ID + "').mask('" + cMask + "');" _
            + "$('#" + Me.ID + "').click(function () { " _
            + "if (document.getElementById('" + Me.ID + "').value == '" + cMask.Replace("9", "_") + "') {" _
            + "setCaretPosition('" + Me.ID + "', 0) }" _
            + "});" _
            + "});</script>"



        Me.Page.ClientScript.RegisterStartupScript(Me.GetType(), _
            Me.ID + "t", scriptText)

        scriptText = "<script>function setCaretPosition(elemId, caretPos) { " _
            + "var el = document.getElementById(elemId);" _
            + "el.value = el.value;" _
            + "if (el !== null) {" _
            + "if (el.createTextRange) {" _
            + "var range = el.createTextRange();" _
            + "range.move('character', caretPos);" _
            + "range.select();" _
            + "return true;}" _
            + "else {" _
            + "if (el.selectionStart || el.selectionStart === 0) {" _
            + "el.focus();" _
            + "el.setSelectionRange(caretPos, caretPos);" _
            + "return true;}" _
            + "else {" _
            + "el.focus();" _
            + "return false;}}}}</script>"


        Me.Page.ClientScript.RegisterStartupScript(Me.GetType(), _
            "setCursor", scriptText)


    End Sub
End Class

Once you create this class file in your project. you have to register this control wherever you want to use. you can register it either on the page or in web.config if you want to use throughout the project.

For web.config:
<configuration>

  <system.web>
    
    <pages>
      <controls>
         <add assembly="CustomControls" namespace="CustomControls" tagprefix="cc">
      </add>
    </controls>
    </pages>

  </system.web>
</configuration> 


For .aspx page:
<%@ Register TagPrefix="cc" Namespace="CustomControls" Assembly="CustomControls" %>

Complete .aspx page code:
<%@ Page Language="vb" AutoEventWireup="false" 
    CodeBehind="Default.aspx.vb" Inherits="CustomControls.WebForm1" %>

<%@ Register TagPrefix="cc" Namespace="CustomControls" Assembly="CustomControls" %>
   
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>MaskedTextBox<title/>
</head> 
<body> 
<form id="form1" runat="server"> 

U.S. Phone: 
<cc:MaskedTextBox ID="mtxtPhone" runat="server" 
 cMask="(999) 999-9999" /> 
U.S. Phone: 
<cc:MaskedTextBox ID="mtxtPhone1" runat="server"
 cMask="(999) 999-9999" />  
SSN 1: 
<cc:MaskedTextBox ID="mtxtSSN" runat="server"
 cMask="999-99-9999" /> 
SSN 2: 
<cc:MaskedTextBox ID="mtxtSSN1" runat="server"
 cMask="999-99-9999" /> 

</form> 
</body> 
</html> 


Final Result and sample project structure will look like this:

How to sort on "List of objects" in VB.net?

Simple solution is below:
 
Public Class History
        Property OldValue As String
        Property NewValue As String
        Property UpdatedOn As DateTime
        Property ByWhom As String
End Class

Dim lstHistory As New List(of History)
lstHistory.Add(new History.....) 'And you have added few history objects in it.

Now we will sort it on "UpdatedOn" property.
For Ascending:
lstHistory.Sort(Function(x, y) x.UpdatedOn.CompareTo(y.UpdatedOn))

For Descending:
lstHistory.Sort(Function(x, y) y.UpdatedOn.CompareTo(x.UpdatedOn))

What is the difference between Web Application Projects and Web Site Projects in Visual Studio? Asp.net

I was creating new web project and was thinking that which one is better choice? Web Application or Web Site to build web project. I have found following scenarios on both. So based on these scenarios, you can decide which one is perfect match for your web project.

Scenarios in which web application projects are the preferred choice include the following:

•You want to be able to use the Edit and Continue feature of the Visual Studio
 debugger. 

•You want to run unit tests on code that is in the class files that are associated
 with ASP.NET pages.

•You want to refer to the classes that are associated with pages and user controls 
 from standalone classes.

•You want to establish project dependencies between multiple web projects.

•You want the compiler to create a single assembly for the entire site.

•You want control over the assembly name and version number that is generated for the
 site.

•You want to use MSBuild or Team Build to compile the project. For example, you 
 might want to add prebuild and postbuild steps.

•You want to avoid putting source code on a production server.


Scenarios in which Web site projects are the preferred choice include the following:

•You want to include both C# and Visual Basic code in a single web project. 
 (By default, a web application is compiled based on language settings in 
 the project file. Exceptions can be made, but it is relatively difficult.)

•You want to open the production site in Visual Studio and update it in real time
 by using FTP.

•You do not want to have to explicitly compile the project in order to deploy it.

•If you do precompile the site, you want the compiler to create multiple assemblies 
 for the site, which can include one assembly per page or user control, or one 
 or more assemblies per folder.

•You want to be able to update individual files in production by just copying 
 new versions to the production server, or by editing the files directly on 
 the production server.

•If you precompile the site, you want to be able to update individual ASP.NET 
 web pages (.aspx files) without having to recompile the entire site.

•You like to keep your source code on the production server because it can serve 
 as an additional backup copy.

Wednesday, May 28, 2014

How to display text in HTML format in GridView?

I was working on GridView for displaying history of records. I realized that I need to highlight some keywords. I was wondering why GridView is not showing text in HTML format. I had a code like this:
<asp:gridview id="gvHistory" runat="server">
    <columns>
        <asp:boundfield datafield="OldValue" headertext="Old Value"/>
        <asp:boundfield datafield="NewValue" headertext="New Value"/>
        <asp:boundfield datafield="strWhen" headertext="Updated On"/>
        <asp:boundfield datafield="ByWhom" headertext="Updated By"/>
    </columns>
</asp:gridview>

Then I found that GridView has by default HTMLEncode=”True”
HTMLEncode: HTML-encodes a string and returns the encoded string.

HTML encoding makes sure that text is displayed correctly in the browser and not interpreted by the browser as HTML. For example, if a text string contains a less than sign (<) or greater than sign (>), the browser would interpret these characters as the opening or closing bracket of an HTML tag. When the characters are HTML encoded, they are converted to the strings & lt ; and & gt ;, which causes the browser to display the less than sign and greater than sign correctly.

Simple Solution for it is to make "False" to HTMLEncode attribute as follow:
<asp:gridview id="gvHistory" runat="server">
    <columns>
        <asp:boundfield datafield="OldValue" headertext="Old Value" 
HTMLEncode="false"/>
        <asp:boundfield datafield="NewValue" headertext="New Value" 
HTMLEncode="false"/>
        <asp:boundfield datafield="strWhen" headertext="Updated On"/> 
        <asp:boundfield datafield="ByWhom" headertext="Updated By"/> 
    </columns>
</asp:gridview>

By making HTMLEncode attribute to "False", You can allow text in HTML Format.

Tuesday, May 27, 2014

ASP.NET pipeline



The ASP.NET pipeline model consists of an HttpApplication object, various HTTP module objects, and an HTTP handler object, along with their associated factory objects. An HttpRuntime object is used at the start of the processing sequence. Throughout the request life cycle, an HttpContext object is used to convey details about the request and response.

For more information about the ASP.NET request life cycle, see "ASP.NET Life Cycle" at http://msdn.microsoft.com/en-us/library/ms227435(VS.80).aspx.

How to sign out from forms authentication?

The FormsAuthentication.Signout() method is used to sign out from the forms authentication.

What is the difference between SQL notification and SQL invalidation?

SQL Notification: The SQL cache notification generates notifications when the data of a database changes, on which your cache item depends.

SQL Invalidation: The SQL cache invalidation makes a cached item invalid when the data stored in a SQL server database changes.

Friday, May 23, 2014

How to make checkboxlist required on clientside using validator in ASP.Net?

You can do that by using CustomValidator.

Here is the simple code:

<script> 
function ValidateChkBxLst(source, args) {
var chkListModules = document.getElementById('<%= chkBxLst.ClientID%>'); var chkListinputs = chkListModules.getElementsByTagName("input"); for (var i = 0; i < chkListinputs.length; i++) { if (chkListinputs[i].checked) { args.IsValid = true; return; } } args.IsValid = false; } </script> <asp:checkboxlist id="chkBxLst" repeatcolumns="3" repeatdirection="Vertical" runat="server"/> <asp:customvalidator clientvalidationfunction="ValidateChkBxLst" errormessage="CheckBox List" id="cvList" runat="server" text="Please select at least one checkbox." />
Here I have created "CustomValidator" which is pointing to "ValidateChkBxLst" Javascript function to validate it clientside without postback. Isn't it simple?

Thanks

How to log only updated columns for audit table in SQL Server (using Update Trigger)?

Keeping track of all updates for audit log table is common practice. But the question is how we will keep track only those values which have been updated. It is wise decision to capture only updated columns instead of capturing all the columns unnecessary.

We can do so by creating “Update Trigger” in SQL Server. SQL Server provides “COLUMNS_UPDATED()” function to get those. You can learn more about this function from msdn : http://msdn.microsoft.com/en-us/library/ms186329.aspx

I have used temporary table to hold deleted and inserted values for old and new changes. Use of temporary table will not be a problem of overridden values by running simultaneous firing of trigger because they are scope sensitive to the procedure that created them and will remove on their own.

I have created “AuditLog_TestTable” just with one column which is “ModifiedFields” column to represent how it works. So here is the complete Trigger which will log only updated columns in audit table.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[TestTable_Upon_Update]
ON [dbo].[TestTable]
AFTER UPDATE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @sql as NVARCHAR(max);

-- Temp table for Inserted/Deleted
SELECT * INTO #tempInserted FROM Inserted;
SELECT * INTO #tempDeleted FROM Deleted;

SELECT @sql = COALESCE(@sql + ',' + QUOTENAME(COLUMN_NAME), QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE ( SUBSTRING(COLUMNS_UPDATED(), 
COLUMNPROPERTY(OBJECT_ID(TABLE_SCHEMA + '.' + TABLE_NAME, 'U'),
COLUMN_NAME, 'columnId') / 8 + 1 , 1) & 
POWER(2, -1 + COLUMNPROPERTY(OBJECT_ID(TABLE_SCHEMA + '.' + TABLE_NAME, 'U'),
COLUMN_NAME, 'columnId') % 8 ) > 0 
OR ( (COLUMNPROPERTY(OBJECT_ID(TABLE_SCHEMA + '.' + TABLE_NAME, 'U'),
COLUMN_NAME, 'columnId') % 8 = 0) AND (SUBSTRING(COLUMNS_UPDATED(), 
(COLUMNPROPERTY(OBJECT_ID(TABLE_SCHEMA + '.' + TABLE_NAME, 'U'),
COLUMN_NAME, 'columnId') / 8) , 1) & POWER(2,(8-1))) > 0 ) )
AND TABLE_NAME = 'TestTable' 

-- and column_name in ('c1', 'c2') 
-- limit to specific columns 
-- and column_name not in ('c3', 'c4') -- or exclude specific columns 

SET @sql = ' DECLARE @x as NVARCHAR(max); 
SET @x = ''OLD:'' + 
(SELECT ' + @sql + ' FROM #tempDeleted FOR XML RAW); 
SET @x = @x + ''NEW:'' + 
(SELECT ' + @sql + ' FROM #tempInserted FOR XML RAW); 
INSERT INTO [dbo].[AuditLog_TestTable] 
([ModifiedFields]) VALUES (@x);'; 

EXECUTE (@sql); 
EXECUTE ('DROP TABLE #tempInserted; DROP TABLE #tempDeleted;'); 

END 
Above trigger steps are following:
1. I am storing “Inserted/Deleted” record into temp table.
2. Then, setting @sql variable with only updated columns.
3. Then, getting XML formatted updated columns and it's value to insert into auditLog table
4. Finally, Inserting into auditLog table and dropping #temp tables.

Your comments are most welcome, I hope this can help you.

React-select is very slow on larger list - Found solution - using react-window

 I had more than 4000 items in searchable dropdownlist. I have used react-select but it was very slow. finally I found complete solution to ...