Thursday, December 29, 2011

How Does the Garbage Collector Work in .NET

While you are doing application programming and when you are creating objects of classes, have you ever wondered, in the end what will happen to all these objects you have created. Well I have always wondered and today I am going to write about this nice mechanism called Garbage Collection which is responsible for proper resource management in .NET.

Every object that you create has a life cycle, from creation to destruction. When an object is destroyed, its state must be cleaned, and any managed resources used must be reclaimed. And that's where the Garbage Collector comes in. Garbage collection in the Microsoft .NET common language runtime environment, completely absolves the developer from tracking memory usage and knowing when to free memory.

Implementing a proper resource management mechanism by us for our own applications would be a difficult and time taking task. It will surely distract our concentration on the real problems that we are going to solve. Garbage Collector will take all the trouble of doing the resource management, so we will only have to focus our minds on our real problem.

So as I have mentioned before, every object that we create has a life cycle.
  1. First, block of memory will be allocated and that block of memory is big enough to hold the object.
  2. Then by calling the constructor we initialize the object. Now memory will be converted into an object.
  3. Object can be then used by our application.
  4. Object will then arranged for clean up.
  5. After the cleaning up is completed, the allocated memory for that particular object is reclaimed.
From above things, we can only control the second step and the fourth step. We call the constructor for the second step and we can implement and call the destructor for the fourth step.

So How Does the Garbage Collector Work

The garbage collector runs in its own thread and normally runs automatically, under well defined circumstances. When the garbage collector runs, other threads in an application are halted because the garbage collector may move objects in memory and must update pointers to the correct addresses for these objects.

The steps that the garbage collector would take to reclaim resources are as follows.
  1. It marks every object as dead; objects are considered dead unless proved otherwise.
  2. It starts from objects referenced on the stack, marking referenced objects as alive. It performs this recursively; if an object that is already marked as alive references another object, that object is also marked as alive. The garbage collector includes logic to prevent infinite recursion, for example, where there is a circular reference between two objects.
  3. It checks whether any of the objects that have been marked as dead have a destructor that must be run. Running the destructor is referred to as finalization. Any objects that require finalization are moved to a data structure maintained by the garbage collector called the freachable queue. The freachable queue stores pointers to objects that require finalization before their resources can be reclaimed.
  4. Objects added to the freachable queue are marked as alive because there is now a valid reference to them; the destructor must be run before their memory can be reclaimed. Objects are normally added to the freachable queue only once.
  5. Objects marked as alive are moved down the heap to form a contiguous block, defragmenting the heap. References to objects (on the stack and in other objects on the heap) moved by the garbage collector are updated.
  6. Other threads resume.
  7. On a separate thread, objects added to the freachable queue are finalized. After an object is finalized, the pointer to that object is removed from the freachable queue. Objects are not removed from memory until the next time the garbage collector runs.
So that's how the garbage collector works in .NET framework. Please feel free to give me your valuable feedback.

Happy Coding.

Regards,
Jaliya

Tuesday, December 6, 2011

Mono for Android 4.0 is Here.

Xamarin has announced the release of its Mono open-source .NET development platform for Android 4.0. This release supports all the new features introduced in Android 4.0 which is code named as "Ice Cream Sandwich". Mono for Android 4.0 comes with a VS plug-in, incremental build, incremental deployment, installer with all packages needed, Google Maps integration, and support for Java 7.

The new features that are introduced with this release are,
  1. An incremental builder which is reducing build times by 40%
  2. Incremental deployment support reducing the deployment time “from minutes to seconds”
  3. An installer that packages together all the pieces necessary for Android development on Mono: JDK, Android SDK, GTK#, MonoDevelop and Mono for Android
  4. Google Maps integration - Integrate Google Map functionality into your apps easier than ever before with newly bound APIs.
  5. Java 7 support
So why not try it out guys. If you already have Mono for Android, simply launch MonoDevelop and you will be prompted to update. If you're using Visual Studio then you can download and install the update manually from the following link.

Happy Coding.

Regards,
Jaliya

Friday, November 25, 2011

Created my first Android Application using C#

I was always amazed by the beauty of Android applications, they are very light weight and they are running very smoothly. Since I am having an Android powered HTC mobile, I always wanted to write an Android application. I have seen many nice applications in Android Market, some of course comes with a price and some are totally free.

Android applications are usually developed in Java language using the Android Software Development Kit. Since I am a .NET developer and I have not used Java for like 2 years, I wanted to create an Android application using C#. I first heard about MonoDroid couple of months back, which is a software development kit that allows developers to use C# language to create mobile applications for Android-based devices.

Recently they have changed their name from MonoDroid to Mono for Android. So this Mono for Android exposes two sets of APIs, the core .NET APIs that C# developers are familiar with as well as a C# binding to Android's native APIs exposed through the "Mono.Android.*" namespace. We can use both these API's to develop applications and we can deploy applications to our personal hardware/Android simulator or we can create a package and can upload to the Android Market.

So I have created my first "Hello World!" Android application using C# and it's just great.

My Android Application

My Android Application "Hello Android!!!"

For More information on Mono for Android, visit
     Mono for Android

You can find a step by step guide to learn how to setup your computer to build Mono for Android applications using Visual Studio 2010 from following link.
     Building Mono for Android applications using Visual Studio 2010

Please note that Visual Studio 2010 Express is not supported with Mono for Android. So enjoy writing Android applications using Mono for Android. Appreciate your feedback.

Happy Coding.

Regards,
Jaliya

Tuesday, November 1, 2011

What is IronPython

Today, it's a special day to me. Today I am writing my 50th post and it's exactly after 2 years from the first day I started blogging. It's a great feeling.

So today I would write about IronPython. If you have not heard about IronPython before, don't be surprised. I am pretty sure you must have heard Python programming language before. If you have not, it's a open source high level programming language which is used by world's largest software companies to develop world's famous systems. Here is a list of systems that is developed using Python.
    List of Python software

