As we all know web pages are stateless pages and we need to use session variables in web application to maintain some session over page. Some time we divide our application into multiple layers for example business logic layer,database layer etc. This all layers will be a class library projects.
So when you have your applications divided into the multiple layers at that time you might need to use session variables in the class library projects. For that we are adding System.Web namespace as a reference to a class library project and then we can use session with HttpContext object. That’s works fine if your layers are going to be used in web application projects. But for example if you have service oriented architecture and your services also access your class libraries via non standard protocol i.e. WCF Service hosted on TCP/IP bindings. At that time sessions will not work.
Instead of that you should always use the parameters in method and avoid direct use of session variables. That parameters will passed either from the web application or from the services which is calling the class libraries.
Hope you liked it. Stay tuned for more..
Showing posts with label C#.NET. Show all posts
Difference between All and Any operator in linq
In this post we are going to learn about difference between ‘All’ and ‘Any’ operator in Linq.
Difference between ‘All’ and ‘Any’ operator:
All operator checks whether all elements have met specific conditions or not while Any operator check whether there is any elements exist in collection or not?So what we are waiting for Let’s take a example.
using System;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] intArray = {1,2,3,4,5};
bool result = intArray.All(i => i > 2);
Console.WriteLine(result);
result = intArray.Any();
Console.WriteLine(result);
Console.ReadLine();
}
}
}
In the above example you can see that I have created an integer array and then checked with both all and any operator. In first condition I have checked that whether elements are greater then 2 or not and same way I have checked with any operator that its contains any element or not?Now let’s run that example. To see how its works.
All operator in linq
Few days back I came across “All” operator in Linq. I thought it will be good idea to write a blog post about it and share it with community.
All operator in linq:
It’s almost similar to select it returns all the element in the input sequence with matching condition in given predicate. Following is syntax for All.public static bool All<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate)
It check the condition whether all the elements on collection matches given criteria and based on that it will return bool value. It can be useful in scenario where we need to do some kind of validation whether all the elements of collection matches with certain condition or not.
So Let’s take a simple example. Following is a code for that.
using System;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] intArray = {1,2,3,4,5};
bool result = intArray.All(i => i > 2);
Console.WriteLine(result);
result = intArray.All(i => i < 6);
Console.WriteLine(result);
}
}
}
Default keyword in c#
In this post, I am going to explain about default keyword in c#.
Introduction:
As per MSDN default keyword in C# used to assign the default value of the type. In some situation its comes very handy where we don’t want to create object and directly assign the default value of it.The basic syntax of default is default(T) where t is any reference type of value type and If T is a value type, whether it will be a numeric value or struct.
Default Keyword usage:
We can use Default keyword in variety of cases.Assigning value to nullable Type:
using System;
namespace ConsoleApplication3
{
class Program
{
static void Main() {
int? i = default(int);
Console.WriteLine(i);
}
}
}
Here output will be.
How to convert a list into array with Linq
In this post, I am going to explain how we can convert an generic list to simple int array with Help of Linq. Recently, I was working on an application and there I needed an Int array of for list of ids in generic list. I tried various methods and then with the help of ‘Select’ operator and ToArray method I have easily converted an generic list to the int array.
Lets take a simple example. I need a contact id list from a generic list of contacts and following is my contact class.
public class Contact
{
public int ContactId { get; set; }
public string Name { get; set; }
}
Now I have created a new GetContacts methods to create a new Generic List of Contacts.
Redirection with ASP.Net friendly URLs
How to redirect a page to ASP.Net friendly URLs:
Actually!! there is nothing to learn. It’s very easy You can directly use the ‘Response.Redirect’ with the ASP.Net friendly URLs. The NuGet Package itself takes care of all the things. You just need to write the route name as a parameter in ‘Response.Redirect’ and you are done!!Uh!! don’t believe me!!. Let’s take a sample example. I am going to use by default template with ASP.NET Friendly URLs. So for this example I have created a ASP.Net button in Default template AboutUs.aspx page. Once the click of that button we are going to use ‘Response.Redirect’ for redirection and redirect this page to Contact Page. Following is a html code for that button.
ASP.NET Friendly URLs – Cleaner, SEO friendly URLs
www.foo.com ?Product.aspx?Category=1& Page=1
If you search engine read this URL then search engine will not know much about this URLs. Even normal people who does not know querystring menaing(?Category=watch&Page=1) will not understand it. But If you have URL like following.
www.foo.com/prduct/category/watch/page/1
It’s easy to read and search engine and normal people will know that you are loading products that belongs to category watch and this is a first page.
How to create overload methods in WCF service with C#
So let’s consider same Hello world example which we have used web service overload method. Let’s create two methods HelloWorld one is with name and another is without parameter. For WCF service we have to first create interface following is a code for that.
SelectMany operator in Linq C#
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.selectmany.aspx
In this post I am going to explain How it can be really useful when you want to find list related to two entities. Practical example will be like a person can have multiple address and if you want to find list of addresses that are used with person then this SelectMany operator can be really useful.
So for this example First, I have create Address class with Street and Postalvcode property
public class Address
{
public string Street { get; set; }
public string PostalCode { get; set; }
}
C# null-coalescing operator ??
You can find more information about null-coalescing operator from the below link.
http://msdn.microsoft.com/en-us/library/ms173224.aspx
Tip-Convert array to Comma delimited string
After doing some research I have found string.Join. With the help of this we can easily an array into the comma delimited string.
String.join have two arguments one is separator and other one is either array or enumerable.
Following is a code for that.
namespace ConsoleApplication3
{
class Program
{
static void Main() {
string[] name = {"Jalpesh", "Vishal", "Tushar", "Gaurang"};
string commnaDelmietedName = string.Join(",", name);
System.Console.WriteLine(commnaDelmietedName);
}
}
}
Linq performance with Count() and Any()
Difference between Count() and Any():
In Count() method code will traverse all the list and get total number of objects in list while in Any() will return after examining first element in the sequence. So in list where we have many object it will be significant execution time if we use count().How to get N row from datatable in C#
Problem:
Recently one of my friend was needed only first three rows of data table and so he asked me and I have multiple solutions for that. So thought it would be great idea to share with you guys.Possible Solutions to problem:
There are two ways to solve this problem.- With normal for loop
- With lamda expression and linq
1. With normal for loop:
Following is code from where we can get 3 rows of data table.Search and filters available in visual studio 2012
Visual Studio 2012 features
In this post we are going to talk about search and filters provided into the visual studio 2012. There are lots of emphasis there in search and filters in visual studio 2012.You can almost search every thing including errors also. There are different search options are available for that.
Quick launch search in visual studio:
Prior to previous edition in visual studio 2012 there was quick launch search given at the top of the visual studio. From here you can search for anything in solutions and even menu’s also. It will provide you a quick launch for that.Lazy<T> in C# 4.0
It is very useful for UI responsiveness and other scenario's. Lazy initialization delays certain initialization and it’s improve the start-up time of a application. In the earlier framework if we need this kind of functionality we have to do it manually via coding but from C# 4.0 onwards it have Lazy<T> class. With the Help of this we can improve the responsiveness of C# application. Following is a simple example.
Lock keyword in C#
Let’s consider a scenario. We are having a small firm of computers and each computer is shared by two employees and they need to use computer for putting their sales data in excel sheet. So they can not work together at same time and one has to work and other has to wait till first one complete the work. Same situation can be occurred in programming in where we are using same resource for multiple thread.
C# provides locking mechanism via lock keyword. It restricts code from being executed by more then one thread at a time. That is the most reliable way of doing multi threading programming.
Where I can find SQL generated by Linq-To-SQL
For this post I am going to use same table like following. A customer table with two columns CustomerId and CustomerName.
Where I can find SQL Generated by Entity framework?
Few days back I was optimizing the performance with Entity framework and Linq queries and I was using LinqPad and looking SQL generated by the Linq or entity framework queries. After some point of time I got the same question in mind that how I can find the SQL Statement generated by Entity framework?
After some struggling I have managed to found the way of finding SQL Statement so I thought it would be a great idea to write a post about same and share my knowledge about that. So in this post I will explain how to find SQL statements generated Entity framework queries.
To demonstrate the idea Let’s a very simple console application with C# and then create a table called ‘Customer’ with CustomerId and CustomerName field in sql server.
Caller Info Attributes in C# 5.0
With the help of Caller Information we can get following information over there.
- CallerFilePathAttribute: With help of this attribute we can get full path of source file that contains caller. This will be file path from which contains caller at compile time.
- CallerLineNumberAttribute: With the help of this attribute we can get line number of source file which the method is called.
- CallerMemberNameAttribute: With the help of this attribute we can get the method or property name of the caller.
Let’s write a simple example for that to see how its works. Following is a code for that.
Parallel task in C# 4.0

