static keyword in C#

When a class member is prefixed by a static keyword, it becomes a static member, and it must be invoked directly from the class level, rather than from an object reference variable. Static members promote a given item to the class level rather than the object level. Static data is allocated once and shared among all instances of the class. The CLR allocates the static data into memory exactly one time.

While any class can define static members, they are quite commonly found within utility classes. By definition, a utility class is a class that only exposes static functionality. It does not maintain any object-level state and is not created with the new keyword.
Rather, a utility class exposes all functionality as class-level (a.k.a., static) members.

The static keyword can be applied to data members, methods, properties, constructor, and entire class definition.

Note: this keyword cannot be used with a static member because this implies an object. A static member cannot reference non-static members in its implementation (it will generate a compiler error).

Q: What will happen if you attempt to assign the value of a static data member in a typical (non-static or instance level) constructor?

A: The the value of the static data member will be reset each time you create a new object.

Static Constructor: A static constructor is a special constructor that is an ideal place to initialize the values of static data when the value is not known at compile time (e.g., read in the value from an external file, a database, generate a random number, etc).

A static constructor allows us to initialize static members of a class at runtime. The CLR calls all static constructors before first use (and never calls them again for that instance of the application).

Few interesting points regarding static constructors:
  1. A given class can define only one static constructor. The static constructor cannot be overloaded.
  2. A static constructor does not take an access modifier and cannot take any parameters.
  3. A static constructor executes exactly one time, regardless of how many objects of the type are created.
  4. The runtime invokes the static constructor when it creates an instance of the class or before accessing the first static member invoked by the caller.
  5. A static constructor cannot be called directly through the code.
  6. The static constructor executes before any instance-level constructors.
Static Class: A static class cannot be created using the new keyword (i.e; it cannot have an instance or object). It can contain only static members (static data members, static methods, static properties or a static constructor).

Endpoint in a WCF Service

A WCF service exposes its contract via collection of Endpoints (one or more endpoints). An endpoint in WCF is an entity which facilitates access of a client to a WCF service. All communication with the WCF service occurs through the endpoints exposed by the service.

In simple terms, it's an URL on which clients can communicate to the service.

An endpoint consists of the following four properties:
  1. Address – The Endpoint's Address is a network address where the Endpoint resides. It indicates the location of the endpoint, i.e.; where it can be found. The address uniquely identifies the endpoint.
    The address of an endpoint is represented in the WCF object model by the EndpointAddress class.
    An EndpointAddress class contains:
    1. A URI property which represents the address of the endpoint.
    2. An Identity property, which represents the security identity of the service and a collection of optional message headers. The optional message headers are used to provide additional and more detailed addressing information to identify or interact with the endpoint.
  2. Binding – The binding specifies how a client can communicate with the endpoint and includes:
    1. Transport protocol (ex – TCT or HTTP).
    2. Message encoding (text or binary).
    3. Security requirements (SSL or SOAP message security).
    A binding is represented in the WCF object model by the abstract base class Binding
  1. Contracts – The contract outlines the functionality exposed by the endpoint to the client. It specifies:
    1. The operations available for the client.
    2. The form of the message.
    3. The type of input parameters or data required to call the operation.
    4. The expected type of processing or response message for the client.
  2. Behaviors – The endpoint has a set of behaviors that specify local implementation details of the endpoint. The local behavior of the service endpoint can be customized by using endpoint behaviors (which achieves this by participating in the process of building a WCF runtime).

Endpoint in a WCF Service - Explained by Mr. Sandeep Karan



Endpoint in a WCF Service


Ranking functions in SQL

Ranking functions introduced with SQL Server 2005 allow us to assign a number to each row returned from a query. They allow us to rank each row in respect to others in several different ways. Ranking functions can be used only with the SELECT and ORDER BY statements. They cannot be used directly in a WHERE or GROUP BY clause, but can be used in a CTE or derived table.

The syntax for ranking functions is shown as follows:

<function_name>() OVER([PARTITION BY <partition_by_list>]
ORDER BY <order_by_list>)
  • function_name: Can be one of ROW_NUMBER, RANK, DENSE_RANK, and NTILE
  • OVER: Defines the details of how the ranking should order or split the data
  • PARTITION BY: Details which data the column should use as the basis of the splits
  • ORDER BY: Details the ordering of the data