So what is this IronPython? Actually IronPython is the .NET version of the Python language. For a .NET developer, developer has the advantage of developing aplications using IronPython and still having the full access to the .NET Framework. Which means you can work with IronPython and other .NET languages that you already know and by that you can use the right tool for every job.

The most important thing in IronPython is, it is a dynamic language, which means that it performs many tasks during run time, rather than compile time. And of course, using a dynamic language means that your code has the advantages of static languages, such as C#.

Dynamic languages are not new to the industry. It has been there for a very long time. Dynamic languages provides many advantages. One is it has the ability to enter several statements and execute them immediately to obtain feedback. Another thing is using a dynamic language, it's easier to refactor the code and modify the code, because you don’t have to change static definitions throughout your code. You also have the possibility to call functions which you haven’t implemented yet and add an implementation later in the code when it’s needed.

In addition to the great features that Python provides, IronPython provides a few of its own. I would list some of them down here.
  • Full access to the .NET Framework.
  • Full extensibility using the .NET Framework.
  • Complete source code available.
  • Usability within Silverlight applications.
IronPython also runs on Mono, cross platform open source .NET development framework, enables IronPython to be used on Linux, Mac OS, and BSD systems.

But IronPython has few differences from the CPython (Python) implementation that everyone else uses. One major thing is IronPython is a managed application, CPython is written in C.

And that is some basic but important things that we all should know before writing applications using IronPython.

IronPython is not included in the .NET Framework. So to use it, you will have to install it.

To download and for more information, visit IronPython web site.

When you have installed IronPython in your machine, you must wonder that whether it has added some new project templates to the Visual Studio. It will not and you can find the Python Tools for Visual Studio from the following link.

So enjoy writing applications using IronPython. Appreciate your feedback.

Happy Coding.

Regards,
Jaliya

Thursday, October 20, 2011

Successfully completed a SharePoint 2010 Farm Restore

Today, I feel happy because today I did a successful and a complete SharePoint 2010 Farm Restore. And that is on a different server machine and on a different SQL Server from where the backup was taken. I have restored Site Collection backups couple of times before, but not a full farm.

When you are restoring a SharePoint farm in a separate server, there will be some major points that you might want to consider. Your server name might be different. Your domain might be different. And most importantly, when your SQL server which you are going to do the restore on is different from the SQL server where your backup was taken, you will have to do the restore process in a very careful manner.

Since I don't trust this method of doing the restore using SharePoint 2010 Central Administration, I have used SharePoint 2010 PowerShell. Using commands we can fully customize the restore options and I should tell you that it saved my day.

Happy Coding.

Regards,
Jaliya

Monday, September 26, 2011

out and ref Parameters in C#

Today I am going to write about two nice modifiers that we can use when defining parameters in a method. While parameters are very simple and straight forward to use, there are tricks which can make them a lot more powerful than it seems.

C#, as well as other languages have two types of parameters. One is passing parameters 'by value' and the other is 'by reference'. The default is 'by value'. If we pass a parameter 'by value', that means we are passing a variable to a method and actually we are sending a copy of a variable instead of a reference to it. What happens here is, all the changes we do to that variable in our method, will not affect the original variable which we passed as a parameter.

If you want to pass parameters 'by reference', that's where out and ref modifiers comes in. With the help of out and the ref keyword, we can change this behavior, so we pass along a reference to the object instead of its value.

Difference between out and ref

Actually these two modifiers pretty much acts like the same. They both ensure that the parameter is passed 'by reference' instead of 'by value', but they have one significant difference. That is when we are using out parameter, before passing the variable into the method we don't have to initialize the variable. But in the method before leaving the method, we should assign a value for that. If not we will get a compile error saying "The out parameter 'x' must be assigned to before control leaves the current method".

When we are using ref parameter, before we pass the variable into the method, we must initialize it. if not we will get a compile error saying "Use of unassigned local variable".

I am going to write down a simple code, so you will be able to get a good understanding about how to use these two modifiers and their difference.

using out modifier

static void Main(string[] args)
{
     int i; //no need to assign a value to i
     Method(out i);
     Console.WriteLine(i); //i is 10
     Console.ReadLine();
}

static void Method(out int x)
{
     x = 10; //must assign a value
}

using ref modifier

static void Main(string[] args)
{
     int i = 5; //must initialize the variable
     Method(ref i);
     Console.WriteLine(i); //i is 10
     Console.ReadLine();
}

static void Method(ref int x)
{
     x = 10; //can change the value, but not a must
}

As you can see, when I am using out modifier I did not set a value to the variable before passing it. But in the method I have set a value and it is a must. When using ref modifier, I have initialized the variable and then passed it. Without initializing the variable I can't use ref and in the method, it's up to you to change the value or not. Hope you all got a good understanding in out and ref.

Feel free to give me your feedback.

Happy Coding.

Regards,
Jaliya

Friday, September 23, 2011

Named and Optional Arguments for Methods in C# 4.0

With C# 4.0, Microsoft has introduced a nice concept of this Named and Optional arguments for methods. So today I am going to write about how great this concept is.

I will start by writing down a very simple method. This method GetSum() will return the sum of two supplied values.

static void Main(string[] args)
{
     int sum = GetSum(5, 10); //5 and 10 are arguments
     Console.WriteLine(sum);
     Console.ReadLine();
}

static int GetSum(int i, int j) //i and j are parameters
{
     return i + j;
}

Please note the difference between arguments and parameters. Arguments are actual value you pass to the method when calling the method. Parameters are variables in the method declaration.

Named arguments enable you to specify an argument for a particular parameter by associating the argument with the parameter's name rather than with the parameter's position in the parameter list. Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates.

The general thing is when we are passing values to a method, they should be in the order same as in the parameter list. If I take above example, the values 5 and 10 are for i and j respectively. But when you use named and optional arguments, the arguments are evaluated in the order in which they appear in the argument list, not in the parameter list.

