Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Left outer join using LINQ - yields different outputs

Couple of days ago, I was working on a project where I was supposed to convert SQL queries in LINQ. There was a simple SQL query as;

1
2
3
4
5
SELECT  * FROM Table1 td1LEFT
OUTER JOIN Table2ON 
td1.ColumnName = td2.ColumnName
WHERE td2.ColumnName IS NULL
ORDER BY SomeColumns

I ran this query in SQL Query analyzer, it returned me 100 records. And my converted LINQ code returned me 105 records. I converted this query intto LINQ to perform Left Outer Join as;
I did this in 2 ways;
Method 1:

1
2
3
4
5
6
var data= (from td1in Table1
           join td2 in Table2.Where(a => a.ColumnName == (int?)null) 
           on td1.ColumnName equals td2.ColumnName into outer
           from x in outer.DefaultIfEmpty()
           orderby SomeColumns
           select td1);

Method 2: 
1
2
3
4
5
6
7
var data = from td1 in Table1
           join td2 in Table2
           on td1.ColumnName equals td2.ColumnName into outer
           from item in outer.DefaultIfEmpty()
           where item.ColumnName.Value == (int?)null
           orderby somecolumns
           select td1 ;

This gave me an exception as, failed to enumerate results 

1
2
3
4
5
6
7
var data = from td1 in Table1
           join td2 in Table2
           on td1.ColumnName equals td2.ColumnName into outer
           from item in outer.DefaultIfEmpty()
           where item == null
           orderby somecolumns
           select td1 ;

In my original query that line item.ColumnName.Value == (int?)null was wrong, because I tried to retrieve value for all ColumnName even if item was null. I corrected that with the following query and it worked fine.

Implementing Singleton Design Pattern using C#

Hello friends,

All of you must be aware of what Singleton Design Pattern is. Just to define it in one line, It is a pattern which allows creation of one and only instance of a class. 

The practical scenario where you can go with this pattern is having a print job class instance, single running instance of an application etc. 

The best example is Google Talk desktop application.
Let us try to implement this pattern via C# code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPatternsDemo
{
    public class SingletonClass
    {
        private SingletonClass()
        {
        }

        //Implementation #1
        //static SingletonClass _instance = null;
        //public static SingletonClass GetInstance()
        //{
        //    if (_instance == null)
        //    {
        //        _instance = new SingletonClass();
        //    }
        //    return _instance;
        //}

        //Implementation #2
        //Be aware that in a multithreaded program, different threads could try
        //to instantiate a class simultaneously. For this reason, a Singleton
        //implementation that relies on an if statement to check whether the
        //instance is null will not be thread-safe. Do not use code like that!

        static readonly SingletonClass _instance = new SingletonClass();

        public static SingletonClass GetInstance
        {
            get
            {
                return _instance;
            }
        }

        public string GetWelcomeMessage()
        {
            return "Welcome to the Singleton world!! ";
        }
    }
}

The Singleton class above will be instantiated only once.
When the GetInstance is called, it will return the statically created instance of the class.

HostingEnvironmentException while running application from IIS


I was trying to run a simple ASP.Net application on my machine. Surprisingly it failed and below exception occured.

