Sai Stuff to Developers

May 17, 2012

Basic Concepts of C#

Filed under: DotNet — tosaik @ 12:23 pm
Tags: ,


Introduction:

      As C++ language, C# is an Object Oriented programming language. Generally many people spells C# as C#.Net (C Sharp dot Net), But here Microsoft developed .Net environment mainly for distributed applications( Sharing Processing between client and server) and in C#.Net Net signs that C# is used to develop only Distributed Applications but using C# we can develop any kind of Software applications including windows applications.

C# is a new language especially developed from scratch to work with .NET environment. Using C# we can write a webpage, XML based applications like web services, Components for distributed applications as well as desktop applications.

Writing First C# Program:

     Writing a program in C# language is similar as we write in traditional C++ language, if you are aware of C++ language its easy you to writing and understanding the C# Code. Anyway I will explain every line in our basic First C# program where we will cover the things using that we can write and understand a simple to complex programs. Let’s look at our first C# program.

Program 1-1:

 

Using System;

Namespace sai.CS

{

Class FirstCSProgram

{

Static void main()

{

Console.WriteLine(“This Is Our First CSharp Program.”);

Console.ReadLine();

Return;

}

}

}

Compiling and Executing the Program:

The above Program can be write on any text editor like notepad, editplus, vi editor(in Linux) etc..,  or we can use Visual Studio’s .NET IDE(Integrated Development Environment) designed by Microsoft especially to write, compile and Execute the .NET Compatible Languages, C# is one of the  .NET Compatible Languages the other compatible languages of .NET are VB.NET, J# etc..,

There are two ways of compiling the above C# Program.

1)   If you write this Program in Visual Studio’s .NET IDE, then there is no additional work do perform for Compiling and Executing the application. Just Use functional Key F5 or go to <Debug> Menu and select <Start Debugging >. The IDE internally complies and executes the application without any user interaction.

2)    In this method we manually compile and execute the above application using command Prompt. Now open you command prompt (Start->Run->cmd or command).

You can compile the program by simply using the C# compiler Tool (csc.exe) as shown below

Csc  FirstCSProgram.cs

 

As you press <Enter> Key this csc.exe tool will compile our application named FirstCSProgram.cs and creates an exe file with same file name such as FirstCSProgram.exe.

Now using type FirstCSProgram.exe in your command prompt to execute our sample first C# program.

Note: cs is the file extension for C# applications.

Important point: Before using the tools such as csc.exe in your command prompt you have to set some environmental variables, to set these environmental variables you have two choices first, you can run a batch file named vcvars32.bat which is located at <Microsoft visual studios folder>/common7/Tools Folder (here <Microsoft visual studios folder> location is where your visual studios installed). Second, you will find a <visual studios 2005 or 2008> command prompt in start Menu ->programs -> Microsoft visual studios 2005 or 2008 -> visual studios Tools-> visual studio 2005 or 2008 command prompt which automatically set up these environmental variable for you. So you can directly use the .NET tools here.

A Close Look at the Code:

Line 1:  The first line of our sample program is

Using System;

Here we are importing the namespaces using <using> keyword in the above statement system is the namespace and we are importing it in our program. I will explain what is this namespace and how to use it and its importance in our next session for now just remember that namespace is a group of similar type of items and every class should belong to a specific namespace.

Line 2: Our next line in our program defining a namespace to our class as shown below,

Namespace sai.CS

Here we can define a namespace to our class by simply writing a user defined namespace name preceding with <namespace> keyword.