Named Arguments

Let's say in your method you are having 3 parameters. First one is int, second one is string and the third is again int. So when I am calling the method I will have to pass an integer first,string for next and again integer for the third. For that I should keep the order of parameter list in mind and of course it is a trouble. So with Named arguments, it will free you from the need of remembering or looking up the order of parameters in the parameter lists of called methods. The parameter for each argument can be specified by parameter name. I will modify the above example with Named arguments.

static void Main(string[] args)
{
     int sum = 0;

     //without using named arguments
     sum = GetSum(5, 10);

     //with named arguments
     //named arguments can be supplied for the parameters in either order
     sum = GetSum(i: 5, j: 10);
     sum = GetSum(j: 5, i: 10);

     //named arguments can follow positional arguments
     sum = GetSum(5, j: 10);

     //named argument 'i' specifies a parameter for which a positional argument has already been given
     //so the following statement causes a compiler error
     num = GetSum(5, i: 10);

     //positional arguments cannot follow named arguments
     //so the following statement causes a compiler error
     sum = GetSum(i: 5, 10);
}

static int GetSum(int i, int j)
{
     return i + j;
}


Optional Arguments

The definition of a method, constructor, indexer, or delegate can specify that its parameters are required or that they are optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters.

Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used.

When defining optional parameters you should keep this in your mind. Optional parameters are defined at the end of the parameter list, after any required parameters.

I will modify the first example for you to get a good understanding about this concept.

static void Main(string[] args)
{
     int sum = 0;

     sum = GetSum(5); //sum is 30
     sum = GetSum(5,20,30); //sum is 55
     sum = GetSum(5, 20); //required_i=5, optional_j=20, optional_k=15 and sum is 40

     //the following call causes a compiler error
     //because an argument is provided for the third parameter but not for the second
     sum = GetSum(3, ,4);

     //however, if you know the name of the third parameter, you can use a named argument to give a value for third
     sum = GetSum(5, optional_k: 20); //required_i=5, optional_j=10, optional_k=20 and sum is 35

     //the following call causes a compiler error
     //because the required marametr is missing
     sum = GetSum(optional_j: 20, optional_k: 30);
}

static int GetSum(int required_i, int optional_j = 10, int optional_k = 15)
{
     return required_i + optional_j + optional_k;
}

when writing your code in Visual Studio, you will notice that IntelliSense uses brackets to indicate optional parameters, as shown in the following image.

IntelliSense


Named and optional arguments, along with support for dynamic objects and other enhancements, greatly improve interoperability with COM APIs, such as Office Automation APIs. For an example, the AutoFormat method in the Microsoft Office Excel Range interface has seven parameters, all of which are optional. So it's up to you to provide optional values, if you want to change the default values.

Feel free to give me you feedback.

Happy Coding.

Regards,
Jaliya

Friday, September 9, 2011

Windows Presentation Foundation(WPF) vs Silverlight

Yesterday I did a session about Microsoft Windows Presentation Foundation in Sri Lanka .NET Forum User Group meeting and it was a great experience. Audience was really friendly and there was some nice questions from the audience. One of the interesting questions is that comparison of WPF vs Silverlight. So today I am going to write a post about Windows Presentation Foundation and Silverlight. Please note that I am getting information for my post from the msdn.

Windows Presentation Foundation(WPF)

Windows Presentation Foundation (WPF) is a next-generation presentation system for building Windows client applications with visually stunning user experiences. With WPF, you can create a wide range of both standalone and browser-hosted applications. The core of WPF is a resolution-independent and vector-based rendering engine that is built to take advantage of modern graphics hardware. WPF extends the core with a comprehensive set of application-development features that include Extensible Application Markup Language (XAML), controls, data binding, layout, 2-D and 3-D graphics, animation, styles, templates, documents, media, text, and typography. WPF is included in the Microsoft .NET Framework, so you can build applications that incorporate other elements of the .NET Framework class library.

Here is a image of sample desktop application created using WPF.

Sample desktop application created using WPF
For more information on Windows Presentation Foundation, please visit the following link.
     Windows Presentation Foundation

Silverlight

Microsoft Silverlight is a cross-browser, cross-platform implementation of the .NET Framework for building and delivering the next generation of media experiences and rich interactive applications (RIA) for the Web. You can also create Silverlight applications that run outside of the browser on your desktop. Finally, you use the Silverlight framework to create applications for Windows Phone. Silverlight uses the Extensible Application Markup Language (XAML) to ease UI development (e.g. controls, animations, graphics, layout, etc.) while using managed code or dynamic languages for application logic.

What Features are in Silverlight?

Silverlight combines multiple technologies into a single development platform that enables you to select the right tools and the right programming language for your needs. Silverlight offers the following features,
  • WPF and XAML. Silverlight includes a subset of the Windows Presentation Foundation (WPF) technology, which greatly extends the elements in the browser for creating UI. Silverlight lets you create immersive graphics, animation, media, and other rich client features, extending browser-based UI beyond what is available with HTML alone. XAML provides a declarative markup syntax for creating elements.
  • Extensions to JavaScript. Silverlight provides extensions to the universal browser scripting language that provide control over the browser UI, including the ability to work with WPF elements. 
  • Cross-browser, cross-platform support. Silverlight runs the same on all popular browsers (and on popular platforms). You can design and develop your application without having to worry about which browser or platform your users have.
  • Access to the .NET Framework programming model. You can create Silverlight applications using dynamic languages such as IronPython as well as languages such as C# and Visual Basic.
  • Tools Support. You can use development tools, such as Visual Studio and Expression Blend, to quickly create Silverlight applications.

For more information on Silverlight, please visit the following link.
     Silverlight

WPF compatibility with Silverlight 4

As I told you before Silverlight offers a subset of the functionality provided by Windows Presentation Foundation (WPF) and enables you to build rich Internet applications that are easy to deploy and quick to install. An additional goal for Silverlight is to enable you to transfer your .NET Framework development experience to Silverlight, and vice versa. You should also be able to port Silverlight applications to the desktop, mainly reusing the XAML.

