Skip to main content

Posts

Showing posts with the label C#

Optimization through WeakReference

WeakReference is a new element added into 4.5 framework, but it was available in Java from the earlier stage only. So, this article could be useful for .Net, Java, and Android as well. What is it? It is nothing more than a class but what special about is to interact with Garbage Collector in a certain way which could help out in optimization. Scenario We all know that static members are created and shared throughout the application and life cycle by maintaining only single instance. Possibly it can useful in cases where data need to be frequently accessed but what about those that doesn't need to be frequently accessed all times. Those data might be resource hungry data so static or some kind of caching mechanism is required. Storing something in static members or caching increases memory footprint for the application. This is once situation, but there might be other situation as well. WeekReference is a technique to hook up member with Garbage collector to retrieve actual ...

Configuring Ninject, Asp.Net Identity UserManager, DataProtectorTokenProvider with Owin

It can be bit tricky to configure both Ninject and Asp.Net Identity UserManager if some value is expected from DI to configure UserManager. We will look into configuring both and also use OwinContext to get UserManager. As usual, all configuration need to be done on Startup.cs. It is just a convention but can be used with different name, the important thing is to decorate class with following attribute to make it Owin start-up: [assembly: OwinStartup(typeof(MyProject.Web.Startup))] Ninject configuration Configuring Ninject kernel through method which would be used to register under Owin. Startup.cs public IKernel CreateKernel() { var kernel = new StandardKernel(); try { //kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); // TODO: Put any other injection which are required. return kernel; } catch { kernel.Dispose(); thro...

Using LINQ to Entity efficiently with First/FirstOrDefault/Last/LastOrDefault/Single/SingleOrDefault

We generally use these extension methods First/FirstOrDefault/Last/LastOrDefault/Single/SingleOrDefault with predicates like ctx=> ctx.Model.FirstOrDefault(item => item.Id == 1 ) Or ctx=> ctx.Model.Where(item => item.Id == 1 ).FirstOrDefault() What is the problem with these? FirstOrDefault or similar methods immediately loads all data at once. So, let's say we have fifty columns on table then all those columns data would be retrieved from DB and saved into memory. This link gives a fair idea of different function behavior.  https://msdn.microsoft.com/en-us/library/bb882641.aspx .  So, even if we require only one value from selected field it retrieves all values. What is the solution? The solution is pretty simple. Whenever we need selected items better to do projection before calling FirstOrDefault or similar methods. Ex: Selecting single item ctx.Model.Where(itm => itm.Id == 1) .Select(itm => itm.Name).FirstO...

Easy way to parse SQL data reader objects

Many a times, I have seen that people end up writing lot of codes to read from SQL data reader or there is no fail safe mechanism to handle, if parse fails out. In this article, I will try to cover up above issue and implement uniform way to handle things with fail safe mechanism using TryParse approach. Mainly, I will extend inbuilt try parse mechanism comes with .Net. Int.TryParse and similar type of methods was introduced in 2.0 Framework, so the code should be compatible with 2.0 or higher framework. Let's directly dive into usage since we have just single function DbTryParse. I will be explaining function on later stage. We can use with fail safe mechanism where some values are not properly parsed then row will get skipped or in normal way, we define some default value and move ahead with other rows. int id; string val; double dbl; reader["id"].DbTryParse(out id, int.TryParse, 89); reader["val"].DbTryParse(out val, "NA...

Advance enum generation for lookup table through T4

Sometime back I had written simple T4 to generate enum for look up tables http://vikutech.blogspot.in/2014/01/enumeration-generation-for-lookup-table.html . Later on I had posted same on Nu-Get https://www.nuget.org/packages/t4.lookup . This time I am going to extend it to support multiple enums, enum Id, configuration through class and different settings for enum description, columns. Here is the entire code for generating code <#@ template debug="true" hostSpecific="true" #> <#@ output extension=".cs" #> <#@ Assembly Name="System.Data" #> <#@ import namespace="System" #> <#@ import namespace="System.Collections.Generic" #> <#@ include file="EF.Utility.CS.ttinclude"#> <#@ import namespace="System.Data.SqlClient" #> <# // TODO: Look for alternatives to remove connection string var connectString = "data source=.;initial...

Extending WhenAny,WhenAll like feature to get the task as soon as it completes

While working with list of task, we only get two built in options to retrieve task info for completion. First is WhenAny and other WhenAll. WhenAny can be used when any of the given tasks gets completed first where as WhenAll notifies when all of the task gets completed. There is no option to know each task as soon as it gets completed. I was going through  Pro Asynchronous Programming with .NET  book which shows better option to deal with notification of task completion efficiently. To return the task on completion,  TaskCompletionSource  will be used . Through TaskCompletionSource,  Task  could be created and with provided inbuilt methods outcome can be handled. This can be also helpful to wrap up legacy codes as well to built up task. Let's directly look in to core code to return task based on completion. /// <summary> /// Order by completion for Task. /// </summary> /// <typeparam name="...

Displaying progress status in asynchronous programming

UX is most important in any application and responsive application is an add-on to make UI free by running long running task in background. Sometimes we need to show more useful information about long running task to keep user informed about progress. In this article, we will be looking into showing up progress status for long running process with Task Parallel Library (TPL). In this particular example, we will be creating a Console application to re-size any amount of jpg files under directory with new image dimension but our main focus would be on showing progress status. Prior to .Net 4.5 Framework version, there was no inbuilt mechanism to show status of task. If it was needed, then we need to create event handler on class that is processing the long running task with custom defined event argument for progress status class and then subscription need to be done on consuming class for getting progress information. This was better and tidy approach for getting progress status...

Strongly typed configuration through database

We usually save most of application setting under app.config or web.config with key and value pair under appSetting element. The big problem with those are whenever you need value, typecasting need to be done and also need to be called through key. The other problem I find is with hierarchy of settings like download related setting present should under download element for easy accessing. To solve strongly typed configuration and hierarchy, ConfigurationManager ( http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager(v=vs.110).aspx ) class comes for rescue. You might have seen under web.config where we have sectionGroup and related configuration under elements. To implement it, lot of codes need to written to achieve simplification. To reduce numbers of codes for implementing XML configuration a very good and free tool is available called "Configuration Section Designer" available on http://csd.codeplex.com/ . There we do not have to wri...

Interface based model binding to populate properties value automatically

Interface is great way to make consistency and re-useability of codes. In this tutorial, I am going to show the power of interface to populate view/domain models automatically and interchange values between models. Technologies or techniques used in this approach: - MVC. - Interface for models. - MVC model binder for associated model with interface. Through this model binder we will populate values. - T4 template to generate code to register model binder with all models associated with interface. - Generic extension method to interchange values. It might sounding bit complex to achieve small thing. Just hold on with me and see unfolding. This will result in easier maintenance and less repetitive code. First let's start with creation of Interface that need to be populate automatically. This interface would be implemented on models and values will be auto-populated on binder. /// <summary> /// Interface for storing entry related values /// </summar...