Tuesday, November 17, 2009

Features in .NET Framework 4.0


Features in the .NET Framework 4.0

The Microsoft .NET Framework is one of the favorite development frameworks platform running on Microsoft Windows family of operating systems. Currently (on 12 October 2009) the .NET Framework 3.5 Service Pack 1 is the Stable release of .NET Framework released on 11 August 2008. Microsoft also announced the .NET Framework 4.0 on 29 September 2008. The Public Beta was released on 20 May 2009. Here we will take a look at new and enhanced features in the .NET Framework version 4.0 Beta 2 release. This is not final features and is subject to change with respect to the Stable release of .NET Framework version 4.0.

The Microsoft .NET Framework 4 coming up with many new features for enabling developers to create applications faster than ever and fully compatible with the older versions of .NET Framework. Some of the New Features in the .NET Framework Version 4.0 are as follows:

• Improved Security
• Parallel Computing
• Visual Basic and C# languages innovations
• Performance and Diagnostics
• Dynamic Language Run-time
• In-Process Side-by-Side Execution
• Interoperability
• Profiling
• Garbage Collection
• Exceptions Handling
  o Corrupted State Exceptions
• Covariance and Contra-variance
  o Base Class Libraries
• Collections and Data Structures
  o BigInteger
  o SortedSet Generic Class
  o Tuples
• I/O
  o File System Enumeration Improvements
  o Memory-Mapped Files
  o Isolated Storage Improvements
  o Compression Improvements
• Reflection
  o Application Domain Resource Monitoring
• 64-bit View and Other Registry Improvements
• Threading
  o Unified Model for Cancellation
  o Thread-Safe Collection Classes
  o Synchronization Primitives
• Networking
• Web
  o Core Services
  o New Features in ASP.NET AJAX 4
  o Web Forms
  o ASP.NET MVC
  o Dynamic Data
  o Visual Studio 2010 Web Designer Improvements
  o Web Application Deployment with Visual Studio 2010
• Windows Presentation Foundation (WPF) Improvement
• Windows Communication Foundation (WCF) Improvement
• Managed Extensibility Framework
• ADO.NET Improvement
  o Expression Trees
• Support for WS-Discovery
• Standard Endpoints
• Workflow Services
• Workflow Activity Model
• Richer Composite Activity Options
• Expanded Built-in Activity Library
• Enhanced Persistence and Unloading

Improved Security

There have been two major changes to security in the .NET Framework version 4 Beta 1. Machine-wide security policy has been eliminated, although the permissions system remains in place, and security transparency has been extended to become the default enforcement mechanism.

Visual Basic and C# languages innovations

Many innovations in the Visual Basic and C# languages like statement lambdas, implicit line continuations, dynamic dispatch, named parameters, and optional parameters.

Parallel Computing

Parallel Extensions to improve support for parallel computing, which target multi-core or distributed systems. .NET Framework 4 Beta 1 enhance support for parallel programming with a new run-time, new class library types, and diagnostic tools. These features simplify parallel development and enable developers to write efficient, fine-grained, and scalable parallel code in a natural idiom without having to work directly with threads, or the thread pool. .NET Framework 4 Beta 1 is categorized into these four areas:

    1. TaskParallelLibraryOverview
           Includes parallel implementations of for and foreach loops (For and For Each in Visual Basic). Enables you to define concurrent, asynchronous tasks without having to work with threads, locks, or the thread pool.

    2. Parallel LINQ(PLINQ)
           A parallel implementation of LINQ to Objects that significantly improves performance in many scenarios.

    3. Data Structures for Parallel Programming

          Includes high-performance collection classes that are lock-free and thread-safe. Also includes other lightweight objects for synchronization and lazy initialization.

    4. Parallel Diagnostic Tools
          Includes debugger windows for tasks and parallel stacks, and concurrency views in the Visual Studio Team System Profiler that you can use to debug and to tune the performance of parallel code.

Performance and Diagnostics