Since there is a lot of things about this in the msdn site, I will just provide the link. So you all can go through it.
     WPF compatibility with Silverlight 4

Hope you all got a good understanding about Windows Presentation Foundation and Silverlight. Please feel free to give me your feedback.

Happy Coding.

Regards,
Jaliya

Tuesday, September 6, 2011

What is Web 1.0, Web 2.0 and Web 3.0

Today after sometime of silence, I am going to write about these three categories in Web applications. Actually I happened to know about these categories today and thought it's better if write a post about it. So I will start with Web 1.0.

Web 1.0 - Websites, E-mail Newsletters

It's hard to define Web 1.0 for several reasons. So I will put it this way. What Web 1.0 really is, it's everything in between from the day World Wide Web has introduced and the day Web 2.0 has introduced. So keeping that in mind, Web 1.0 category web applications contains following features.
  • Web 1.0 sites are Static.
  • Web 1.0 sites aren't Interactive.
  • Web 1.0 applications are Proprietary.
  • Web 1.0 sites are One-way.
  • Web 1.0 sites are Passive.
  • Web 1.0 sites are Closed.

Web 1.0 category sites basically contains information that user's might find useful, but there's no reason for a visitor to return to the site later. An example might be a personal Web page that gives information about the site's owner, but never changes. And visitors can only visit these sites, they can't contribute to these sites. Because of this, these kind of sites are Static and they are not Interactive to the visitor which will make the site  a Passive, One-way and a Closed site.

Web 2.0 - Blogs, Wikis, and Social Networking sites

At its core, Web 2.0 is the beginning of two-way communication in Web Applications. Web 2.0 sites invite participation and that might be voting, rating, commenting and submitting new posts. So Web 2.0 sites are collaborative. For example in Social networking sites like Twitter, Facebook you can have friends, fans, followers, connections etc. So Web 2.0 category sites contains following features.
  • Web 2.0 sites are Two-way.
  • Web 2.0 sites are Active.
  • Web 2.0 sites are Dynamic.
  • Web 2.0 sites are Collaborative.

Web 3.0 - Mobile Websites, Text Campaigns and Smartphone Applications

Web 3.0 is all of the above with web experience that is no longer limited to desktop and laptop computers. It’s the Internet on the go fueled by mobile phones and tablets. Websites must be designed to be easily read on mobile devices. Group text campaigns function like e-mail newsletters in Web 1.0 which will drive traffic to your mobile website. Smartphone Applications enable content to be published and shared easily while on the go.

So I hope you all got some understanding about these categories. With such a rapid growth in technology and with the combination of Web 1.0, Web 2.0 and Web 3.0, you will soon face a day that you feel the world is in your hands.

Happy Coding.

Regards,
Jaliya

Monday, August 8, 2011

What is Microsoft® Visual Studio® LightSwitch™ 2011

Today I am going to write about the newest development tool which has introduced by Microsoft. Microsoft is known as a company for delivering great development tools. To develop data driven applications, for  a long time Microsoft has been offering two main development tools targeting two these audiences,
  1. Microsoft Visual Studio for wide range of developers from students and hobbyists, to enterprise developers and architects.
  2. Microsoft Access (included in Microsoft Office package) for basic level developers.

Microsoft® Visual Studio® LightSwitch™ 2011

As a member of the Visual Studio family, Visual Studio LightSwitch is the newest development tool. Microsoft introduced this product especially to support rapid application development (RAD) techniques in line-of-business (LOB) application development. LightSwitch is combined with the simplicity of Microsoft Access and the Flexibility of Microsoft Visual Studio. How Microsoft describes their newest development tool is "The simplest way to create business applications for the desktop or the cloud.".

Visual Studio LightSwitch in RAD tool like Visual Basic, Microsoft Access, and Delphi. It's audience is mainly not only the developers but also the business analysts, consultants, and IT experts working on business projects.

Installing Visual Studio LightSwitch

Visual Studio LightSwitch uses integrated shell mode. So that means LightSwitch can be integrated into the shell of an existing Visual Studio 2010 installation or If you do not have a previous installation of Visual Studio 2010, the set-up process will install Visual Studio shell to your machine with all of the LightSwitch features.

LightSwitch Applicability

In terms of LightSwitch applicability, development with LightSwitch is available on Visual Basic and Visual C# programming language under the following three groups or zones which describe the degree to which this new member of the Visual Studio family can be applied in a Line Of Business project,
  1. White zone - LightSwitch would be a great tool for these kinds of projects.
  2. Black zone - LightSwitch cannot be used as the main tool for projects in this zone.
  3. Grey zone - Certain parts (or phases) of your LOB project can be implemented with LightSwitch, but you definitely need other tools to complete it.
Take a look at the following image. It contains a full explanation of above three zones.

Applicability of Visual Studio LightSwitch.

What you can do with Microsoft® Visual Studio® LightSwitch™ 2011

Using LightSwitch, it's like Microsoft has made the developer's life so easy. I would list down some of the most important things that is available with Microsoft® Visual Studio® LightSwitch™ 2011.
  • Rapid Application Development.
  • Already designed UI templates.
  • Ability to connect to an existing SQL Server and retrieve and update data from the provided UI screens in the double.
  • Ability to connect to SharePoint lists and retrieve and update data.
  • Ability to deploy applications to the Windows Azure platform.
  • Microsoft Office Integration.
  • Authentication and Access Control.
  • Code is fully customizable.

Hope you all got a basic understanding about what Microsoft® Visual Studio® LightSwitch™ 2011 is and what you can do with this great tool. Appreciate your kind feedback.

Happy Coding.

Reagrds,
Jaliya

Wednesday, August 3, 2011

ASP.NET Menu control's submenu hides behind Silverlight

