Split string with no literal

       Couple of days ago I had a problem with split function in String class. I was having a string with me and I wanted to get the individual characters from it. Split function in string class requires a separator criteria. In my case there was none. so I used a regular expression to do the work. Here is the code for the same.

string sample = "abcdefg";
Regex regex = new Regex("");          
string[] substrings = regex.Split(sample, sample.Length, 1);
foreach (string s in substrings)
{
   if (!string.IsNullOrEmpty(s))
   {
       Console.WriteLine("The splitted character is: " + s);                    
   }
}

The output of this program is splitted string based on every character.
a, b, c, d, e, f, g The for is to just display the output. You can manipulate it as you wanted to.

Pure Join Table and Entity Framework

A table that contains only foreign keys (sometimes called a pure join table) and represents a many-to-many relationship between two tables in the database will not have a corresponding entity in the conceptual model. When the Entity Data Model tools encounter such a table, the table is represented in the conceptual model as a many-to-many association instead of an entity. 

Performing Inner Joins in LINQ


To start with I have created a database schema with 2 tables as;

  1. LeftTable

    2. RightTable


Added the sample data as;



If inner join is applied on these 2 tables the result set will return rows when there is at least one match in both the tables.

Using SQL syntax for inner join we get following results;

SELECT lefttable.lefttablefield1, lefttable.lefttablefield2, lefttable.lefttablefield3
FROM lefttable
INNER JOIN righttable
ON lefttable.lefttablefield1 = righttable.lefttablereferrence



I applied the join syntax which we are using in Dynamic Budgets in most of the cases and got the same result set;

var qry = from leftTable in instance.LeftTable
join rightTable in instance.RightTable on
new { a = leftTable.LeftTableField1 } equals
new { a = rightTable.LeftTablereferrence }
select leftTable;

Found result as;



Returning from finally



Can we return from finally block? If your answer is yes, take a look at this code.
We have a function body as ;

try
{  
   return "From try"; 
}
catch (Exception ex)
{ 
   return "From Catch"; 
}
finally
{
   return "From Finally"; 
}

If this is enclosed in a function and we are giving call to the function,
what will be the return value of this statement?
And the answer is, it will give a compilation error, as we cannot return from finally block.

Nested insert using LINQ


Consider database structure we have created in previous post. Both tables share a relationship.
Now if one wants to insert records in both the tables, 2 seperate queries are required to update each table.
LINQ provides a mechanism where tables are interdependent it manages the insertion of records. i.e. using LINQ one need to fire the insert query only once and that on parent table.

Database structure is;
Here is a code to illustrate that;

string employeename = txtEmployeeName.Text;
string deptName = txtDeptName.Text;

Employee emp = new Employee();
emp.EmployeeName = employeename;

Department dept = new Department();
dept.DeptName = deptName;
dept.Employee.Add(emp);           

instance.Department.InsertOnSubmit(dept);
instance.SubmitChanges();

This will insert records in both the tables at one insert request and it will 
handle the responsibility of updating references.

How to use SQL metal to generate entity set


Let's start with database creation. Here I have created 2 tables as
Employee
       EmployeeID *
       EmployeeName
       DeptID (FK)

Department
       DeptID *
       DepartmentName


Create a windows forms application using Visual studio ( I am using Visual Studio 2010). Let's say LINQSample.
Create a class to have entity set which we are going to generate through SQLMETAL command. I have created a class say LINQSample.cs.
Then create a sqlmetal command as;

cd "E:\MySamples\LINQSample\LINQSample"
sqlmetal /conn:"Integrated Security=SSPI;Persist Security Info=False;INITIAL CATALOG=MySampleDB;DATA SOURCE=(local)" 
/code:E:\MySamples\LINQSample\LINQSample\LINQSample.cs /sprocs /views /namespace:LINQSample

Here I have created project in above mentioned location with database name as MySampleDB. You can use any other names here.

Go to visual studio command prompt and run the above command. This will generate a class with database name. It consist of the entity set provided in database. It is a C# representation of the database where tables are mapped as individual classes which we can use in our code anywhere and perform database operations using c# code.

Populate combobox from Datatable

Sometimes a need comes to to populate a combobox in such a way that values displayed to user are different than the actual selection options. In this case a mapping is created via code like key-value pair.
Recently I was doing the same thing, when I tried to do the same using DataTable.