There are four ranking functions in SQL Server:
  1. ROW_NUMBER – It allows us to provide incrementing sequential integer values to the rows in the result-set of a query based on logical order that is specified in the ORDER BY subclause of the OVER clause. The ROW_NUMBER function contains the OVER clause, which the function uses to determine the numbering behavior. The ORDER BY option, which determines the order in which the function applies the numbers, must be included in the query. We have the option of starting the numbers over whenever the values of a specified column change, called partitioning, with the PARTITION BY clause.

    Example Query 1: Basic use of ROW_NUMBER()
    SELECT CustomerID, FirstName + ' ' + LastName AS Name,
    ROW_NUMBER() OVER (ORDER BY LastName, FirstName) AS Row
    FROM Sales.Customer AS c
    INNER JOIN Person.Person AS p ON c.PersonID = p.BusinessEntityID;

    Example Query 2: Using ROW_NUMBER() in a CTE
    WITH customers AS(
      SELECT CustomerID, FirstName + ' ' + LastName AS Name,
      ROW_NUMBER() OVER (ORDER BY LastName, FirstName) AS Row
      FROM Sales.Customer AS c
      INNER JOIN Person.Person AS p ON c.PersonID = p.BusinessEntityID
      )
    SELECT CustomerID, Name, Row
    FROM customers
    WHERE Row > 50
    ORDER BY Row;

    Example Query 3: Using PARTITION BY option in ROW_NUMBER()
    SELECT CustomerID, FirstName + ' ' + LastName AS Name, c.TerritoryID,
    ROW_NUMBER() OVER (PARTITION BY c.TerritoryID ORDER BY LastName, FirstName) AS Row
    FROM Sales.Customer AS c
    INNER JOIN Person.Person AS p ON c.PersonID = p.BusinessEntityID;

  2. RANKRANK assigns the same number to the duplicate rows and skips numbers not used. It assigns an ascending, nonunique ranking number to a set of rows, giving the same number to duplicate rows; numbers are skipped for the number of rows that have the same value.
    If rows 2 and 3 are duplicates, RANK will supply the values 1, 3, 3, and 4.

    Example Query 1: Using RANK
    SELECT ROW_NUMBER() OVER (PARTITION BY SUBSTRING(LastName,1,2) ORDER BY LastName) AS RowNum,
    RANK() OVER(ORDER BY SUBSTRING(LastName,1,2) ) AS Ranking, CONCAT(FirstName,' ',LastName) AS CustomerName, UnclearedBalance
    FROM CustomerDetails.Customers
    WHERE UnclearedBalance is not null
    ORDER BY Ranking

  3. DENSE_RANK - This is similar to RANK, but each row number returned will be one greater than the previous setting, no matter how many rows are the same. DENSE_RANK doesn’t skip numbers.
    If rows 2 and 3 are duplicates, DENSE_RANK will supply the values 1, 2, 2, and 3.

    Example Query:
    SELECT ROW_NUMBER() OVER (PARTITION BY SUBSTRING(LastName,1,2) ORDER BY LastName) AS RowNum,
    DENSE_RANK() OVER(ORDER BY SUBSTRING(LastName,1,2) ) AS Ranking, CONCAT(FirstName,'',LastName) AS CustomerName, UnclearedBalance
    FROM CustomerDetails.Customers
    WHERE UnclearedBalance is not null
    ORDER BY Ranking

    Note: Both RANK and DENSE_RANK are similar to the ROW_NUMBER function, but they produce the same ranking value in all rows that have the same logical ordering value.
    The difference between RANK and DENSE_RANK is that RANK indicates how many rows have a lower ordering value, whereas DENSE_RANK indicates how many distinct ordering values are lower.
    For example, a rank of 9 indicates eight rows with lower values. A dense rank of 9 indicates eight distinct lower values.

  4. NTILE – The NTILE function assigns buckets to groups of rows. It allows us to associate the rows in the result with tiles (equally sized groups of rows) by assigning a tile number to each row. This takes the rows from the query and places them into an equal (or as close to equal as possible) number of specified numbered groups, where NTILE returns the group number the row belongs to. The value in parentheses after NTILE defines the number of groups to produce, so NTILE(25) would produce 25 groups of as close a split as possible of even numbers.

    Example Query:
    SELECT NTILE(10) OVER (ORDER BY LastName) AS BatchNumber, CONCAT(FirstName,' ',LastName) AS CustomerName, UnclearedBalance
    FROM CustomerDetails.Customers
    WHERE UnclearedBalance is not null
    ORDER BY BatchNumber