When developing ASP.NET web sites, have you ever faced to this problem where your ASP.NET Menu control's submenu hides behind Silverlight slide show or some Silverlight application you have integrated into your site and it's right below the Menu control.

Well I faced that problem and since I know that a lot developers might face this problem, thought to share the answer. The answer is pretty simple. I am writing down the code below.

<div id="silverlightControlHost">
     <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
          <param name="source" value="ClientBin/ImageSlideShow.xap"/>
          <param name="onError" value="onSilverlightError" />
          <param name="minRuntimeVersion" value="4.0.50826.0" />
          <param name="autoUpgrade" value="true" />
          <param name="background" value="transparent" />
          <param name="windowless" value="true" />
          <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" style="text-decoration:none">
               <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
          </a>
     </object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px:;"></iframe>
</div>

Just make sure to add the highlighted lines. Hope it helps. Appreciating your feedback.

Happy Coding.

Regards,
Jaliya

Sunday, July 17, 2011

Parallel Programming with C# and .NET Framework 4.0 - Distributed-Memory Systems

It's been a long time since my last post and I was having a tough time. And that tough time seems to be having like forever I thought I can't let them disturb my work. Then lets begin.

In my previous post I wrote about Parallel Programming and I said that I will write some posts related to Parallel Programming. In that post I wrote what Parallel Programming is and I described the simplest microprocessor architecture which is Shared-Memory Multicore.

Today I am going to continue with another topic that will be discussed in Parallel Programming which is Distributed-Memory Systems. Today also I should mention that I am referring the book "Professional Parallel Programming with C# - Master Parallel Extensions with .NET 4 - 2010" by "Gaston C. Hillar" which is a Wrox Publication. I am getting data (both information and images) for my posts about Parallel Programming from that book. I think everyone who is interested in Parallel Programming should start reading that book and a great appreciation goes out to Gaston C. Hillar.

Post 02. Distributed-Memory Systems

You can think of a Distributed-Memory System as an interconnected microprocessors with their own private memory. A distributed-memory system forces you to think about the distribution of the data, and accessing them through different ways and from different places. You can add new machines (nodes) to increase the number of microprocessors for the system and by doing that, distributed-memory systems can offer a great scalability.

Take a look at the following image.

Distributed-Memory Systems Architecture (small)

In here each microprocessor can be in a different computer, with different types of communication channels between them. The thing to note is the communication channel which interconnects the each microprocessor. One of the most popular communications protocols used to program parallel applications to run on distributed-memory systems is Message Passing Interface (MPI). And the most interesting thing with MPI and .NET is you can use MPI with C#.

Let's say if a process which is running in one of the microprocessors needs remote data, it has to communicate with the corresponding remote microprocessor through the communication channel. And you might think that it will add a additional work and a pretty good overhead, because not like in Shared-Memory Multicore, messages has to be trasfered through a communication channel. And because of that reason Distributed-Memory Systems are only used for applications that do high end calculations and for applications that has distributed processing and distributed data access.

Take a good look at the following imge. It's actually the larger image of what I explained above.

Distributed-Memory Systems Architecture (large)

It is a Distributed-Memory Computer System with three machines. Each machine has a quad-core microprocessor, and a shared-memory architecture for these cores. This way, the private memory for each microprocessor acts as a shared memory for its four cores.

And that's a brief explanation about Distributed-Memory Systems. Hope you found it interesting and feel free to give me your feedback.

Happy Coding.

Regards,
Jaliya

Monday, June 27, 2011

Parallel Programming with C# and .NET Framework 4.0 - Shared-Memory Multicore

Everyday processor manufactures introduces highly advanced processors with multicores. Since multicores offers the advantage of carring out many programs simultaneously, Parallel Programming is becoming a major topic in the Software Industry. Since I am new to Parallel Programming and I have already started learning Parallel Programming, I thought to write some posts about Parallel Programming as I go forward with learning. So someone who is passionate about learning this interesting topic might get these posts helpful. I should mention that I am referring the book "Professional Parallel Programming with C# - Master Parallel Extensions with .NET 4 - 2010" by "Gaston C. Hillar" which is a Wrox Publication.

What is Parallel Programming?

Parallel programming is a form of computation in which many calculations are carried out simultaneously and by doing so large problems can often be divided into smaller ones, which are then can be solved in parallel ("concurrently").

Post 01. Shared-Memory Multicore

Now to speed up the processing power, Microprocessor manufacturers are adding processing cores instead of increasing their clock frequency. Most machines today have at least a dual-core microprocessor. However, quad-core and octal core microprocessors, with four and eight cores, respectively, are quite popular on servers, advanced workstations, and even on high-end mobile computers.

You can think of a multicore microprocessor as many interconnected microprocessors in a single package. All the cores have access to the main memory. Thus, this architecture is known as shared-memory multicore. Sharing memory in this way can easily lead to a performance bottleneck.

shared-memory multicore architecture

Multicore microprocessors has nicely designed architecture that offers more parallel execution, more overall throughput and most importantly it reduces the potential of having bottlenecks. Not only that multicore microprocessors uses less power and there by generates less heat. If you haven’t heard about this already Microsoft has offered a new feature called Core Parking in their latest Operating Systems which are Windows 7 and Windows Server 2008 R2. What Core Parking does is when many cores aren’t in use, operating system put the remaining cores to sleep. When these cores are necessary, the operating system wake the sleeping cores and allocate them to the additional work.

Modern microprocessors work with dynamic frequencies for each of their cores. Because the cores don’t work with a fixed frequency, it is difficult to predict the performance for a program. When the workload is becoming large, operating system changes the frequencies of its microprocessor's cores. The process of increasing the frequency for a core is known as overclocking.

But one main point is, the microprocessor cannot keep all the cores overclocked a lot of time, because it consumes more power and because of that its temperature increases faster. Then there have to be a proper cooling system to reduce the heat.

So that's the end of my first post in Parallel programming. Hoping to write another post with the next topic in Parallel programming.