Here is a code sample which shows that how to make use of DataTable to populate combobox.

            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("Name", typeof(string));

            dt.Rows.Add(1, "Batman");
            dt.Rows.Add(2, "Spiderman");
            dt.Rows.Add(2, "Iron man");
            dt.Rows.Add(2, "Megamind");
            dt.Rows.Add(2, "Bug");

            comboBox1.DataSource = dt;
            comboBox1.DisplayMember = "Name";
            comboBox1.ValueMember = "ID";

When you do so, combobox will show you the values specified in column "Name". But in the actual the ValueMember specified over here is column "ID".

If you check the SelectedValue property of the combobox, you will find the value from column "ID".
This technique has got many applications like showing user-friendly value to the user and use some other value for computations.

Are you planning for .Net certification exam ?


There are 45 questions to be attempted in atleast 2 hours. You must plan properly before appearing for the exam.
There is a 2nd edition of certification book is available which focuses on Visual Studio 2008. Earlier was focused on
Visual Studio 2005. This new edition also comes up with updates and corrections to the prior version.
This exam mainly focus on fundamentals of .Net framework so it is not at all required to know .net frameworks other than 2.0.
If you are working on 2.0 version it is perfectly fine.
The passing score is 700 out of 1000 or 70%.

To know more details kindly visit this link.

Perform LINQ join on nullable and non-nullable types


When working with Nullable types, join statement in LINQ need to be handled carefully. When you perform a join over nullable and non-nullable types,
compile time exception is thrown saying that "Type inference failed in the call to join". For example consider following classes.

public class Employee
{
   public int EmployeeId
   {
      get;
      set;
   }
        
   public string EmployeeName
   {
      get;
      set;
   }
}


public class Employee
{
   public int EmployeeId
   {
      get;
      set;
   }
        
   public string EmployeeName
   {
      get;
      set;
   }
}

To fetch data from these let's write code as;

class Test
   {
       static void Main()
       {
           var employees = new List<Employee>
           {
               new Employee
               {
                   EmployeeId = 1,
                   EmployeeName = "E1",
               },
               new Employee
               {
                   EmployeeId = 2,
                   EmployeeName = "E2",
               },
               new Employee
               {
                   EmployeeId = 3,
                   EmployeeName = "E3",
               },
           };

           var departments = new List<Department>
           {
               new Department
               {
                   EmployeeId = 2,
                   EmployeeName = "E2",
               },
               new Department
               {
                   EmployeeId = null,
                   EmployeeName = "D1",
               },
               new Department
               {
                   EmployeeId = 3,
                   EmployeeName = "E3",
               },
           };

           var r =
               from dept in departments
               where dept.EmployeeId != null
               join emp in employees
               on new { SourceEmployeeID = dept.EmployeeId.Value, SourceEmployeeName = dept.EmployeeName }
               equals new { SourceEmployeeID = emp.EmployeeId, SourceEmployeeName = emp.EmployeeName }
               select new
               {
                   emp,
                   dept,
               };

           foreach (var item in r)
           {
               Console.WriteLine("{0}", item.emp.EmployeeId);
           }
       }
   }
}

The query highlighted in above code will match the LHS with EmployeeID which is nullable with RHS EmployeeID which is not nullable.

Setup your own source control system

How to setup your own SVN system on local machine?

  • Download and install tortoise SVN
  • Create a folder which will be used as a server folder say "F:/ServerData".
  • Right-click to this folder and select "create repository here"
  • This will create a server folder and will provide you the repository path e.g. file:///F:/ServerData
  • Create another folder which will be served as a client folder say "F:/SourceData"
  • Right-click to this newly created folder and select SVN-checkout option
  • Provide repository path obtained in previous step. This will create a repository folder structure with 3 sub-folders as branches, tags and trunk.
  • Now copy the source folder under trunk folder.
  • Right-click trunk , select TortoiseSVN -> Add. This will add your source code under source control.

All set and you are ready to use your own source control system to track your own progress.

How to guarantee memory cleanup using Dispose()


  
It's been said that Dispose() function cleans up the memory utilized by objects. Now consider a scenario where you have created an instance. 


.Net CLR may eventually call its Finalize() method, but Dispose() is never called automatically. Calling Dispose() method is the responsibility of consumer of your instance.

Now let's say you have called Dispose method explicitly. In the flow of execution if any exception is thrown before reaching to the call to Dispose() method, the memory leak can arise.

To resolve this issue C# provides a using keyword. Advantages of making use of using keyword it calls the Dispose() method in finally block. You can verify the code in MSIL.


try
{
}
finally
{
    IL_0010: 1dloc.0
    IL_0011: brfalse.s IL_0019
    IL_0013: ldloc.0
    IL_0014: callvirt instance void [mscorlib]system.IDisposable::dispose()
    IL_0019:endfinally
}

//Test.cs
using System;

namespace DisposePattern
{
    class Test
    {
        [STAThread]
        static void Main(string[] args)
        {
            using(Derived object1 = new Derived(1))
            {
                Derived object2 = new Derived(2);
            }
        }
    }
}

You can declare more than one reference in the using declaration: using(Derived obj1 = new Derived(1), obj2 = new Derived(2)) The Dispose() method, in this case, will be called on each referenced object at the appropriate time. You can also achieve this without making use of using keyword. What you have to do is to call Dispose() in finally block. The using keyword in C# improves your chances of cleaning up your resources properly.

How to create a comma separated string from List

Here is a sample code which shows how to create a comma separated string from List<string>. I know this is not a big deal to do this but in some circumstances it can be used to resolved complex problems.


    List<string> lstStr = new List<string>();
    lstStr.Add("item1");
    lstStr.Add("item2");
    lstStr.Add("item3");
    lstStr.Add("item4");
    lstStr.Add("item5");
    lstStr.Add("item6");

    string str = string.Join(",", lstStr);
    MessageBox.Show(str);

Output of this code will be as;
item1,item2,item3,item4,item5,item6

Now you can manipulate this comma separated string as per your needs.

How to read CDATA section using c#

CDATA means character data is used to store information in markup languages like XML. Here we will take a look at how to read this CDATA section using C#. Let's consider a XML file as;

<?xml version="1.0" encoding="utf-8" ?>
<Books>
  <Book ID="ISBN001" Title="ABC">
    <![CDATA[This is the information of ABC]]>
  </Book >
  <Book  ID="ISBN002" Title="DEF">
    <![CDATA[This is the information of DEF]]>
  </Book >
</Books>

Now we will take a look at the code which will read the CDATA section.

string strPath = @"<<Path of XML file>>";
XmlDocument doc = new XmlDocument();
doc.Load(strPath);
XmlElement root = doc.DocumentElement;
XmlNode node = doc.DocumentElement.SelectSingleNode(
@"/Books/Book");
XmlNode childNode = node.ChildNodes[0];
if (childNode is XmlCDataSection)
{
       XmlCDataSection cdataSection = childNode as XmlCDataSection;
       MessageBox.Show(cdataSection.Value);
}

Here I have retrieved only first node from the xml, you can select nodes as a node list and iterate through it to get CDATA section from all the nodes.

Write text files without Byte Order Mark (BOM)

I was working on a eLearning tool which supports various Learning Management Systems. Out of those one of the LMSs require files written in UTF8 encoding without Byte Order Mark(BOM).

If you are using Notepad++, you will find such type of encoding scheme over there. I was writing this piece of code in VB.Net.

The below code illustrates how to write files omitting BOM.

There seems to be a way of omitting the byte order mark (BOM) via passing False True to the UTF8Encoding constructor (link to MSDN reference page).
That is, use your own instance of UTF8Encoding instead of the default System.Text.Encoding.UTF8:
Dim utf8WithoutBom As New System.Text.UTF8Encoding(True)
                                                  '^^^^'
Using sink As New StreamWriter("Foobar.txt", False, utf8WithoutBom)
    sink.WriteLine("...")
End Using
(Note that omitting the BOM is only permissible for UTF-8, not for UTF-16.)

Datagridview error : Value' should be between 'minimum' and 'maximum'

I was trying to populate data in DataGridView control. It was getting populated into it correctly. But when I was trying to scroll down it was throwing an exception like;

> Value of '352' is not valid for 'Value'. 'Value' should be between
> 'minimum' and 'maximum'. Parameter name: Value

    at System.Windows.Forms.ScrollBar.set_Value(Int32 value)
       at System.Windows.Forms.DataGridView.ScrollRows(Int32 rowCount, Int32 deltaY, ScrollEventType scrollEventType)
       at System.Windows.Forms.DataGridView.ScrollRowsByCount(Int32 rows, ScrollEventType scrollEventType)

The Dynamic binding was used to fill the Datagridview.

After a lot of debugging and searching this issue got resolved with just one statement.
I called dataGridView1.PerformLayout() after populating data.

Thanks to Google :)

Joins in Database world

I don't remember when I last touched databases before today. It must be in my college days. These days almost every software system is built on a database. So I thought why not to refurbish my owns knowledge. So today I have picked up a very important terminology from Database world, "Join".
There are 3 kinds of joins as;
  • Join
  • Left Join
  • Right Join