The following SQL query uses all the ranking functions in a single query:
 
SELECT orderid, custid, val,
ROW_NUMBER() OVER(ORDER BY val) AS rownum,
RANK() OVER(ORDER BY val) AS rank,
DENSE_RANK() OVER(ORDER BY val) AS dense_rank,
NTILE(100) OVER(ORDER BY val) AS ntile
FROM Sales.OrderValues
ORDER BY val;

Differentiate between WCF and ASMX Web Service

  • ASMX Web Services (ASP.NET Web Service) are designed to exchange messages only using SOAP over HTTP.
    However, WCF can exchange messages using any format (SOAP is the default format) over any transport protocol (HTTP, TCP/IP, MSMQ, NamedPipes, etc).
  • ASMX Web Services can only be hosted in IIS over HTTP.
    However, WCF service can be hosted in IIS, WAS (Windows Process Activation Services), Console Application, Windows NT Services, WCF provided host.
  • There is limited security in ASMX Web Services. IIS is responsible for authentication and authorization and ASP.NET security configuration, and transport layer security. WSE can be used for message layer security.
    WCF supports many of the capabilities provided by IIS and WS-* security models. It provides a consistent security programming model for any protocol. The security provided by WCF is consistent regardless of the host that is used to implement the service. WCF also supports claim based authorization, that provides much better control over resources than role based security.
  • ASMX Web Services uses XmlSerializer for serialization while WCF uses DataContractSerializer which is far better in performance than XmlSerializer. Major issues with XmlSerializer is as given below:
    a) Only public fields or properties can be translated to XML.
    b) The classes which implements IEnumerable interface can only be translated.
    c) Classes that implement IDictionary such as Hashtable cannot be serialized.
  • Web Services are not as flexible as WCF services. If you make a new version of the service then you need to just expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends.

    Note: WebService supports Early Binding while WCF supports Late Binding.

    A major advantage of WCF over WebServices is that it can exchange messages in the following patterns:

    1)    Request – Reply Message Exchange Pattern
    2)    One – Way Message Exchange Pattern
    3)    Duplex Message Exchange Pattern

    WebServices only supports Request – Reply Message Exchange Pattern.

Differentiate between Server.Transfer() & Response.Redirect()

Both Server.Transfer and Response.Redirect are ASP.NET objects and are used for navigation between web-pages. However, there are noticeable differences between these two techniques:

Response.Redirect()
  • Response.Redirect() redirects the user to another web-page which may or may not be on the same server. It can redirect the user to an external website on a different server.
  • Response.Redirect() updates the address bar and adds the updated URL to the browser history. User can click back on the browser to navigate to the previous page.
  • Response.Redirect() terminates the request with HTTP 302 status and client-side roundtrip. Client then navigates to the new address and the browser address bar and history updates. The client pays the cost of additional round-trips to the server on each request.
  • Form variables are are not transferred upon a call to Response.Redirect().

Server.Transfer()
  • Server.Transfer() quits current execution of the web-page and redirects the user to another web-page on the same server. It cannot send the user to an external website on a different server.
  • Server.Transfer() keeps the URL unchanged in the address bar. It happens entirely on the server side and the client browser’s address bar remains constant. User cannot click on back button on the browser to navigate to the previous page
  • Server.Transfer() reduces the server request and conserves server resources. It simply changes the focus on the Web Server and transfers the request. With Server.Transfer() there are less number of HTTP requests, which eases pressure on the Web Server and makes the application execute faster.
  • Developer can transfer Query Strings and form variables with a little bug-bashing. The Server.Transfer() method has a second parameter – preserveForm. If this is set to True, the existing query string and form variables will be available to the transferred page. Ex – Server.Transfer(“webpage2”, True);

How can you force Garbage Collection

The GC.Collect method of the garbage collection GC class can be used to force garbage collection. The GC.Collect method may be used if there is a significant reduction in the amount of memory being used at a defined point in an application's code.

The garbage collector suspends all threads that are currently in the process of execution, before it performs a collection. Frequent calls to GC.Collect method may create performance issues. In most cases the optimizing engine in the garbage collector (which determines the best time to run a garbage collection) is better at determining the best time to perform a collection. 

In general, calls to any of the collect methods should be avoided, and the garbage collector should be allowed to run independently.