Appreciate your feedback.

Happy Coding.

Regards,
Jaliya

Thursday, June 23, 2011

Word Automation Using C# and Visual Studio 2010

I have been engaged with Word Automation using C# for some time and I thought to share the basic steps of doing it. Word Automation is simply generating Word Documents programmatically. Lets take a simple scenario. Let's say that you have a common document which you want to address to different personals. And you are storing Person's details in an database. Since I want this example to be simple, I will assume that there will not be two Persons which have the same name which inheritingly means I can say the Person's name is unique.

So in my database I will have a Table called 'RECEIVER_DETAILS' which has following Fields.
  1. RECEIVER_TITLE
  2. RECEIVER_NAME
  3. ADDRESS_LINE1
  4. ADDRESS_LINE2
  5. ADDRESS_LINE3
  6. ADDRESS_LINE4
I have created a simple Windows Forms Application with a simple Windows Form like this.


Now what I want is when I typed the Name and press enter other fields should be automatically filled. Since this post is mainly about Word Automation I will not describe how to do that, and I think for you all it's a simple piece of work. Now what I want is when I clicked Generate button I want all address details to be written back in a Word Document. And that is a simle Word Automation. Since it's always better to use Step by Step approach, I will start from Step 01.

Step 01.

Open a Microsoft Word Document. I am using Microsoft Office 2010.


Now go to Insert tab, under that go to Quick Parts and under that click Field.


Then the following screen will appear.


From Categories drop down list select Mail Merge.


And from Mail Merge select MergeField, under Field Name type "To Title" and select "(none)" as Format.


Click OK and you will get something like this.


Likewise I have created some fields to store Person's address details.


Now you should save this document as a Word Template.


Now you have successfully created a Word Template and this template will be used to create new documents with Person's address details.

Step 02.

Now it's the programming part. I assume you all can write the part of code to fill text boxes, when you have typed the Name and hit Enter. Now open the solution which you have created the Windows Form in and add the following references to the Project.
  • Microsoft.Office.Tools.Word
  • Microsoft.Office.Interop.Word
In the Form code, add following lines to the using section.

using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office.Tools.Word;
using Microsoft.Office.Interop.Word;

Declare global type objects before Form Constructor.

Object oMissing = System.Reflection.Missing.Value;

// if you want your document to be saved as pdf
Object format = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF;

Word.Application oWord = new Word.Application();
Word.Document oWordDoc = new Word.Document();

In btnGenerate_Click event write the following.

// path of the Word Template document
Object oTemplatePath = @"C:\Users\Jaliya\Desktop\Temp\Word Automation.dotx";
oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
int iFields = 0;

foreach (Word.Field myMergeField in oWordDoc.Fields)
{
     iFields++;
     Word.Range rngFieldCode = myMergeField.Code;
     String fieldText = rngFieldCode.Text;

     if (fieldText.StartsWith(" MERGEFIELD"))
     {
          Int32 endMerge = fieldText.IndexOf("\\");
          Int32 fieldNameLength = fieldText.Length - endMerge;
          String fieldName = fieldText.Substring(11, endMerge - 11);
          fieldName = fieldName.Trim();
          if (fieldName == "\"To Title\"")
          {
                myMergeField.Select();
                // check whether the control text is empty
                if (cboTitle.Text == "")
                {
                      oWord.Selection.TypeText(" ");
                }
                else
                {
                      oWord.Selection.TypeText(cboTitle.Text);
                }
          }
          if (fieldName == "\"To Name\"")
          {
                myMergeField.Select();
                // check whether the control text is empty
                if (txtName.Text == "")
                {
                      oWord.Selection.TypeText(" ");
                }
                else
                {
                      oWord.Selection.TypeText(txtName.Text);
                }
         }
         if (fieldName == "\"To Address Line 1\"")
         {
                myMergeField.Select();
                // check whether the control text is empty
                if (txtAddressLine1.Text == "")
                {
                      oWord.Selection.TypeText(" ");
                }
                else
                {
                      oWord.Selection.TypeText(txtAddressLine1.Text);
                }
         }
         if (fieldName == "\"To Address Line 2\"")
         {
                myMergeField.Select();
                // check whether the control text is empty
                if (txtAddressLine2.Text == "")
                {
                     oWord.Selection.TypeText(" ");
                }
                else
                {
                     oWord.Selection.TypeText(txtAddressLine2.Text);
                }
          }
          if (fieldName == "\"To Address Line 3\"")
          {
                myMergeField.Select();
                // check whether the control text is empty
                if (txtAddressLine3.Text == "")
                {
                     oWord.Selection.TypeText(" ");
                }
                else
                {
                     oWord.Selection.TypeText(txtAddressLine3.Text);
                }
          }
          if (fieldName == "\"To Address Line 4\"")
          {
                myMergeField.Select();
                // check whether the control text is empty
                if (txtAddressLine4.Text == "")
                {
                     oWord.Selection.TypeText(" ");
                }
                else
                {
                     oWord.Selection.TypeText(txtAddressLine4.Text);
                }
          }
     }
}

string s = @"C:\Users\Jaliya\Desktop\Temp";

// if you want your document to be saved as pdf
object savePath = s + "\\Temp Word.pdf";

oWordDoc.SaveAs(ref savePath, ref format, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);


// if you want your document to be saved as docx
object savePath = s + "\\Temp Word.docx";

