Showing posts with label architecture. Show all posts
Showing posts with label architecture. Show all posts

Monday, February 27, 2012

Inter-Process Communication using MemoryMappingFile

In an operating system, a Memory Mapping file are virtual storage place which has direct byte to byte correlation between the Virtual Address Space and the corresponding physical storage. So when we access the Virtual Address space via a memory mapping file we are directly communicating with the kernel space where the file is actually loaded. The portion of calculation between the physical storage and logical storage is hence avoided.

Memory Mapping files allows application to access files in the same way as memory. Generally as address between the physical storage and virtual memory address space, we cannot access the physical address directly. But using Memory Mapping Files, the process loads a specific range of address within the process address space with which the storage of memory into the file can be done by just assigning value to a dereferenced pointers. The IO operation on a MemoryMapping file is so fast that from the programmers point of view it seems to be like accessing the memory rather than actual physical storage. To increase performance memory mapping files are not actually stored to the disk file as well, but rather it will be stored automatically in background when FlushViewOfFile is executed or paging file is written. To Read more about memory mapping files, read here.

Memory Mapping file inside .NET Framework

.NET introduces a separate namespace to handle Memory Mapping files. Previously, we needed to do this using unmanaged Api's but with the introduction of managed API into the .NET framework library, it becomes very easy to handle MemoryMapping file directly from .NET library.

As memory mapping files are loaded into memory on a separate range of address space, two process can easily share the same page file instance and thus interprocess communication can be made with fast access to memory. It is recommended to back data with an actual disk file when large data is loaded into memory, so that there is no memory leak on the system when there is large memory pressure.

Saturday, February 4, 2012

Optimizing INPC Objects against memory leaks using WeakEvents

Working with WPF has always been a fun. Dealing with animation and richness in UI to its optimum level often gives you an edge to present something to your client and to ensure that your client shouts with a "WOW!". The Wow factor of applications can give you high rank in the first place, but increases expectation from the software. It is practically very hard to maintain with this expectation as time progresses. The survival of the fittest chooses one which best suits to the problem.

One of the major problems that developers face today is the memory leaks in an applications. Often the software that is built looks great but does not follow basic guidelines to ensure that the application is not memory hungry or even there are no existing memory leaks.

Note : By memory leak we mean, some portion of memory is not reclaimed by the garbage collector even though the object is not in use. 

By this way, the memory usage of the application increases at a certain extent and finally crashes with the OutOfMemoryException. To detect a memory leak there exists a large number of tools of which some are free while others are used as commercial purposes. Most of these problems can be fixed by either using Disposable pattern ( IDisposable interface) or manually de - referencing each and every object that are not in use. Sometimes, this can be also done in destructor / finalizers in .net too (but remember using destructors lose GC cycle).

Friday, October 7, 2011

Generic Types and Static Members

One of my friend recently asked me a question that I think I should share with you. Say you have a Static Implementation of a Type T which you pass as Open Type in your Generic Class. Now the problem is how to get reference to the Static Members or invoke a method that is Static to the Type from the Open Type T.  In this post, I will demonstrate few implementations that help you getting the Static implementation.

First of all, According to C# documentation, any type allocates its static members once per Type rather than once per Open Type. Now lets define this using the code below :

Monday, September 26, 2011

Internals of .NET Objects and Use of SOS

Well, now getting deeper into the facts, lets talk about how objects are created in .NET and how type system is laid out in memory for this post in my Internals Series.  As this is going to be very deep dive post, I would recommend to read this only if you want to kill your time to know the internal details of .NET runtime and also you have considerable working experience with the CLR types and type system.


Recently I have been talking with somebody regarding the actual difference between the C++ type system and managed C# type system. I fact the CLR Type system is different from the former as any object (not a value type) is in memory contains a baggage of information when laid out in memory. This makes CLR objects considerable different from traditional C++ programs.

Classification of Types

In .NET there are mainly two kind of Types.
  1. Value Types (derived from System.ValueType)
  2. Reference  Type (derived directly from System.Object)
Even though ValueTypes are internally inherited from System.Object in its core, but CLR treats them very differently.  Indeed from your own perception the Value Types are actually allocated in stacks (occationally) while reference types are allocated in Heaps. This is to reduce the additional contension of GC heaps for Heap allocation, GC cycles, occasional call to OS for additional memory needs etc. The object that is allocated in managed Heap is called Managed Object and the pointer that is allocated in stack to refer to the actual object in heap is called Object Reference (which is sometimes called as Managed Pointer). 

Monday, September 12, 2011

Writing a Custom ConfigurationSection to handle a Collection

Configuration is one of the major thing that you need to keep in mind while building any application. Either its an Windows Forms application or a Web site, configuration file is always needed. We write all the configuration that are needed to be changed after it is being deployed in confugration files. It is an XML File which lists all the configuration blocks itself and also allows you to define your own custom configuration sections yourself. Today I am building my own custom configuration section and show how easily you can build yourself.

While dealing with Configurations, there are two things that you need to address

  1. ConfigurationSection
  2. ConfigurationElement
  3. ConfigurationElementCollection

For most of the simple configurations, it is pretty much common to use these two classes, but when you need more complex configuration block, like appsettings which actually puts a Collection of ConfigurationElements, you might need to use ConfigurationElementCollection to hold the collection of ConfigurationElement. 

Thursday, September 1, 2011

31 Tips for the month on Threading, WPF, MEF, ASP.NET


Daily .NET Tips is aiming to sharing useful coding tips and tricks for .NET Developers. This site completely design for sharing Tips and Tricks, useful Code Snippet which anyone use in daily development work and targeted anything related with .NET.   This month we have wide range of tips including Threading, MEF, WPF and MVC. In this post I am quickly listing down all the tips which are published over the month August 2011. And the most important point to mention, among those 31 tips that has been posted on DailyDotnettips this month 22 is coming from me. 

  1. Working with AggregateCatalog in MEF
  2.  Working with DirectoryCatalog in MEF
  3. Working with AssemblyCatalog in MEF
  4. Working with TypeCatalog in MEF
  5. How to use DebuggerTypeProxy while debugging your sensitive Type
  6. ASP.NET Calendar Control as Outlook Calendar
  7. Initialize assemblies using PreApplicationStartMethod for ASP.NET 4.0 Application
  8. Async Lambda Expression
  9. Playing with ASP.NET List Controls using jQuery
  10. How to allow user to input html in ASP.NET MVC?
  11. Using Mutex to avoid deadlocks
  12. Writing inline Code in WPF
  13. What is SynchronizationContext all about
  14. ThreadLocal storage in .NET
  15. Barrier in .NET 4.0
  16. Use of Interlocked in Race Condition
  17. Call ASP.NET Page Methods using your own AJAX
  18. Use of SpinLock for ThreadLocking
  19. Using ReaderWriterLock over Monitor for Thread Locking
  20. What is the use of IsBackground property of Thread?
  21. Enable Address Level Debugging in Visual Studio
  22. Get List of all Control Types in WPF
  23. How to apply simple faded transparent effects on WPF controls ?
  24.  Use Visual Studio Server Explorer to Add New or Existing SQL Server CE Database
  25. Co-Ordinated Thread Shutdown with and without using CancellationTokenSource
  26. Generate thousand of request
  27. Writing a Stretchable ContentControl in WPF
  28. How to Retrieve WPF Visual Tree Programmatically ?
  29. What is Visual Tree and Logical Tree in WPF?
  30.  Dealing with HWND in WPF
  31. Hosting a WPF control inside a Windows Form
To get regular updates visit http://dailydotnettips.com and follow @dailydotnettips at Twitter.

I hope you would like the posts. Stay tune for more. 

Sunday, August 28, 2011

Monday Mornings : Extensibility in .NET 4.0

It is my great pleasure to speak at Microsoft Moday's last Monday on 22nd August 2011. I have introduced a way to develop a plugin based application with and without MEF. I have also touched some of the interfaces which Visual Studio uses for Extensibility. It has been a very good session and I have learned a lot from it.

If you are a part of the session, please get the Power Point Presentation and the updated source code.


Sunday, July 31, 2011

Internals of Dependency Property in WPF

WPF introduces new property system to us. Every WPF objects that is inherited from DependencyObject inherently supports Dependency property containers within it. That means you can define your own dependency property in your code which can take part in some of the interesting features of WPF like Binding, Styles, Triggers, Animation, Property Inheritence etc. Today I will concentrate on how Dependency Property system is actually built and what are the benefits we get instead of using CLR property system.

Note : If you are really new in WPF and don't know about Dependency Property, it would be nice to read my post on Dependency Property or you can also try WPF Tutorial series to start on.



So lets start on using the most basic code of creating your own Dependency Property.

Saturday, July 23, 2011

Writing a Reusable WPF Control with Design Support

Code reusablity is one of the major concern to many of us. When dealing with large projects, modularizing your project is one of the primary thing that you should look for. I have talked about many of the approaches that you can use to deal with modularizing your code, eg, Prism. In this post our intent is not to talk hard on some pattern, rather I will discuss how your WPF application supports code reusability. There are a number of approaches that WPF supports to deal with reusable component. We can use Resources to define a Resource or even use CodeBehind to write our reusable component or even load the XAML from a file using XAML Loader. Each of the approaches has its own pros and cons. Today I will show you another cool technique to write a reusable XAML for your project which will allow you to easily use Visual Studio design surface to design the component.