The Windows Software Development Kit (SDK) provides a set of performance counters that you can use to track the performance of an application. In addition to the following features, the .NET Framework 4 Beta 1 provides improvements in startup time, working set sizes, and faster performance for multithreaded applications. A bref information on the Performance console are as follows:

Runtime Profiling

   Provides an overview of the tools you can use to gather performance data about an application.

Exception Performance Counters
   Describes the performance counters that provide information about the exceptions thrown by an application.

Interop Performance Counters
   Describes the performance counters provide information about an application’s interaction with COM components, COM+ services, and external type libraries.

JIT Performance Counters
   Describes the performance counters that provide information about code that has been just-in-time (JIT) compiled.

Loading Performance Counters

   Describes the performance counters that provide information about assemblies, classes, and application domains that are loaded.

Lock and Thread Performance Counters
   Describes the performance counters provide information about managed locks and threads that an application uses.

Memory Performance Counters
   Describes the performance counters provide information about the garbage collector.

Networking Performance Counters
   Describes the performance counters that provide information about data that an application sends and receives over the network.

Security Performance Counters
   Describes the performance counters that provide information about the security checks that the common language runtime performs for an application.

Performance Counters and In-Process Side-By-Side Applications
   Describes the registry setting that disambiguates multiple runtimes that may be loaded by an in-process side-by-side application.

Dynamic Language Runtime 

The dynamic language runtime (DLR) is a runtime environment that adds a set of services for dynamic languages to the common language runtime (CLR). The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages. We will discuss on above feature in coming article or you can also get more information on it through links provided in bibliography.
Dynamic languages can identify the type of an object at run time, whereas in statically typed languages such as C# and Visual Basic (when you use Option Explicit On) you must specify object types at design time. Examples of dynamic languages are Lisp, Smalltalk, JavaScript, PHP, Ruby, Python, ColdFusion, Lua, Cobra, and Groovy.

In-Process Side-by-Side Execution

In-process side-by-side hosting enables an application to load and activate multiple versions of the common language runtime (CLR) in the same process.

Interoperability

New interoperability features and improvements include the following:
• You no longer have to use primary interop assemblies (PIAs). Compilers embed the parts of the interop assemblies that the add-ins actually use, and type safety is ensured by the common language runtime.
• You can use the System.Runtime.InteropServices..::.ICustomQueryInterface interface to create a customized, managed code implementation of the IUnknown::QueryInterface method. Applications can use the customized implementation to return a specific interface (except IUnknown) for a particular interface ID.

Profiling

In the .NET Framework 4 Beta 1, you can attach profilers to a running process at any point, perform the requested profiling tasks, and then detach.

Garbage Collection