Line 3: Opening flower braces ({) this indicates to the compiler that the block is opened or started, it is similar as we use in C++ programming Language. When the compiler occurs this opening braces it will crease a new space on the stack memory where it will declares the variables which is scope to that block only (in the next chapter I will explain about variables, declaring a variables and their scopes) and allocating some memory from that newly created space for that block. Like that the compiler maintains n number of variables on the memory.

Line 4: In line 4 of our program we are declaring the class and its name as shown below,

Class FirstCSProgram

In C# programming what ever the business logic you want to write should be in class block I will explain what is class and its uses in our coming chapters so don’t worry for now just remember that what ever you want to write should write under class block and every program should contain at least one class. A class contains an optionally variables and optionally methods or functions   here we can define a class by simply writing a user defined class name preceding with <class> keyword.

Line 5: Opening flower braces ({) as I explained above in line 3, but this braces opening indicates class block has opened to the compiler.

Line 6: As I said in the above line that a class contains an optionally variables and optionally methods or functions, here  now in line 6 we defined a function or method as shown below,

Static void main()

One important point should note by you that a program can contain multiple classes under one namespace but in that classes at least one class should contain this main() method because the compiler starts its job from this main() function, if you not mention this function in your program then the compiler cannot compile you program because it doesn’t know from where should it start compiling?, And raises an error. So if you can define a main() method as we defined in our program.

Note: A deep discussion on this main() method and their uses will be in coming chapters

Line 7: Opening flower braces ({) as I explained above in line 3 & 5, but this braces opening indicates main() method block has opened to the compiler.

Line 8:  This is the first statement in our main() method and note that every statement should end with semi colon(;). Here in the following statement console is the class in System namespace as  explained above and writeLine() is a static method I will explain you later what difference between static method and normal method for now just remember that static methods will call directly by its class name as in this case, In writeline() method we are sending a some text “This Is Our First CSharp Program.”  When the compiler read this line it just prints the text “This Is Our First CSharp Program.” On the command prompt at runtime.

Console.WriteLine(“This Is Our First CSharp Program.”);

Note: A console class is developed to read and print or write a text on the console i.e., on command prompt, this class contains a functions by using these methods we can read and print a

Text on the console.

In console class we have two methods to print a text on the command prompt there are WriteLine() and Write() method. Both prints the text on the screen but writeLine() method prints the text followed by a new line character (\n) with this every WriteLine() method writes text on separate new line. For example,

Console.WriteLine(“This Is First Line.”);
Console.WriteLine(“This Is Second Line.”);

The output will be


In the same example replace the WriteLine() Method with Write() method  as shown below

Console.Write (“This Is First Line.”);
Console.Write (“This Is Second Line.”);

The output will be


Line 9:  As we know by above discussion about the console class we said that we can read and print the text on the console, above we came to know how we can print a text on the console screen but how we will read a text written by user at runtime ?. The answer is as I said that console class has a functionality using that we can read and print a text, as we seen to print a text on the screen we used writeLine() and Write() method in console class to read we have another method ReadLine() the name itself resembles the functionality of this method i.e.., it reads the text which is written by user at runtime.

Console.ReadLine();

Let’s take one example program to know how ReadLine() method works and their important. Here I this example we accept two numbers from the user ar runtime and we print the sum of that two numbers. Here the Program.

using System;
namespace FirstCSprogram
{

class Program
{
static voidMain()
{
int a, b;

Console.Write(“Enter First Number : “);
a=int.Parse(Console.ReadLine());
Console.Write(“Enter First Number : “);
b = int.Parse(Console.ReadLine());
Console.WriteLine(“The Sum Of {0} and {1} Is : {2}”,a,b,(a +  b).ToString());
Console.ReadLine();
}
}
}

When you compile and run this program on console it will ask you to enter first number after entering the fist number and press enter again it prompts for second number after giving the send number it will calculates the sum of these two numbers and displays the result on the console. Here how the output screen will look like.

Note: As we have ReadLine() to read a line of text similarly we have another method Read() which reads the next character on the input stream.

Line 10: The next statement is

Return;

This statement indicates to the compiler that the end of the scope of its belonging Block. It return’s the control to its calling method which is waiting for this control on the stack memory.

Line 11, 12, and 13: These three lines indicating end of their block. As I explained that opening of the block is represented by Opening flower braces ({) similarly the closing of the block is represented by closing flower braces (}).

Happy Coding 🙂

May 15, 2012

Making Our Component to be dynamically loading the Config File

Filed under: DotNet — tosaik @ 11:00 am
Tags: , , ,

Introduction
Generally there could be a requirement such that any independent component needs to be having its own configuration settings like for example, let say I have a vc++ application which acts as a container so that it can load any Active X Control in it. Now as a new technology I want to use some plugin to be built in Visual C# Language using .NET Framework. As we already know we can build the Active X Component using .NET Framework. Now let’s say my component plugin need to interact with Database so I need to provide it a Connection string and I can’t hard code it inside my Component so I decided to have application configuration file (i.e., App.Config file), but how can I map this file to my plugin when it is running in my VC++ container?
This article explains how we can solve this issue, and how can we map this config file even when it is converted to Active X Control and running in other environment.
Background
Need to have a basic knowledge in creating Active X Control or look for my next article “How to create an Active X Control using .NET Framework”.
Explanation
I don’t want to make it complex for you, as we are on path what we want now by reading the Introduction section.
We may have other options like maintaining separate xml file and have all the complex custom access through the xml file using xpath technology. But the way we access this configuration file using System. Configuration.ConfigurationManager Class is very Flexible and comfortable.
The solution is simple we need to create a class and name ig from my side I named as “ChangeMyAppConfig” and this class need to be Implement “AppConfig” Class.

public class ChangeAppConfig : AppConfig
{
private readonly string oldConfig =
AppDomain.CurrentDomain.GetData(“APP_CONFIG_FILE”).ToString();

private bool disposedValue;

public ChangeAppConfig(string path)
{
AppDomain.CurrentDomain.SetData(“APP_CONFIG_FILE”, path);
ResetConfigMechanism();
}

public override void Dispose()
{
if (!disposedValue)
{
AppDomain.CurrentDomain.SetData(“APP_CONFIG_FILE”, oldConfig);
ResetConfigMechanism();

disposedValue = true;
}
GC.SuppressFinalize(this);
}

private static void ResetConfigMechanism()
{
typeof(ConfigurationManager)
.GetField(“s_initState”, BindingFlags.NonPublic |
BindingFlags.Static)
.SetValue(null, 0);

typeof(ConfigurationManager)
.GetField(“s_configSystem”, BindingFlags.NonPublic |
BindingFlags.Static)
.SetValue(null, null);

typeof(ConfigurationManager)
.Assembly.GetTypes()
.Where(x => x.FullName ==
“System.Configuration.ClientConfigPaths”)
.First()
.GetField(“s_current”, BindingFlags.NonPublic |
BindingFlags.Static)
.SetValue(null, null);
}
}

The main AppDomain has the property called “APP_CONFIG_FILE” where it stores the configuration file information now we need to fetch this property using AppDomain.GetData() method and set our new configuration file path using AppDomain.SetData() Method. It’s not enough to change the value of the property with this we need to reset the configuration mechanism as we are doing the same in ResetConfigMechanism() method in the above code.

That’s it Now you need to call the ChangeAppConfig() Method from your component by providing the valid configuration path.
After calling this method you can now access the Configuration file settings using System. Configuration.ConfigurationManager Class as we do normally in every application in .NET Environment.
Example:
public string strCommonFolder = ConfigurationManager.AppSettings[“FolderPath”];

Happy Coding 🙂

May 3, 2012

Converting DataTable to a List of Entity Object

Filed under: DotNet,LINQ — tosaik @ 12:30 pm
Tags: , , , , ,

Recently some one asked me how should i need to convert a DataTable to an List of Entity Object. Let me Explain in detail below…

Let say we have following Entity Class called Testimonial with two properties i.e.., Comment and Commentedby here Comment is the property where we have the actual comment by the User and Commentedby is the property to store the name of the User who commented it.

 public class Testimonial
    {
        public string Comment { get; set; }
        public string Commentedby { get; set; }
    }

Now we need to get these Testimonial data from data source it may be from Database / XML file / CSV File etc.., we use XML file for this example . Now using linq we Enumerate the collection of dataRows in the datatable and create a list of Testimonials as shown below

List<Testimonial> lstTestimonial = new List<Testimonial>();

 string strpath = System.IO.Path.Combine(AppDomain.CurrentDomain.GetData(“DataDirectory”).ToString(), “Testimonials.xml”);
            DataSet ds = new DataSet();
            ds.ReadXml(strpath);

            if (ds != null && ds.Tables.Count > 0)
            {
                lstTestimonial = (from r in ds.Tables[0].AsEnumerable()
                                  select new Testimonial
                                  {
                                      Comment = r.Field<string>(“Comment”),
                                      Commentedby = r.Field<string>(“Commentedby”)
                                  }).ToList<Testimonial>();
            }

Note this is the best way to convert because due to strong data-type using Field Method, we can rectify any type conversion issues at Compile time.

Hope this short explanation (due to insufficient time) Helps you… Please comment me in any case…

Happy Coding 🙂

 

 

Finding Full Qualified Path for ASP.NET App_Data Folder

Filed under: DotNet — tosaik @ 12:06 pm
Tags: ,

Recently i had a requirement to add and use some xml files in my application and i pleased these xml files in ASP.NET special folder App_Data.

As we know the benefits of adding this folder in our application or for shortly i described in below couple of points.

  1. App_Data is essentially a storage point for file-based data store like .mdb, .mdf, .xls, .csv, .xml etc.., .
  2. It should not be viewable by the web and is a place for the web app to store and read data from.

and now  i need to map that xml file(s) so that i can get/set some data to it, for this as commonly need to get it though their respective path like the below:

XmlDocument xdoc = new XmlDocument(“~/App_Data/abc.xml”);

and now i dont want to hardcode the path as shown above, for this i searched the entire BCL (Base Class Libraries) because App_Data is a special folder creating by ASP.NET so it is treated as a special folder. And finally i got the solution and below the code through which i can get fully qualified path for our App_Data folder from any place with in our application.

XmlDocument xdoc = new XmlDocument(System.IO.Path.Combine(AppDomain.CurrentDomain.GetData(“DataDirectory”),”abc.xml”));

 

Thats it….. Happy Coding 🙂

May 2, 2012

Finding what are the Assemblies are loaded currently in Current AppDomain

Filed under: Uncategorized — tosaik @ 7:38 am
Tags: ,

Today i am going to show you a problem solving issue, generally we use to create an separate assemblies (i.e, dll’s) and reference them to the main application in this process most common issue is we have coded a logic in our dll but its not applied/running through main application… as many people ask me how to fix this issue due to this reason i may posting this… the issue is simple and cause of issue may be of two reasons those are:

  1. Your dll may not updated in you main application.
  2. You may coded in one location and referring from other location in your main Application.

These two are most common issues, the first will be raised if you are manually copy the dll from the bin folder of you

component project to your main application bin folder. If you do like this every time you change your component you need to repeat this process, if you forgot to update the above issue will occur.. for this a better option is to while adding reference to you component select the component project instead of selecting a dll in your bin folder this will
automatically updates your component dll in your main application’s bin folder whenever a change is done this way we can fix the 1st cause of issue.

Image

Second cause is straight forward and most people suffers with this kind of issue, to fix this issue we need to know from where the respective component is picking by the CLR.. we can do this using Modules window in visual studio 2010.
To open this window go to Debug->Windows->Modules as shown below.
Note: This will be visible while running the application.

Image

Now you will see the below window with grid of Assemblies loaded

Image

In this window you can find all the information regarding your component from where it is loaded and etc.., using this we can fix another issue too as many people cannot debug their components in the main application the reason for this is your main application doesn’t have the respective components symbol file i.e.., .pdb file and in this modules window you can find is the CLR picks its symbol file or not.. if not just copy the latest one in to your main application’s bin folder and build and restart the application.

That’s it …… Have an Happy Coding  🙂

 

Create a free website or blog at WordPress.com.

%d bloggers like this: