Tuesday, March 30, 2010

Jquery + Asp.net page methods really cool you got to love it...

In your aspx page....

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <link rel="Stylesheet" type="text/css" href="CSS/Main.css" />
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="Javascript/Data.js"></script>
<form id="form1" runat="server">
   <div id="PagerUp" class="pager">

</div><br /><br /><br />
    <div id="ResultsDiv">
<div id="PagerDown" class="pager">

    <input id="HfId" type="hidden" />
     <script type="text/javascript">
         var itemsPerPage = 5;
         $(document).ready(function() {
             getRecordspage(0, itemsPerPage);
             $(".pager").pagination($("#HfId").val(), {
                 callback: getRecordspage,
                 current_page: 0,
                 items_per_page: itemsPerPage,
                 num_display_entries: 5,
                 next_text: 'Next',
                 prev_text: 'Prev',
                 num_edge_entries: 1

In yourcodebehind aspx.cs;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using Microsoft.ApplicationBlocks.Data;
using System.Text;

public partial class _Default : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)

    public static string GetRecords(int currentPage,int pagesize)
        string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
        SqlParameter[] _spParams = new SqlParameter[2];
        _spParams[0] = new SqlParameter("@CurrentPage", currentPage);
        _spParams[1] = new SqlParameter("@PageSize", pagesize);
        DataSet ds = SqlHelper.ExecuteDataset(connectionString, CommandType.StoredProcedure, "Employee_View_Paging", _spParams);

StringBuilder headStrBuilder = new StringBuilder(ds.Tables[0].Columns.Count * 5); //pre-allocate some space, default is 16 bytes
        for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
            headStrBuilder.AppendFormat("\"{0}\" : \"{0}{1}¾\",", ds.Tables[0].Columns[i].Caption, i);
        headStrBuilder.Remove(headStrBuilder.Length - 1, 1); // trim away last ,

        StringBuilder sb = new StringBuilder(ds.Tables[0].Rows.Count * 5); //pre-allocate some space
        sb.Append("\" : [");
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            string tempStr = headStrBuilder.ToString();
            for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                ds.Tables[0].Rows[i][j] = ds.Tables[0].Rows[i][j].ToString().Replace("'", "");
                tempStr = tempStr.Replace(ds.Tables[0].Columns[j] + j.ToString() + "¾", ds.Tables[0].Rows[i][j].ToString());
            sb.Append(tempStr + "},");
        sb.Remove(sb.Length - 1, 1); // trim last ,

         return sb.Append("##").Append(ds.Tables[1].Rows[0].ItemArray[0]).Append("##").Append(ds.Tables[2].Rows[0].ItemArray[0]).ToString();



In your js....

function getRecordspage(curPage) {
        type: "POST",
        url: "Default.aspx/GetRecords",
        data: "{'currentPage':" + (curPage + 1) + ",'pagesize':5}",
        contentType: "application/json; charset=utf-8",
        async: false,
        dataType: "json",
        success: function(jsonObj) {
            var strarr = jsonObj.d.split('##');
            var jsob = jQuery.parseJSON(strarr[0]);
            var divs = '';
            $.each(jsob.Table, function(i, employee) {
                divs += '<div class="resultsdiv"><br /><span class="resultName">' + employee.Emp_Name + '</span><span class="resultfields" style="padding-left:100px;">Category&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.Desig_Name + '</span><br /><br /><span id="SalaryBasis" class="resultfields">Salary Basis&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.SalaryBasis + '</span><span class="resultfields" style="padding-left:25px;">Salary&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.FixedSalary + '</span><span style="font-size:110%;font-weight:bolder;padding-left:25px;">Address&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.Address + '</span></div>';
            $(".resultsdiv").hover(function() {
            }, function() {
var paginationClone = $("#PagerUp > *").clone(true);


background-color: #FFF;border-top:solid 1px #ddd; height:50px; border-bottom:solid 1px #ddd; padding-bottom:15px; width:450px; 
.resultseven { background-color: #EFF1f1; }
.resultshover { background-color: #F4F2F2; cursor:pointer; }

font-size:125%;font-weight:bolder;color:#476275;font-family:Arial,Liberation Sans,DejaVu Sans,sans-serif;
font-size:110%;font-weight:bolder;font-family:Arial,Liberation Sans,DejaVu Sans,sans-serif;
color:#476275;font-size:110%;font-weight:bold;font-family:Arial,Liberation Sans,DejaVu Sans,sans-serif;

Stored Procedure:

ALTER PROCEDURE [dbo].[Employee_View_Paging] 
@CurrentPage INT,
@PageSize INT
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.

    -- Insert statements for procedure here
-- SELECT e.Emp_Id,e.Identity_No,e.Emp_Name,e.Address,convert(varchar, e.Date_Of_Birth, 103) as Date_Of_Birth,d.Desig_Name,d.Desig_Description,case WHEN e.SalaryBasis=1 THEN 'Weekly' ELSE 'Monthly' end as SalaryBasis,e.FixedSalary
--      from Employee as e inner join Designation as d on e.Desig_Id=d.Desig_Id where e.Is_Deleted=0

    SELECT ROW_NUMBER() OVER (ORDER BY Emp_Id) AS Row,Emp_Id,Emp_Name,[Address],Desig_Name,SalaryBasis,FixedSalary FROM    
      ROW_NUMBER() OVER (ORDER BY Emp_Id) AS Row,Emp_Id,Emp_Name,[Address],Desig_Name,SalaryBasis,FixedSalary
       FROM Employee_View
     ) AS EmpWitRowNos
    WHERE  Row >= (@CurrentPage - 1) * @PageSize + 1 AND Row <= @CurrentPage*@PageSize

    SELECT COUNT(*) as TotalCount FROM Employee_View
    SELECT  CEILING(COUNT(*) / CAST(@PageSize AS FLOAT)) NumberOfPages
     FROM  Employee_View

Thursday, March 25, 2010

ViewState Compression ....

Compressing and Decompressing Data in Memory

The code below is really simple, and doesn't need further explanation:

using System.IO;
using System.IO.Compression;

public static class Compressor
    public static byte[] Compress(byte[] data)
        MemoryStream output = new MemoryStream();
        GZipStream gzip = new GZipStream(output,
                          CompressionMode.Compress, true);
        gzip.Write(data, 0, data.Length);
        return output.ToArray();

    public static byte[] Decompress(byte[] data)
        MemoryStream input = new MemoryStream();
        input.Write(data, 0, data.Length);
        input.Position = 0;
        GZipStream gzip = new GZipStream(input,
                          CompressionMode.Decompress, true);
        MemoryStream output = new MemoryStream();
        byte[] buff = new byte[64];
        int read = -1;
        read = gzip.Read(buff, 0, buff.Length);
        while (read > 0)
            output.Write(buff, 0, read);
            read = gzip.Read(buff, 0, buff.Length);
        return output.ToArray();

In your base page include these methods and you are done:
protected override object LoadPageStateFromPersistenceMedium()
        string viewState = Request.Form["__VSTATE"];
        byte[] bytes = Convert.FromBase64String(viewState);
        bytes = Compressor.Decompress(bytes);
        LosFormatter formatter = new LosFormatter();
        return formatter.Deserialize(Convert.ToBase64String(bytes));

    protected override void SavePageStateToPersistenceMedium(object viewState)
        LosFormatter formatter = new LosFormatter();
        StringWriter writer = new StringWriter();
        formatter.Serialize(writer, viewState);
        string viewStateString = writer.ToString();
        byte[] bytes = Convert.FromBase64String(viewStateString);
        bytes = Compressor.Compress(bytes);
        ClientScript.RegisterHiddenField("__VSTATE", Convert.ToBase64String(bytes));

Now view your aspx page in firefox Viewstate size addon will show your reduced size...

Tuesday, March 23, 2010

Add divs below a parent div using jquery...

The following function will allow you to add div below a parent div

function Iteratejsondata(HfJsonValue) {
    var jsonObj = eval('(' + HfJsonValue + ')');

    for (var i = 0, len = jsonObj.Table.length; i < len; ++i) {
        var employee = jsonObj.Table[i];
        $('<div  class="resultsdiv"><br /><span id="EmployeeName" style="font-size:125%;font-weight:bolder;">' + employee.Emp_Name + '</span><span style="font-size:100%;font-weight:bolder;padding-left:100px;">Category&nbsp;:</span>&nbsp;<span>' + employee.Desig_Name + '</span><br /><br /><span id="SalaryBasis" style="font-size:100%;font-weight:bolder;">Salary Basis&nbsp;:</span>&nbsp;<span>' + employee.SalaryBasis + '</span><span style="font-size:100%;font-weight:bolder;padding-left:25px;">Salary&nbsp;:</span>&nbsp;<span>' + employee.FixedSalary + '</span><span style="font-size:100%;font-weight:bolder;padding-left:25px;">Address&nbsp;:</span>&nbsp;<span>' + employee.Address + '</span></div>').insertAfter('#ResultsDiv');

Friday, March 19, 2010

FInd 3rd MAX salary in Sql Server?

Use the following...

        Wages FLOAT


--SELECT  MAX(Wages)
--FROM    @Table where Wages < (select MAX(Wages) from @Table where wages < (select MAX(Wages) from @Table))

FROM    (
            SELECT  *,
                    ROW_NUMBER() OVER(ORDER BY Wages DESC) RowID
            FROM    @Table
        ) sub
WHERE   RowID = 3

Wednesday, March 17, 2010

Advantages of jQuery

Advantages of jQuery
1.      It’s lightweight, easy and fast.
2.      Write less but do more.
3.      Cross Browser Compatibility.
4.      Separate javascript code from HTML mark-up.
5.      Easy and Light-weight Ajax Application.
6.      Availability of various plug-in’s.
7.      You can extend it.
8.      We can use CDN (Content Distribution Network) for internet site.
9.      Microsoft and Intellisense support in Visual Studio 2008.
10.  Easy Integration with ASP.Net Ajax projects.

Moving forward, we will look deeply into the above advantages with examples.

1.    It’s lightweight, easy and fast
jQuery library as such is not a bulky library in terms of size(just 20KB in compressed form), execution time, etc. Once you start using jQuery, you can understand its simplicity and it will take very less development time when compared to classical javascript code. As I said earlier, just including the jQuery library using <script> tag is all you need to work on jQuery. It has no security risk associated with it. You can include it in your project just like any other javascript file.

2.    Write less but do more
The main advantage of jQuery library is, we can do various complex client side operations with very less code. This is because of various selector expressions support, chaining mechanism and other similar features of jQuery which makes the complex DOM manipulation lot easier.

To select a HTML element in javascript,
The above equivalent in jQuery will be,

To select all the rows in a table and setting a background color,
<script src="_scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
    <script language="javascript">
        $(document).ready(function() {
            $('#table1 > tbody > tr').css("background-color", "Red");          
Refer jQuery selector documentation to know more on jQuery selectors.

Refer the below 2 articles which will check the CheckBoxes in all the rows when we select the header CheckBox in a GridView control to understand the above point. First uses javascript and former uses jQuery library.

GridView with CheckBox – Select All and Highlight Selected Row – JavaScript Version and more code.
Check All Checkboxes in GridView using jQuery – jQuery version and less code.

The other advantage of jQuery is using the chaining mechanism which will help us to reduce the code.
Refer the below code to understand better,
<script language="javascript">
        $(document).ready(function() {          
            $('#txtName').css("background-color", "Red").val("Test");
The above code selects a TextBox control with ID txtName, then applies css style and then set its text as “Test”.

3.    Cross Browser Compatibility
The jQuery code we write is compatible with all the browsers and hence it prevents the need to write separate client side code for different browsers. Remember to set the css properties that are cross-browser compatible when using jQuery for cross browser compatibility.

4.    Separate javascript code from HTML mark-up
jQuery library enables us to separate the client side scripts from the HTML mark-ups. This is possible because of $(document).ready() function of jQuery.
For example,
<input id="btnSubmit" onclick="javscript:Save()" type="button" value="button" />

The above code can written as,
    <script src="_scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
    <script language="javascript">
        $(document).ready(function() {         
            $('#btnSubmit').click(function() {
                alert('Submit Clicked!');
Thus, when we use jQuery library we can make our HTML code neat without any javascript code combined with it.
It is also possible to separate jQuery code into a separate javascript file and link to the aspx page. For example, the above code can be separated in a separate javascript file and it can be linked to the aspx page. Refer the below code,

<head runat="server">
    <script src="_scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
     <script src="_scripts/Default.js" type="text/javascript"></script>
$(document).ready(function() {  
    $('#btnSubmit').click(function() {
        alert('Submit Clicked!');

5.    Easy and Light-weight Ajax Application
One of biggest advantages of using jQuery library is developing light weight Ajax application in ASP.Net with JSON support. With jQuery library we can prevent the bulky ASP.Net AJAX’s UpdatePanel control for Ajax communications.
Refer my articles on codedigest.com to know more,

6.    Availability of various plug-in’s
There are various free plug-in’s available on the internet which we can use in our projects. For example, jQuery tabs, jTemplate, etc.
Refer the plug-in’s directory here. Since, the jQuery usage is becoming high day by day there are already lots of plug-in’s available online which we can re-use.

7.    You can extend it
It is also possible to extend existing functionality provided by jQuery library.
Refer the below post which talks about jQuery Custom Selectors.

8.    We can use CDN (Content Distribution Network) for internet site
If our site is hosted on internet, then we can start using the jQuery library hosted by Google CDN, Content Distribution Network.
Google's Content Distribution Network (also, AJAX Libraries API) hosts most widely used open source JavaScript libraries which can be used globally across the websites. The main advantage of using google's CDN is they manage all the bug fixes, recent updates and provide a high speed access due to better caching, etc.
Read Using the JQuery Library hosted by Google CDN (Content Distribution Network) in ASP.Net Applications to know more.

9.    Microsoft and Intellisense support in Visual Studio 2008
Refer the below 2 FAQ’s to know more,
How to enable jQuery intellisense in Visual Studio 2008?
How to use jQuery intellisense in an external javascript file?

10.                       Easy Integration with ASP.Net Ajax projects
jQuery library can be easily integrated with ASP.Net Ajax applications. Remember the ready event will not fire for an asynchronous postback caused from UpdatePanel control. The ASP.Net AJAX equivalent of ready() function is endRequest event.

<script type="text/JavaScript" language="JavaScript">
    function pageLoad()
       var manager = Sys.WebForms.PageRequestManager.getInstance();
    function endRequest(sender, args)
      //Do all what you want to do in jQuery ready function

Tuesday, March 2, 2010

C# Interview Questions

General Questions
  1. Does C# support multiple-inheritance? 
  2. Who is a protected class-level variable available to? It is available to any sub-class (a class inheriting this class).
  3. Are private class-level variables inherited? Yes, but they are not accessible.  Although they are not visible or accessible via the class interface, they are inherited.
  4. Describe the accessibility modifier “protected internal”. It is available to classes that are within the same assembly and derived from the specified base class.
  5. What’s the top .NET class that everything is derived from? 
  6. What does the term immutable mean?
    The data value may not be changed.  Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.

  7. What’s the difference between System.String and System.Text.StringBuilder classes?
    System.String is immutable.  System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.
  8. What’s the advantage of using System.Text.StringBuilder over System.String?
    StringBuilder is more efficient in cases where there is a large amount of string manipulation.  Strings are immutable, so each time a string is changed, a new instance in memory is created.
  9. Can you store multiple data types in System.Array?
  10. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array.  The CopyTo() method copies the elements into another existing array.  Both perform a shallow copy.  A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array.  A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.
  11. How can you sort the elements of the array in descending order?By calling Sort() and then Reverse() methods.
  12. What’s the .NET collection class that allows an element to be accessed using a unique key?HashTable.
  13. What class is underneath the SortedList class?A sorted HashTable.
  14. Will the finally block get executed if an exception has not occurred?Yes.
  15. What’s the C# syntax to catch any possible exception?A catch block that catches the exception of type System.Exception.  You can also omit the parameter data type in this case and just write catch {}.
  16. Can multiple catch blocks be executed for a single try statement?No.  Once the proper catch block processed, control is transferred to the finally block (if there are any).
  17. Explain the three services model commonly know as a three-tier application.Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources).
Class Questions
  1. What is the syntax to inherit from a class in C#? Place a colon and then the name of the base class.
    Example: class MyNewClass : MyBaseClass
  2. Can you prevent your class from being inherited by another class? Yes.  The keyword “sealed” will prevent the class from being inherited.
  3. Can you allow a class to be inherited, but prevent the method from being over-ridden?Yes.  Just leave the class public and make the method sealed.
  4. What’s an abstract class?A class that cannot be instantiated.  An abstract class is a class that must be inherited and have the methods overridden.  An abstract class is essentially a blueprint for a class without any implementation.
  5. When do you absolutely have to declare a class as abstract?
    1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden.
    When at least one of the methods in the class is abstract.
  6. What is an interface class?Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes.
  7. Why can’t you specify the accessibility modifier for methods inside the interface?They all must be public, and are therefore public by default.
  8. Can you inherit multiple interfaces?Yes.  .NET does support multiple interfaces.
  9. What happens if you inherit multiple interfaces and they have conflicting method names?It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.
    To Do: Investigate
  10. What’s the difference between an interface and abstract class?In an interface class, all methods are abstract - there is no implementation.  In an abstract class some methods can be concrete.  In an interface class, no accessibility modifiers are allowed.  An abstract class may have accessibility modifiers.
  11. What is the difference between a Struct and a Class?
    Structs are value-type variables and are thus saved on the stack, additional overhead but faster retrieval.  Another difference is that structs cannot inherit.
Method and Property Questions
  1. What’s the implicit name of the parameter that gets passed into the set method/property of a class? Value.  The data type of the value parameter is defined by whatever data type the property is declared as.
  2. What does the keyword “virtual” declare for a method or property? The method or property can be overridden.
  3. How is method overriding different from method overloading? When overriding a method, you change the behavior of the method for the derived class.  Overloading a method simply involves having another method with the same name within the class.
  4. Can you declare an override method to be static if the original method is not static? No.  The signature of the virtual method must remain the same.  (Note: Only the keyword virtual is changed to keyword override)
  5. What are the different ways a method can be overloaded? Different parameter data types, different number of parameters, different order of parameters.
  6. If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded constructors; can you enforce a call from an inherited constructor to a specific base constructor?Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.
Events and Delegates
  1. What’s a delegate? A delegate object encapsulates a reference to a method.
  2. What’s a multicast delegate? A delegate that has multiple handlers assigned to it.  Each assigned handler (method) is called.
XML Documentation Questions
  1. Is XML case-sensitive? Yes.
  2. What’s the difference between // comments, /* */ comments and /// comments? Single-line comments, multi-line comments, and XML documentation comments.
  3. How do you generate documentation from the C# file commented properly with a command-line compiler? Compile it with the /doc switch.
Debugging and Testing Questions
  1. What debugging tools come with the .NET SDK?1.   CorDBG – command-line debugger.  To use CorDbg, you must compile the original C# file using the /debug switch.2.   DbgCLR – graphic debugger.  Visual Studio .NET uses the DbgCLR.
  2. What does assert() method do? In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false.  The program proceeds without any interruption if the condition is true.
  3. What’s the difference between the Debug class and Trace class? Documentation looks the same.  Use Debug class for debug builds, use Trace class for both debug and release builds.
  4. Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The tracing dumps can be quite verbose.  For applications that are constantly running you run the risk of overloading the machine and the hard drive.  Five levels range from None to Verbose, allowing you to fine-tune the tracing activities.
  5. Where is the output of TextWriterTraceListener redirected? 
    To the Console or a text file depending on the parameter passed to the constructor.
  6. How do you debug an ASP.NET Web application? 
    Attach the aspnet_wp.exe process to the DbgClr debugger.
  7. What are three test cases you should go through in unit testing? 1.       Positive test cases (correct data, correct output).2.       Negative test cases (broken or missing data, proper handling).3.       Exception test cases (exceptions are thrown and caught properly).
  8. Can you change the value of a variable while debugging a C# application? Yes.  If you are debugging via Visual Studio.NET, just go to Immediate window.
ADO.NET and Database Questions
  1. What is the role of the DataReader class in ADO.NET connections? It returns a read-only, forward-only rowset from the data source.  A DataReader provides fast access when a forward-only sequential read is needed.
  2. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET? SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix.  OLE-DB.NET is a .NET layer on top of the OLE layer, so it’s not as fastest and efficient as SqlServer.NET.
  3. What is the wildcard character in SQL? Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.
  4. Explain ACID rule of thumb for transactions.A transaction must be:1.       Atomic - it is one unit of work and does not dependent on previous and following transactions.2.       Consistent - data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t.3.       Isolated - no transaction sees the intermediate results of the current transaction).4.       Durable - the values persist if the data had been committed even if the system crashes right after.
  5. What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password).
  6. Between Windows Authentication and SQL Server Authentication, which one is trusted and which one is untrusted? 
    Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.
  7. What does the Initial Catalog parameter define in the connection string? 
    The database name to connect to.
  8. What does the Dispose method do with the connection object? Deletes it from the memory.To Do: answer better.  The current answer is not entirely correct.
  9. What is a pre-requisite for connection pooling? 
    Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.  The connection string must be identical.
Assembly Questions
  1. How is the DLL Hell problem solved in .NET? Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.
  2. What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command.
  3. What is a satellite assembly? 
    When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.
  4. What namespaces are necessary to create a localized application? System.Globalization and System.Resources.
  5. What is the smallest unit of execution in .NET?
    an Assembly.
  6. When should you call the garbage collector in .NET?
    As a good rule, you should not call the garbage collector.  However, you could call the garbage collector when you are done using a large object (or set of objects) to force the garbage collector to dispose of those very large objects from memory.  However, this is usually not a good practice.
  7. How do you convert a value-type to a reference-type?
    Use Boxing.
  8. What happens in memory when you Box and Unbox a value-type?
    Boxing converts a value-type to a reference-type, thus storing the object on the heap.  Unboxing converts a reference-type to a value-type, thus storing the value on the stack.

Why C# is used more or preferred over VB.NET?

I believe the answer to this question has mostly to do with syntax and history.
Although VB.NET is an excellent language, the problem with VB.NET has more to do with the history of BASIC than what VB.NET is today.  I can tell you that I prefer C# over VB.NET, and I programmed with Visual Basic versions 3 through 6 with much success.  However, as any ex-Visual Basic developer an attest to, Visual Basic was always viewed as a second-rate language by C++ and Java developers.  There were certainly a number of things that the C++ language would allow over Visual Basic, and not all of them were necessarily positive.  Much of the flexibility allowed by C++ was also the demise of many C++ applications.
I viewed C++ like a surgeon’s scalpel.  With a scalpel, it can take a long time to carve out a piece of art.  And, in the wrong hands you can do more damage than good, as I have seen.  However, in the right hands, you can do very good things. With C++ a developer could do virtually anything since C++ was the core language on which most operating systems were written, and the core for the Microsoft libraries.
Visual Basic was intended to address the need to rapidly develop applications for the largest share of applications needed, such as business applications.  Business applications are more about good business process logic and intuitive user interfaces, not complex user interfaces or algorithms.  Visual Basic was Microsoft's initial attempt at providing a development language to improve programmer productivity.  Visual Basic addressed this need well.
With this little bit of history, programmers who used Visual Basic were not considered by some (C++ and Java developers) to be “professional” developers.  The fact that Visual Basic had the word “Basic” in it was probably the single most dominating reason – in my opinion.  Anything that is “Basic” is probably not powerful – as viewed by many who never really ever used Visual Basic.  I must confess, I had the same biases about other database-related languages like FoxPro and DBase – and I was probably overly critical about those and other tools as well.
I personally have a great deal of respect for Visual Basic and its place in history.  For me, it was the right tool for many solutions at that time.  Visual Basic versions 3 through 6 existed during a time when companies were only beginning to see the advantages of Local Area Networks (LAN), the wide-spread introduction of the Internet and the explosion of the Internet, all of which happened during the timeline of Visual Basic.
If I may deviate a bit, during this time most companies; except for the large Fortune 1000 type companies), viewed personal computers and LAN’s as an expensive investment with very little return on investment (ROI).  This close scrutiny of Information Technology investments eventually proved to be a good investment in productivity for the average company.  The investment in technology then began to swing the other direction at a pace where many companies and investors could not throw enough money into the advancement of technology and new technology companies; and as we all know, this ended with the DOT-COM boom and bust.
Back to the original question about VB.NET or C#.  The important thing to remember is that both VB.NET and C# get their muscle from the .NET Framework.  Other than a few minor differences in functionality between the two, the decision becomes mostly driven by syntax.  I do not include functional because all .NET languages are interoperable with one another.  Again this is provided by the .NET Framework.  I personally prefer the C# syntax.  It is more like C++, JavaScript, and Java.  Although I don’t use Java, I like developing in a syntax that is more widely adopted.  I use JavaScript occasionally and as a creature of habit I like that C# and JavaScript are similar in basic syntax.  I also prefer the terminology or keywords used by C# because they are more object oriented in nature.
This is my preference from a non-technical approach.  Your comments are welcome.