The .NET Framework 4 Beta 1 provides background garbage collection; for more information, see the entry So, what’s new in the CLR 4.0 GC?(http://go.microsoft.com/fwlink/?LinkId=151482) in the CLR Garbage Collector blog.

Exceptions Handling

System.Runtime.ExceptionServices namespace, and adds the ability to handle corrupted state exceptions.

   Corrupted State Exceptions

     The CLR no longer delivers corrupted state exceptions that occur in the operating system to be handled by managed code, unless you apply the HandleProcessCorruptedStateExceptionsAttribute attribute to the method that handles the corrupted state exception.
Alternatively, you can add the following setting to an application’s configuration file:
legacyCorruptedStateExceptionsPolicy=true

Covariance and Contravariance

Several generic interfaces and delegates now support covariance and contravariance. For more information, see Covariance and Contravariance in the Common Language Runtime.

Base Class Libraries
    The following sections describe new features in collections and data structures, exception handling, I/O, reflection, threading, and Windows registry.

Collections and Data Structures

Enhancements in this area include the new System.Numerics … BigInteger structure, the System.Collections.Generic… SortedSet < (Of <(T>) >) generic class, and tuples.

BigInteger
   The new System.Numerics… BigInteger structure is an arbitrary-precision integer data type that supports all the standard integer operations, including bit manipulation. It can be used from any .NET Framework language. In addition, some of the new .NET Framework languages (such as F# and IronPython) have built-in support for this structure.

Sorted Set Generic Class
   The new System.Collections.Generic… SortedSet < (Of <(T>)> ) class provides a self-balancing tree that maintains data in sorted order after insertions, deletions, and searches. This class implements the new System.Collections.Generic… ISet <(Of <(T>)>) interface.
The System.Collections.Generic… HashSet <(Of <(T>)>) class also implements the ISet <(Of <(T>)>) interface.

Tuples
   A tuple is a simple generic data structure that holds an ordered set of items of heterogeneous types. Tuples are supported natively in languages such as F# and IronPython, but are also easy to use from any .NET Framework language such as C# and Visual Basic. The ..NET Framework 4 Beta 1 adds eight new generic tuple classes, and also a Tuple class that contains static factory methods for creating tuples.

I/O

The key new features in I/O are efficient file enumerations, memory-mapped files, and improvements in isolated storage and compression.

File System Enumeration Improvements
    New enumeration methods in the Directory and DirectoryInfo classes return IEnumerable<(Of <(T>)>) collections instead of arrays. These methods are more efficient than the array-based methods, because they do not have to allocate a (potentially large) array and you can access the first results immediately instead of waiting for the complete enumeration to occur.
There are also new methods in the static File class that read and write lines from files by using IEnumerable<(Of <(T>)>) collections. These methods are useful in LINQ scenarios where you may want to quickly and efficiently query the contents of a text file and write out the results to a log file without allocating any arrays.

Memory-Mapped Files
   The new System.IO.MemoryMappedFiles namespace provides memory mapping functionality, which is available in Windows. You can use memory-mapped files to edit very large files and to create shared memory for inter-process communication. The new System.IO… UnmanagedMemoryAccessor class enables random access to unmanaged memory, similar to how System.IO… UnmanagedMemoryStream enables sequential access to unmanaged memory.

Isolated Storage Improvements
   Partial-trust applications, such as Windows Presentation Framework (WPF) browser applications (XBAPs) and ClickOnce partial-trust applications, now have the same capabilities in the .NET Framework as they do in Silverlight. The default quota size is doubled, and applications can prompt the user to approve or reject a request to increase the quota. The System.IO.IsolatedStorage..::.IsolatedStorageFile class contains new members to manage the quota and to make working with files and directories easier.

Compression Improvements
   The compression algorithms for the System.IO.Compression… DeflateStream and System.IO.Compression… GZipStream classes have improved so that data that is already compressed is no longer inflated. This results in much better compression ratios. Also, the 4-gigabyte size restriction for compressing streams has been removed.

Reflection

The .NET Framework 4 Beta 1 provides the capability to monitor the performance of your application domains.

Application Domain Resource Monitoring
   Until now, there has been no way to determine whether a particular application domain is affecting other application domains, because the operating system APIs and tools, such as the Windows Task Manager, were precise only to the process level. Starting with the .NET Framework 4 Beta 1, you can get processor usage and memory usage estimates per application domain.
Application domain resource monitoring is available through the managed AppDomain class, native hosting APIs, and event tracing for Windows (ETW). When this feature has been enabled, it collects statistics on all application domains in the process for the life of the process.

64-bit View and Other Registry Improvements

Windows registry improvements include the following:

• Ability to specify a 32-bit or 64-bit view of the registry with the Microsoft.Win32… RegistryView enumeration when you open base keys.
• the new Microsoft.Win32… RegistryOptions enumeration, which lets you specify a volatile registry key that does not persist after the computer restarts.

Threading

General threading improvements include the following:

• The new Monitor… Enter(Object, Boolean%) method overload takes a Boolean reference and atomically sets it to true only if the monitor is successfully entered.
• You can use the Thread… Yield method to have the calling thread yield execution to another thread that is ready to run on the current processor.

The following sections describe new threading features.

Unified Model for Cancellation
   The .NET Framework 4 Beta 1 provides a new unified model for cancellation of asynchronous operations. The new System.Threading… CancellationTokenSource class is used to create a CancellationToken that may be passed to any number of operations on multiple threads. By calling Cancel()()() on the token source object, the IsCancellationRequested property on the token is set to true and the token’s wait handle is signaled, at which time any registered actions with the token are invoked. Any object that has a reference to that token can monitor the value of that property and respond as appropriate.

Thread-Safe Collection Classes
   The new System.Collections.Concurrent namespace introduces several new thread-safe collection classes that provide lock-free access to items whenever useful, and fine-grained locking when locks are appropriate. The use of these classes in multi-threaded scenarios should improve performance over collection types such as ArrayList, and List< (Of <(T>) >).

Synchronization Primitives
   New synchronization primitives in the System.Threading namespace enable fine-grained concurrency and faster performance by avoiding expensive locking mechanisms. The Barrier class enables multiple threads to work on an algorithm cooperatively by providing a point at which each task can signal its arrival and then block until the other participants in the barrier have arrived. The CountdownEvent class simplifies fork and join scenarios by providing an easy rendezvous mechanism. The ManualResetEventSlim class is a lock-free synchronization primitive similar to the ManualResetEvent class. ManualResetEventSlim is lighter weight but can only be used for intra-process communication. The SemaphoreSlim class is a lightweight synchronization primitive that limits the number of threads that can access a resource or a pool of resources at the same time; it can be used only for intra-process communication. The SpinLock class is a mutual exclusion lock primitive that causes the thread that is trying to acquire the lock to wait in a loop, or spin, until the lock becomes available. The SpinWait class is a small, lightweight type that will spin for a time and eventually put the thread into a wait state if the spin count is exceeded.

Networking

Enhancements have been made that affect how integrated Windows authentication is handled by the HttpWebRequest, HttpListener, SmtpClient, SslStream, NegotiateStream, and related classes in the System.Net and related namespaces. Support was added for extended protection to enhance security. The changes to support extended protection are available only for applications on Windows 7. The extended protection features are not available on earlier versions of Windows. For more information, seeIntegrated Windows Authentication with Extended Protection.

Web

    Core Services
      ASP.NET 4 introduces a number of features that improve core ASP.NET services such as output caching and session-state storage.
     • Web.config File Minification
     • Extensible Output Caching
     • Auto-Start Web Applications
     • Permanently Redirecting a Page
     • The Incredible Shrinking Session State
     • Expanding the Range of Allowable URLs
     • Extensible Request Validation
     • Object Caching and Object Caching Extensibility
     • Extensible HTML, URL, and HTTP Header Encoding
     • Performance Monitoring for Individual Applications in a Single Worker Process
     • Multi-Targeting

  New Features in ASP.NET AJAX 4 

     The new functionality in ASP.NET AJAX enables new client data scenarios for page and component developers that enable JSON data from the server to be rendered as HTML in a highly manageable and efficient way. To enable these scenarios, ASP.NET AJAX includes the following major features:

     • Client-side template rendering.
     • Declarative instantiation of client-side behaviors and controls.
     • Live data binding.
     • Use of the observer pattern with JavaScript types.
     • An AdoNetServiceProxy class for client-side interaction with ADO.NET Data Services.
     • A client-side DataView control for data-bound UI in the browser.
     • DataContext and AdoNetDataContext classes for interaction with Web services.
     • Refactored ASP.NET AJAX framework libraries.
     • Support for the DOM Ready event.
     • Using JSONP to retrieve cross-domain data.

  Web Forms
     Web Forms has been a core feature in ASP.NET since the release of ASP.NET 1.0. Many enhancements have been in this area for ASP.NET 4, including the following:
     • The ability to set meta tags.
     • More control over view state.
     • Easier ways to work with browser capabilities.
     • Support for using ASP.NET routing with Web Forms.
     • More control over generated IDs.
     • The ability to persist selected rows in data controls.
     • More control over rendered HTML in the FormView and ListView controls.
     • Filtering support for data source controls.

   ASP.NET MVC
     ASP.NET MVC was introduced as an add-on framework to ASP.NET 3.5 SP1 in March 2009. Visual Studio 2010 will include a preview of ASP.NET MVC 2. When Visual Studio 2010 ships, it will include the RTM version of ASP.NET MVC 2. The version of ASP.NET MVC 2 that is included in ASP.NET 4 Beta 2 includes new features and capabilities.

   Dynamic Data
     Dynamic Data was introduced in the .NET Framework 3.5 SP1 release in mid-2008. This feature provides many enhancements for creating data-driven applications, including the following:
     • Enabling Dynamic Data for Existing Projects
     • Declarative DynamicDataManager Control Syntax
     • Entity Templates
     • New Field Templates for URLs and E-mail Addresses
     • Creating Links with the DynamicHyperLink Control
     • Support for Inheritance in the Data Model
     • Support for Many-to-Many Relationships (Entity Framework Only)
     • New Attributes to Control Display and Support Enumerations
     • Enhanced Support for Filters

   Visual Studio 2010 Web Designer Improvements
     The Web page designer in Visual Studio 2010 has been enhanced for greater CSS compatibility, includes additional support for HTML and ASP.NET markup snippets, and features a redesigned version of IntelliSense for JScript.
     • Improved CSS Compatibility
     • HTML and JScript Snippets
     • JScript IntelliSense Enhancements.

   Web Application Deployment with Visual Studio 2010
     Today, deploying a Web application is not as easy as it should be. ASP.NET developers often find that they encounter issues such as the following:
     • Web Packaging
     • Web.config Transformation
     • Database Deployment
     • One-Click Publish for Web Applications
     • Resources

Windows Presentation Foundation (WPF) Improvement

Improvements in WPF with new Line of Business controls. Improved Ability to Extend WF Designer Experience. Windows Presentation Foundation (WPF) contains changes and improvements in many areas includes controls, graphics, and XAML.

Windows Communication Foundation (WCF) Improvement

New enhancements to Windows Communication Foundation (WCF) such as support for WCF Workflow Services enabling workflow programs with messaging activities, correlation support, durable two-way communication and rich hosting capabilities. .NET Framework 4 also provides new WCF features such as service discovery, router service, simplified configuration and a number of improvements to queuing, REST support, diagnostics, and performance.

Managed Extensibility Framework

The Managed Extensibility Framework (MEF) is a new library in the .NET Framework 4 Beta 1 that enables you to build extensible and composable applications. MEF enables application developers to specify points where an application can be extended, expose services to offer to other extensible applications, and create parts for consumption by extensible applications. It also enables easy discoverability of available parts based on metadata, without the need to load the assemblies for the parts.

ADO.NET Improvement 

The ADO.NET Entity Framework, which simplifies how developers program against relational databases by raising the level of abstraction.

   Expression Trees
     Expression trees are extended with new types that represent control flow, for example, LoopExpression and TryExpression. These new types are used by the dynamic language runtime (DLR) and not used by LINQ.

Support for WS-Discovery 

The Service Discovery feature enables client applications to dynamically discover service addresses at run time in an interoperable way using WS-Discovery. The WS-Discovery specification outlines the message-exchange patterns (MEPs) required for performing lightweight discovery of services, both by multicast (ad hoc) and unicast (using a network resource).

Standard Endpoints

Standard endpoints are pre-defined endpoints that have one or more of their properties (address, binding, contract) fixed. For example, all metadata exchange endpoints specify IMetadataExchange as their contract, so there is no need for a developer to have to specify the contract. Therefore, the standard MEX endpoint has a fixed IMetadataExchange contract.

Workflow Services

With the introduction of a set of messaging activities, it is easier than ever to implement workflows that send and receive data. These messaging activities enable you to model complex message exchange patterns that go outside the traditional send/receive or RPC-style method invocation.

   Workflow
     Windows Workflow Foundation (WF) in .NET Framework 4 Beta 1 changes several development paradigms from earlier versions. Workflows are now easier to create, execute, and maintain.

Workflow Activity Model

The activity is now the base unit of creating a workflow, instead of using the SequentialWorkflowActivity or StateMachineWorkflowActivity classes. The WorkflowElement class provides the base abstraction of workflow behavior. Activity authors implement WorkflowElement objects imperatively when they have to use the breadth of the runtime. The Activity class is a data-driven WorkflowElement object where activity authors express new behaviors declaratively in terms of other activity objects.

Richer Composite Activity Options

The Flowchart class is a powerful new control flow activity that enables authors to construct process flows more naturally. Procedural workflows benefit from new flow-control activities that model traditional flow-control structures, such as TryCatch and Switch.

Expanded Built-in Activity Library

New features of the activity library include the following:
• Data access activities for interacting with ODBC data sources.
• New flow control activities such as DoWhile, ForEach, and ParallelForEach.
• Activities for interacting with PowerShell and SharePoint.

Enhanced Persistence and Unloading

Workflow state data can be explicitly persisted by using the Persist activity. A host can persist a WorkflowInstance without unloading it. A workflow can specify no-persist zones when working with data that cannot be persisted so that persistence is postponed until the no-persist zone exits.

Friday, September 11, 2009

Disable All the Controls in ASP.Net Web Forms using C#.net

To disable all the controls(label,textbox,dropdown etc) in a web form use the following function

Call the below function like: SetControlsDisable(Page);

public void SetControlsDisable(Control Page)
{
foreach (Control ctrl in Page.Controls)
{
if (ctrl is TextBox)
{
((TextBox)(ctrl)).Enabled = false;
}
else
{
if (ctrl.Controls.Count > 0)
{
SetControlsDisable(ctrl);
}
}

if (ctrl is Button)
{
((Button)(ctrl)).Enabled = false;
}
else
{
if (ctrl.Controls.Count > 0)
{
SetControlsDisable(ctrl);
}
}

if (ctrl is DropDownList)
{
((DropDownList)(ctrl)).Enabled = false;
}
else
{
if (ctrl.Controls.Count > 0)
{
SetControlsDisable(ctrl);
}
}


if (ctrl is CheckBoxList)
{
((CheckBoxList)(ctrl)).Enabled = false;
}
else
{
if (ctrl.Controls.Count > 0)
{
SetControlsDisable(ctrl);
}
}

if (ctrl is ImageButton)
{
((ImageButton)(ctrl)).Enabled = false;
}
else
{
if (ctrl.Controls.Count > 0)
{
SetControlsDisable(ctrl);
}
}

if (ctrl is CheckBox)
{
((CheckBox)(ctrl)).Enabled = false;
}
else
{
if (ctrl.Controls.Count > 0)
{
SetControlsDisable(ctrl);
}
}


if (ctrl is LinkButton)
{
((LinkButton)(ctrl)).Enabled = false;
}
else
{
if (ctrl.Controls.Count > 0)
{
SetControlsDisable(ctrl);
}
}
}
}

Format Currency Textbox in US$ using AJAX in ASP.Net

The following code is used to format (display the currency value in US$ in textbox) the currency field using AJAX in asp.net

First include the AJAX Toolkit controls in your project and add the below code in your form (ASPX file)

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>

Next drag and drop the text box, script manager and FilteredTextBoxExtender

Add the below code




Display the currency(US$) format in textbox in code behind

TextBox1.Text = String.Format("{0:C2}", (ds.Tables[0].Rows[0]["Price"]));

The price will display as “$250,200,000.00”

At the time of inserting the Price in DB, remove the $ and , using the below function and insert into table

public string removeFormat(string amount)
{
string replace;
replace = amount.Replace("$", "");
replace = replace.Replace(",", "");
return replace;
}

Decimal price = Convert.ToDecimal(removeFormat(TextBox1.Text));

Read Excel File using DataReader in ASP.Net using C#.Net


The following code is used to read the excel sheet using data reader in asp.net,
            using System.Data.Common;
      public void ReadXLSFile()
      {
        string Field1, Field2;
        Field1 = "";
        Field2 = "";
        string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data  Source=Book1.xls;Extended Properties=""Excel 8.0;HDR=YES;""";
        
 DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
        using (DbConnection connection = factory.CreateConnection())
        {
            connection.ConnectionString = connectionString;
            using (DbCommand command = connection.CreateCommand())
            {
                command.CommandText = "SELECT Field1, Field2 FROM [Sheet1$]";
                connection.Open();
                using (DbDataReader dr = command.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        Field1 = dr["Field1"].ToString();
                        Field2 = dr["Field2"].ToString();
                    }
                }
            }
        }
    }

Thursday, September 10, 2009

Autoincrement Filed in Sql table with Initial Charecter

Here is the Function to increment the ID Field in Sql table with Initial Character

The below function will get the Tablename,Column name and Field Character(initial character) as a Parameter and return the Increment value with Field Character. Example to increment UserId, need to pass the table name, field name and character as "UI", then the function will return UI00001
public string Autoincrement(string TName, string CName, string FCode)
        {
            string Id = null;
            string strSql = null;
            string tmp = null;
            sqlconn = sqlConnection();
            strSql = "";
            strSql = "select max(cast(substring(" + CName + ",3,10)as integer))+1 from " + TName + "";
            SqlCommand SqlCmd = new SqlCommand(strSql, sqlconn);
            if (sqlconn.State == ConnectionState.Closed)
                sqlconn.Open();
            if (string.IsNullOrEmpty(SqlCmd.ExecuteScalar().ToString()))
            {
                Id = FCode + "00001";
                if (sqlconn.State == ConnectionState.Open)
                    sqlconn.Close();
                return Id;
            }
            strSql = "";
            strSql = SqlCmd.ExecuteScalar().ToString();
            if (strSql.Length == 1)
                tmp = FCode + "0000";
            else if (strSql.Length == 2)
                tmp = FCode + "000";
            else if (strSql.Length == 3)
                tmp = FCode + "00";
            else if (strSql.Length == 4)
                tmp = FCode + "0";
            else
                tmp = FCode;

            tmp = tmp + strSql;
            Id = tmp;
            if (sqlconn.State == ConnectionState.Open)
                sqlconn.Close();
            return Id;
        }

Call the above function as

string userid = Autoincrement("tblUser","UserId","UI");

Default Button in ASP.Net Form

One can set the default button at the form level meaning of all the buttons in the form the one that is set as default will be triggered whenever user presses Enter key.
To set the default button one has to do the following
<form id="index" runat="server" defaultbutton="btn1">
<asp:Button ID="btn1" runat="server" Text="Button"
    OnClick = "btn1_Click" />
<asp:Button ID="btn2" runat="server" Text="Button"
    OnClick = "btn2_Click" />
<asp:Button ID="btn3" runat="server" Text="Button"
    OnClick = "btn3_Click" />
<asp:TextBox ID="txt1" runat="server">asp:TextBox>
form>
Need to provide the ID of the Button to the defaultbutton property and it is set as default.
If you want to do it from code behind refer below (C#)
this.Form.DefaultButton = "btn1"; 
 To do the same things in Master Form, use the below code in code behind
this.Form.DefaultButton = btn1.UniqueID;
  

Prevent user from navigate to previous page using back button of the browser

Prevent user from navigate to previous page using back button of the browser or the back option in the context menu.
One cannot disable the browser back button functionality only thing that can be done is prevent them.
Below is the JavaScript snippets that needs to be placed in the head section of the page where you don’t want the user to revisit using the back button
 
Suppose there are two pages Page1.aspx and Page2.aspx and Page1.aspx redirects to Page2.aspx
Hence to prevent user from visiting Page1.aspx using Back Button you will need to place the script in the head section of Page1.aspx like in the (in above image).

 

Sql Server Date/Time Conversion

SQL Server provides a number of options you can use to format a date/time string. One of the first considerations is the actual date/time needed. The most common is the current date/time using getdate(). This provides the current date and time according to the server providing the date and time. If a universal date/time is needed, then getutcdate() should be used. To change the format of the date, you convert the requested date to a string and specify the format number corresponding to the format needed. Below is a list of formats and an example of the output:

DATE FORMATS
Format # Query(Current date : 09/10/2009 Sample

1

select convert(varchar, getdate(), 1) 09/10/09

2

select convert(varchar, getdate(), 2) 09.09.10

3

select convert(varchar, getdate(), 3) 10/09/09

4

select convert(varchar, getdate(), 4) 10.09.09

5

select convert(varchar, getdate(), 5) 10-09-09

6

select convert(varchar, getdate(), 6) 10 Sep 09

7

select convert(varchar, getdate(), 7) Sep 10, 09

10

select convert(varchar, getdate(), 10) 09-10-09

11

select convert(varchar, getdate(), 11) 09/09/10

101

select convert(varchar, getdate(), 101) 09/10/2009

102

select convert(varchar, getdate(), 102) 2009.09.10

103

select convert(varchar, getdate(), 103) 10/09/2009

104

select convert(varchar, getdate(), 104) 10.09.2009

105

select convert(varchar, getdate(), 105) 10-09-2009

106

select convert(varchar, getdate(), 106) 10 Sep 2009

107

select convert(varchar, getdate(), 107) Sep 10, 2009

110

select convert(varchar, getdate(), 110) 09-10-2009

111

select convert(varchar, getdate(), 111) 2009/09/10

Time Format:

Time Format
8 or 108 select convert(varchar, getdate(),8) 00:38:54
9 or 109 select convert(varchar, getdate(), 9) Sep 10 2009 12:38:54:840AM
14 or 114 select convert(varchar, getdate(), 14) 00:38:54:840

You can also format the date or time without dividing characters, as well as concatenate the date and time string:

Sample Statement Output
select replace(convert(varchar, getdate(),101),’/',”) 09102009
select replace(convert(varchar, getdate(),101),’/',”) + replace(convert(varchar, getdate(),108),’:',”) 09102009004426

Maintain the scroll bar position in the same location

In the Page Directive of the Asp.Net Page, add the property ‘MaintainScrollPositionOnPostback’ and set its value as ‘true’.

Example:

<%@ Page CodeFile=”Default.aspx.cs” MaintainScrollPositionOnPostback=”true” Inherits=”_Default” %>

Now, the page will maintain the scroll bar position in the same location as it is before postback

Shrink the DataBase

Try the following code through your Query Analyser to shrink the database.

backup log with truncate_only
use database_name
dbcc SHRINKFILE (database_name_Log,2)
dbcc ShrinkDatabase (database_name, 2)

To set the maximum file upload size supported by Asp.Net

To set the maximum file upload size supported by Asp.Net, you must add the under section in the web.config file. The syntax is below

httpRuntime maxRequestLength=”Maximum size you want to upload in KB”
executionTimeout=”No. of seconds for Execution Time Out” />

Limit the number of characters in the Asp.Net TextArea

This tips will help you to limit the number of characters in the Asp.Net TextArea or Asp.Net Multiline Textbox. It uses a JavaScript function to limit the characters keyed in the TextArea.

Step 1: Add the below JavaScrpit function between the in your aspx page.

function fnLimitTextAreaChars(textareaName, NoOfChars)
{
if (textareaName.value.length > NoOfChars)
{
textareaName.value = textareaName.value.substring(0, NoOfChars);
}
}

Step 2: In the code-behind at Page_Load event, add the two lines as follows.

TextBox1.Attributes.Add(”onKeyDown”, “fnLimitTextAreaChars(this, 150)”);
TextBox1.Attributes.Add(”onKeyUp”, “fnLimitTextAreaChars(this, 150)”);

It’s done. Now when you type any letters in the TextArea, it will allow only first 150 characters. The rest will be truncated. Try yourself.