Dot Net Tips Tricks C # Tips Tricks and Solutions

Being a web developer is not an easy task. Programming in ASP.NET requires a lot of hard work and brains. Many small things seem difficult sometimes and require a lot of time. This could be frustrating and might lead to less productivity. Therefore, this article is aimed at those ASP.NET developers who go through these sorts of situations. It will provide them with some .NET tricks that might be of some help to them.

Our article would provide some .NET tips and tricks that could make your problems disappear. Apart from that, C# tips will also be provided. First of all, I would like to start by sharing some useful .NET tricks with all the readers.
How to send a raw JSON request to ASP.NET from jQuery?
The first step is to build a class in ASP.NET project and name that as SaveData.cs. We execute the SaveData class from IHttpHandler and instigate both,  IsReusable and ProcessRequest. After that, you must ascribe the HttpHandler with Web.Config; and for this purpose, you can use ashx to outline the handler.
  1. & lt;  
  2. httpHandlers & gt; & lt;  
  3. add verb = "*"  
  4. path = "Save.ashx"  
  5. type = "MyProject.SaveData" / & gt; & lt;  
  6. /httpHandlers>  
Once you have ascribed the HttpHandler with the Web.Config, make a jQuery AJAX request and transfer the data to SaveData handler.
  1. var strJson = JSON.stringify(JsonDetails);  
  2. $.ajax({  
  3.     url: 'Save.ashx',  
  4.     type: 'post',  
  5.     async: false,  
  6.     contentType: 'application/json; charset=utf-8',  
  7.     data: strJson,  
  8.     dataType: 'json',  
  9.     success: function(result) {  
  10.         alert('success');  
  11.     },  
  12.     error: function(result) {  
  13.         alert('failed');  
  14.     }  
  15. });  
