SARGable Query

Just by adding an index to a table doesn’t mean you get performance improvement.
To make query sargable by not altering the column side of Where predicate or join clause so that SQL Server can utilize the index on that column whithout having to do any extra work.
Non-Sargable Query example on dbo.Invetory table with 100 records:

</pre>
Select Name FROM dbo.Inventory WHERE CONVERT(CHAR(10), CreateDate, 121) = '2018-06-28' 

Here Sql Server will perform Index Scan on each row

Sargable Query example:

SELECT Name
FROM dbo.Inventory
WHERE CreateDate = CAST('2018-06-28' as datetime2)

Here Sql Server will perform Index Seek.

Reference
https://blog.bertwagner.com/how-to-search-and-destroy-non-sargable-queries-on-your-server-ff9f57c7268e

Leave a comment

Filed under SQL

Q How can you prevent a cleint by using Action method in MVC?

I have two actions inside my controller (shoppingCartController)

public ActionResult Index()
{
	//some stuff here
	return View(viewModel);
}

public ActionResult AddToCart(int id)
{

	return RedirectToAction("Index");

}

Is there anyway to prevent the users from directly calling the index action by typing the url in the browser?
For example: If the user browses to shoppingCart/index be redirected to Home/Index.
Solution
You could use the [ChildActionOnly] attribute on your action method to make sure it’s not called directly, or use the ControllerContext.IsChildAction property inside your action to determine if you want to redirect.
For example:

//[ChildActionOnly]
public ActionResult Index()
{
    if(!ControllerContext.IsChildAction)
    {
       //perform redirect here
    }

    //some stuff here
    return View(viewModel);
}

Reference:
https://stackoverflow.com/questions/9407172/asp-net-mvc-how-to-prevent-browser-from-calling-an-action-method

 

Leave a comment

Filed under C#, Interview question, MVC, Uncategorized

Q Explain deferred execution vs. immediate execution in LINQ. Provide examples.

In LINQ, deferred execution simply means that the query is not executed at the time it is specified. Specifically, this is accomplished by assigning the query to a variable. When this is done, the query definition is stored in the variable but the query is not executed until the query variable is iterated over. For example:

DataContext productContext = new DataContext();

var productQuery = from product in productContext.Products
where product.Type == "SOAPS"
select product; // Query is NOT executed here

foreach (var product in productQuery) // Query executes HERE
{
	Console.WriteLine(product.Name);
}

You can also force immediate execution of a query. This can be useful, for example, if the database is being updated frequently, and it is important in the logic of your program to ensure that the results you’re accessing are those returned at the point in your code where the query was specified. Immediate execution is often forced using a method such as Average, Sum, Count, List, ToList, or ToArray. For example:

DataContext productContext = new DataContext();

var productCountQuery = (from product in productContext.Products
where product.Type == "SOAPS"
select product).Count(); // Query executes HERE

Ref
https://www.toptal.com/dot-net/interview-questions

Leave a comment

Filed under C#, Interview question

How does HTTPS works?

How does HTTPS works?

  1. Client request for secure Https  page.
  2. Web server respond by sending certificate with public key.
  3. Client checks the validity of the certificate and create a symmetric session key using the public key and sends it back to Web serer.
  4. Web server decrypt the symmetric session key using it’s private key and sends page encrypted using the symmetric session key.
  5. Secure session has now been established between Client browser & Web server.

ssl-in-a-nutshell

HTTPS pages typically use one of two secure protocols to encrypt communications – SSL (Secure Sockets Layer) or TLS (Transport Layer Security). Both the TLS and SSL protocols use what is known as an ‘asymmetric’ Public Key Infrastructure (PKI) system. An asymmetric system uses two ‘keys’ to encrypt communications, a ‘public’ key and a ‘private’ key. Anything encrypted with the public key can only be decrypted by the private key and vice-versa.

The ‘private’ key should be kept strictly protected and should only be accessible the owner of the private key. In the case of a website, the private key remains securely ensconced on the web server. Conversely, the public key is intended to be distributed to anybody and everybody that needs to be able to decrypt information that was encrypted with the private key.

HTTPS-workflow

 

Leave a comment

Filed under .Net, ASP.Net, C#, WCF

When to use Channel factory in WCF

If you are using assembly-sharing (which is, let’s face it, hugely convenient if you own both ends of the pipe), then both ends already have a complete version if the interface etc. It seems redundant to run the svcutil tool (at command-prompt or via the IDE) just to get back a wrapper for what we already have. It also works very well when you want to code only to an interface, not to the wrapper class – and use some centralised code to get a channel to a particular interface at a given address. This is actually how I mainly use WCF.

The “client” approach works well for one-off services, or where it doesn’t need to go through any central tooling. It also makes for very simple demos.

How to: Use the ChannelFactory

Leave a comment

Filed under WCF

EmitDefaultValue Significance

In .Net, types have default value. Like for reference type default value is null, and for integer type default value is 0.
It is desirable to omit data member from serialized data which is set to it’s default value as a performance advantage.

To omit a member from serialised data, set the EmitDefaultValue property of the attribute to false. Default is true.

[DataContract]
public class Employee
{
    [DataMember]
    public string employeeName = null;

    [DataMember]
    public int employeeID = 0;

    [DataMember(EmitDefaultValue = false)]
    public string position = null;

    [DataMember(EmitDefaultValue = false)]
    public int salary = 0;

    [DataMember(EmitDefaultValue = false)]
    public int? bonus = null;

    [DataMember(EmitDefaultValue = false)]
    public int targetSalary = 57800;
}

XML Representation

<Employee>
   <employeeName xsi:nil="true" />
   <employeeID>0</employeeID>
<targetSalary>57800</targetSalary>
</Employee>

Refrences:
Data Member Default Values

Leave a comment

Filed under WCF

Benefit of const

A Very similar to a #define in C, const “variables” in the .NET Framework don’t have their own actual storage location but rather are substituted into the Microsoft Intermediate Language (MSIL) instructions at compile time where they are referenced. For example, if I have the following C# code

int myInt = 5; 
Console.WriteLine(myInt);

csc.exe will generate this MSIL:

ldc.i4.5 stloc.0 ldloc.0 call void [mscorlib]System.Console::WriteLine(int32)

In other words, it loads the value 5, stores it to the myInt variable, then loads this value back onto the execution stack, and prints it out using Console.WriteLine.

If you change the myInt variable to be a constant, like so

const int myInt = 5; 
Console.WriteLine(myInt);

the MSIL generated will be:

ldc.i4.5 call void [mscorlib]System.Console::WriteLine(int32)

Now, wherever myInt is referenced in the code, instead of having to do a “ldloc.0” to get the value from the variable, the MSIL just loads the constant value which is hardcoded into the MSIL. As such, there’s usually a small performance and memory advantage to using constants.
However, in order to use them you must have the value of the variable at compile time, and any references to this constant at compile time, even if they’re in a different assembly, will have this substitution made. Constants are certainly a useful tool if you know the value at compile time.
If you don’t, but want to ensure that your variable is set only once, you can use the readonly keyword in C# (which maps to initonly in MSIL) to indicate that the value of the variable can only be set in the constructor; after that, it’s an error to change it. This is often used when a field helps to determine the identity of a class, and is often set equal to a constructor parameter.

Leave a comment

Filed under C#

Channel Factory

What is Channel Factory
There are three ways to create a WCF client:

  1. Proxy – Using VS or SvcUtil.exe
  2. WCF Channel Factory
  3. REST services, using HttpClient or WebClient

A Channel Factory enables you to create a communication channel to the service without a proxy.
A Channel Factory is implemented by the IChannelFactory Interface.
The Channel Factory class is useful when you want to share a common service contract DLL between the client and the server.

Using the ChannelFactory<T> class is an easier alternative to making calls to the WCF services to the laborious process of generating proxies via the SvcUtil.exe tool every time a service contract changes. Channel Factory is a factory for creating service communication channels at runtime.
ChannelFactory<T> takes a generic parameter of the service type (it must be a service contract interface) to create a channel.

Implementation
For using channel factory, the following steps are necessary:

  • Create a binding in WCF
  • Create a ChannelFactory class
  • Create a Channel
  • Send-Receive messages over that channel
[ServiceContract]
public interface IService1
{

    [OperationContract]
    string GetData(int value);

}

How to Call WCF Service Use Channel Factory

//1. Create a binding  in WCF
BasicHttpBinding myBinding = new BasicHttpBinding();
EndpointAddress myEndpoint = new EndpointAddress("http://localhost:3047/Service1.svc");

//2. Create a ChannelFactory class
ChannelFactory myChannelFactory = new ChannelFactory(myBinding, myEndpoint);
//3. Create a Channel
IService1 instance = myChannelFactory.CreateChannel();

//4. Send-Receive messages over that channel
Console.WriteLine(instance.GetData(10));

myChannelFactory.Close();

Difference between proxy and channel factory

PROXY Channel Factory
1 Only require URL where the service resides You must have direct access to the assembly that contains that service contract T for
2 Very Simpler Not easier
3 Easy to Understand channels are complex, network-related
4 There is Visual Studio gives you add the reference When you share a common service contract dll between the client and the server, you’ll be using the ChannelFactory class
5 Proxies have several restrictions like:

  1. Properties need to have gets and sets
  2. Contructors can’t be exposed
  3. Methods other than the service contract cannot be exposed
If you know that your entities will not change much and the client code is less, then a DLL would work better than a proxy
6 By using SVCutil.exe you will create PRoxy When you are using DLL that refers Service contract interface then use the channel factory class

When to use a ChannelFactory i.e. a shared DLL?

A DLL is helpful if the client code is under you control and you’d like to: share more than just the service contract with the client — such as some utility methods associated with entities and make the client & the service code more tightly bound. If you know that your entities will not change much and the client code is less, then a DLL would work better than a proxy. Proxies have several restrictions like:

  1. Properties need to have gets and sets
  2. Contructors can’t be exposed
  3. Methods other than the service contract cannot be exposed

What all to package in the DLL?

You’ll need to package the following:

  1. Entities
  2. Service contract — the interface
  3. RequestMsg classes (if any)
  4. ResponseMsg classes (if any)

So if you are designing a connected system and using WCF for that, then you can use a shared dll instead of a proxy, to avoid code repetition and be more effective in the use of the service entities.


Refrences:

http://www.codeproject.com/Tips/558163/Difference-between-Proxy-and-Channel-Factory-in-WC

Leave a comment

Filed under WCF

What does cherry-picking a commit with git means?

Cherry picking in git means to choose a commit from one branch and apply it onto another.

This is in contrast with other ways such as merge and rebase which normally applies many commits onto a another branch.

Make sure you are on the branch you want apply the commit to.

git checkout master

Execute the following:

git cherry-pick

Refrences:-
What does cherry-picking a commit with git means?

Leave a comment

Filed under .Net

Transaction in WCF

http://msdn.microsoft.com/en-us/library/ff384250(d=printer).aspx

http://www.c-sharpcorner.com/UploadFile/81a718/simple-steps-to-enable-transactions-in-wcf/

http://www.c-sharpcorner.com/uploadfile/shivprasadk/wcf-faq-part-5-transactions/

Leave a comment

Filed under WCF

Yield keyword in C#

What is the use of c# “Yield” keyword.

Leave a comment

Filed under C#

Calling Page_View jQuery function

1. Include utility.js which include below script:

$(document).ready(function () {
    var activePage = $("body");
    activePage.InitializeComponent({ Init: $("body").attr("id") });
});

(function () {
    var baseMethods = {
        InitializeComponent: function (options) {
            var defaults =
                {
                    Base: "Page_",
                    Init: "",
                    Data: "",
                    Date: ""
                };
            var opts = $.extend(defaults, options);
            var functionName = opts.Base + opts.Init;
            var C_Ref = null;
            C_Ref = $(this);
            var state = (C_Ref.data("IsBinded") === undefined || C_Ref.data("IsBinded") === null || !C_Ref.data("IsBinded")) ? false : true;

            if (typeof window[functionName] !== "undefined") {
                window[functionName]({ Handled: state, Reference: C_Ref, Data: opts.Data, Date: opts.Date });
                C_Ref.data("IsBinded", true);
            }
        }
                      
    };

    jQuery.each(baseMethods, function (i) {
        jQuery.fn[i] = this;
    });
})(jQuery);

2. Now add a Common js file all views which has js function Page_ for all view pages. Like

 function Page_HelloJQueryTest(e) {
	alert('hi Demo');
 }

here ‘HelloJQueryTest’ is the name of my view.

3. Add both above js file reference layout view. And in html body tag of layout add id attribute i.e. . So your layout will look like:

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/utility.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/Demo.js")" type="text/javascript"></script>
</head>

<body id="@ViewBag.PageID">
    @RenderBody()
</body>
</html>

4. Add ViewBag.PageID = “HelloJQueryTest” to each view which include above layout. Like:
For View HelloJQueryTest.cshtml

	@{
		ViewBag.Title = "HelloJQueryTest";
		ViewBag.PageId = "HelloJQueryTest";
		Layout = "~/Views/Shared/_Layout.cshtml";
	}

	<h2>HelloJQueryTest</h2>
   

5. Above view will have controller action defined. Like:

	public class DemoController : Controller
        {
             public ActionResult HelloJQueryTest()
             {
                return View();
             }
        }
       

6. Now when you run your MVC application then for “HelloJQueryTest” all script user function Page_HelloJQueryTest(e) will be called.
Happy coding

Leave a comment

Filed under jQuery

Garbage Collector

When space is not available on heap, new keyword triggers GC for heap cleanup and then reclaims the space

Leave a comment

Filed under C#

Sessionless Controller

With Sessionless Controller you can easily control your session behavior for controllers.
Before going further better to understand Concurrent Requests in MVC & what are the limitation with the same. And how it is resolved with Sessionless Controller

Leave a comment

Filed under MVC

ASP.Net MVC 3 – New Features

1. New Razor View Engine
Razor view are speedy, smaller & lighter in size. They are easy to learn.
For more detail: Introduction RAZOR

2. Granular Request Validation

3. Sessionless Controller Support

http://weblogs.asp.net/imranbaloch/archive/2011/01/16/asp-net-mvc-3-new-features.aspx

Leave a comment

Filed under MVC

Granular Request Validation MVC 3

This is a new feature provided in MVC 3. We will discuss what is request validation & why it is great to make it granular
Request Validation is a feature of ASP.Net that analyzes the data that a browser send to server when a user interact with your site (such as form or query string data) and reject the request that contain suspicious input that looks like html code (basically anything with a ‘<‘). This protects you from HTML injection such as cross site scripting (XSS). It is enabled by default.
However in previous version it was an all-on-or-off feature, meaning that if you want to be able to accept HTML-formatted input from your users in just one field you had to completely turn this protection off. This in turn meant that you now had to validate every bit of data that came from the client.

AllowHtmlAttribute SkipRequestValidationAttribute
In MVC 3 we have introduced a new attribute called AllowHtmlAttribute. You can You can use this attribute to annotate your model properties to indicate that values corresponding to them should not be validated. Let’s take this User model and UserController as an example:

public class User {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    [AllowHtml]
    public string Description { get; set; }
    [AllowHtml]
    public string Bio { get; set; }
}
 
public class UserController {
    [HttpPost]
    public ActionResult Update(User user) {
        // update user database
    }
}

I have annotated the Description and Bio properties to indicate they should not be request-validated. Now when the Update action method gets invoked these two properties on the User object will not be validated and any HTML they might contain will be passed straight through to the action method. However, everything else will still go through request validation and requests that contain suspicious content in the Name or Email fields will get rejected.

ValidateInputAttribute
AllowHtmlAttribute can only be applied to properties of a model class. For other request validation scenarios the existing ValidateInputAttribute is still helpful. For example, you can use it to disable request validation for action methods that bind to a loose collection of parameters:

[ValidateInput(false)]
public ActionResult Update(int userId, string description)
{
           // Do something
}

Now when the parameters of the Update method get bound request validation will not be performed. You can apply ValidateInput to action methods as shown above or to the entire controller to affect all of its action methods.

ValidateInput is also more usable in MVC 3. In MVC 2 running on .NET 4 you had to set requestValidationMode=”2.0″ in order to turn request validation off. In MVC 3 this is no longer necessary.

Reference: Granular Request Validation in ASP.NET MVC 3

Leave a comment

Filed under MVC

what is lock?

lock marks a statement block as critical section and ensures one thread doesn’t enter critical section with another thread.
lock can be applied on an object. Avoid lock on public type. Below lock should be avoided:

  • lock (this) is a problem if the instance can be accessed publicly.
  • lock (typeof (MyType)) is a problem if MyType is publicly accessible.
  • lock(“myLock”) is a problem because any other code in the process using the same string, will share the same lock.

Best practice is to define private object or private static object variable to protect data common to all instance.

class Account
    {
        decimal balance;
        private Object thisLock = new Object();

        public void Withdraw(decimal amount)
        {
            lock (thisLock)
            {
                if (amount &gt; balance)
                {
                    throw new Exception("Insufficient funds");
                }
                balance -= amount;
            }
        }
    }

for more explanation refer:
http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx

Leave a comment

Filed under C#

What makes thread-safe?

  • struct & immutable are thread safe. so string is also thread safe as all you can do is read them.
  • Reading is safe, if all the threads are reading.
  • If a method only access variable scoped within the method then it is thread safe beacuse each thread has it’s own stack.
  • Also if method calls other method which only use local scoped variables.
public class Thing
{
    public int ThreadSafeMethod(string parameter1)
    {
        int number; // each thread will have its own variable for number.
        number = this.GetLength(parameter1);
        return number;
    }

    private int GetLength(string value)
    {
        int length = value.Length;
        return length;
    }
}

 

  • but if a method use any properties or fields then you need to use lock to ensure the values are not modified by a different thread.
public class Thing
{
    private string someValue; // all threads will read and write to this same field value

    public int NonThreadSafeMethod(string parameter1)
    {
        this.someValue = parameter1;

        int number;

        // Since access to someValue is not synchronised by the class,
        // a separate thread could have changed its value.
        number = this.someValue.Length;
        return number;
    }
}

To ensure proper concurrency you need to use lock.

Leave a comment

Filed under C#

jQuery Explained

How to use jQuery selectors with examples.
http://jquerybyexample.blogspot.com/2011/05/jquery-selectors-examples.html

Difference between $(this) & this in jQuery?
http://jquerybyexample.blogspot.com/2010/08/difference-between-this-and-this-in.html

Does jQuery returns error if DOM element doesn’t exist?
http://jquerybyexample.blogspot.com/2010/08/how-to-check-element-exists-or-not-in.html

What is .bind() method do? And differ from .click() ?
http://jquerybyexample.blogspot.com/2010/06/jquery-bind-function-exampledemo.html

Differ between .bind(), .live() & .delegate()?
http://jquerybyexample.blogspot.com/2010/08/bind-vs-live-vs-delegate-function.html

Understand $.proxy() in jQuery.
http://stackoverflow.com/questions/4986329/understanding-proxy-in-jquery

Leave a comment

Filed under jQuery

MVC Life Cycle Explained

1) An application has one and only one Route Table. This Route Table is setup in the Global.asax file
Initially Application_Start() event is called for the application, where we set all the Routes in the static RouteTable.Route collection (which is of type RouteCollection)

routes.MapRoute(
 "Default", // Route name
 "{controller}/{action}/{id}", // URL with parameters
 new { controller = "Home", action = "Index", id = UrlParameter.Optional }
 );

All route object map route Url to MVCRouteHandler which implement IHttpHandler.

2) The UrlRoutingModule class matches an HTTP request to a route in an ASP.NET MVC application.
UrlRoutingModule passes HttpContext object to RouteTable. The HttpContext object includes Url, form parameters, query string, cookies with the current request.

ControlFlow of MVC

3) The MapRoute method being invoked inside of the RegisterRoutes method is an extension method. Every route registered with MapRoute is configured to use MvcRouteHandler, which is a RouteHandler provided by MVC framework.
It is route handler job to find the HTTP Handler (which implement IHttpHandler) for a request, in MVC this handler is called MvcHandler.

4) When control reaches this MvcHandler, it extract the controller parameter from RouteData and send them to ControllerFactory. It is the factory responsibility to return a controller. All controller in MVC implement IController.
MVC framework provide a default controller factory named DefaultControllerFactory that will search assemblies in appdomain to the Controller with implement IController & ends with Controller. Then the same instance is returned to the MvcHandler. When MvcHandler has a IController reference, it invokes the Execute() on controller.

5) The Execute() method extract members from the Request object and some of which act as method parameter.
The Execute() method finds method of the controller by using reflection on Controller class. It finds the method (action) which matches the route and executes it.

6) When controller transfer to RenderView() method, the call is delegated to ViewEngine’s RenderView() method. It uses ViewLocator class to find the View. And all master page, ViewBag, ViewData are set.

References :
http://msdn.microsoft.com/en-us/magazine/dd695917.aspx

image

2 Comments

Filed under C#

Referential Integrity

Referential Integrity is a database concept which ensures that relationship between tables remain constant.

When one table has a foreign key to another table, the concept of referential integrity states that you may not add a record to the table that contains the foreign key unless there is a corresponding record in the linked table.
There are 3 rules:
1) Insert
2) Cascading delete
3) Cascading update

Reference
http://www.programmerinterview.com/index.php/database-sql/what-is-referential-integrity/

Leave a comment

Filed under SQL

Can foreign Key be NULL and Duplicate?

Yes, Foreign Key can be NULL as well as Duplicate (duplicate in one to many relationship).

Justification
http://stackoverflow.com/questions/7573590/can-foreign-key-null-and-duplicate

Leave a comment

Filed under SQL

Reverse String

Below is the code in two approach:


class ReverseString
    {
        public string Reverse(string str)
        {
            char[] chr = str.ToArray();
            StringBuilder news = new StringBuilder();

            for (int i = str.Length - 1; i >= 0; i--)
                news.Append(str[i]);

            return news.ToString();
        }

        public string ReverseRecursive(string str)
        {
            if (str.Length > 0)
                return str[str.Length - 1] + ReverseRecursive(str.Substring(0, str.Length - 1));
            else
                return str;
        }
    }

class MainReverse
    {
        public static void Main(string[] args)
        {
            Console.Write("Enter the string: ");
            string s = Console.ReadLine();
            ReverseString rs = new ReverseString();
            Console.WriteLine("\nReverse: " + rs.Reverse(s));
            Console.ReadLine();
        }
    }

Refrences :
http://en.support.wordpress.com/code/posting-source-code/

Leave a comment

Filed under C#

What is Dependency Injection (DI)

Dependency Injection allows you to inject object into the class, rather then relying on class to create object.

http://msdn.microsoft.com/en-us/magazine/cc163739.aspx

http://weblogs.asp.net/shijuvarghese/archive/2008/10/24/asp-net-mvc-tip-dependency-injection-with-unity-application-block.aspx

http://www.mikesdotnetting.com/Article/117/Dependency-Injection-and-Inversion-of-Control-with-ASP.NET-MVC

Leave a comment

Filed under C#

Differences Article

Response.Redirect vs Server.transfer

http://quickdotnetsolutions.blogspot.in/2011/05/difference-between-responseredirect-and.html

 

wcf service over web services.

http://quickdotnetsolutions.blogspot.in/2011/05/advantages-of-wcf-service-over-web.html?utm_source=blog&utm_medium=gadget&utm_campaign=bp_random

Leave a comment

Filed under ASP.Net, C#, WCF

Wcf Duplex Contract – Subscriber-Publisher usng wsDualHttpBinding

Any real time Application (like score-card etc) that involves update are follow either of two process i.e Pulling or Pushing.

Pulling– client constantly sending request to server for updates. This implementation works fine when there are frequent updates but pulling can be an overhead when updates are very less.

Pushing– Server sends update to client when available. This is the best approach over pulling where we have very less updates from server.

wsDualHttpBinding is used Pushing implementation.
In .net netTcp & namedPipe binding support bi-directional binding but http not, so in WCF they introduced a new binding wsHttpBinding().
It has two channels, one is client to server & other is server to client.
Here we basically have two contracts,
->one contract which is used by service.
->other is used by Client which is a Callback contract.

[ServiceContract(CallbackContract = typeof(IMessageCallback))]
public interface IMessage
{
}

interface IMessageCallback
{
      [OperationContract(IsOneWay = true)]
      void OnMessageAdded(string message, DateTime timestamp);
}

Leave a comment

Filed under WCF

What can’t be saved in ViewState?

Any data (Serialized) that you want to access over the postback can be saved in ViewState.

DataReader can’t be serialized as it is in Connected mode. So you can save DataReader in ViewState.

Leave a comment

Filed under C#

Cookies

Cookies are sent to the browser via the HttpResponse object that exposes a collection called Cookies. You can access the HttpResponse object as the Response property of your Page class.

You can also set a cookie’s date and time expiration. Expired cookies are deleted by the browser when a user visits the site that wrote the cookies. you can set the expiration date to be 50 years from now.

If you do not set the cookie’s expiration, the cookie is created but it is not stored on the user’s hard disk. When the user closes the browser, the cookie is discarded. Those are called non- Persistant cookies.
eg: non-persistent cookies are useful if the user is working on a public computer, where you do not want to write the cookie to disk due to security reason.

You can add cookies to the Cookies collection in a number of ways.

Response.Cookies["userName"].Value = "patrick";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1);

HttpCookie aCookie = new HttpCookie("lastVisit");
aCookie.Value = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);

Cookies with More Than One Value
You can store multiple name-value pairs in a single cookie.
eg: instead of creating two separate cookies named userName and lastVisit, you can create a single cookie named userInfo that has the subkeys userName and lastVisit.
Benefits
1) cookie attribute such as expiration can be applied to single cookie file instead of each cookie individually.
2) as we know we can’t store more then 20 cookies per site, so by using single cookie like above we save on number of cookies per site.

Response.Cookies["userInfo"]["userName"] = "patrick";
Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString();
Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);

HttpCookie aCookie = new HttpCookie("userInfo");
aCookie.Values["userName"] = "patrick";
aCookie.Values["lastVisit"] = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);

Controlling Cookie Scope
By default, all cookies for a site are stored together on the client, and all cookies are sent to the server with any request to that site. In other words, every page in a site gets all of the cookies for that site. However, you can set the scope of cookies in two ways:
Limiting Cookies to a Folder or Application
To limit cookies to a folder on the server, set the cookie’s Path property, as in the following example:

HttpCookie appCookie = new HttpCookie("AppCookie");
appCookie.Value = "written " + DateTime.Now.ToString();
appCookie.Expires = DateTime.Now.AddDays(1);
appCookie.Path = "/Application1";
Response.Cookies.Add(appCookie);

The path can either be a physical path under the site root or a virtual root. The effect will be that the cookie is available only to pages in the Application1 folder. So cookie will be available to path http://www.contoso.com/Application1/ or any page beneath that folder.

Limiting Cookie Domain Scope
By default, cookies are associated with a specific domain. For example, if your site is http://www.contoso.com, the cookies you write are sent to the server when users request any page from that site. If your site has subdomains—for example, contoso.com, sales.contoso.com, and support.contoso.com—then you can associate cookies with a specific subdomain.

Response.Cookies["domain"].Value = DateTime.Now.ToString();
Response.Cookies["domain"].Expires = DateTime.Now.AddDays(1);
Response.Cookies["domain"].Domain = "support.contoso.com";

Reading Cookies
When a browser makes a request to the server, it sends the cookies for that server along with the request. In your ASP.NET applications, you can read the cookies using the HttpRequest object, which is available as the Request property of your Page class. structure of the HttpRequest is same as HttpResponse object, so you can read them much the same way as you wrote them.

if(Request.Cookies["userName"] != null)
Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);

if(Request.Cookies["userName"] != null)
{
HttpCookie aCookie = Request.Cookies["userName"];
Label1.Text = Server.HtmlEncode(aCookie.Value);
}

HtmlEncode method was called to encode the contents of a cookie to make sure executable script are not added into the cookie.
Similarly reading a subkey: Server.HtmlEncode(Request.Cookies[“userInfo”][“userName”]);
The subkeys in a cookie are typed as a collection of type NameValueCollection. Therefore, another way to get an individual subkey is to get the subkeys collection and then extract the subkey value by name, as shown in the following example:
System.Collections.Specialized.NameValueCollection
UserInfoCookieCollection;

UserInfoCookieCollection = Request.Cookies["userInfo"].Values;
Label1.Text =
Server.HtmlEncode(UserInfoCookieCollection["userName"]);
Label2.Text =
Server.HtmlEncode(UserInfoCookieCollection["lastVisit"]);

Leave a comment

Filed under C#

SQL

Referential Inegrity
http://www.programmerinterview.com/index.php/database-sql/what-is-referential-integrity/

Having clause & Where clause
http://www.programmerinterview.com/index.php/database-sql/having-vs-where-clause/

Inner Join vs Outer Join
http://www.programmerinterview.com/index.php/database-sql/inner-vs-outer-joins/

Self Join
http://www.programmerinterview.com/index.php/database-sql/what-is-a-self-join/

Correlated vs Uncorrelated query
http://www.programmerinterview.com/index.php/database-sql/correlated-vs-uncorrelated-subquery/

Index
http://www.programmerinterview.com/index.php/database-sql/what-is-an-index/

SELECT b.Emp_id, b.Emp_name,e.emp_id as managerID, e.emp_name as managerName
FROM Employee b
JOIN Employee e ON b.Emp_ID = e.emp_mgr_id

This is a classic self-join, try the following:

http://blog.sqlauthority.com/2010/07/08/sql-server-the-self-join-inner-join-and-outer-join/

SELECT e.ename, e.empno, m.ename as manager, e.mgr
FROM
emp e, emp m
WHERE e.mgr = m.empno

And if you want to include the president which has no manager then instead of an inner join use an outer join in Oracle syntax:

SELECT e.ename, e.empno, m.ename as manager, e.mgr
FROM
emp e, emp m
WHERE e.mgr = m.empno(+)
Or in ANSI SQL syntax:

SELECT e.ename, e.empno, m.ename as manager, e.mgr
FROM
emp e
LEFT OUTER JOIN emp m
ON e.mgr = m.empno

Leave a comment

Filed under SQL

Imp Terms
IIS is the most popular ASP.Net web server provided by Micrsoft.

Worker Process: All asp.net application runs under the scope of Worker Process (w3wp.exe), which act as application boundary. When a request comes to the server from a client worker process is responsible to generate the request and response.

Application pool:
Application Pool is the container of worker process. An app pool can have multiple worker process that share same configuration, by default there is only one worker process per app pool. A server can have multiple App pool for different application.
eg: an enterprise organization might place its human resources Web site and its finance Web site on the same server, but in different application pools.

Application Pool with multiple Worker process is “Web Garden“.

Now the request handling by IIS is divided into two stages:
Kernal Mode
User Mode

1) In Kernal level, the request received by IIS is handled by HTTP.SYS, which identify the App pool to process the request.

2) In User Level, we have Web Admin Services (WAS) which takes the request from HTTP.SYS and pass it to App pool.

3) When App pool rceive the request it simply passes the request to the worker process (w3wp.exe) which looks up the URL of request to load the correct ISAPI extension.
ISAPI extensions are the IIS way to handle requests for different resources. Once ASP.NET is installed, it installs its own ISAPI extension (aspnet_isapi.dll) and adds the mapping into IIS.

4) When wp loads the aspnet_iisapi.dll, it starts the HttpRuntime, which is the entry point of your application.

5) HttpRuntime calls the ProcessRequest method to start processing
HttpRuntime.ProcessRequest(HttpWorkerRequest wr)
It creates the instance of HttpContext which provide access to all it’s properties like Request, Response, Session using HttpContext.Current properties.

6) Then HttpRuntime loads HttpApplication object

References:
http://abhijitjana.net/2010/03/14/beginner%E2%80%99s-guide-how-iis-process-asp-net-request/
http://www.codeproject.com/Articles/42724/Beginner-s-Guide-Exploring-IIS-6-0-With-ASP-NET
http://www.iis.net/learn/get-started/introduction-to-iis/introduction-to-iis-architecture

http://www.codeproject.com/Articles/28693/Deploying-ASP-NET-Websites-on-IIS-7-0

Leave a comment

Filed under .Net

How to make your ViewState secure?

ASP.Net viewstate is client side state management and is stored in hidden field with id __VIEWSTATE as shown below:

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjkPFgYLl/p5/cggNdr/yAizfkifBJ20CwQ=" />

Now the string in value is is not encrypted but serialized(encoded) use Base64 en ccoding, which can be easily decoded using many tools.

Now there are mainly two approach to secure your Viewstate:
1) EnableViewStateMAC / Hash code (Hashing)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DataSetToViewState.aspx.cs"
EnableViewState="true" EnableViewStateMac="true" Inherits="WebWorld.DataSetToViewState" %>

Make sure viewstate data is tamper proof using Hash Code, you can do this by adding EnableViewStateMAC=true. MAC stands for Message Authentication Code. It internally added a Hash code with ViewState content and store in hidden field. During postback, the checksum data is verified again by ASP.Net and if there is mismatch, the postback will be rejected.
2) Encryption

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DataSetToViewState.aspx.cs"
EnableViewState="true" ViewStateEncryptionMode="Always" Inherits="WebWorld.DataSetToViewState" %>

The second option ViewStateEncryptionMode=”Always”. It will encrypt the viewstate, there are three option
Always: Encrypt the viewstte always.
Auto: Encrypt if the control require for encyrption. For this to happen, the control must call the Page.RegisterRequiresViewStateEncryption() method.
Never: Never encrypt the viewtate.

We can also enable these settings for EnableViewStateMAC and ViewStateEncryptionMode in web.config:

<system.web>
<pages enableViewStateMac="true" viewStateEncryptionMode="Always"></pages>
</system.web>

Note: Try to avoid ViewState encryption if it is not necessary as it can cause performance issues.

References:
http://www.codeproject.com/Articles/150688/How-to-make-ViewState-secure-in-ASP-NET

Leave a comment

Filed under ASP.Net

Can we store DataSet into ViewState?

DataSet is a disconnected object. DataSet is a fully serializable object. It can be serialized in three different ways—to a standard .NET formatter, to an XML writer, and through the XML serializer.

//Create new dataset :
DataSet ds = new DataSet();
//Store the dataset directly into view state
ViewState["dsn"]=ds;
//retrieve the dataset where it required
GridView1.DataSource = (DataSet)ViewState["dsn"];

Leave a comment

Filed under ASP.Net

How to store object in ViewState?

We can store objects in viewstate like we store string or integer. But before storing we need to convert them into stream of bytes to keep tem in hidden field. So we need to use Serialization. And object which can’t be serialised, they will not be able to keep in viewstate.

[Serializable]
public class Student
{
public int Roll;
public string Name;
public void AddStudent(int intRoll, string strName)
{
this.Roll = intRoll;
this.Name = strName;
}
}

Now we need to store them to viewstate.

Student _objStudent = new Student();
_objStudent.AddStudent(2, "Max");
ViewState["StudentObj"] = _objStudent;

//Retrieving student
Student _objStudent;
_objStudent = (Student)ViewState["StudentObj"];

Leave a comment

Filed under ASP.Net

Encoding vs Encryption

First Similarities:
1) They both transform data into different format.
2) They both are reversible (unlike Hashing).

Differences:

Encoding
1) to transform data it uses a scheme that is publicly available
2) don’t require any key to transform, just algorithm & the same is used to decode it.
eg: ASCII, Unicode, Base64

Encryption
1) to transform data it uses the way that only specific user can reverse it.
2) it uses key with plaintext & algorithm to encrypt and the ciphertext, algorithm & key is used to decrypt it.
eg: AES, RSA

References:
http://danielmiessler.com/study/encoding_encryption_hashing/

Leave a comment

Filed under .Net

Access Modifiers in C#

In C# there are 5 different types of Access Modifiers.

Modifier Description
public There are no restrictions on accessing public members.
private Access is limited to within the class definition. This is the default access modifier type if none is formally specified
protected Access is limited to within the class definition and any class that inherits from the class
internal Access is limited exclusively to classes defined within the current project assembly
protected internal Access is limited to the current assembly and types derived from the containing class. All members in current project and all members in derived class can access the variables.

DEFAULT ACCESS MODIFIER

An enum has default modifier as public.

class has default modifiers as Internal.

An interface has default modifier as public.

struct has default modifier as Internal.

methods, fields, and properties has default access modifier as “Private” if no modifier is specified.

Access modifiers

Leave a comment

Filed under C#

Stack, heap, Value types, Reference types, boxing, and unboxing

When you declare a variable in .Net, it allocates some chunk of memory in RAM. This memory has three things :
name
data type &
value of the variable.
Depending upon the data type there are two types of memory allocation: Stack and Heap


The Stack is responsible for keeping track of the running memory needed in your application.

Heap doesn’t track the running memory. It is just a pile of object which can be reached at any time. It is dynamic memory allocation.

eg:

public void Method1()
{
// Line 1
int i=4;

// Line 2
int y=2;

//Line 3
class1 cls1 = new class1();
}

Line1: When Line1 is executed the compiler allocate small chunk of memory in the Stack.

Line2: It allocates memory for y on top of the first memory in Stack (LIFO).
Line3: Here an object is created. When this line is executed it creates a pointer on Stack and the actual object is stored in a Heap memory.

NB: Reference pointer is allocated on Stack. The statement
Class1 cls1;
doesn’t allocate memory for an instance of Class1, it only allocates a stack variable cls1 (and sets it to null). The time it hits new keyword, it allocates on “heap”.

Exiting the above Method
On exiting the method, it clears all the memory variable which are assigned on Stack.
But it didn’t de-allocate the heap memory. This memory will be later de-allocated by the garbage collector.

Now we have discussed about the Stack & Heap memory. Let’s move on to Value & Reference Types.

Value types
1. Value types are types which hold both memory & data on the same location i.e Stack.
2. Below we assign an int value (i) to another int value (y). Both these memory are separately allocated on stack. So if we change either of them then other doesn’t change. This is Value type.


Reference Type
1. A reference type has a pointer which points to the memory location.
2. Now when we create an object and assign an object to another object, they both point to same memory location (in heap). So if we change one of them, the other object is also affected. This is Reference type.


Type Chart


Boxing and Unboxing

Boxing
When we move data from Value type to Reference type, data is moved from Stack to Heap. It is termed as Boxing.

Unboxing
When we move data from Reference type to Value type, data is moved from Heap to stack. It is termed as Unboxing.

References:

http://www.codeproject.com/Articles/76153/Six-important-NET-concepts-Stack-heap-value-types

6 Comments

Filed under C#

Aggregation & Composition

Aggregation
Aggregation means “has-a” relationship. Here the two entity are dependent on each other but the can exist alone as well.
eg: Person and Shirt entity. Shirt is dependent upon the person who wears it, but it can exist alone as well.

Composition 

Composition means “is-a” relationship. Here the two entity are tightly dependent on each other and can’t exist alone.
Eg: Human and Heart they both are dependent on each other and can’t exist alone.

Leave a comment

Filed under C#

Abstraction vs Encapsulation

Below is the difference:

Encapsulation

Abstraction

Encapsulation is the act of packing data and function into a single unit.

Abstraction means representing the essential features without representing/hiding the background details.

Eg: Class

Eg: abstract class, interface.

Encapsulation is achieved using abstraction.

It is achieved using access modifier.

 

 

 

 

Here if we make Validate() and CreateBDObject() methods public and let the client call these method before calling Add() then it will be showing extra information to user as these two methods will only be called if we want to perform Add operation.

 

So if we follow abstraction then we make these two methods private and include them in Add() method. This way only the essential features are shown to the client and hiding the background details.

Leave a comment

Filed under C#

How to Dispose a Static member?

Static finalizer & dsetructor are not possible and these types are unloaded only when the AppDomain shuts down.

However, to make the Static object ready for Garbage collection, you can assign it to null.

static List<Customers> customers = new List<Customers>();

customers = CustomerDAC.GetCustomers();

//To unload static class

customers = null;

Leave a comment

Filed under C#

Static vs Singleton

Though both restrict to have only one instance of the class to be created but there are differences:

Static

Singleton

It doesn’t maintain any state as no object is created. It maintains the state of object.
Static class gets activated at run-time. Singleton follows lazy loading, so object gets created when required.
It doesn’t implement interface. It implement interface.
Disposing Static is not possible, as types are only unloaded when the AppDomain shut down. They can be disposed at run time.
We can’t create object of Static class. Singleton object can be used as parameter.

Ref

http://quickdotnetsolutions.blogspot.in/2011/05/difference-between-singleton-and-static.html

Leave a comment

Filed under C#

Static members in Generic class

Yes it is possible as shown below but:
Bear in mind that for every Generic type you get a different Static variable. SO if the Static member value has nothing to do with the Generic type then they shouldn’t be in Generic class. They should be declared in different class. 

Leave a comment

Filed under C#

ASP.Net life cycle in plain English

ASP.NET Page Lifecycle is very important piece of knowledge every ASP.NET developer must know, and unfortunately some of ASP.NET developer out there don’t know and they think it’s not important to know.

Let’s dig in and let’s examine ASP.NET Lifecycle but in short list and description:

  1. PreInit():
    • In this event all Controls created and Initialized with their default values. You can create dynamic Controls here. You can set theme programmatically here
  2. OnInit():
    • In this event you can read the Controls properties the were set in Design Mode and can not read values changed by user.
  3. LoadViewState():
    • This event fires only if the page is posted back “IsPostback == true;” and here View State data where are stored in hidden form fields get de-serialized and loads all controls View State data.
  4. LoadPostBackData():
    • This event only fires when Page is posted back and Controls which implement IPostBackDataHandler interface get loaded with values from HTTP POST data.
  5. Page_Load():
    • This event is well known among ASP.NET developers and here Page gets loaded and after it all Load() events of Page Controls fired.
  6. Control Event Handlers:
    • These are basically event handlers like Button click event handler “Button1_Click()” which fires after Page_Load() event.
  7. PreRender():
    • This event is fired for each page child controls and her you can change controls values.
  8. SaveViewState():
    • In this event Controls View State saved in Page hidden fields.
  9. Render():
    • Here all Controls get rendered or every Page Controls Render method is called.
  10. Unload():
    • Here we can have Page and Controls clean up operations. This event the Page and its Controls are rendered.

Notes:

  1. ASP.NET Lifecycle will be called ever time there a request for the page.
  2. HTTP POST data has only one value per control, that’s why Control like Textbox can gets value from HTTP Post but Control like DropDownList can not gets data from HTTP Post it can gets data from View State.
  3. Init() and Unload() events are fired from outside to inside controls, fro example: user control Init() event will be fired beforePage_Init() event

1 Comment

Filed under ASP.Net

WCF Concurrency and Throttling

WCF concurrency tells how it can serve multiple requests at same time.

WCF instance dictates how objects are created.

WCF concurrency dictates how many requests can be handled by WCF objects.

The reasons why we need concurrency are Increase throughput and Integration with a legacy system.

There are three types of WCF Concurrency:

  • Single

Only one request will be processed at any given moment of time. The other request have to wait until the request processed by WCF service is completed.

  • Multiple

Multiple requests can be handled by WCF service object. Requests are handled at the same time by multiple threads on WCF service object but we need to take care of concurrency issues.

  • Reentrant

A single request thread has access to the WCF service object, but the thread can exit the WCF service to call another WCF service or can also call a WCF client through callback and reenter without deadlock.

Below is the example:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

References:

http://www.codeproject.com/Articles/89858/WCF-Concurrency-Single-Multiple-and-Reentrant-and

Leave a comment

Filed under WCF

WCF Instance Management

WCF can control how WCF service objects are created on WCF server using Wcf Instance. There are three ways of WCF instance creation InstanceContextMode.

  • PerCall (default)
  • PerSession
  • Single


PerCall

Create a new WCF instance on every WCF client call

