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 to those ASP.NET developers who go through these sort 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 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.
- & lt;
- httpHandlers & gt; & lt;
- add verb = "*"
- path = "Save.ashx"
- type = "MyProject.SaveData" / & gt; & lt;
- /httpHandlers>
Once you have ascribed the HttpHandler with the Web.Config, make a jQuery AJAX request and transfer the data to SaveData handler.
- var strJson = JSON.stringify(JsonDetails);
- $.ajax({
- url: 'Save.ashx',
- type: 'post',
- async: false,
- contentType: 'application/json; charset=utf-8',
- data: strJson,
- dataType: 'json',
- success: function(result) {
- alert('success');
- },
- error: function(result) {
- alert('failed');
- }
- });
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 actual JSON object will be given to you. In order to explain the JSON request by yourself, use the code given below.
- public class SaveData: IHttpHandler {
- public bool IsReusable {
- get {
- return true;
- }
- }
- public void ProcessRequest(HttpContext context) {
- var jsonString = String.Empty;
- context.Request.InputStream.Position = 0;
- using(var inputStream = new StreamReader(context.Request.InputStream)) {
- jsonString = inputStream.ReadToEnd();
- }
- JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
- object serJsonDetails = javaScriptSerializer.Deserialize(jsonString, typeof(object));
-
- }
Remove persistent cookies before expiration time
Persistent cookies are those form of cookies that are saved in 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.
-
- HttpCookie _userInfoCookies = new HttpCookie("UserInfo");
-
- _userInfoCookies["UserName"] = "Abhijit";
- _userInfoCookies["UserColor"] = "Red";
- _userInfoCookies["Expire"] = "5 Days";
-
- _userInfoCookies.Expires = DateTime.Now.AddDays(5);
-
- 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.
- HttpCookie _userInfoCookies = new HttpCookie("UserInfo");
-
- _userInfoCookies.Expires = DateTime.Now.AddDays(-1);
-
- Response.Cookies.Add(_userInfoCookies);
For C# programmers, there are 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 present PDF document, so I would suggest you all to 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.
- public Tuple < int, string, string > GetEmployee() {
- int employeeId = 1001;
- string firstName = "Rudy";
- string lastName = "Koertson";
-
- return Tuple.Create(employeeId, firstName, lastName);
- }
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.
- public List < int > GetValuesGreaterThan100(List < int > masterCollection) {
- List < int > tempResult = new List < int > ();
- foreach(var value in masterCollection) {
- if (value > 100) tempResult.Add(value);
- }
- return tempResult;
- }
In order to avoid temporary collection and using field, use the code given below.
- public IEnumerable < int > GetValuesGreaterThan100(List < int > masterCollection) {
- foreach(var value in masterCollection) {
- if (value > 100) yield
- return value;
- }
- }
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 the repetitive execution, you must transform the LINQ outcomes to list upon execution, for this purpose use the code, given below.
- public void MyComponentLegacyMethod(List < int > masterCollection) {
-
- var result = masterCollection.Where(i => i > 100).ToList();
- Console.WriteLine(result.Count());
- Console.WriteLine(result.Average());
- }
Recollecting the Precise Stack Trace
When you throw the exception in 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.
- public void RunDataOperation() {
- try {
- Intialize();
- ConnectDatabase();
- Execute();
- } catch (Exception exception) {
- throw exception;
- }
- }
In order to preserve the real stack trace throw, use the code, given below.
- public void RunDataOperation() {
- try {
- Intialize();
- ConnectDatabase();
- Execute();
- } catch (Exception) {
- throw;
- }
- }
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.
- class Program {
- static void Main(string[] args) {
- int snakes = 14;
- Console.WriteLine((Reptile) snakes);
- }
- }
- [Flags]
- enum Reptile {
- BlackMamba = 2,
- CottonMouth = 4,
- Wiper = 8,
- Crocodile = 16,
- Aligator = 32
- }
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 the developers is that they must have a profiler 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 as 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.