In the above example, the JSON item that is supposed to be sent to the Server is kept into JsonDetails object. To transform the JSON object into string and transfer it to AJAX, we used JSON.stringify. Now, AJAX has been designed to circulate and transfer the data to the request body. The datatype of the AJAX request has been aligned as JSON.
Now, the browser will call the recently created IHttpHandler with raw JSON data into it. The request is in raw format and parameters cannot be found from the request context. Although, the API is available to deal with this but it is unable to describe the raw JSON object in most cases.
That’s it. Now, when you execute the project and call the AJAX request through JavaScript, the data will be described in the Server and an actual JSON object will be given to you. In order to explain the JSON request by yourself, use the code given below.
  1. public class SaveData: IHttpHandler {  
  2.         public bool IsReusable {  
  3.             get {  
  4.                 return true;  
  5.             }  
  6.         }  
  7.         public void ProcessRequest(HttpContext context) {  
  8.             var jsonString = String.Empty;  
  9.             context.Request.InputStream.Position = 0;  
  10.             using(var inputStream = new StreamReader(context.Request.InputStream)) {  
  11.                 jsonString = inputStream.ReadToEnd();  
  12.             }  
  13.             JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();  
  14.             object serJsonDetails = javaScriptSerializer.Deserialize(jsonString, typeof(object));  
  15.             // You can now add logic to work with serJsonDetails object  
  16.         }  
Remove persistent cookies before expiration time
Persistent cookies are those forms of cookies that are saved in the user’s hard drive and stay until they expire automatically. This .NET trick would help the developers in removing persistent cookies from the hard drive before its expiration time. The code, given below, will help you in setting the expiration time for cookies.
  1. //Creting a Cookie Object  
  2. HttpCookie _userInfoCookies = new HttpCookie("UserInfo");  
  3. //Setting values inside it  
  4. _userInfoCookies["UserName"] = "Abhijit";  
  5. _userInfoCookies["UserColor"] = "Red";  
  6. _userInfoCookies["Expire"] = "5 Days";  
  7. //Adding Expire Time of cookies  
  8. _userInfoCookies.Expires = DateTime.Now.AddDays(5);  
  9. //Adding cookies to current web response  
  10. Response.Cookies.Add(_userInfoCookies);  
The above code would help you in setting the expiration time for the persistent cookies. If you are willing to remove the cookies prior to their expiration time, you just need to override the cookie’s information and for that purpose, the code, given below, is recommended.
  1. HttpCookie _userInfoCookies = new HttpCookie("UserInfo");  
  2. //Adding Expire Time of cookies before existing cookies time  
  3. _userInfoCookies.Expires = DateTime.Now.AddDays(-1);  
  4. //Adding cookies to current web response  
  5. Response.Cookies.Add(_userInfoCookies);  
For C# programmers, there are a few C# tips and tricks that I would like to share. Usage of these C# tricks can be very useful and effective.
Bytescout’s C# PDF generator has the ability to add content on the top of the present PDF document, so I would suggest you all use it if you are facing any problem.
For Non-Public Methods, always write unit test cases
Most developers never try to write unit test cases for private methods of an assembly because they are not noticeable by the test project. With the help of C#, you can make the internals of an assembly observable to other assemblies. For that, you just have to add the below code in AssemblyInfo.cs and this would do the trick.
//Make the internals visible to the test assembly
[assembly: InternalsVisibleTo("MyTestAssembly")]
Use Tuples
Many developers have been generating a POCO class for the purpose of recurring various values from a method. For this purpose, tuples are designed and are available in .NET Framework 4.0. They can be used efficiently with the code, given below.
  1. public Tuple < int, string, string > GetEmployee() {  
  2.     int employeeId = 1001;  
  3.     string firstName = "Rudy";  
  4.     string lastName = "Koertson";  
  5.     //Create a tuple and return  
  6.     return Tuple.Create(employeeId, firstName, lastName);  
  7. }  
Instead of using temporary collections, use Yield
Most of the times, developers form a temporary list in order to keep saved items. The code in C#, given below, can help in using the temporary list.
  1. public List < int > GetValuesGreaterThan100(List < int > masterCollection) {  
  2.     List < int > tempResult = new List < int > ();  
  3.     foreach(var value in masterCollection) {  
  4.         if (value > 100) tempResult.Add(value);  
  5.     }  
  6.     return tempResult;  
  7. }  
In order to avoid temporary collection and using field, use the code given below.
  1. public IEnumerable < int > GetValuesGreaterThan100(List < int > masterCollection) {  
  2.     foreach(var value in masterCollection) {  
  3.         if (value > 100) yield  
  4.         return value;  
  5.     }  
  6. }  
When you are writing LINQ queries, always remember about deferred execution
The LINQ query in .NET helps in performing the query only when the LINQ outcome is retrieved. This occurrence of LINQ is basically defined as deferred execution.
Now, here comes the most important part. Whenever you access the result, the query gets implemented again. So, in order to prevent repetitive execution, you must transform the LINQ outcomes to a list upon execution, for this purpose use the code, given below.
  1. public void MyComponentLegacyMethod(List < int > masterCollection) {  
  2.     //Without the ToList this linq query will be executed twice because of the following usage  
  3.     var result = masterCollection.Where(i => i > 100).ToList();  
  4.     Console.WriteLine(result.Count());  
  5.     Console.WriteLine(result.Average());  
  6. }  
Recollecting the Precise Stack Trace
When you throw the exception in the C# program, as shown in the code below, some errors would be followed in the method ConnectDatabase. So, the thrown exception stack trace would only show the occurrence of error in RunDataOperation method, and the real error source would be lost.
  1. public void RunDataOperation() {  
  2.     try {  
  3.         Intialize();  
  4.         ConnectDatabase();  
  5.         Execute();  
  6.     } catch (Exception exception) {  
  7.         throw exception;  
  8.     }  
  9. }  
In order to preserve the real stack trace throw, use the code, given below.
  1. public void RunDataOperation() {  
  2.     try {  
  3.         Intialize();  
  4.         ConnectDatabase();  
  5.         Execute();  
  6.     } catch (Exception) {  
  7.         throw;  
  8.     }  
  9. }  
Enum Grouping Flags Attributes
In C#, naming the enum with flag attributes can allow you to permit the enum as the bit fields. This could be of assistance for us in grouping the enum values. A sample of C# is available below.
  1. class Program {  
  2.     static void Main(string[] args) {  
  3.         int snakes = 14;  
  4.         Console.WriteLine((Reptile) snakes);  
  5.     }  
  6. }  
  7. [Flags]  
  8. enum Reptile {  
  9.     BlackMamba = 2,  
  10.         CottonMouth = 4,  
  11.         Wiper = 8,  
  12.         Crocodile = 16,  
  13.         Aligator = 32  
  14. }  
In the above code, the outcome would be BlackMamba, CottonMouth, and Wiper but if the flags attribute is detached, then the outcome will be 14 directly.
Always Use a Profiler
One of the most important C# tips for all developers is that they must have a profile and use it often. Profilers help in determining the slower part of application easily. If there are any bugs present in the application, they can also be recognized by profilers. So, my advice to all the developers out there is that they must use a profiler.
I would recommend you all to use Bytescout’s developer tools as they are extremely effective and easy to use. Bytescout PDF SDK is considered one of the best for .NET developers who are willing to control barcodes and PDF documents.
These are some of the C# tricks from my side. Hopefully, they might be of some help to anyone who uses them.