[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
public class MyService : IMyService

PerSession
Ony one WCF instance is created for all the call from a WCF client session.

[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
public class MyService : IMyService
{

NOTE:- If you doesn’t create Sessionful binding then PerSession will act as PerCall. As a result every request to the service creates a new instance of the service class. http://forums.silverlight.net/t/118971.aspx/1

Single

Only one global WCF intance should be created for all WCF clients.

[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class MyService : IMyService

Leave a comment

Filed under WCF

ASP.NET 4.0 Features

1) Output Cache Extensible

ASP.Net 1.0 introduced the concept of Output Caching, which enable developers to store generated output of pages/controller (MVC)/HTTP response in an in-memory cache.

So on subsequent request, ASP.Net retrieves the output from the cache instead of regenerating from scratch. This dramatically improved the performance of the application.

ASP.Net output caching is flexible enough to enable cache different version of content based on query string/form-post parameters.

Also enable to cache different version based on browser type or user-language. Like to have different versions of page for mobile.

Limitation:- From ASP.Net1.0 to 3.5 is that cache store is not extensible i.e. always have to be stored in an in-memory.

Solution:- ASP.Net 4 Output Cache Extensible.

Now enables developers to configure more custom output-cache providers like local/remote disk, database, cloud etc.

To create custom output-cache provider,

1) a class which derived from System.Web.Caching.OutputCacheProvider has to be created, whic involve overriding 4 public methods to provide implementation for adding/removing/retrieving/updating.

2) Also the output-cache provider has to be configured in web.config.

 

 

 

 

 

 

 

 

 

 

2) Session State Compressor

Leave a comment

Filed under ASP.Net

Contracts in WCF

WCF Contracts
There are basically four types of contracts:-
1) Service Contracts
It define what operation the client can perform using the Service. There are two types of Service contracts
a) ServiceContract – This attribute defines Interface.
b) OperationCOntract – This attribute defines method of Interface.

2) Data Contract
It defines the data types passed to and from the service. There are two types again:
a) DataContract – This attribute defines the data class.
b) DataMembers – This attribute defines the properties.
If DataMember attributes are not specified for a properties in the class, that property can’t be passed to-from web service.

3) FaultContract
It defines which type of error will be raised by the Service.

4) Message Contract
It allows service to interact directly with Message. Message Contract can be types or untyped.

Leave a comment

Filed under WCF

WCF Security & Types

There are two types of Security implemented in WCF:
Transport Level  :- It means securing the meadiums on which data travels.
Message Level :- It means securing the actual data packets sent by WCF.

Transport median (like HTTP, TCP, MSMQ etc) itself provide security features like HTTP can have SSL security (HTTPS).

Message security is provided using WS-Securities like message encrypted using encryption algo, message encrypted using X-509 certificate, message protected using username/password.

WCF gives option to either use Message/Transport level security standalone or combination of both.

We will implement combination of both below.

Step 1:- Customize WsHttp binding with Security mode & Credential Type
Configure wsHttp binding with Security Mode & Credential Type. There are three options for security mode i.e.
Transport,
Message &
TransportWithMessageCredential

Now as we are implementing dual security so we will use TransportWithMessageCredential mode where Transport level security is provided by SSL & Message security is provided by Username-Password.
Secondly CredentialType needs to be provided out of
none,
windows,
username,
certificate &
issued token

We will be using CredentialType as username.
Below are the changes done in web.config:

<bindings>
<wsHttpBinding>
<binding name=”Binding1″>
<security mode=”TransportWithMessageCredential”>
<message clientCredentialType=”UserName” />
</security>
</binding>
</wsHttpBinding>
</bindings>

Step 2:- Create Custom Validator Class
After customizing wsHttp binding, we need to create custom validator class for authentications.
To create the custom validator class you need to inherit it from “UserNamePasswordValidator” class & override Validate() method.

class MyValidator : UserNamePasswordValidator
{
protected override void Validate(string userName, string password)
{
if(userName==”Dev” && password=”pass123″)
{
//
}
else
{
throw new FaultException(“Invalid Credentials”);
}
}
}

The faultException is handled by WCF client if the credentials are not valid.

Step 3:- Define Runtime behavior.
Now we need to execute MyValidator class for the Username provided inthe WCF service by WCF client. So for this we add behavior

<behaviors>
<serviceBehaviors>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode=”Custom”
customUserNamePasswordValidatorType=”MyValidator” />
</serviceCredentials>
</serviceBehaviors>
</behaviors>

Step-4 :- Define SSL for your WCF Service
Step 5:- Consume WCF service
Step 6:- Run WCF Service
Above three steps are explained in below link
http://www.dotnetfunda.com/articles/article891-6-steps-to-implement-dual-security-on-wcf-using-user-name-ssl.aspx

Leave a comment

Filed under WCF

Page Life Cycle

Below are the events:

Page_PreInit (EventArgs e)

UC_Init (EventArgs e)
CWebC_Init (EventArgs e)
Master_Init (EventArgs e)
Page_Init (EventArgs e)

UC_TrackViewState ()
CWebC_TrackViewState ()
Master_TrackViewState ()
Page_TrackViewState ()

Page_Load (EventArgs e)
Master_Load (EventArgs e)
UC_Load (EventArgs e)
CWebC_Load (EventArgs e)

Page_PreRender (EventArgs e)
Master_PreRender (EventArgs e)
UC_PreRender (EventArgs e)
CWebC_PreRender (EventArgs e)

Page_SaveViewState()
Master_SaveViewState()
UC_SaveViewState()
CWebC_SaveViewState()

Page_Render(HtmlTextWriter writer)
Master_Render(HtmlTextWriter writer)
UC_Render(HtmlTextWriter writer)
CWebC_Render(HtmlTextWriter writer)

UC_UnLoad()
CWebC_UnLoad()
Master_UnLoad()
Page_UnLoad()

Leave a comment

Filed under C#

try/catch/finally nested

We can have try..catch..finally nested in try/catch/finally blocks:

Leave a comment

Filed under C#

Const vs Readonly

 

Const

Readonly

They are Compile-Time constant means always constant. They are Run-time constant.
value can be set at declaration only. value can be set at declaration or in Constructor.
Can’t be static. Can be static

Leave a comment

Filed under C#

Difference between “==” and Equals() methods?

Value Type:- “==” & Equal() method usually compare object by value.

Reference Type:- “==” compares whether both the reference point to same object.
Equal() returns true if value at reference point to the object are equivalent.

there is an exception here for string that “==” compares value rather then object identity.

In the below example:- for value type is obvious, but for reference types s1 & s2 are different objects so it will return false where as both of objects are equivalent so it will return true.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Refrences

http://dotnetguts.blogspot.in/2007/07/difference-between-and-equals-method.html

1 Comment

Filed under .Net, C#

When is a static constructor in C# called?

A static constructor is invoked by the first of either of the following conditions:

  • Create an instance of the class.
  • Refer any of the static methods of the class.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

For Generic Class, using different type arguments you’ll get different concrete classes, so Static Constructor will be called multiple time (once for each type)

Leave a comment

Filed under C#

Polymorphism

Polymorphism means same operation can be defined in multiple forms.
There are two types of polymorphism:
Compile Time & Run-time polymorphism

Example of Compile Time polymorphism:- Method Overloading

It means having two or more methods having same name but different signature.
-the methods can be in the same class or different class (inherited).
-constructor overloading is also possible.
-it is not mandatory to have different return type, but either the number of parameters or parameters type should be different.

Example of Run time Polymorphism:- Method Overriding

Two or more methods with same signature but different implementation but in different class (base & inherited).

eg:- Using New & Override

1 Comment

Filed under C#

Why do we need Constructor for abstract class?

Yes we can have constructor in Abstract class (though we can’t still create object of abstract class).
Because :- this way you can instantiate the data in abstract class.
And inherited classes can call the base constructor.

public abstract class A{
private string data;
protected A(string myString){
data = myString;
}
}

public class B : A {

B(string myString) : base(mystring){}
}

NOTE:- As you can’t override constructor, so we can’t have abstract constructor.

Leave a comment

Filed under .Net, C#

IEnumerable vs IEnumerator

1) IEnumerable actually uses IEnumerator. i.e IEnumerable uses IEnumerator internally through GetIEnumerator.
2) The biggest difference is states, i.e. IEnumerable does not remember the cursor state i.e currently row which is iterating through, where I enumerator does.
IEnumerator exposes few methods which uses the state like:
MoveNext()
Current()

Leave a comment

Filed under C#

Abstract method vs Virtual method

Abstract method Virtual method
1) Abstract method doesn’t have any body defined. 1) Virtual method have their body defined otherwise it will give compile-time error message “<VirtualMethod()> must declare body because it is not defined abstract, extern, or partial.
2) Mandatory to implement them. 2) Not mandatory to override them.
3) They can be defined in abstract classes only. 3) They can be defined in any instance class.

Leave a comment

Filed under .Net, C#

Difference b/w String and string ?

They both are similar datatype as “string” is the alias of “String”. The original datatype class is String (System.String). Below is few more alias we have in .net:

Leave a comment

Filed under C#

Generics

Generics has the below features:

— makes logic independent of DataTypes.

— strongly types as Array.

— flexible of DataTypes like arraylist without boxing & unboxing.

Below is the project which show use of two Generic classes CoreDemo & CoreDemoDual:

Generic Classes


2 Comments

Filed under .Net, C#

Nullable Types & Why we need them?

The .NET Framework stores value types in the stack and implicitly initializes them to their default values. For example, an int gets initialized to 0, a bool to false, and so on.
In database missing information in records represented by null values. So the problem arises when fetch data from the data base, how to represent missing null value in our program because primitive data only stores real values in C#.

Nullable variable= null;
or
int? variable= null;

You cannot create a nullable type based on a reference type. (Reference types already support the null value.)

Use the ?? operator to assign a default value that will be applied when a nullable type whose current value is null is assigned to a non-nullable type, for example int? x = null; int y = x ?? -1;

Properties
Nullable types has two important property
Hasvalue – indicate that variable contains real values or not. It returns false if variable contains no value and true if some real values is stored in it.
Value – Return real value stored in variable. It throws InvalidOperationException exception.
Method
GetValueOrDefault – Return value stored by Nullable type variable or the value passed in function.
There are two overload of this function.
Syntax
GetValueOrDefault() – returns real value or the default value of object.
GetValueOrDefault(T) – returns real value or the value passed.
Pseudocode Code for above problem
//variable define
DateTime? deathdate = null;

//for the people who is already dead
if( deathdate.Hasvalue) // checking for the nullable varialbe has value or not
age = deathdate.Value – birthdate;
//for the people who is till alive
else
age = todays date – birthdate;

Leave a comment

Filed under C#

Why need Static methods?

I use static methods when I need to get something that is relevant to that class but I don’t want to create an instance every time to get this information. With a static method you cannot access methods/properties/variables from the class. The only variables available are within the static method you are calling.

Typically Helper and Utility methods are good candidates. Often times as well, you may want to create Static as well as instance objects. Looking to the framework, there’s the File and the FileInfo, the Directory and directoryInfo. Similarly, check out the Data Access Application Block – all of the SqlHelper methods are static.

Leave a comment

Filed under C#

Extention Method with Example

Extension methods enable you to “add” methods to existing types without creating a new derived type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

eg: http://blogs.msdn.com/b/wriju/archive/2011/05/04/linq-to-xml-handling-blank-or-no-element-and-attribute.aspx

Handling blank or no Element and Attribute
public static class MyExtension
{
//This method is to handle if element is missing
public static string ElementValueNull(this XElement element)
{
if (element != null)
return element.Value;

return “”;
}
}

You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called.if a type has a method named Process(int i), and you have an extension method with the same signature, the compiler will always bind to the instance method.

Leave a comment

Filed under C#

What Riders in Health Plan?

Riders in Health Plan

When you apply for health insurance, you’ll answer a long series of questions about your medical history. If you have a current medical condition, your plan will include a rider that limits your coverage for care related to that condition. Usually, that limitation will be in effect for a year.
Here’s an example: let’s say you have a back injury when you apply for coverage. The insurance company will likely accept your application — but they also might include a rider on your plan that limits your coverage for treatment related to your back injury. This limitation, or exclusion period, will probably be in effect for a year. After the exclusion period, any medical services related to your back injury will be covered normally under the terms of the plan.

Leave a comment

Filed under Healthcare

ABSTRACT vs INTERFACE

ABSTRACT vs INTERFACE

Abstract Class Interface
1. It is mainly used in versioning scenarios (defining core functionalities). Interface is used as contract mainly.
2. We can use abstract as well non-abstract method. All methods are abstract only. Interface is pure abstract class.
3. We can inherit only one abstract class at a time. We can implement multiple interface.
4. All access modifier can be used. We can have only public access modifier for the methods.

à We can not create object of abstract class, though abstract can have constructors.

àWe can create instance of abstract class like:

AbstractClass obj = new SubClass();

eg:

TextWriter abstract class have two sub classes i.e. StreamWriter & StringWriter

TextWriter tObj = new StreamWriter();

Leave a comment

Filed under C#

Array vs ArrayList

In yet another round of fight, today we have contenders Array and ArrayList:

ARRAY ARRAYLIST
1. Array can store single data like Char[] vowel=new Char[]; Array list you can store multiple datatypes and inserting and removing element is easy.

ArrayList a_list=new ArrayList();

2. Array is in the System namespace ArrayList is in the System.Collections namespace.
3. The capacity of an Array is fixed. ArrayList can increase and decrease size dynamically

Ex:

ArrayList list = new ArrayList();

list.Add(“One”);

list.Add(“Two”);

list.Add(“Three”);

ARRAY

ARRAYLIST

1.

Array can store single data like Char[] vowel=new Char[];

Array list you can store multiple datatypes and inserting and removing element is easy.

ArrayList a_list=new ArrayList();

2.

Array is in the System namespace

ArrayList is in the System.Collections namespace.

3.

The capacity of an Array is fixed.

ArrayList can increase and decrease size dynamically

Ex:

        ArrayList list = new ArrayList();
        list.Add("One");
        list.Add("Two");
        list.Add("Three");

Leave a comment

Filed under C#

Compile Code into Assemblies

To service user request thru application code, it need to be compiled to one or more assemblies.

Assembly files have extension .dll. We can write ASP.net code in many languages like C#, VB.net, J# & others but when compiled, but when compiled, it will be translated into language-independent or CPU-independent language i.e. MS Intermediate Language(MSIL). At run-time in the context of .Net framework, the MSIL gets translated into CPU-specific instructions.

 Benefits of compiling the application code to Assemblies:

Performance:- Compiled code is much faster then scripting language because it’s representation is closer to machine code & doesn’t require additional parsing.

Security:- Compiled code is difficult to the reverse engineer as it lacks the readability & high level of abstraction.

Stability:- Code is checked at compile time for syntax error, type safety, & other problems. By caching these errors at build-time we can eliminate many errors in our code.

Inter-operability:- As MSIL code support all .Net languages so if you are writing an ASP.Net web page in C# then you can use reference of assemblies written in VB.net too.

Leave a comment

Filed under .Net

Factorial

There are actually two ways to get factorial i.e. using recursion or without recursion:

With Recursion

protected int Factorial(int num)

{

              if (num == 1)

                      return num;

              return (num * Factorial(num – 1));

}

Without Recursion

protected int FactorialNoRecursion(int num)

{

             int result=1;

             if (num == 1)

                      return num;

              for (int i = 2; i <= num; i++)

                     result *= i;

             return result;

}

Leave a comment

Filed under C#

AutoCompleteExtender

AutoCompleteExtender control pulls words that start with the prefix typed into the textbox and display in a popup panel. It comes under AJAX control toolkit.

To implement the same we need to call webservice (WebMethod) thru Ajax & First thing you have to do is to add the ScriptService reference to the webserive as follows. 

[System.Web.Script.Services.ScriptService]:

 

 [WebService(Namespace = “http://tempuri.org/&#8221;)]

 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

 [System.Web.Script.Services.ScriptService]

 public class SampleWebService : System.Web.Services.WebService

 {

      [WebMethod]

      public string[] GetName(string prefix)

      {

            List<string> names = null;

            string query = string.Empty;

            SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings[“ConnectionString”]);

             query = “SELECT Name FROM Student WHERE Name = ” + prefix + “%”;

            SqlCommand com = new SqlCommand(query);

            con.Open();

            SqlDataReader dr = com.ExecuteReader();

            if (dr.HasRows)

            {

                names = new List<string>();

                while (dr.Read())

                {

                    names.Add(dr.GetString(1));

                }

            }

           

            return names.ToArray();

        }

    }

 Now at the design level, apart from specifying ScriptManager, we need to provide a <Services> tag as shown below and use Ajax AutocompleteExtender with ServicePath & ServiceMethod:

 <body>

    <form id=”form1″ runat=”server”>

        <asp:ScriptManager ID=”ScriptManager1″ runat=”server”>

            <services>

                <asp:ServiceReference Path=”AutoComplete.asmx” />

            </services>

        </asp:ScriptManager>

        <div>

            <asp:TextBox ID=”txtCountry” runat=”server”></asp:TextBox>

<ajaxToolkit:AutoCompleteExtender runat=”server” ID=”autoComplete1″ TargetControlID=”txtCountry”

ServicePath=”AutoComplete.asmx” ServiceMethod=”GetCountriesList” MinimumPrefixLength=”1″

            EnableCaching=”true” />

        </div>

    </form>

</body>

 

Leave a comment

Filed under Ajax

UpdatePanel

UpdatePanel

The UpdatePanel control is a server control which used to achieve asynchronously postback of limited to regions of the page.
This process is coordinated by the ScriptManager server control.

By default, any postback control inside an UpdatePanel control causes an asynchronous postback and refreshes the panel’s content. However, you can also configure other controls on the page to refresh an UpdatePanel control. You do this by defining a trigger for the UpdatePanel control.
eg:
<form runat=”server”>
    <div>
    <asp:Button
                Text=”Refresh Panel”
                runat=”server” />
    <asp:ScriptManager
                       runat=”server” />
    <asp:UpdatePanel
                     UpdateMode=”Conditional”
                     runat=”server”>
                     <Triggers>
                       <asp:AsyncPostBackTrigger ControlID=”Button1″ />
                     </Triggers>
                     <ContentTemplate>
                     <fieldset>
                     <legend>UpdatePanel content</legend>
                     <%=DateTime.Now.ToString() %>
                     </fieldset>
                     </ContentTemplate>
    </asp:UpdatePanel>

A trigger’s control event is optional. If you do not specify an event, the trigger event is the default event of the control.

UpdateMode (Always, Conditional)
If the UpdateMode property is set to Always, the UpdatePanel control’s content is updated on every postback that originates from anywhere on the page. This includes asynchronous postbacks from controls that are inside other UpdatePanel controls, and postbacks from controls that are not inside UpdatePanel controls.

If the UpdateMode property is set to Conditional, the UpdatePanel control’s content is updated when one of the following is true:

  • When the postback is caused by a trigger for that UpdatePanel control.
  • When you explicitly call the UpdatePanel control’s Update() method.
  • When the UpdatePanel control is nested inside another UpdatePanel control and the parent panel is updated. 

To use an UpdatePanel control in a master page, you must decide how to include the ScriptManager control. If you include the ScriptManager control on the master page, it can act as the ScriptManager control for all content pages.

UpdatePanel controls can be nested. If the parent panel is refreshed, all nested panels are refreshed also.

Leave a comment

Filed under Ajax

Abstract Class FACTS

Abstract Class FACTS

1) We can inherit abstract class from another abstract class also.

Eg:

public abstract class AbstractClass1

{
public abstract string TestMe();       

}

 It is inherited by AbstractClass2 

public abstract class AbstractClass2 : AbstractClass1

{
public abstract string DoSome();

public override string TestMe()

{

return “This is test”;

}

}

2) Abstract class can inherit Interface also.

Leave a comment

Filed under .Net, C#

GROUP BY, Where vs Having

GROUP BY is actually used to group the result-set by using aggregate functions.

Let’s say we have a table Student with columns:

Name Subject Score
Mahesh Math 80
Mahesh Eng 70
Ramesh Eng 70
Somesh Math 65
Ramesh Math 75
Somesh Eng 65
Mahesh Hindi 60
Ramesh Hindi 75

Now to get each student total marks:

SELECT Name, Sum(Score)

FROM Student

GROUP BY Name

Name Score
Mahesh 210
Ramesh 220
Somesh 130

Without GROUP BY,

SELECT Name, Sum(Score)

FROM Student

Name Score
Mahesh 560
Mahesh 560
Ramesh 560
Somesh 560
Ramesh 560
Somesh 560
Mahesh 560
Ramesh 560

WHERE vs HAVING

WHERE HAVING
WHERE is basically used to filter before the Group BY. HAVING is used to filter on GROUP BY result-set.
WHERE can’t be used with aggregate functions. Having is applied with aggregate functions only.
WHERE doesn’t need Group By. HAVING is used with Group By only.

Now for Query to get all students who have appeared in three subject exam:

SELECT Name, Count (Name)

FROM Student

GROUP BY Name

HAVING Count (Name) =3

To get all students who have scored more then 70 & appeared in three subject exam:

SELECT Name, Count(Name)

FROM Student

Where Score>70

GROUP BY Name

HAVING Count(Name)=3

 References:

http://www.programmerinterview.com/index.php/database-sql/having-vs-where-clause/

Leave a comment

Filed under SQL

Protected: Amex work

This content is password protected. To view it please enter your password below:

Comments Off on Protected: Amex work

Filed under Work

User Control Bubble Event

A better idea is to publish an event in the user control to allow any interested parties to handle the event.

This technique is commonly referred to as “event bubbling”.

Here is an exmple:

<%@ Control Language=”C#” AutoEventWireup=”true” CodeBehind=”UserControlDemo.ascx.cs” Inherits=”WellnGood.UserControlDemo” %>
<asp:Button ID=”btn1″ runat=”server” Text=”Bubble to Page”
onclick=”btn1_Click” />

public partial class WebUserControl : System.Web.UI.UserControl

{

public event EventHandler buttonClick;

protected void Button1_Click(object sender, EventArgs e)
{
buttonClick(sender, e);
}

}

Then you can subscribe the event buttonClick at webpage to display the different information .

<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”BubbleEvent.aspx.cs” Inherits=”WellnGood.BubbleEvent” %>

<%@ Register Src=”~/UserControlDemo.ascx” TagName=”UserControlDemo” TagPrefix=”ucDemo” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >
<head runat=”server”>
<title>Untitled Page</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<ucDemo:UserControlDemo ID=”ucDemo1″ runat=”server” />
</div>
</form>
</body>
</html>

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

ucDemo1.buttonClick+=new EventHandler(ucDemo1_buttonClick);

}

protected void ucDemo1_buttonClick(object sender, EventArgs e)
{
Response.Write(“I am User control bubble event on Page”);
}

}

Leave a comment

Filed under .Net

Factory Pattern

Factory Pattern is a creational patter. It provide encapsulation by hiding the complex components and their dependencies from the client.
Why do we need?
1. A class can’t anticipate the class of object it must create.
2. Client don’t need to use lot of new keywords.
3. Classes delegate responsibility to one of several helper subclasses.
4. If you want to develop a data layer that supports many types of database products, it should not be tightly coupled with a particular database product or ADO.NET data provider.

Ex: we will be creating an Employee objects. As with good OO design we will start with an interface.

public interface IEmployee
{
string GetDepartment();
string GetEducation();
}

Now Concrete Classes: we define two class inheriting from IEmployee interface i.e CTechnology & CHumanResource

public Class CTechnology : IEmployee
{
public string GetDepartment()
{
return “IT Department”;
}

public string GetEducation()
{
return “Engineering”;
}
}

public class CHumanResource : IEmployee
{
public string GetDepartment()
{
return “HR Department”;
}

public string GetEducation()
{
return “MBA”;
}
}

Now factory class, it is static and contain one method to return the correct object.
public class EmployeeFactory
{
public enum EmployeeType
{
IT, HR;
}

public static IEmployee CreateEmployee(EmployeeType empType)
{
switch(empType)
{
case EmployeeType.IT:
return new CTechnology;
break;

case EmployeeType.HR:
return new CHumanResource;
break;

default:
throw new ArgumentException(“Invalid Type of Employee”);
}
}
}

Now Client section: there are two buttons “IT EMployee” & “HR Employee” and two labels lblDept & lblEdu.

protected void Page_Load(object sender, EventArgs e)
{

}

protected void btnITEmployee_Click(object sender, EventArgs e)
{
IEmployee emp = EmployeeFactory.CreateEmployee(EmployeeFactory.EmployeeType.IT);
lblDept.Text = emp.GetDepartment();
lblEdu.Text = emp.GetEducation();
}

protected void btnHREmployee_Click(object sender, EventArgs e)
{
IEmployee emp =               EmployeeFactory.CreateEmployee(EmployeeFactory.EmployeeType.HR);
lblDept.Text = emp.GetDepartment();
lblEdu.Text = emp.GetEducation();
}

public interface IEmployee
{
string GetDepartment();
string GetEducation();
}Now we define two class inheriting from IEmployee interface i.e CTechnology & CHumanResource
public Class CTechnology : IEmployee
{
public CTechnology()
{

}
public string GetDepartment()
{
return “IT Department”;
}

public string GetEducation()
{
return “Engineering”;
}
}
public class CHumanResource : IEmployee
{
public CHumanResource()
{

}
public string GetDepartment()
{
return “HR Department”;
}

public string GetEducation()
{
return “MBA”;
}
}

Now our factory class, it is static and contain one method to return the correct object.
public class EmployeeFactory
{
public enum EmployeeType
{
IT, HR;
}

public static IEmployee CreateEmployee(EmployeeType empType)
{
switch(empType)
{
case EmployeeType.IT:
return new CTechnology;
break;

case EmployeeType.HR:
return new CHumanResource;
break;

default:
throw new ArgumentException(“Invalid Type of Employee”);
}
}
}

Leave a comment

Filed under .Net

How GC Works

How GC works

The GC maintains lists of managed objects arranged in “generations.” A generation is a measure of the relative lifetime of the objects in memory. The generation number indicates to which generation an object belongs. Recently created objects are stored in lower generations compared to those created earlier in the application’s life cycle. Longer-lived objects get promoted to higher generations.

Because applications tend to create many short-lived objects compared to relatively few long-lived objects, the GC runs much more frequently to clean up objects in the lower generations than in the higher ones.

Finalization is the process, by which the GC allows objects to clean up any unmanaged resources that they’re holding,

Note that you cannot call or override the Finalize method. It is generated implicitly if you have a destructor for the class.

~Test

{

//Necessary cleanup code

}

Dispose method must call GC.SuppressFinalize(this) to prevent the finalizer from running.

public void Dispose()

{

Dispose(true);

GC.SuppressFinalize(this);

}

Finalize Dispose
The execution order of finalize is non-deterministic. It’s execution is deterministic by using call to Dispose() method.
It doesn’t use any interface. It uses IDisposable interface and then override it’s Dispose() method.
you cannot  override the Finalize method, as it is generated implicitly destructor. Dispose is not depended on destructor.
You can suppress Finalize() by using GC.SuppressFinalize(this) You can’t suppress Dispose() as it is not called implicitly.

Leave a comment

Filed under .Net

Static Classes

Static classes are loaded automatically by the .NET when the program or namespace containing the class is loaded.
The main features of a static class are:
# They only contain static members.
# They cannot be instantiated.
# They are sealed.
# They cannot contain Instance Constructors

If you include instance member in static class then you will get compile time error.

static class CompanyInfo
{
public static string GetCompanyName() { return “CompanyName”; }
public static string GetCompanyAddress() { return “CompanyAddress”; }
}

Leave a comment

Filed under C#

ASP.Net Page Life Cycle

Leave a comment

Filed under .Net

ASP.NET Application Life Cycle for IIS

Application Life Cycle


Step 1:- The user sends a request to IIS. IIS first checks which ISAPI extension can serve this request. Depending on file extension the request is processed. For instance if the page is an ‘.ASPX page’ then it will be passed to ‘aspnet_isapi.dll’ for processing.

Step 2:- If this the first request to the website then a class called as ‘ApplicationManager’ creates an application domain where the website can run. As we all know application domain creates isolation between two web applications hosted on the same IIS. So in case there is issue in one app domain it does not affect the other app domain.

Step 3:- The newly created application domain creates hosting environment i.e. the ‘HttpRuntime’ object. Once the hosting environment is created necessary core ASP.NET objects like ‘HttpContext’ , ‘HttpRequest’ and ‘HttpResponse’ objects are created.

Step 4:- Once all the core ASP.NET objects are created ‘HttpApplication’ object is created to serve the request. In case you have a ‘global.asax’ file in your system then object of the ‘global.asax’ file will be created. Please note ‘global.asax’ file inherits from ‘HttpApplication’ class.
Note: The first time an ASP.NET page is attached to an application, a new instance of ‘HttpApplication’ is created. Said and done to maximize performance, ‘HttpApplication’ instances might be reused for multiple requests.

Step 5:- The ‘HttpApplication’ object is then assigned to the core ASP.NET objects to process the page.

Step 6:-Now following events are executed by HttpAlication like:
–ValidateRequest() for validating information sent by the browser to determine whether it contain malicious markup or for Cross-site scricpting attacks.
–URL mapping if it is configured in UrlMapping section in web.config.
–BeginRequest() event
–AuthenticateRequest() event
–AuthorizeRequest() event
….
….
….
–EndRequest() event

REFERENCES

http://www.codeproject.com/Articles/121096/Web-Server-and-ASP-NET-Application-Life-Cycle-in-D

http://www.codeproject.com/Articles/73728/ASP-NET-Application-and-Page-Life-Cycle

Leave a comment

Filed under .Net

ref vs out

ref
it is necessary to initialize them before passing to the function(compile time error, if not done).

 protected void Page_Load(object sender, EventArgs e)
{           
            int a = 20;
            Response.Write(a + “<BR>”);
            DoSome(ref a);      //we need to pass value with ref keyword
            Response.Write(a + “<BR>”);           
}

private void DoSome(ref int aa)
{
            aa = 30;
}

out
no assignment is required, but you must assign a value in which function this is passed.
If the other side doesn’t need any information about this object except where to store the object, you probably should just use ‘Out’.

protected void Page_Load(object sender, EventArgs e)
 {           
            int a = 20;           
            DoSome(out a);      //we need to pass value with out keyword
            Response.Write(a + “<BR>”);           
}

private void DoSome(out int aa)
{
            aa = 30;
}

2 Comments

Filed under .Net, C#

What is GAC? Where GAC located on machine?

GAC is known as Global Assembly Cache where the shared assembiles are being kept. GAC can be found on a system at \\Assembly ie. C:\Windows\Assembly.
GAC is a Folder that contains DLL that have strong name. As DLL differ by strong names+public key and since strong name can not be same hence we can put two DLL with same name into GAC. For example SameNameApp.dll and SameNameApp.dll can co-exist in GAC if the first one have version 1.0.0.0 and the second have 1.1.0.0.

DLL =Assembly_name + Version + Culture_Info + public_key

Leave a comment

Filed under .Net

Exception Handling in WCF

**********************************

Server Side Exception Handling

**********************************

Exception Handling in WCF

We basically handle two types of exception in WCF service and covert them to the FaultExcetion<SomeErrorDto> to make client familiar with the exceptions. Let me explain the complete scenario with a sample application XYZ:

Catch (XYZException ex)

{

       //Convert Application specific (XYZException) exceptions to FaultException<XYZErrorDto>.

       throw ExceptionHelper.HandleXYZToFaultException(ex);

}

Catch(Exception ex)

{

      //Convert Generic Exception to FaultException<XYZErrorDto>.

       throw ExceptionHelper.HandleGenericToFaultException(ex);

}

 

Our XYZException Class

public class XYZException : System.Exception

{

    private int _errorCode;

     public int ErrorCode

    {

        get { return _errorCode; }

        set { _errorCode = value; }

    }

 

    public XYZException(string message, Exception ex)  : base(message, ex)

    {

    }

    public XYZException(string message, int code, Exception ex)  : base(message, ex)

    {

        _errorCode = code;

    }  

}

Our ExceptionHelper class:

using System;

using System.Data.SqlClient;

using System.ServiceModel;

 

public class ExceptionHelper

{

    //Used in the BL(Business Logic) layer

    public static XYZException HandleGenericToXYZException(Exception genExcep)

    {

        //Logging the Generic Execption here before converting it to Application specific

       // (XYZException) exception.

        if ((genExcep != null))

        {

            return new XYZException(genExcep . Message, genExcep);

        }

        else

        {

            return null;

        }

    }

   

    //Convert Application specific Exception to FaultException<XYZErrorDto>

    public static FaultException<XYZErrorDTO> HandleXYZToFaultException(XYZException xyzExcep)

    {

        return HandleGenericToFaultException(xyzExcep);

    } 

    //Used in WCF service.

    public static FaultException<XYZErrorDTO> HandleGenericToFaultException(Exception genExcep)

    {

        XYZErrorDTO objXYZErrDTO = new XYZErrorDTO();

        if ((genExcep != null))

        {

            objXYZErrDTO = new XYZErrorDTO(genExcep.Message);

        }

        else

        {

            objXYZErrDTO = new XYZErrorDTO(“An unexpected error has occurred in the system”);

        } 

        //Logging the Generic Execption here before converting it to FaultException.

        return new FaultException<XYZErrorDTO>(objXYZErrDTO);

    }

}

*********************

UI Exception Handling

**********************

Now it is clear the UI will only receive Exceptions of type FaultException only from server, moreover we need to handle the Generic exception raised at the UI also. So if the UI code logic involve server resource usage the we have to catch both the exceptions else there will be only catching of general exception as shown below:

 Try

{

     //Logic involve usage of server resources 

}

Catch (FaultException ex)

{

      UIExceptionHelper.HandleFaultException(ex);        

}

Catch (Exception ex)

{

      UIExceptionHelper.HandleGenericException(ex);    

}

Our UIExceptionHelper class:

using System.ServiceModel;

using System.Diagnostics.EventLog;

 public class UIExceptionHelper

{

     public static void HandleFaultException(FaultException<XYZErrorDTO> faultExcep)

    {

        try

        {

            //Logging FaultException before displaying on Screen.          

            LogManager.LogError(faultExcep, errorCode, ConfigurationManager.AppSettings(“LogCategory”));

            WebMsgBox.Show(Decl.WEB_MSG, faultExcep.Detail.Message);

        }

        catch (Exception ex)

        {

        }

    }

     public static void HandleGenericException(Exception excep)

    {

        try

        {

            //Logging the Generic message before redirecting to custom error page.

            string strMsg = excep.Message.Replace(Constants.vbCrLf, ” “);

            string strTrace = excep.StackTrace.Replace(Constants.vbCrLf, ” “);

            LogManager.LogError(excep, errorCode, ConfigurationManager.AppSettings(“LogCategory”));

            //Redirecting to Custom Error Page for Generic Exceptions.

            Response.Redirect(Decl.ERROR_PAGE + “?Error=” + strMsg + “&Trace=” + strTrace);

        }

        catch (Exception ex)

        {

        }

    }

}

Refrences

http://msdn.microsoft.com/en-US/library/seyhszts(v=VS.80).aspx

http://dhananjaykumar.net/2010/05/23/fault-contract-in-wcf-with-learning-video/

Leave a comment

Filed under C#, WCF

Asynchronous Programming

Asynchronous Programming

When you create delegate, the compiler generates three methods Invoke, BeginInvoke, EndInvoke. Invoke is used to execute delegate synchronously, and rest two methods allow you to have asynchronous programming.

BeginInvoke takes the same parameters as delegate itself, plus another two parameters- an AsyncCallback which is called after the BeginInvoke execution, and an object parameter which is made available through the AsyncState property of the IAsyncResult parameter which is passed to the AsyncCallback.

The call to BeginInvoke returns an IAsyncResult which can be used to call EndInvoke, and you don’t have to pass a callback delegate to be executed if you don’t want to – just pass null as the last but one parameter to BeginInvoke.

private delegate int DoubleMeDelegate(int x);

protected void Page_Load(object sender, EventArgs e)

{

   for (int i = 1; i < 5; i++)

  {

     DoubleMeDelegate d = new DoubleMeDelegate(DoubleMe);

     d.BeginInvoke(i, new System.AsyncCallback(InvokeMessage), d);

   }

Thread.Sleep(1900);

}

private void InvokeMessage(IAsyncResult ar)

{

   DoubleMeDelegate dEnd = (DoubleMeDelegate)ar.AsyncState;

   int result = dEnd.EndInvoke(ar);

   Response.Write(result + “<br/>”);

}

private int DoubleMe(int single)

{

   Thread.Sleep(100);

   return (2 * single);

}

Leave a comment

Filed under C#

ThreadPool

ThreadPool

ThreadPool basically maintain “pool” of threads which are waiting for work items. As thread creation is not a cheap process. By default, the thread pool has 25 threads per processor.

We can Queue up method to the ThreadPool using it’s QueueUserWorkItem method. It takes two parameters – a WaitCallback delegate to the method you want to call and the optional object to pass as parameter to the callback method.

     protected void Page_Load(object sender, EventArgs e)  

        {  

            WaitCallback callBack;   

            callBack = new WaitCallback(DoubleMe);  

            ThreadPool.QueueUserWorkItem(callBack, 1);  

            ThreadPool.QueueUserWorkItem(callBack, 2);  

            ThreadPool.QueueUserWorkItem(callBack, 3);  

        }   

        public void DoubleMe(int i)  

        {   

            // Simulation of processing time   

            Thread.Sleep(1000);  

            String result = (2*i).ToString();

            Response.Write(result + “<BR>”);  

        } 

Leave a comment

Filed under C#

State Management

VIEW STATE

  • The ViewState property provides a dictionary object for retaining values between multiple requests for the same page only.
  • ViewState is lost if the user visits a different Web page, so it is useful only for temporarily storing values. They are saved in hidden fields.
  • The viewstate for all of the controls on the page will be stored in a single hidden control called __VIEWSTATE.

<input type=”hidden” name=”__VIEWSTATE” id=”__VIEWSTATE” value=”/wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA2IDE6Mzc6MTEgUE1kZGROWHn/rt75XF/pMGnqjqHlH66cdw==” />

We can encrypt viewstate to make it more difficult for attackers. To configure view state encryption:

At Application Level:

<Configuration>

<system.web>

<pages viewStateEncryptionMode=”Always”/>

</system.web>

</configuration>

At Page level:

<%@ Page AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” ViewStateEncryptionMode=”Always”%>

View State is enabled by default, but we can disable it by setting the EnableViewState property for each web control to false.

Data Types You Can Store in View State

Strings

Integers

Boolean values

Array objects

ArrayList objects

Hash tables

Custom ViewState

ArrayList PageArrayList;

//Get value from ViewState

if (ViewState[“PageArrayList”] != null)

{

PageArrayList = (ArrayList)ViewState[“arrayListInViewState”];

}

//To saves into ViewState

ViewState.Add(“arrayListInViewState”, PageArrayList);

QUERYSTRING

A query string is information sent to the server appended to the end of a page URL.

Benefits: –

• No server resources are required. The query string containing in the HTTP requests for a specific URL.

• All browsers support query strings.

Limitations: –

• Query string data is directly visible to user thus leading to security problems.

• Most browsers and client devices impose a 255-character limit on URL length.

If you have more than one query string then using “&” sign.

eg:

http://www.gurunguns.com/login.aspx?type=testing&uid=qstring

We can use the above queryString in C# as:

string loginType = Request.QueryString[“type”]

string userid = Request.QueryString[“uid”]

To access QueryString using javascript:

http://triaslama.wordpress.com/2008/04/12/retrieving-query-string-values-in-aspnet-and-javascript/

COOKIES

PERSISTENT COOKIE NON-PERSISTENT COOKIE
1. Persistent cookies are stored in text file at the client side. Non-Persistent cookies are stored in the RAM at client.
2. They are permanent cookies. They are destroyed when the browser is closed.
3. Session Id is not stored in them. Session Id is stored in non-persistent cookies.

Leave a comment

Filed under .Net

Http Modules

Http Module

An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules let you examine incoming and outgoing requests and take action based on the request.

eg: BeginRequest, AuthenticationRequest event, EndRequest event etc. You may intercept , participate and modify each request.

Uses for HTTP modules include

1) Security   Because you can examine incoming requests, an HTTP module can perform custom authentication or other security checks before the requested page, XML Web service, or handler is called.

2) Statistics and logging   Because HTTP modules are called on every request, you can gather request statistics and log information in a centralized module, instead of in individual pages.

3) Custom headers or footers   Because you can modify the outgoing response, you can insert content such as custom header information into every page or XML Web service response.

 An HTTP module is supposed to implement the following methods of the IHttpModule interface:

Method Name Description
Init This method allows an HTTP module to register its event handlers to the events in the HttpApplication object.
Dispose This method gives HTTP module an opportunity to perform any clean up before the object gets garbage collected

 An HTTP module can register for the following events exposed by the System.Web.HttpApplication object.

  • Event Name
Description
AuthenticateRequest This event is raised when ASP.NET runtime is ready to authenticate the identity of the user.
AuthorizeRequest This event is raised when ASP.NET runtime is ready to authorize the user for the resources user is trying to access.
BeginRequest This event is raised when ASP.NET runtime receives a new HTTP request.
EndRequest This event is raised just before sending the response content to the client.
Global.asax Events
Application_OnStart This event is raised when the very first request arrives to the Web application.
Application_OnEnd This event is raised just before the application is going to terminate.
Session_OnStart This event is raised for the very first request of the user’s session.
Session_OnEnd This event is raised when the session is abandoned or expired.

 Registering HTTP Modules in Configuration Files

To add an HTTP module:

 <httpModules>

            <add  name=”modulename” type=”classname, assemblyname” />

<httpModules>

Eg:

<httpModules>

 <add name=”OutputCahe”  type=”System.Web.Caching.OutputCacheModule”/>

 <add  name=”Session”  type=”System.Web.SessionState.SessionStateModule”/>

</httpModules>

 To remove an HTTP module

 <httpModules>

            <remove  name=”modulename” />

<httpModules>

 Implementing an HTTP Module for Providing Security Services

HTTP module that provides security services for our Web application. Our HTTP module will basically provide a custom authentication service. It will receive authentication credentials in HTTP request and will determine whether those credentials are valid.

 using System;

using System.Web;

using System.Security.Principal; 

namespace SecurityModules

{

 /// <summary>

 /// Summary description for Class1.

 /// </summary> 

 public class CustomAuthenticationModule : IHttpModule

 {

  public CustomAuthenticationModule()

  {

  }

  public void Init(HttpApplication r_objApplication)

  {

   // Register our event handler with Application object.

   r_objApplication.AuthenticateRequest +=

               new EventHandler(this.AuthenticateRequest) ;

  }

   public void Dispose()

  {

   // Left blank because we dont have to do anything.

  }

   private void AuthenticateRequest(object r_objSender,

                                   EventArgs r_objEventArgs)

  {

   // Authenticate user credentials, and find out user roles.

   1. HttpApplication objApp = (HttpApplication) r_objSender ;

   2. HttpContext objContext = (HttpContext) objApp.Context ;

   3. if ( (objApp.Request[“userid”] == null) ||

   4.                     (objApp.Request[“password”] == null) )

   5. {

   6.  objContext.Response.Write(“<H1>Credentials not provided</H1>”) ;

   7.  objContext.Response.End() ;

   8. }

    9. string userid = “” ;

   10. userid = objApp.Request[“userid”].ToString() ;

   11. string password = “” ;

   12. password = objApp.Request[“password”].ToString() ;                                   

   13. string[] strRoles ;

   14. strRoles = AuthenticateAndGetRoles(userid, password) ;

   15. if ((strRoles == null) || (strRoles.GetLength(0) == 0))

   16. {

   17. objContext.Response.Write(“<H1>We are sorry but we could not

       find this user id and password in our database</H1>”) ;

   18. objApp.CompleteRequest() ;

   19. }

    20. GenericIdentity objIdentity = new GenericIdentity(userid,

                                             “CustomAuthentication”) ;

   21. objContext.User = new GenericPrincipal(objIdentity, strRoles) ;

  }

   private string[] AuthenticateAndGetRoles(string r_strUserID,

                                                 string r_strPassword)