oWordDoc.SaveAs(ref savePath, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

In the FormClosing event add the following code. If you are not using this part in the Form Closing event, after generating the document if you check Processes under Task Manager, you will see a Process called"WINWORD.EXE". To close that Process I am writing this tiny piece of code.

object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
oWordDoc.Close(ref doNotSaveChanges, ref oMissing, ref oMissing);
oWord.Quit(ref doNotSaveChanges, ref oMissing, ref oMissing);


After clicking "Generate" button, here is the screen shot of what I got. I created a ".pdf" document.




And that's the basics of Word Automation Using C# and Visual Studio 2010. Feel free to ask any question and to give me your feedback.

Happy Coding.

Regards,
Jaliya

Sunday, June 19, 2011

Fatal Error : Failed object initialization when Installing AdventureWorks2008R2 Sample Databases

I recently installed AdventureWorks 2008R2 SR1 as a sample database in my SQL Server 2008 R2 to test SharePoint 2010 Enterprise Search with custom databases.While installing the AdventureWorks 2008R2 SR1 I faced some issues and I thought to share those issues and ways to solve those issues with you all.

First you can download AdventureWorks 2008R2 SR1 for free from the following link.
    Download  AdventureWorks 2008R2 SR1

After you have finished downloading, there will be a single self extracting zip file which contains all of the AdventureWorks sample databases for SQL Server 2008R2. When this zip file is run, all content is unzipped to a temporary directory and an installer application is automatically started. This application copies the database scripts and data files to the directory specified, and optionally installs sample databases. If some databases cannot be installed, a brief explanation is displayed and a link is provided for more information about how to resolve the installation issues.

This is what you will get when you ran the self extracting zip file.



Then I ticked that I accept the licence terms and clicked Next hoping that installation will go smoothly. Then the following Error appeared.


It says,

A fatal error occurred during installation. Details:

Failed object initialization (ISupportInitialize.EndInit).An exception occured in SMO while trying to manage a service. Error at object 'DatabaseSelection' in markup file 'DatabaseInstaller;component/databaseselection.xaml' Line 78 Position 3.


First I was little bit surprised. Then I started to troubleshoot the error. First what I did was check the Installation Guide for installing AdventureWorks 2008R2 SR1.

In that there were three main steps to follow. They were,
  1. Installing Full-Text Search.
  2. Enabling the SQL Full-text Filter Daemon Launcher Service.
  3. Enabling FILESTREAM,
I was pretty sure, I have enabled all features with Full-Text Search when I was installing SQL Server 2008 R2. But I wasn't sure about the other two. So after reading the Installation guide I went for Enabling the SQL Full-text Filter Daemon Launcher Service. And for that I needed to go to SQL Server Configuration Manager. I followed StartAll Programs, then Microsoft SQL Server 2008, then Configuration Tools, and then clicked on SQL Server Configuration Manager. And when I clicked on it I was astonished. I got another error.


It says,

Cannot connect to WMI provider. You do not have permission or the server is unreachable. Note that you can only manage SQL Server 2005 and later servers with SQL Server Configuration Manager. Invalid class [0x80041010]

Again I am pretty sure that I do have the permission and I am running on SQL Server 2008 R2. Then I Googled for this error and I found out the reason. Microsoft has provided you the full explanation of this error and answer in this link. After reading Microsoft's solution, in an elevated Command Prompt, I typed the following.

mofcomp.exe "C:\Program Files (x86)\Microsoft SQL Server\100\Shared\sqlmgmproviderxpsp2up.mof"

Then I navigated to SQL Server Configuration Manager and clicked on it. Now there was no error and successfully managed to open Configuration Manager. Now according to AdventureWorks 2008R2 SR1 Installation Guide, enabled the SQL Full-text Filter Daemon Launcher Service and fixed it's Start Mode to Automatic.

Then enabled the FILESTREAM by opening the SQL Server Management Studio (SSMS), and in the query window, running the below code,

EXEC sp_configure filestream_access_level, 1
RECONFIGURE

Now everything was good to go. Again I ran the self extracting zip file of AdventureWorks 2008R2 SR1. Finished extracting files and installer application automatically started. Again ticked that I accept the licence terms and clicked Next. Now there was no fatal error and AdventureWorks 2008R2 SR1 sample databases were ready for installation.

Hope someone gets needed help from this post. Appreciate your feedback.

Happy Coding.

Regards,
Jaliya

Tuesday, June 14, 2011

Business Connectivity Services in SharePoint 2010 Explained

Business Connectivity Services in SharePoint 2010 can be defined as the big brother of Business Data Catalog in SharePoint 2007. BCS is actually the upgraded version of Business Data Catalog in SharePoint 2007. The weaknesses of BDC in SharePoint 2007 are, BDC was mainly used to access the external data. Updating the extenal data was extremely difficult with BDC and what most people say is it is near to impossible.

But with BCS in SharePoint 2010, what Microsoft has does is it let you connect to any external data source which can be either external SQL Server, Windows Communication Foundation (WCF) Service or basically all other external data sources which supports Open Database Connectivity (ODBC) Service. What ODBC is, ODBC refers to a software API method to use with Database Management Systems. Main feature of ODBC is, it is independent of programming language and operational system and so it can be used to access different database systems. To connect to a other database, ODBC defines a connection. Connection is created to define a connection between a computer and a database stored on another system. The ODBC connection contains information needed to allow a computer user to access the information stored in a database that is not local to that computer.

The main key feature of BCS is, with SharePoint 2010 every SharePoint site can access and manipulate external data within SharePoint. When you retrieved data from external data source and the moment that you make changes to those data and update them, the changes will be reflected in the external data source.

Now I will describe the Business Connectivity Services Architecture in SharePoint 2010. Take a good look at the following image. I will explain what every component does in this architecture.


Things to Note

Please note that in SharePoint 2010, BDC refers to Business Data Connectivity and not Business Data Catalog in SharePoint 2007.

  • BDC Metadata Store
The BDC Metadata Store provides storage for a collection of external content types, each of which describes how to connect to the external store. The Metadata Store acts as part of the services layer. External content types are a fundamental building block of BCS.
  • BDC Runtime
The BDC Server Runtime understands how to reach into the back-end store and connect to data based on the external content types defined within the content type store. It’s important to note the new usage of the acronym BDC to refer to the set of services that provides connectivity that is a component of BCS.
  • Security
BCS provides integration with the Secure Store Service (SSS), as well as enabling your own security model. The Secure Store Service stores credentials in database(User Name and the Password) to authorize access to shared resources. SharePoint 2010 using the Secure Store Service to store and retrieve credentials to access external data sources.
  • Solution Packaging
Solutions built with BCS can be packaged as a Visual Studio Tools for Office (VSTO) package to be delivered to a rich client, including SharePoint Workspace, Outlook and Word. BCS also exposes APIs to extend solution packaging to target additional clients.
  • Out of Box UI
BCS carries forward the ability to display external data through a Web Part UI and provides deeper integration through the addition of external lists.
  • BDC Client Runtime
A symmetrical runtime is provided for client and server, enabling you to take solutions offline with a client-side cache and to connect and push changes back to the server in a consistent manner. Use of the BDC Client Runtime enables offline operations, interacting with the external data cache.
  • Design Tools
SharePoint Designer provides a wealth of out-of-box functionality for creating BCS solutions, including the ability to define external content types and external lists, and to define InfoPath forms to surface the data to create simple solutions. Visual Studio provides the ability for the professional developer to extend those capabilities to create advanced solutions while leveraging the existing framework. 
  • Cache
client-side cache provides the ability to sync changes to and from the client-side application with the external data source.

I hope you all got a some idea about how BCS in SharePoint 2010 works. Feel free to correct me if I am wrong with anything.

Appreciate your feedback.

Happy Coding.

Regards,
Jaliya

Monday, June 13, 2011

Everything about SPQuery Class

Every kind of Application or System no matter whether they are simple or complex, they needs their data to be stored in someplace. It can be either a Database, a XML file or simply a text file. And all those applications uses CRUD (Create,Read,Update,Delete) operations to maintain their data. So in SharePoint, one of the major way of Reading or Selecting data is using SPQuery Class in Microsoft.SharePoint Namespace.

Today I am going write about this SPQuery Class. The SPQuery Class is used to represent a query in the list view. Assuming you all know about SQL Select queries, to give you some basic idea on what SPQuery do is, It does what Select query in SQL does but syntaxes are totally different. Since I am hoping to write some examples using SPQuery, I think as we go along with this post you will definetely be able to identify the differences.

Then let's start. I will be using a custom list called Customer List. It contains following columns.
  1. Title - string
  2. Name - string
  3. Field1 - Number
  4. Field2 - Number
First of all, I will write a full simple example. Follwing code will retrieve all the items in the "Customer List" in which Name field equals to "Jaliya Udagedara".

using (SPSite oSPSite = new SPSite("http://ravanaserver/"))
{
     using (SPWeb oSPWeb = oSPSite.OpenWeb())
     {
           oSPWeb.AllowUnsafeUpdates = true;
           SPList oSPList = oSPWeb.Lists["Customer List"];

           SPQuery oSPQuery = new SPQuery();
           
           // your query writes here
           oSPQuery.Query = "<Where><Eq><FieldRef Name='Name'/><Value Type='Text'>Jaliya Udagedara</Value></Eq></Where>";
           SPListItemCollection oSPListItemCollection = oSPList.GetItems(oSPQuery);
           foreach (SPListItem item in oSPListItemCollection)
           {  
                // your code
           }
     }
}

Now I will write example for common scenarios. When modifying, modify only the part where I have put comment "// your query writes here".

  • Retrieve all Items.
    • For this you don't have to write any query. Just modify the above code as follows. This will return the all Items.
           SPQuery oSPQuery = new SPQuery();
           SPListItemCollection oSPListItemCollection = oSPList.GetItems(oSPQuery);

  • Retrieve items that a field matches a given value.
           oSPQuery.Query = "<Where><Eq><FieldRef Name='Name'/><Value Type='Text'>Jaliya Udagedara</Value></Eq></Where>";

  • AND Operator - Retrieve items that matches the following condition,
                                      (Field1 >= 500) AND (Field2 <= 1000)

           oSPQuery.Query = "<Where><And><Geq><FieldRef Name='Field1'/><Value Type='Number'>500</Value></Geq><Leq><FieldRef Name='Field2'/><Value Type='Number'>1000</Value></Leq></And></Where>";

  • OR Operator - Retrieve items that matches the following condition,
                                      (Field1 >= 500) OR (Field2 <= 1000)

           oSPQuery.Query = "<Where><Or><Geq><FieldRef Name='Field1'/><Value Type='Number'>500</Value></Geq><Leq><FieldRef Name='Field2'/><Value Type='Number'>1000</Value></Leq></Or></Where>";

  • BeginsWithANDContains
           oSPQuery.Query = "<Where><And><BeginsWith><FieldRef Name='Name'/><Value Type="Text">Jaliya</Value></BeginsWith><Contains><FieldRef Name="Name" /><Value Type="Text">Udagedara</Value></Contains></And></Where>";

  • IsNull - Retrieve all items Where Name field is empty,
           oSPQuery.Query = "<Where><IsNull><FieldRef Name='Name'></FieldRef></IsNull></Where>";

I think I wrote some examples for most common scenarios. Here is a table of Comparison Operators used in SPQuery Class.

Comparison Operators
General Meaning
Eq
=
Gt
> 
Lt
< 
Geq
>=
Leq
<=
Neq
<> 
Contains
Like
IsNull
Null
IsNotNull
NotNull
BeginsWith
Beginning with word
DateRangesOverlap
compare the dates in a recurring event with a specified DateTime value, to determine whether they overlap


Things to Note

But when writing these queries there is some thing that you all should note about. That is, if your field name contains any spaces for example like "First Name", in your FieldRef Name if you put as 'First Name', you will get a error like "No Matching Field". The reason behind this is when you are leaving spaces in field names, the actual field name changes. You can get the correct field name by opening the List in InfoPath designer and referring the name in that field. For 'First Name', you might get something like 'First_x0020_Name'.

Feel free to give me your feedback.

Happy Coding.

Regards,
Jaliya