What I learned for today is what is the basic difference between these.
Let's say we have 2 tables as;
Customer(Cno, Cname, Address);
Order(Tid, description, amount, Cno);

So the query can be written in format as;
Select <<Column names>> from <<Table name1>> <<Join type>> <<Table name2>> ON <<table name.column>> = = <<table name2.column>>

These 3 types of joins can be summarized as,
  1. Join returns records from both the tables if at-least one condition is matching.
  2. Left join returns records from the left table even if no condition is matching.
  3. Right join returns records from the right table even if no condition is matching.



ASP.Net User Controls


User controls are containers into which you can put markup and Web server controls. You can then treat the user control as a unit and define properties and methods for it. User controls are substantially easier to create than custom controls, because you can reuse existing controls. They make it particularly easy to create controls with complex user interface elements.
Heilights of user control;

  • .ascx files
  • Use of @Control directive instead of @Page
  • Cannot be run as a stand alone application, requires an aspx page
  • No html tags like html, body, form. Other tags are allowed

Steps to create user control;

  1. Create a web application from Visual studio
  2. Select project from solution explorer -> right click, Add new item -> Web User control
  3. Add controls and related events
  4. Add an aspx page to the project
  5. Make use of @Register directive to use created user control
Example:

Page Design -

Page header -

Server script -



Hello World of LINQ

LINQ (Language Integrated Query) is an expression language used to retrieve data from data source. This data source can be a SQL data provider or XML file. LINQ is mainly developed to overcome an extra overhead of learning so many query languages. There are lot of query languages available as of now and they are changing day by day. Developers have to learn each of them based on application needs.
LINQ plays a vital role in this. It is a generalized query language which can be used with various kinds of data sources and formats.
Here is a simple program which demonstrates LINQ functioning.

The query doesn't work by specifying the query variable itself.  "foreach" loop refers to the query variable and then the logic written in query is executed. Then developer can process on fetched data in the loop. Hers is how the LINQ works.


Please see the bottom section of page for references.

How to read data from console ?

One of my friend asked me this question today morning and I was bit surprised. I mixed up things saying it must be something like scanf statements. Then I searched it and figured out the steps to do so.


In this code, Console.ReadLine() will accept an input from the keyboard and it will store it in specified variable. Here I wanted to read an integer value from keyboard, so I used Console.Read() first. Console.Read() accepts one character at a time. So it is of new use for accepting integer value. Int32.TryParse() function accepts the value and tries to convert it to integer. This function returns boolean value as success or failure.

Is this function overloading

Today I was just playing through visual studio with certain classes and functions. I started writing a class with functions overloading mechanism. I wrote down class as;

And its consumer as;

When I executed the above piece I got the output as 5 and 6. ( I have skipped the printing part).
So here I have overloaded AddNumbers with 2 different signature.

Then a question came in my mind as if the function signature is same just a slight change in it's access modifier, will that be a function overloading?
I modified the above 2 signatures as;

I was under impression that a slight change in function signature means it is a function overloading. After compiling the modified piece, I got an error saying function definition already exist.
So I concluded that, difference in access modifier does not matter. To overload a function either it's return type or arguments should differ.


Layered and n-tier architecture


Layered architecture is a logical division of functional units. This is mainly used in enterprise applications to solve complex business scenarios.
Whereas tiered architecture is more of physical division of functional units.
To have a closer look following diagram will elaborate this.
 
Here a single layer can have multiple logical units like presentation layer, database layer etc. In tiered architecture these units represents physical entities like presentation server , database servers. These entities may or may not be a different computers, but in most enterprise applications for the scalability and maintenance these units are distributed.

Here is a sample layered application for reference.
 
 

How Partial class and constructor works

In this case first we will try to take a look at partial class. In the simple terms Partial classes are used when functionality is distributed. When the assembly is compiled, the partial classes gets combined together to form a single class unit. Have you ever thought what happens with the constructors, properties or methods for that matter.
Are these all also gets combined to form a single unit.
Let's take a look at this with simple partial class definition.



Now when this piece of code is compiled it will try to combine MyPartialClass into a single unit. When similar definitions for constructor and other functions are encountered compiler enters in ambiguity to decide which definition to be picked. It generates compile time error.
We cannot have similar constructor in partial classes. So is methods. Because at compile time partial classes gets combined to form one single unit so it created an ambiguity for constructors and methods.


Returning value from Method/Property is Risky

Value types are stored on Stack and reference types are stored on heap. Now here comes the twist as if a programmer by mistake or by intention returns a value from a method or property which is of type value it could lead to havoc.