  {

   string[] strRoles = null ;

   if ((r_strUserID.Equals(“Steve”)) &&

                                  (r_strPassword.Equals(“15seconds”)))

   {

    strRoles = new String[1] ;

    strRoles[0] = “Administrator” ;

   }

   else if ((r_strUserID.Equals(“Mansoor”)) &&

                                        (r_strPassword.Equals(“mas”)))

   {

     strRoles = new string[1] ;

     strRoles[0] = “User” ;                                             

    }

    return strRoles ;

   }

  }

}

 We start with the Init function. This function plugs in our handler for the AuthenticateRequest event into the Application object’s event handlers list. This will cause the Application object to call this method whenever the AuthenticationRequest event is raised.

 Once our HTTP module is initialized, its AuthenticateRequest method will be called for authenticating client requests. AuthenticateRequest method is the heart of the security/authentication mechanism. In that function:

 Line 1 and Line 2 extract the HttpApplication and HttpContext objects. Line 3 through Line 7 checks whether any of the userid or password is not provided to us. If this is the case, error is displayed and the request processing is terminated.

 Line 9 through Line 12 extract the user id and password from the HttpRequest object.

 Line 14 calls a helper function, named AuthenticateAndGetRoles. This function basically performs the authentication and determines the user role. This has been hard-coded and only two users are allowed, but we can generalize this method and add code for interacting with some user database to retrieve user roles.

 Line 16 through Line 19 checks whether the user has any role assigned to it. If this is not the case that means the credentials passed to us could not be verified; therefore, these credentials are not valid. So, an error message is sent to the client and the request is completed.

 Line 20 and Line 21 are very important because these lines actually inform the ASP.NET HTTP runtime about the identity of the logged-in user. Once these lines are successfully executed, our aspx pages will be able to access this information by using the User object.

 Now we have to perform some changes in our web.config file. First of all, since we are using our own custom authentication, we don’t need any other authentication mechanism.

 <authentication mode=”None”/>

 Similarly, don’t allow anonymous users to our Web site. Add the following to web.config file:

 <authorization>

  <deny users=”?”/>

</authorization> 

Users should at least have anonymous access to the file that they will use for providing credentials. Use the following configuration setting in the web.config file for specifying index.aspx as the only anonymously accessible file:

 <location path=”index.aspx”>

 <system.web>

  <authorization>

   <allow users=”*”/>

  </authorization>

 </system.web>

</location> 

Reference:

http://www.15seconds.com/issue/020417.htm

Leave a comment

Filed under .Net

Logging with HttpModule

In order to build an Http module we only need to implement 
the IHttpModule interface. The following is a simple 
LoggingHttpModule which log details when a web request start 
and when web request end: 
using System;
using System.Web;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging; 
namespace HttpModules
{
  public class LoggingHttpModule : IHttpModule
  {
    #region Members 
    private LogWriter _writer; 
    #endregion 
    #region IHttpModule Members 
    public void Dispose()
    {
      if (_writer != null)
      {
        _writer.Dispose();
      }
    } 
    public void Init(HttpApplication context)
    {
      CreateLogWriter();
      context.BeginRequest += new EventHandler(context_BeginRequest);
      context.EndRequest += new EventHandler(context_EndRequest);
    } 
    private void CreateLogWriter()
    {
      ConfigureEnterpriseLibraryContainer();
      _writer = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
    } 
    private void ConfigureEnterpriseLibraryContainer()
    {
      var builder = new ConfigurationSourceBuilder(); 
      builder.ConfigureInstrumentation().EnableLogging();
      builder.ConfigureLogging().WithOptions
             .LogToCategoryNamed("General")
               .WithOptions
               .SetAsDefaultCategory()
               .SendTo
               .FlatFile("Log File")
               .FormatWith(new FormatterBuilder()
               .TextFormatterNamed("Textformatter"))
                   .ToFile("file.log"); 
      var configSource = new DictionaryConfigurationSource();
      builder.UpdateConfigurationWithReplace(configSource);
      EnterpriseLibraryContainer.Current =
        EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
    } 
    void context_BeginRequest(object sender, EventArgs e)
    {
      _writer.Write(new LogEntry
      {
        Message = "BeginRequest"
      });
    } 
    void context_EndRequest(object sender, EventArgs e)
    {
      _writer.Write(new LogEntry
      {
        Message = "EndRequest"
      });
    } 
    #endregion
  }
}

 

In order to use the module all we need to do is to add a reference
to the class library that holds the LoggingHttpModule. Then we need
to register the module in the web.config file in the httpModules 
element like:

<httpModules>
    <add name="LoggingHttpModlue" type="HttpModules.LoggingHttpModule, HttpModules"/>
</httpModules> 

That is it. Now the module will be executed whenever a request
start or end.

Leave a comment

Filed under .Net

Cookieless Session

SessionId is stored at client side in cookies. Therefore we won’t be able to retrieve session’s data in the case when cookies are not enable.
ASP.NET support cookieless execution of the application when the client doens’t have cookies support. The Session id is embedded to the request url.

To set Cookieless session in an ASP.NET application set following value in web.config file
<sessionstate cookieless=”true” />

When you have cookieless session then the url may look like this
http://www.gurunguns.com/Posts/(_entv9gVODTzHuenph6KAlK07..)/test.aspx

Leave a comment

Filed under .Net

Nth Highest salary & Nth Lowest salary of employee

There are two approaches for the same, I will show the example with N=2
1 using CTE

Highest
With cteH
{
   Select Emp_Name, Emp_Salary, Row_Number() over (Order By Emp_Salary Desc) as Rn
   From Emp
}

Select Emp_Name, Emp_Salary
From cteH
Where Rn=2

Lowest
With cteL
{
   Select Emp_Name, Emp_Salary, Row_Number() over (Order By Emp_Salary Asec) as Rn
   From Emp
}
Select Emp_Name, Emp_Salary
From cteL
Where Rn=2

2 using Distinct

Highest
Select e1.Emp_Name, e1.Emp_Salary
From Emp e1
Where 2=(Select Count(DISTINCT(e2.Emp_Salary)) From Emp e2
  Where e2.Emp_Salary>=e1.Emp_Salary)

Lowest
Select e1.Emp_Name, e1.Emp_Salary
From Emp e1
Where 2=(Select Count(DISTINCT(e2.Emp_Salary)) From Emp e2
  Where e2.Emp_Salary<=e1.Emp_Salary)

Leave a comment

Filed under SQL

How SSL Works

How SSL Works

Secure Sockets Layer (SSL) is the public -key encryption approach. SSL is an Internet security protocol used by Internet browsers and Web servers to transmit sensitive information.

SSL doesn’t authenticate a user.

Look for the “s” after “http” in the address whenever you are about to enter sensitive information & a small padlock in the status bar at the bottom of the browser window. 

How SSL handshake works:

Like XYZ Inc., intends to secure their customer transactions

Step 1: Client makes a connection to xyz.com on an SSL port, typically 443. This connection is denoted with https instead of http.

Step 2: xyz.com sends back its public key to the client. Once client receives it, his/her browser decides if it is alright to proceed on the basis of below points:

  • the certificate comes from a trusted party (like VeriSign);
  • the certificate is currently valid; and
  • the certificate has a relationship with the site from which it’s coming.

Step 3: If the client decides to trust the certificate, then the client will be sent to xyz.com his/her public key.

Step 4: xyz.com will next create a unique hash and encrypt it using both the customer’s public key and xyz.com’s private key, and send this back to the client.

Step 5: Customer’s browser will decrypt the hash. This process shows that the xyz.com sent the hash and only the customer is able to read it.

Step 6: Customer and website can now securely exchange information.

Certificates and Public Key Infrastructure
During the handshake, the service also sends its SSL certificate to the client. The certificate contains information, such as its expiration date, issuing authority, and the site’s Uniform Resource Identifier (URI). The client compares the URI to the URI it had originally contacted to ensure a match, and also checks the date and issuing authority.

Every certificate has two keys, a private key and a public key, and the two are known as an exchange key pair. In brief, the private key is known only to the owner of the certificate while the public key is readable from the certificate. Either key can be used to encrypt or decrypt a digest, hash, or other key, but only as contrary operations. For example, if the client encrypts with the public key, only the site can decrypt the message using the private key. Similarly, if the site encrypts with the private key, the client can decrypt with the public key. This provides assurance to the client that the messages are being exchanged only with the possessor of the private key because only messages encrypted with the private key can be decrypted with the public key. The site is assured that it is exchanging messages with a client that has encrypted using the public key. This exchange is secure only for an initial handshake, however, which is why much more is done to create the actual symmetric key. Nevertheless, all communications depend on the service having a valid SSL certificate.
(Refer to here)

1 Comment

Filed under .Net

Nullable Type

Nullable types are instances of the System.Nullable struct.

Variables are of two types.

Value type eg. int, char, date. A data type is a value type if it holds the data within its own memory allocation.
Reference type eg. string, object. A reference type contains a pointer to another memory location that holds the data.
 For more details on Value types and Reference type of variable, please read http://msdn.microsoft.com/en-us/library/t63sy5hs(VS.80).aspx

Reference types variable can be assigned null but value types of variables like integer can’t because they can’t contain reference, even the reference of nothing.

int i = 0;
The above statement shall throw error because we are trying to store null in the integer variable.

To avoid this we can use nullable modifier like this.

int? ii = null;
In the above code, ii is the nullable type of variable that can store either null or any integer type of variable. When a variable is declared as nullable, its extends two properties called HasValue and Value. Both property are public and read-only.

Leave a comment

Filed under C#

New vs Override

New vs Override 

Override

  • Override method actually override the virtual method.
  • When a method of a base class is overridden in a derived class (subclass), the version defined in the derived class is used.
  • This indicates for the compiler to use the last defined implementation of a method i.e. override the last implented method.
  • if you want to prevent anymore overridden from inherited class then use sealed keyword along with override.

New

  • It actually hides the base class method.
  • The new modifier instructs the compiler to use your implementation instead of the base class implementation. Any code that is not referencing your class but the base class will use the base class implementation.
  • new keyword doesn’t allow the method to be more overridden.

Example:

class BaseClass
{
public virtual void WhichClass()
{
System.Console.WriteLine(“BASE CLASS”);
}
}

class NewClass : BaseClass
{
public new void WhichClass()
{
//base.WhichClass();
System.Console.WriteLine(“NEW CLASS”);
}
}

class OverrideClass : BaseClass
{
public override void WhichClass()
{
//base.WhichClass();
System.Console.WriteLine(“OVERRIDE CLASS”);
}
}
class Program
{
static void Main(string[] args)
{
BaseClass bObj = new BaseClass();
bObj.WhichClass();
System.Console.WriteLine(“———-“);

NewClass nObj = new NewClass();
nObj.WhichClass();
System.Console.WriteLine(“———-“);

BaseClass bnObj = new NewClass();
bnObj.WhichClass();
System.Console.WriteLine(“———-“);

OverrideClass oObj = new OverrideClass();
oObj.WhichClass();
System.Console.WriteLine(“———-“);

BaseClass boObj = new OverrideClass();
boObj.WhichClass();
System.Console.WriteLine(“———-“);

Console.ReadLine();
}
}

1 Comment

Filed under .Net, C#

Static ClientID ASP.Net 4.0

Static ClientID
When writing JavaScript code to get any control in a page, We don’t know the control client

ID. Now in ASP.Net 4.0 you can make the client id of the control fixed

By making your control implement the following interface:

INamingContainer “ and set the ClientIDMode property to Static.

For example, here is the codebehind for a simple web user control (ASCX) with a label in it.

public partial class WebUserControl1 : System.Web.UI.UserControl, INamingContainer
{
   protected void Page_Load(object sender, EventArgs e)
   {
     this.ClientIDMode = ClientIDMode.Static;
   }
}
That’s all you need to do, and the control gets rendered to the page with an ID of Label1.

Leave a comment

Filed under .Net

C# 4.0 new features

In every new release of C# there is a major new feature like in C# 2.0 (Generics), C# 3.0 (Linq), and here C# 4.0 (dynamic programming support) 

1. Named and optional parameters: Now declare optional parameters simply by providing a default value for it. And call params by name: like so,      

        // Definition of the method

        public void Method(int x, int y = 1, int z = 2)

        {        } 

        // Using the optional params

        Method(1);          // same as Method(1, 1, 2);

        Method(1, 2);       // same as Method(1, 2, 2);

        Method(1, 2, 3);   

       // Named params called, note arbitrary order and missing y

        Method(z: 1, x: 2);

 2. dynamic object:

A new type has been introduced called dynamic. The idea is that you can call any operation on the dynamic type you want, the compiler won’t check it at compile-time, but figure it out at runtime. A dynamic object is assumed to support any operation at compile-time; only at runtime will you get an error. The result of any dynamic operation is of type dynamic.

        // Instantiation
        dynamic d = 7; // implicit conversion
        dynamic d = GetStudentData(); //GetStudentData() returns object of type Student class
        // Operations on dynamic       

        d.f = d.P;           // getting and settings types fields and properties
        d[“one”] = d[“two”]; // getting and setting thorugh indexers
        int i = d + 3;       // calling operators

 
// in the previous examples if f,p are not properties on the Student class and also there is no indxer it will be   compiled successfully ,it will be detected at runtime.

Leave a comment

Filed under C#

C# 3.0 new features

1. Implicitly typed local variables and arrays:  A new keyword is introduced called var. This allows you to declare a variable and let the compiler figure out the type  

ex:

        // Declare a variable of type int

            var i = 5;

            // Declare an int array

            var a = new[] { 1, 10, 100, 1000 };

            // Usage:

            for (var i = 0; i < 5; i++) { }

            foreach (var item in MyList) { }

            using (var file = new StreamReader(“Filename.txt”)) { } 

2. Auto-implement properties: Use this when no additional logic is required in the property accessors. 

ex:

        // Previously we had to do this,

        private string _name;

        public string Name

        {

            get { return _name; }

            set { _name = value; }

        }

        // Now we can shorthand it, there’s no need to declare the _name variable

        public string Name { get; set; } // The compiler creates a private anonymous backing field

Behind the scene, compiler automatically creates private, anonymous fields that can be accessed from the above auto-implemented properties.

 3. Object and collection initializers: Set properties inline during object creation.    

 ex:

    public class A {

    public string Name { get; set; }

    public string Address { get; set; }

}

// Previously we would have to do,

A a = new A();

a.Name = “…”;

a.Address = “…”;

// Now we can do this,

A a = new A { Name = “…”, Address = “…” };

// Similarly, we can initialize collections,

List<int> MyList = new List<int> { 0, 1, 2, 3, 4 };

 4. Extension methods: Now you can add methods to existing types without creating a new derived type, recompiling or modifying the original type’s code. This is incredibly useful in writing cleaner code,

ex:

public static void ExportToExcel(this DataSet ds)
{
    //do something…
}

Extension methods are declared by specifying the “this” keyword as the modifier in the first parameter. The ExportToExcel method is declared as an extension method for the DataSet class.
Extension methods are invoked as soon the namespace of the containing static class is included.
In the below code snippet, the extension method is declared inside
namespace Orcas.Samples
{
   public static class Extensions
   {
       public static void ExportToExcel(this DataSet ds)
      {
             //do something…
      }
   }
}

Above method is invoked in the client program as,
using Orcas.Samples;
DataSet ds = new DataSet();
ds.ExportToExcel()
;

5. Anonymous types: If you need a small class with read only properties, you can now use a simple syntax,     

ex:

// a is an anonymous type, the compiler creates the class with

// private string fields _name and _address

// and public string properties Name and Address,

var a = new { Name = “Dev”, Address = “Delhi” };

// a.Name and a.Address are read-only,

string s = a.Name;

 6. Query keywords (LINQ): We are now able to use TSQL like syntax inside C# to query data sources (could be objects, collections, XML, or SQL databases). Introduces a host of new keywords like from, where, select, group, orderby, join, etc.      