Note : It is a very basic article, if you want to know about details on WPF, please read my tutorial on it.

Steps to Create your Reusable Component


Lets create a series of steps to create a reusable component for your application to make it easier for you to write one yourself.


Sunday, July 17, 2011

ValueType and ReferenceType : Under the Hood Part 2

Well, if you have read my previous post, you should be already clear how memory of ValueTypes and ReferenceTypes are allocated and De-allocated internally in terms of IL. Here in this post, I am going to cover some more concepts behind ValueTypes and ReferenceTypes and what exactly comprises of them.

In my previous post on the series, I have told you that any type that inherits from System.ValueTypes is stored in Stack while any type that is not inherited from System.ValueType is stored in Heap. Well, the statement is not correct totally.

Sunday, July 3, 2011

Rethinking my Session on TechEd on Road

Hi Folks,

Its been a great time together on TechEd on Road event here in Kolkata. I can recollect the fun we had out of the sessions with Pinal Dave, nice to find you here Pinal and with Bijoy Singhal on Windows Phone 7. I would also like to thank Dhanajay Kumar for coming all the way from Pune only for this session, and also for giving a wonderful session to us. 

Lets now talk about my session on ".NET Fundamentals that every developers should Know". In this post I will share all the resources and source codes to make your easy way round to understand everything that you didnt understand in the session,  of course if any... :) 

Saturday, June 25, 2011

Some facts about Null in .NET

As I am tweeting around the facts on Nulls for last couple of days, I thought of writing a blog on that as many of you have already requested me on this regard. This post is basically dealing with Nulls and will go through only with basic C# stuffs, so for geeks, it is not recommended and you might end up knowing a little or almost nothing. So if you just here for time pass, then I refer to read on.

Considering the fact Nulls appear on any objects, we have mainly two categories of programmable storage in .NET.

  1. Nullables (generally mutable with exceptions like strings)
  2. Value Types / struct (generally immutable)
Nullables are types that either user defined or in framework in which one of its value can be null. .NET treats null specially. Say for instance :

Thursday, April 28, 2011

Async support for Silverlight and WP7

Async support in C# language brings the new life to the modern application development to bring forth the same technique of writing your code and bring asynchrony easily. The main focus of async ctp is to ornament the language in such a way so that the developer could seamlessly create applications that brings asynchrony yet not dealing with its complexity. Hence using the new technique, asynchrony could easily achieved in a program without refactoring the whole program with lots of callbacks and method calls. I have already talked about it in a separate article. If you don’t know, please visit “Async CTP 5.0”.


Async CTP is released again recently and announced in MIX 11. Just after it is released, the first thing that everyone looks for is what is new in the release. As a matter of fact, I did jumped back to see them but eventually found out that there is nothing new in this build in terms of new features is concerned but the release focuses on fixes of performance adding debugging capabilities etc. I will definitely look back to them later in another post, but in this post I am going to talk about another important thing that featured with this release. As opposed to the previous release, the current release now supports Silverlight and Windows Phone 7 environments. This seems to be interesting.

What is Asynchrony?

The word asynchrony means something that is running without blocking other operations running in parallel. If you have created a background Thread to process some data, you are actually doing asynchronous job in background as your foreground operation does not get hampered. In vNext C# introduces Asynchrony using TPL. The two new keywords “async” and “await” could be used to make one sequential method asynchronous. Hence the new way of developing asynchronous program replaces the traditional approach where we needed to refactor the code totally to gain asynchrony in our application. Basically, this is done using the StateMachine to store the entire method into a form of states, and each states are delegated into batch of statements. The Task.ContinueWith is used in the system to ensure that the method body gets executed sequentially. Yes, it’s a compiler trick. If you want to know more about it, please read through my entire article on “Async CTP”.

Sunday, April 17, 2011

Closures in CSharp

Closures are an interesting feature for a language. I have heard a lot of questions around how we can declare closures in C# and hence I thought to start a blog on it. Over the internet, there are lots of examples on closures available which are taking help of functional languages like F#, yes it is very important in perspective of these languages as those are easy to declare and also inherently supported yet other languages like C# or VB.NET can also take help of these feature. Lets take a look how C# can take help of closures in this post.

What is a Closure? 

Closures may be defined as a set of behaviour or instructions that are encapsulated as an object such that it could be sent to other object yet can hold the context of the caller.  In other words, a closures are special object that are encapsulated into an object but can hold the context of the caller.