Let’s take a look at this by an example;


After executing this program you will get the output as 0 instead of 4. This is because the property myNumber of class Arithmetics returns a copy of structure of type MyNumber and not reference type. If you replace the struct with class ypu will get result as 4 instead of 0, because in that case a reference will be passed.

What will be the impact of doing so?
If you call a method or access a property that returns a value-type object, do not modify it or call mutators (methods that modify its state or data) on it. You are dealing with a copy and any change you make does not affect the real instance.
Ref: .Net Gotchas

Aliases doesn’t work always

.Net CTS i.e. Common Type System have defined aliases for primitive data types. This facility is made available for the programmers who come from the programming languages prior to .Net like C++, VB6 etc.C3 makes use of int and long for 32 bit and 64 bit unassigned integer whereas VB makes use of Integer and long for the same.
Lets take a look at CTS memory allocation table for C# and C++;

CTS type
Size
C# alias
Type equivalent in C++
System.Int32
4 bytes
int
int or long
System.Int64
8 bytes
long
_ _int64
System.Char
2 bytes
char
WCHAR
System.Double
8 bytes
double
double

Now from the table above it is clear that C# makes use of int as an alias for 32 bit unassigned integer and C++ makes use of int or long. But long in case of C# is 64 bit unassigned integer.

Now you might ask what does that make difference. Let's have a look at it by an example.
We will call beep() function from an unmanaged code with its required arguments.
VB6 prototype is;
Beep(dwFreq as Long, dwDuration as Long) as Boolean
Now if we write it in .net, we might pass arguments as ;
Beep(long dwFreq,long dwDuration)
Now in this case long for VB is 32 bit unassigned integer and long for C# is 64 bit unassigned integer. The function will never return any output because of expected type mismatch.
If you are having any doubts about types in your mind, it is always a good practice to make use qualified names from CTS.

Ref: .Net Gotchas

Localization in ASP.Net

Localization

ASP.Net provides a technique to develop a multilingual web application. Such applications use same code-base but different language cultures. To accomplish this ASP.Net provides resource files. These files are with extension .resx, are local files which reside at server’s local machine. Depeneding upon the browser culture the web application picks up necessary resource file and display the text accordingly. Internally resources are stored in the form of key-value pair. User can have custom resources as well such as database, XML files etc.

Steps to demonstrate the Localization concept:
  • Create a web application using Visual Studio(I am using VS2005)
  • Add a new folder to the project solution App_localResources
  • Add a resource file to this folder say Default.aspx.resx ( it is a file with .resx extension)
  • Add a label on aspx page in design view.
  • Add a resource string with name value pair as label1.text as Welcome.
  • Add one more resource file say Default.aspx.es.resx and add it’s relative value. es stands for spanish, it’s universal standard.
    Go to the source view of aspx page and add meta:resourceKey=”label1” to the label
    The code will look like,
  • Go to the page directive of the page and add culture details as,Culture="auto:en-US" UICulture="auto"
  • Here auto keyword will detect the browser culture and will apply appropriate resource file to the page and en-US is default setting.
  • Now run the page in any browser, it will show the text depending upon the language it is configured to.
  • Try running this application by adding spanish language into the browser.
  • Here are the steps to change/add language to Internet Explorer.

Labels

.net .Net Instrumentation logging .net localization Agile amazon amazon elasticache amazon services AppDomain Application Domain architecture asp ASP.Net authentication authentication mechanisms Byte order mark c# cache canvas app cdata certifications class classic mode cloud cloud computing cluster code-behind Combobox compilation Configuration providers configurations connection connectionString constructors control controls contructor CSV CTS .net types conversion database DataGridView DataSource DataTable DataType DBML delegates design pattern dispose double encoding Entity framework Events exception handling expiry fault contracts fault exceptions function pointers functions generics help HostingEnvironmentException IIS inner join instance management integrated mode javascript join left outer join LINQ LINQ join LINQ to SQL memory leak methods microsoft model driven app modes in IIS MSIL multiple catch blocks no primary key Nullable Osmos Osmotic Osmotic communication Osmotic communications page events page life cycle partial class PMI powerapps preserve precision points private contructor ProcessExit Project management properties property protect connectionString providerName providers query regular expression repository Responsive Web Design return type run-time RWD Saas self join session session expiry sessions singelton singleton pattern software as a service source control system SQLMetal string time management time-boxing toolstrip ToolStrip controls ToolStripControlHost tortoise SVN ToString() try catch finally update wcf web application web design web site web.config where-clause xml

Pages