ex:

// The data source,

     int[] numbers = { 0, 1, 2, 3, 4, };

     // Create the query,

     var lessthan3 =

         from num in numbers

         where num < 3

         select num;

     // Output: 0 1 2

     foreach (var m in lessthan3) {

         Console.Write(m.ToString() + ” “);

     }

7. Partial method definitions: A partical class (introduced in C# 2.0) can now have partial methods. This simply means the method signature is in one partial class and the implementation in another. There are some constraints, like the method is implicitly private (and therefore cannot be virtual) and must return void.      

 ex:

public partial class A

{

    // Method definition

    partial void Method();

}

public partial class A

{

    // Method implementation

    partial void Method() { /* Do Work */ }

} 

Leave a comment

Filed under C#

Explanation of WCF web.config

Explanation of WCF web.config class 

<configuration xmlns=”http://schemas.microsoft.com/.NetConfiguration/v2.0″&gt;

  <system.serviceModel>

    <services>

      <service behaviorConfiguration=”returnFaults”>

        <endpoint contract=”IMyService” binding=”wsHttpBinding”/>

      </service>

    </services>

    <behaviors>

      <serviceBehaviors>

        <behavior >

          <serviceDebug includeExceptionDetailInFaults=”true” />

<serviceMetadata httpGetEnabled=”true” />

        </behavior>

      </serviceBehaviors>

    </behaviors>

  </system.serviceModel>

  <system.web>

    <compilation debug=”true”/>

  </system.web>

</configuration> 

Within the <system.serviceModel> we will host Serivces tag, which will has all services we will have in our project or what we want to expose. 

Within   <Services> we will host service by service

Each service tag has a name attribute “the name of the service class” and “behaviorConfiguration” that specify name of behaviour tag within serviceBehaviors tag

Each service has endpoint (“ABC”) tag with three attributes

Address(“Where”): will be “” empty if the service on the localhost.

Binding(“How”): binding=”wsHttpBinding” we will use http or https for transportation and communication

Contract(What”):the Name of the interface

Within <ServiceBehaviours> there are behaviour tag

<serviceDebug includeExceptionDetailInFaults=”true />

Each behaviour has name attribute so service can find it as mentioned before

serviceDebug includeExceptionDetailInFaults=”true” specify that occurrence of exceptions include details of the exception in the message. 

<serviceMetadata httpGetEnabled=”true” />

To enable service client to get metadata of the service project assembly to view and call service contained types

Refrences

http://blog.flair-systems.com/search/label/WCF

Leave a comment

Filed under WCF

Returning Data

Returning Data from Strored Procedure
There are three common ways to return data from stored procedures: returning result sets (SELECT statements), using output variables and using the RETURN statement.

Result Sets
Like the procedure to return a list of all the people with a given last name

Create Procedure dbo.GetPeopleByLastName(@LastName varcgar(200))
As
Select FirstName, LastName
From Person
Where
LastName=@LastName

Using OUTPUT variables
To return a single value (or a couple of values) you can use output variables.

Create Procedure dbo.GetCountByLastName(@LastName varchar(200), @LNameCount int OUTPUT)
As
Select @LNameCount=  Count(*)
From Person
Where
LastName=@LastName
And how to execute it :
DECLARE @TheCount INT

EXEC dbo.GetCountByLastName 
    @LastName = ‘Alexander’,
    @LastNameCount = @TheCount OUTPUT

Using Return

It only returns a single numeric value. This is most commonly used to return a status result or error code from a procedure.

Create Procedure TestReturn(@IntValue int)
As
RETURN @IntValue
Go

Note that executing a RETURN statement causes a stored procedure to stop executing and return control back to the calling program. This is often used to test for error conditions and stop processing if one is found.

Leave a comment

Filed under SQL

SSRS – Reporting Services Database

Some report developers don’t realize that there are two databases that you can use to lookup or analyze reporting services information. It’s often useful to write your own reports, based on information stored in these databases.

The first database is ReportServer, which is used by the Report Services to store all the information about reports that have been uploaded to the report manager. Information such as the report catalog, settings, and security are all stored within the ReportServer database.  The database ReportServerTempDB stores temporary information such as report snapshots, user sessions, and report execution information.

I have three examples of useful reports created from the ReportServer database. The first report is what I call the Report Index. It provides a list of all the items in the reporting services catalog, with links to render each report in the catalog, as shown in Figure 35. This can prove to be useful as it allows your report users to run just one report and get a list of all reports, without having to navigate through the report manager.

Figure : The Report Index report

I provide an example Report Index.rdl report as part of the code download with this article. You’ll have to point the report to your ReportServer database.

The second report, Report Usage, is basically a metrics-type report, providing details of reports that are being executed and how many times per month. The ReportServer database contains a table called ExecutionLog that, by default, stores every report execution for 60 days. You can update the setting ExecutionLogDaysKept in table ConfigurationInfo to allow for more than 60 days of execution tracking. Again, you can obtain the Report Usage.rdl file from the download file, and an example of the report is shown in Figure .

Figure : The Report Usage report

The third report, Report Users, is similar to the Report Usage report. Report Users report is basically a metrics-type report, providing details of which users are executing the reports.  Again, you can obtain the Report Users.rdl file from the download file, and an example of the report is shown in Figure.

You will need to point all the report mentioned in this section to your ReportServer database.

Leave a comment

Filed under SSRS

Playing with REST !

REST Services

àREST stands for Representational State Transfer, means that each unique URL is a representation of some object.

-to get the contents of that object use an HTTP GET,

-to delete you then might use a POST, PUT, or DELETE to modify the object.

àUnlike SOAP, REST is not a standard; it is just an architectural style.

àREST uses HTTP for all four CRUD (Create/Read/Update/Delete) operations.

àMuch like Web Services, a REST service is:

* Platform-independent (you don’t care if the server is Unix, the client is a Mac, or anything else),

* Language-independent (C# can talk to Java, etc.)

eg:

-The famous Twitter API is all REST.

Yahoo! offer most of their services using REST including Search API, Maps, Photos.

Flickr,

-Amazon.com offer several REST services, e.g., for their S3 storage solution

Atom is a RESTful alternative to RSS.

Like the following URL sends a REST request to Yahoo!’s web-search service:

http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=rest.

Click it, and observe the XML results, ready to be used directly.

This REST request includes two parameters:

appid“, used by Yahoo! to specify your application, and

query“, which is the actual search query.

REST vs SOAP

Yahoo’s web services are using REST and google using SOAP for their web services.

REST is Lightweight than SOAP because it does not requires lot of xml markup.

WCF 3.5 provides explicit support for RESTful communication using a new binding named WebHttpBinding.

The below code shows how to expose a RESTful service

[ServiceContract]

interface IStock

{

[OperationContract]

[WebGet(UriTemplate:=”/Stock/{StockId}”)]

int GetStock(string StockId);

}

By adding the WebGetAttribute, we can define a service as REST based service that can be accessible using HTTP GET operation, like GetStock from Stock.

We can use REST style to get order as shown in the below URL with Stock

http://localhost/stock.svc/Stock/100234

How to consume REST services

There are different ways to consume the REST services as per requirements, below I am mentioning some:

1) Here I am actually reading the Xml from REST service and writing to the file.  WebClient() is defined in System.Net
WebClient() objWebClient = new WebCleint();
objWebClient.Credentials = new NetworkCredential(uid, pwd, domain);
XmlTextReader objXmlTextReader = new XmlTextReader(objWebClient.OpenRead(path));
string objXml = string.Empty;

while(objXmlTextReader.Read())
{
   objXml = objXmlTextReader.ReadOuterXml;
}

string filePath = serverPath + “\” + Date.UtcNow.Year.Tostring();

if(File.Exists(filePath))
{  
   StreamWriter wr;
   File.Delete(filePath);
   wr = File.CreateText(filePath)
   wr.WriteLine(objXml)
   wr.Close();        
}
else
{
   StreamWriter wr;
   wr = File.CreateText(filePath)
   wr.WriteLine(objXml)
   wr.Close();
}

2) To query a REST service, like the one I mentioned above, we can use LINQ’s XML functionality.  The XElement class (declared in System.Linq.XML) provides a Load method that can retrieve an XML data from a url with GET  method:

XElement rootXml = XElement.Load(“http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=rest”);

var SearchResult = from R in rootXml.Elements()

select new { Topic = (string)R.Element(“Title”),

Detail = (string)R.Element(“Summary”),

Link = (string)R.Element(“Url”) };

foreach (var x in SearchResult)

Console.WriteLine(“{0}  {1}”, x.Topic, x.Detail, x.Link);

Console.ReadKey();

Using POST method is a bit more complex. First we have to obtain a channel by which we may POST the information. Then we have to create an instance of data entity in XML format. Finally we have to POST data through the channel.

To get access to REST service we use a HttpWebRequest since it lets use the POST method and let us specify the type of information we are posting.

HttpWebRequest channel = (HttpWebRequest)WebRequest.Create(“http://ws.geonames.org/countryInfo”);

channel.Method = “POST”;

channel.ContentType = “text/xml”;

HttpWebRequest class provides a stream to which we can write information :

StreamWriter sw = new StreamWriter(channel.GetRequestStream());

Then we can create a concerete entity to post:

XElement country = new XElement(“country” ,

new XElement(“countryCode”, “AUS”),

new XElement(“countryName” , “Australia”),

….

);

Finally we just need to save this XElement object to the stream we obtained from HttpWebRequest:

country.Save(sw);

References:

http://aspguy.wordpress.com/2008/10/10/dealing-with-rest-web-services/

http://developer.yahoo.com/dotnet/howto-rest_cs.html

2 Comments

Filed under .Net, C#

SET vs SELECT

SET and SELECT both key words are used to Assign Variables in SQL Server.

SET and SELECT both specifies the columns to be changed and the new values for the columns.
The values in the specified columns are updated with the values specified in the SET and SELECT in all rows that match the WHERE clause search condition.
If no WHERE clause is specified, all rows are updated.

There are some difference based on the Performance, Process like Follows :

1. SET is the ANSI standard for variable assignment, SELECT is not. 

2. SELECT can be used to assign values to more than one variable at a time, Whereas SET allows to assign data to only one variable at a time.

Example :

/* Declaring variables */
DECLARE @Var1 AS int, @Var2 AS int

/* The same can be done using SET, but two SET statements are needed */
SET @Var1 = 1
SET @Var2 = 2  

/* Initializing two variables at once */
SELECT @Var1 = 1, @Var2 = 2

But use SET instead SELECT, for variable initialization, It will throw the following error

SET @Var1 = 1, @Var2 = 2  

Msg 102, Level 15, State 1, Line 10
Incorrect syntax near ‘,’.

3. When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all .so the variable will not be changed from it’s previous value.  

Example :

Run it in master Database in SQL Server.

/* Returns NULL */
DECLARE @Title varchar(80)
–SET @Title = ‘Not Found’

SET @Title =
(
SELECT error
FROM SysMessages
WHERE Description = ‘Invalid Description’
)

SELECT @Title
GO

/* Returns the string literal ‘Not Found’ */
DECLARE @Title varchar(80)
SET @Title = ‘Not Found’

SELECT @Title = error
FROM SysMessages
WHERE Description = ‘Invalid Description’

SELECT @Title
GO  

4. Let using a query needs to populate a variable and the Query returns more than one value.
SET will fail with an error in this scenario.
But SELECT will assign one of the returned rows and mask the fact that the query returned more than one row.

As a result, bugs in your the could go unnoticed with SELECT, and this type of bugs is hard to track down too.

Example :

/* Consider the following table with two rows */
SET NOCOUNT ON
CREATE TABLE #Table (i int, j varchar(10))
INSERT INTO #Table (i, j) VALUES (1, ‘Sunday’)
INSERT INTO #Table (i, j) VALUES (1, ‘Monday’)
GO

/* Following SELECT will return two rows, but the variable gets its value from one of those rows, without an error.
you will never know that two rows existed for the condition, WHERE i = 1 */
DECLARE @j varchar(10)
SELECT @j = j FROM #Table WHERE i = 1
SELECT @j
GO

/* If you rewrite the same query, but use SET instead, for variable initialization, you will see the following error */
DECLARE @j varchar(10)
SET @j = (SELECT j FROM #Table WHERE i = 1)
SELECT @j

Msg 512, Level 16, State 1, Line 4
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Based on the above results, when using a query to populate variables, we should always use SET.
If you want to be sure that only one row is returned then only use SELECT, as shown below:

DECLARE @j varchar(10)
SELECT @j = (SELECT j FROM #Table WHERE i = 1)
SELECT @j

5. This very feature of SELECT makes it a winner over SET, when assigning values to multiple variables. A single SELECT statement assigning values to 3 different variables, is much faster than 3 different SET statements assigning values to 3 different variables.
In this scenario, using a SELECT is at least twice as fast, compared to SET.

Leave a comment

Filed under SQL

Report Data in Page Header/Footer

Reporting Services does not provide out of-the-box support for use of information from your queries in Page Headers and Footers. There are two ways around this.

The first way is to create controls in the body of your report, holding the values you need to display in the header and/or footer. You can set these controls to “hidden”, and place them in some out-of-the-way place, towards the bottom of the report. Then, you can set expressions on controls in your header and footer sections to the value of the control in the body of your report.

In the following example, shown in Figure 27, I placed a textbox control in the body of the report named “textbox1”, with a value of “Hello World”. In the header section, I placed a textbox with a value of “=ReportItems!textbox1.Value”. I then copied the control in the header section and pasted it into the footer section.

Figure : Display report data in headers and footers, using a hidden control in the body

If you preview this report, the value of “textbox1” will be displayed in the header and footer.

Figure: Three times Hello World

A slightly cleaner option, in my opinion, is to create a public function that can be called to set the value of a variable, which can then be used in any or all sections of the report body, header, and footer. Figure shows the embedded code that creates this SetReportTitle function, containing the _Title variable.

Figure: The SetReportTitle function.

In this example, you can then simply set the value of the hidden textbox in the body of your report to “=Code.SetReportTitle(“Report Title”)“. This calls our function and sets the value of the _Title variable to Report Title.

Now, you can set the value of any control in the header or footer to “=Code._Title”. The variable can be used in any or all sections of the report body, header, and footer.

Leave a comment

Filed under SSRS

Extension Methods

They are static methods that can be invoked like an instance method. Static methods can be declared only in Static classes. Let’s see how extension methods are declared.
public static void ExportToExcel(this DataSet ds)
{
//do something…
}

Extension methods are declared by specifying the “this” keyword as the modifier in the first parameter. The ExportToExcel method is declared as an extension method for the DataSet class.
Extension methods are invoked as soon the namespace of the containing static class is included.
In the below code snippet, the extension method is declared inside
namespace Orcas.Samples
{
public static class Extensions
{
public static void ExportToExcel(this DataSet ds)
{
//do something…
}
}
}

Above method is invoked in the client program as,
using Orcas.Samples;
DataSet ds = new DataSet();
ds.ExportToExcel();

Leave a comment

Filed under C#