In C# we define closures using delegates. In C# 3.0 we have language support to easily declare a delegate in a program. This widely increases the use of delegates in the program using lamda expressions. Lets put the closures in terms of some examples.

Monday, April 4, 2011

Internals of LINQ

If you remember my post on Annonymous Types, I have already stated that there is no concept of annonymous types in MSIL. Every generated type will be mapped to a concrete type produced by C# compiler during the runtime. In this post, I am going to cover few basics of LINQ, and how it is been maintained in IL. If you are very new to Linq, it is recommended to learn the basic usage of it first. You can read my article on Linq Basics, to know more about it.

LINQ means Language Integrated Query is one of the major step forward to .NET framework to support queries to work on objects. LINQ allows you to write custom query statements on .NET objects or more specifically any IEnumerables to filter or fetch data from it.

In this post, I am not covering the basics as I have already discussed it in a separate article. Lets start with internals.

Tuesday, March 15, 2011

Internals of Events

If you are looking already at my internal series, you must by now know what does an entry from Internal series means. Yes, In each of those articles, I have tried to at least give some basic idea about the usage and later tried to show you some of the internal process that is happening to achieve the technique. In this post, as the name suggest, I will show how the event system works in .NET (or rather C#) and how this system is actually achieved into the system.

The Basics

Event is a special object in .NET which allows you to give notification to the external world. As far as I am concerned, its a means of communication between the object to the external world, or rather a means of inversion of control to the caller. Now what exactly an event does ?


Sunday, March 13, 2011

Internals to .NET

C# is a language which most of us like the most. I like to code in C# and want to delve deep into its internals. I wrote few posts too regarding Internals of C# language. Here in this post I am going to jot down all the links on Internal Series.for you. If you havent started reading them, its time to go on with it.

Internals of .NET Objects and use of SOS

Internals to C# Language Basics

Internals of Interface and its Implemention
Internals of LINQ
Internals of Events
Internals of Annonymous Method
Internals of Exception Handling
Internals of C# iterators
Internals to Convert and Cast
Internals to C# loops
Internals to Extension Methods
Internals to Delegates
Internals to Array

Internals of ValueType and Reference Types
Value Types and Reference Type : Under the Hood
Value Types and Reference Type : Under the Hood Part 2

ADO .NET internals 
Part 1
Part 2

Miscellaneous Entries

Internals to Code Contracts in .NET 4.0
Hidden Facts of C# structures in terms of MSIL
C# 5.0 vNext - Asynchronous Pattern Made Easy

I hope you did like the series. I will update the post as soon as there is any new post on the subject. Please stay tuned with me for more internals.

Also I have recently released a book which would be worth trying for you.


You can get the book from the link below :
http://www.packtpub.com/visual-studio-11-and-dotnet-4-5-expert-development-cookbook/book

Also you can read more about it from :
http://www.abhisheksur.com/2013/04/net-book-visual-studio-2012-and-net-45.html


Thanks for appreciating my posts.

Sunday, February 27, 2011

Dependency Injection & IOC

Well, after I introduced Inversion of Control with few simple examples in my previous post, I  thought it would be nice to take this discussion further with more implementation of Dependency Injection Principles. Later I would also take a look at some of the existing frameworks available with MS Patterns and Practices which follow these well known principles. If you remember my previous post on Inversion of control with interfaces, I have clearly stated that we could invert the control to some other module to make strong decoupling on one class with the other. In this post I will first cover the basics of the design principle on Dependency Injection and later talk about DI containers.

Dependency Injection

If you know about traditional Design Patterns, you should already know few of the most used pattern called Factory. Factory pattern allows you to put your object creation into a special module called Factory. Thus your objects will be created just inside your factory classes. But does it worth to put all the object creation inside your factory classes ? That means each of those classes will hold reference of all the objects that needed to be created. Lets see the code to show up what I am talking about :


public enum ProcessorType
{
    x86,
    x64
}
public class Computer
{
    public IntelProcessor GetProcessor(double speed, ProcessorType type, string version)
    {
        return new IntelProcessor { Speed = speed, Type = type, Version = version };
    }
}

public class IntelProcessor
{
    public string Version { get; set; }
    public ProcessorType Type { get; set; }

    public double Speed { get; set; }

    public string GetProcessorInfo()
    {
        return string.Format("{0} Ghz Processor for {1}, v{2}", this.Speed, this.Type, this.Version);
    }

    public override string ToString()
    {
        return this.GetProcessorInfo();
    }
}

Author's new book

Abhishek authored one of the best selling book of .NET. It covers ASP.NET, WPF, Windows 8, Threading, Memory Management, Internals, Visual Studio, HTML5, JQuery and many more...
Grab it now !!!