Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Friday, May 20, 2011

How to Fixed GridView's Header and Footer when scrolling?

1: Use the below  Css Classes for GridView Header and footer
<style type="text/css">
        .GVFixedHeader { font-weight:bold; background-color: Green; position:relative; top:expression(this.parentNode.parentNode.parentNode.scrollTop-1);}
        .GVFixedFooter { font-weight:bold; background-color: Green; position:relative; bottom:expression(getScrollBottom(this.parentNode.parentNode.parentNode.parentNode));}
    </style



2: Use the below JavaScript to compute Footer's Position 
<script language="javascript" type="text/javascript">
        function getScrollBottom(p_oElem)
        {
            return p_oElem.scrollHeight - p_oElem.scrollTop - p_oElem.clientHeight;
        }
    </script>


3: Create GridView inside a Panle, Set Panle's property ScrollBars to "Auto", Gridview's HeaderStyle to "GVFixedHeader" and FooterStyle to "GVFixedFooter".

 <asp:Panel runat="server" ID="pnlContainer" ScrollBars="Auto" Height="150px" Width="400">
    <asp:GridView ShowFooter="True" runat="server" Width="96%" ID="gvDemo" AutoGenerateColumns="False">
    <HeaderStyle CssClass="GVFixedHeader" />
    <FooterStyle CssClass="GVFixedFooter" />
        <Columns>
            <asp:TemplateField HeaderText="C1">
                <ItemTemplate>
                    <asp:Label ID="Label2" runat="server" Text='<%# Bind("C1") %>'></asp:Label>
                </ItemTemplate>
                <FooterTemplate>
                    C1 Footer Here
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="C2">
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("C2") %>'></asp:Label>
                </ItemTemplate>
                <FooterTemplate>
                    C2 Footer Here
                </FooterTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
   </asp:Panel>

4: Code Behide: In the Page_Load function we Bind the data source to GridView.

protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt=new DataTable();
        dt.Columns.Add("C1");
        dt.Columns.Add("C2");
        DataRow drRow;
        for(int i=0;i<=10;i++)
        {
             drRow = dt.NewRow();
            drRow[0] = "C1" + i;
            drRow[1] = "C2" + i;
            dt.Rows.Add(drRow);
        }
        gvDemo.DataSource=dt;
        gvDemo.DataBind();
        
    }

5: Run the Page, you will see that the Header and Footer is fixed when you scrolling.



6:  Default.aspx page

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>GridViewDemo</title>
    <style type="text/css">
        .GVFixedHeader { font-weight:bold; background-color: Green; position:relative; top:expression(this.parentNode.parentNode.parentNode.scrollTop-1);}
        .GVFixedFooter { font-weight:bold; background-color: Green; position:relative; bottom:expression(getScrollBottom(this.parentNode.parentNode.parentNode.parentNode));}
    </style>
    <script language="javascript" type="text/javascript">
        function getScrollBottom(p_oElem)
        {
            return p_oElem.scrollHeight - p_oElem.scrollTop - p_oElem.clientHeight;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Panel runat="server" ID="pnlContainer" ScrollBars="Auto" Height="150px" Width="400">
    <asp:GridView ShowFooter="True" runat="server" Width="96%" ID="gvDemo" AutoGenerateColumns="False">
    <HeaderStyle CssClass="GVFixedHeader" />
    <FooterStyle CssClass="GVFixedFooter" />
        <Columns>
            <asp:TemplateField HeaderText="C1">
                <ItemTemplate>
                    <asp:Label ID="Label2" runat="server" Text='<%# Bind("C1") %>'></asp:Label>
                </ItemTemplate>
                <FooterTemplate>
                    C1 Footer Here
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="C2">
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("C2") %>'></asp:Label>
                </ItemTemplate>
                <FooterTemplate>
                    C2 Footer Here
                </FooterTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
   </asp:Panel>
    </form>
</body>
</html>

7: Default.aspx.cs page

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt=new DataTable();
        dt.Columns.Add("C1");
        dt.Columns.Add("C2");
        DataRow drRow;
        for(int i=0;i<=10;i++)
        {
             drRow = dt.NewRow();
            drRow[0] = "C1" + i;
            drRow[1] = "C2" + i;
            dt.Rows.Add(drRow);
        }
        gvDemo.DataSource=dt;
        gvDemo.DataBind();
        
    }
}

Sunday, May 1, 2011

What is the difference between thread and process?


A thread is a path of execution that run on CPU, a process is a collection of threads that share the same virtual memory. A process has at least one thread of execution, and a thread always run in a process context.

How can you avoid deadlock in threading?


A good and careful planning can avoid deadlocks.There are so many ways Microsoft has provided by which you can reduce deadlocks example Monitor, Interlocked classes, Wait handles, Event raising from one thread to other thread, ThreadState property which you can poll and act accordingly etc.

What is ReaderWriter Locks ?


You may want to lock a resource only when data is being written and permit multiple clients to simultaneously read data when data is not being updated. The ReaderWriterLock class enforces exclusive access to a resource while a thread is modifying the resource, but it allows nonexclusive access when reading the resource. ReaderWriter locks are a useful alternative to exclusive locks that cause other threads to wait, even when those threads do not need to update data.

What is ManualResetEvent and AutoResetEvent ?


Threads that call one of the wait methods of a synchronization event must wait until another thread signals the event by calling the Set method. There are two synchronization event classes. Threads set the status of ManualResetEvent instances to signaled using the Set method. Threads set the status of ManualResetEvent instances to no signaled using the Reset method or when control returns to a waiting WaitOne call. Instances of
the AutoResetEvent class can also be set to signaled using Set, but they automatically return to nonsignaled as soon as a waiting thread is notified that the event became signaled.

What is ManualResetEvent and AutoResetEvent ?


Threads that call one of the wait methods of a synchronization event must wait until another thread signals the event by calling the Set method. There are two synchronization event classes. Threads set the status of ManualResetEvent instances to signaled using the Set method. Threads set the status of ManualResetEvent instances to no signaled using the Reset method or when control returns to a waiting WaitOne call. Instances of
the AutoResetEvent class can also be set to signaled using Set, but they automatically return to nonsignaled as soon as a waiting thread is notified that the event became signaled.

What is ManualResetEvent and AutoResetEvent ?


Threads that call one of the wait methods of a synchronization event must wait until another thread signals the event by calling the Set method. There are two synchronization event classes. Threads set the status of ManualResetEvent instances to signaled using the Set method. Threads set the status of ManualResetEvent instances to no signaled using the Reset method or when control returns to a waiting WaitOne call. Instances of
the AutoResetEvent class can also be set to signaled using Set, but they automatically return to nonsignaled as soon as a waiting thread is notified that the event became signaled.

What are wait handles ?


Wait handles sends signals of a thread status from one thread to other thread. There are three kind of wait modes :-
√ WaitOne.
√ WaitAny.
√ WaitAll.
When a thread wants to release a Wait handle it can call Set method. You can use Mutex (mutually exclusive) objects to avail for the following modes. Mutex objects are synchronization objects that can only be owned by a single thread at a time. Threads request ownership of the mutex object when they require exclusive access to a resource. Because only one thread can own a mutex object at any time, other threads must wait for ownership of a mutex object before using the resource. The WaitOne method causes a calling thread to wait for ownership of a mutex object. If a thread terminates normally while owning a mutex object, the state of the mutex object is set to be signaled and the next waiting thread gets ownership

What is a monitor object?


Monitor objects are used to ensure that a block of code runs without being interrupted by code running on other threads. In other words, code in other threads cannot run until code in the synchronized code block has finished.
SyncLock and End SyncLock statements are provided in order to simplify access to monitor object.

What is use of Interlocked class ?


Interlocked class provides methods by which you can achieve following functionalities :-
√ Increment Values.
√ Decrement values.
√ Exchange values between variables.
√ Compare values from any thread.
in a synchronization mode.
Example :- System.Threading.Interlocked.Increment(IntA)

How can we know a state of a thread?


"ThreadState" property can be used to get detail of a thread. Thread can have one or a combination of status.System.Threading. Threadstate enumeration has all the values to detect a state of thread. Some sample states are Isrunning, IsAlive, suspended etc.

How can we know a state of a thread?


"ThreadState" property can be used to get detail of a thread. Thread can have one or a combination of status.System.Threading. Threadstate enumeration has all the values to detect a state of thread. Some sample states are Isrunning, IsAlive, suspended etc.

Can we use events with threading ?


Yes, you can use events with thread; this is one of the techniques to synchronize one thread with other.

When working with shared data in threading how do you implement synchronization ?


There are certain somethings that you need to be careful with when using threads. If two threads (e.g. the main and any worker threads) try to access the same variable at the same time, you'll have a problem. This can be very difficult to debug because they may not always do it at exactly the same time. To avoid the problem, you can lock a variable before accessing it. However, if the two threads lock the same variable at the same time,
you'll have a deadlock problem.
SyncLock x
'Do something with x
End SyncLock

What are Daemon threads and how can a thread be created as Daemon?


Daemon thread's run in background and stop automatically when nothing is running program. Example of a Daemon thread is "Garbage collector". Garbage collector runs until some .NET code is running or else its idle.
You can make a thread Daemon by
Thread.Isbackground=true

What is Thread.Join() in threading ?


There are two versions of Thread.Join :-
√ Thread.join().
√ Thread.join(Integer) this returns a Boolean value.
The Thread.Join method is useful for determining if a thread has completed before starting another task. The Join method waits a specified amount of time for a thread to end. If the thread ends before the time-out, Join returns true; otherwise it returns False. Once you call Join, the calling procedure stops and waits for the thread to signal that it is done.
Example you have "Thread1" and "Thread2" and while executing 'Thread1" you call" Thread2.Join()".So Thread1" will wait until "Thread2" has completed its execution and the again invoke "Thread1".
Thread.Join(Integer) ensures that threads do not wait for a long time. If it exceeds a specific time which is provided in integer the waiting thread will start.

What the way to stop a long running thread ?

Thread.Abort() stops the thread execution at that moment itself.

What is Suspend and Resume in Threading ?


It is Similar to Sleep and Interrupt. Suspend allows you to block a thread until another thread calls Thread.Resume. The difference between Sleep and Suspend is that the latter does not immediately place a thread in the wait state. The thread does not suspend until the .NET runtime determines that it is in a safe place to suspend it. Sleep will immediately place a thread in a wait state.

How can we make a thread sleep for infinite period ?


You can also place a thread into the sleep state for an indeterminate amount of time by calling Thread.Sleep (System.Threading.Timeout.Infinite). To interrupt this sleep you can call the Thread.Interrupt method.

What's Thread.Sleep() in threading ?


Thread's execution can be paused by calling the Thread.Sleep method. This method takes an integer value that determines how long the thread should sleep. Example
Thread.CurrentThread.Sleep(2000).

How can you reference current thread of the method ?


"Thread.CurrentThread" refers to the current thread running in the method."CurrentThread" is a public static property.

What does AddressOf operator do in background ?


The AddressOf operator creates a delegate object to the BackgroundProcess method. A delegate within VB.NET is a type-safe, object-oriented function pointer. After the thread has been instantiated, you begin the execution of the code by calling the Start() method of the thread

How can we change priority and what the levels of priority are provided by .NET ?


Thread Priority can be changed by using Threadname.Priority = ThreadPriority.Highest. In the sample provided look out for code where the second thread is ran with a high priority.
Following are different levels of Priority provided by .NET :-
√ ThreadPriority.Highest
√ ThreadPriority.AboveNormal
√ ThreadPriority.Normal
√ ThreadPriority.BelowNormal
√ ThreadPriority.Lowest

Which namespace has threading ?


Systems.Threading has all the classes related to implement threading. Any .NET application who wants to  mplement threading has to import this namespace.

Can we have multiple threads in one App domain ?


One or more threads run in an AppDomain. An AppDomain is a runtime representation of a logical process within a physical process. Each AppDomain is started with a single thread, but can create additional threads from any of its threads.

Did VB6 support multi-threading ?


While VB6 supports multiple single-threaded apartments, it does not support a freethreading model, which allows multiple threads to run against the same set of data.

What is a Thread ?

A thread is the basic unit to which the operating system allocates processor time.

What is Multi-threading ?


Multi-threading forms subset of Multi-tasking. Instead of having to switch between programs this feature switches between different parts of the same program. Example you are writing in word and at the same time word is doing a spell check in background.

What is Multi-tasking ?


It’s a feature of modern operating systems with which we can run multiple programs at same time example Word, Excel etc.

What is CodeDom?


“CodeDom” is an object model which represents actually a source code. It is designed to be language independent - once you create a “CodeDom” hierarchy for a program we can then generate the source code in any .NET compliant language.

What is Native Image Generator (Ngen.exe)?


The Native Image Generator utility (Ngen.exe) allows you to run the JIT compiler on your assembly's MSIL and generate native machine code which is cached to disk. After the image is created .NET runtime will use the image to run the code rather than from the hard disk. Running Ngen.exe on an assembly potentially allows the assembly to load and execute faster, because it restores code and data structures from the native image cache rather than generating them dynamically.

Below are some points to be remembered for Native Image Generator:-
√ Native images load faster than MSIL because JIT compilation and type-safety verification
is eliminated.
√ If you are sharing code between process Ngen.exe improves the performance significantly. As Native image generated Windows PE file so a single DLL file can be shared across applications. By contrast JIT produced code are private to an assembly and can not be shared.
√ Native images enable code sharing between processes.
√ Native images require more storage space and more time to generate.
√ Startup time performance improves lot. We can get considerable gains when applications share component assemblies because after the first application has been started the shared components are already loaded for subsequent applications. If assemblies in an application must be loaded from the hard disk, does not benefit as much from native images because the hard disk access time shadows everything.
√ Assemblies in GAC do not benefit from Native image generator as the loader performs extra validation on the strong named assemblies thus shadowing the benefits of Native Image Generator.
√ If any of the assemblies change then Native image should also be updated.
√ You should have administrative privilege for running Ngen.exe.
√ While this can fasten your application startup times as the code is statically compiled but it can be somewhat slower than the code generated dynamically by the JIT compiler. So you need to compare how the whole application performance with Ngen.exe and with out it.
To run Ngen.exe, use the following command line.
ngen.exe install <assemblyname>


This will synchronously precompile the specified assembly and all of its dependencies. The generated native images are stored in the native image cache. In .NET Framework 2.0 there is a service (.NET Runtime Optimization Service) which can precompile managed assemblies in the background. You can schedule your assemblies to be precompiled asynchronously by queueing them up with the NGEN Service. Use the following command line.

ngen.exe install <assemblyname> /queue:<priority>

Assemblies which are critical to your application's start up time should either be precompiled  synchronously or asynchronously with priority 1. Priority 1 and 2 assemblies are precompiled aggressively while Priority 3 assemblies are only precompiled during machine idle-time.

Synchronously precompiling your critical assemblies guarantees that the native images will be available prior to the first time your end user launches the application but increases the time taken to run your application's set up program. You can uninstall an assembly and its dependencies (if no other assemblies are dependent on
them) from the native image cache by running the following command.

ngen.exe uninstall <assemblyname>

Native images created using Ngen.exe cannot be deployed; instead they need to be created on the end user's machine. These commands therefore need to be issued as part of the application's setup program. Visual Studio .NET can be used to implement this behavior by defining custom actions in a Microsoft Installer (MSI) package

What is the difference between Convert.toString and .toString() method ?


Just to give an understanding of what the above question means seethe below code.
int i =0;
MessageBox.Show(i.ToString());
MessageBox.Show(Convert.ToString(i));
We can convert the integer “i” using “i.ToString()” or “Convert.ToString” so what’s the difference. The basic difference between them is “Convert” function handles NULLS while “i.ToString()” does not it will throw a NULL reference exception error. So as good coding practice using “convert” is always safe.

How to prevent my .NET DLL to be decompiled?


By design .NET embeds rich Meta data inside the executable code using MSIL. Any one can easily decompile your DLL back using tools like ILDASM (owned by Microsoft) or Reflector for .NET which is a third party. Secondly there are many third party tools which make this decompiling process a click away. So any one can easily look in to your assemblies and reverse engineer them back in to actual source code and understand some real good logic which can make it easy to crack your application.
The process by which you can stop this reverse engineering is using “obfuscation”. It’s a technique which will foil the decompilers. There are many third parties (XenoCode, Demeanor for .NET) which provide .NET obfuscation solution. Microsoft includes one that is Dotfuscator Community Edition with Visual Studio.NET.

What is CODE Access security?


CAS is part of .NET security model that determines whether or not a piece of code is allowed to run and what resources it can use while running. Example CAS will allow an application to read but not to write and delete a file or a resource from a folder..

What is the difference between System exceptions and Application exceptions?


All exception derives from Exception Base class. Exceptions can be generated programmatically or can be generated by system. Application Exception serves as the base class for all applicationspecific exception classes. It derives from Exception but does not provide any extended functionality. You should derive your custom application exceptions from Application Exception. Application exception is used when we want to define user defined exception, while system exception is all which is defined by .NET.

What is the difference between VB.NET and C# ?


Well this is the most debatable issue in .NET community and people treat there languages like religion. Its a subjective matter which language is best. Some like VB.NET’s natural style and some like professional and terse C# syntaxes. Both use the same framework and speed is also very much equivalents. But still let’s list down some major differences between them :-

Advantages VB.NET :-
√ Has support for optional parameters which makes COM interoperability much easy.
√ With Option Strict off late binding is supported.Legacy VB functionalities can be used by using Microsoft.VisualBasic namespace.
√ Has the WITH construct which is not in C#.
√ The VB.NET part of Visual Studio .NET compiles your code in the background. While this is considered an advantage for small projects, people creating very large projects have found that the IDE slows down considerably as the project gets larger.
Advantages of C#
√ XML documentation is generated from source code but this is now been incorporated in Whidbey.
√ Operator overloading which is not in current VB.NET but is been introduced in Whidbey.
√ Use of this statement makes unmanaged resource disposal simple.
√ Access to Unsafe code. This allows pointer arithmetic etc, and can improve performance in some situations. However, it is not to be used lightly, as a lot of the normal safety of C# is lost (as the name implies).This is the major difference that you can access unmanaged code in C# and not in VB.NET

What is concept of Boxing and Unboxing ?


Boxing permits any value type to be implicitly converted to type object or to any interface type implemented by value type. Boxing is a process in which object instances are created and copy values in to that instance.

Unboxing is vice versa of boxing operation where the value is copied from the instance in to appropriate storage location.

Below is sample code of boxing and unboxing where integer data type is converted in to object
and then vice versa.

Dim x As Integer
Dim y As Object
x = 10
‘ boxing process
y = x
112
‘ unboxing process
x = y

What are Value types and Reference types ?


Value types directly contain their data which are either allocated on the stack or allocated in-line in a structure.
Reference types store a reference to the value's memory address, and are allocated on the heap. Reference types can be self-describing types, pointer types, or interface types.
Variables that are value types each have their own copy of the data, and therefore operations on one variable do not affect other variables. Variables that are reference types can refer to the same object; therefore, operations on one variable can affect the same object referred to by another variable. All types derive from the  ystem.Object base type.

What are different types of JIT ?


JIT compiler is a part of the runtime execution environment.
In Microsoft .NET there are three types of JIT compilers:

Pre-JIT :- Pre-JIT compiles complete source code into native code in a single compilation cycle. This is done at the time of deployment of the application.
Econo-JIT :- Econo-JIT compiles only those methods that are called at runtime However, these compiled methods are removed when they are not required.
Normal-JIT :- Normal-JIT compiles only those methods that are called at runtime .
 These methods are compiled the first time they are called, and then they are stored in cache. When the same methods are called again, the compiled code from cache is used for execution.

What is reflection?


All .NET assemblies have metadata information stored about the types defined in modules. This metadata information can be accessed by mechanism called as “Reflection”.System. Reflection can be used to browse through the metadata information. Using reflection you can also dynamically invoke methods using  ystem.Type.Invokemember.

Can we force garbage collector to run ?


System.GC.Collect() forces garbage collector to run. This is not recommended but can be used if situations arises.

What is garbage collection?


Garbage collection is a CLR feature which automatically manages memory. Programmers forget to release the objects while coding ..... Laziness (Remember in VB6 where one of the good practices is to set object to nothing). CLR automatically releases objects when they are no longer in use and refernced. CLR runs on non-deterministic to see the unused objects and cleans them. One side effect of this non-deterministic feature is that we cannot assume an object is destroyed when it goes out of the scope of a function. Therefore, we should not put code into a class destructor to release resources.