Exception Details: System.Web.Hosting.HostingEnvironmentException: Failed to access IIS metabase.
The process account used to run ASP.NET must have read access to the IIS metabase (e.g. IIS://servername/W3SVC).
For information on modifying metabase permissions, please see http://support.microsoft.com/?kbid=267904.
Source Error:
An unhandled exception was generated during the execution of the current web request.
Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[HostingEnvironmentException: Failed to access IIS metabase.]

The framework versions installed on my machine were 1.1, 2.0, 4.0. And my application was configured for 4.0 version.
To resolve this issue we just need to open visual studio command prompt and type the following command.

aspnet_regiis.exe /r

This will install the respective version of ASP.Net.

How to call default contstructor from another one


One of my team mate asked me this question today. I was not aware of this before that.
Here is a code for the same,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class A
    {
        public A()
        {
            Console.WriteLine("Default");
        }

        public A(string msg) : this()
        {
            Console.WriteLine("this is param : " + msg);
        }
    }
    
Now when you create instance of class A as,

1
A objA = new A("Hello");

It will print statements as;
Default
this is param : Hello

ToolStrip control extended


Today one of my clients asked me to show a button in ToolStrip control. He provided that this button should look like a regular button. The one which we use on WinForms. The default button available in ToolStrip control provided limited set of properties than the regular button control. It does not support border, flaststyle etc. properties.

Then from MSDN I found out the ToolStripControlHost class which allows developer to extend any standard .net control and add it to the ToolStrip.
You have to just extend this class so as to add any control. Here is a sample code,
I have used 2 controls A Button and A LinkLabel.
    public class ToolStripControlButton : ToolStripControlHost
    {
        public ToolStripControlButton()
            : base(new Button())
        {
        }

        public Button ButtonControl
        {
            get
            {
                return Control as Button;
            }
        }
    }


    public class ToolStripControlLinkLabel : ToolStripControlHost
    {
        public ToolStripControlLinkLabel()
            : base(new LinkLabel())
        {
        }

        public LinkLabel LinkLabelControl
        {
            get
            {
                return Control as LinkLabel;
            }
        }
    }
Then in the loading event of a form you can add these controls to the ToolStrip as,

ToolStripControlButton tsBtn = new ToolStripControlButton();
tsBtn.Text = "test";

ToolStripControlLinkLabel tsCal = new ToolStripControlLinkLabel();
tsCal.Text = "Visit us";
tsCal.Alignment = ToolStripItemAlignment.Left;
            
toolStrip1.Items.Add(tsCal);
toolStrip1.Items.Add(tsBtn);

When you run your program and when form is loaded it will show you these statndard controls as a part of ToolStrip.

DBML designer over SQLMetal


Today I got an assignment from client that the update query is running too slow. I started debugging it and found that the update is using all the fields. I came to know that LINQ to SQL by default assume that all columns participate in opt concurrency and generates a full WHERE clause.
So the query looks like,

UPDATE [dbo].[TableName]
SET [Column1] = @p1, [Column2] = @p2, [Column2] = @p3, [Column3] = @p4, [Column4] = @p5
WHERE [PRIMARYKEY] = @p0 AND
[Column2] = @p2 AND
[Column2] = @p3 AND
[Column3] = @p4 AND
[Column4] = @p5

From this link http://stackoverflow.com/questions/10136450/submitchanges-internally-adds-all-the-fields-as-where-clause-how-to-get-rid-of I came to know about a property UpdateCheck. This has to be set to NEVER in order to remove it from concurrency controlling. But this is not possible with SQLMetal tool because it generates the class structure straight away through command line.

Then I tried DBML designer. In DBML designer you can set the properties for every column from visual studio. So I dropped my table into the designer and it's respective code generated. Both the tools generate the same code, but designer facilitates you with properties window to change them at any point of time.
With UpdateCheck set to never the query gets generated like this,

UPDATE [dbo].[TableName]
SET [Column1] = @p1, [Column2] = @p2, [Column2] = @p3, [Column3] = @p4, [Column4] = @p5
WHERE [PRIMARYKEY] = @p0

To mention the disadvatages of setting UpdateCheck to never is the application looses concurrency control. The where clause gets cut down and allows multiple users to update the table at the same time.

ABC of WCF




Address

This is a url which specifies where the service is hosted. Example is like,
http://localhost:2190/MyFirstService/MyService.svc

Binding

Binding decribes how the client will communicate with the service. WCF makes use of various protocols to communicate with client.
You can read more details about types of bindings here.

Contract

This specified what operation(s) to be carried out. It is simple request/response, duplex exchange of information between client and service.
Examining end-points, client come to know what all operations are exposed by a service.

Creating Singleton class in C#


In many of the cases, we come accross situations where we want to create only one instance of a class. And use it throughout the application. As a programmer we have to take care of that from the code itself. Let's take a look at this step by step.

We will create a class MySingletonClass in such a way that it can be instantiated only once.

    public class MySingletonClass
    {
        //This will create a static instance of the class MySingletonClass
        private static MySingletonClass instance;

        //Private constructor
        private MySingletonClass() { }

        public static MySingletonClass Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new MySingletonClass();
                }
                return instance;
            }
        }

        public void DoWork()
        {
            Console.WriteLine("I am going for lunch");
        }
    }

So we are done with the class definition. Now let's start creating it's instances.

    class Program
    {
        static void Main(string[] args)
        {
            MySingletonClass objMySingleton = MySingletonClass.Instance;
            MySingletonClass objMySingleton2 = MySingletonClass.Instance;

            objMySingleton.DoWork();

            Console.ReadLine();
        }
    }

If you debug this code and put a break-point at get of Instance, you will notice that the object creation statement will get executed only once for the first object. For later requests the program will serve the existing one.

Now, if by mistake or intentionally, someone else tries to create an instance of MySingletonClass in traditional way as;

MySingletonClass objMySingleton = new MySingletonClass();

Our private constructor will not allow this to be compiled due to protection level.
So our class can be instantiated only once from anywhere in the application and the instance can be shared.


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;



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.

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