Archive for the ‘C#’ Category

PLINQO by CodeSmith

A lot of people have doubts about whether to use LINQ to SQL for real-world applications, especially since Microsoft has encouraged in favor of the new version of the Entity Framework slated for release with .NET 4.0 and Visual Studio 2010.

Recently, I have read the book ASP.NET 3.5 Enterprise Application Development with Visual Studio 2008: Problem Design Solution (Wrox Programmer to Programmer) ~ Vincent Varallo (Author)

This book faithfully follows the very popular Wrox “Problem – Design – Solution” format, evolving chapter by chapter while analyzing business requirements, examining various design scenarios, and implementing a beginning-to-end solution in a reusable framework. The book uses LINQ to SQL for data access. It covers a lot of important material.

The bottom line is that LINQ to SQL is a perfectly viable alternative when you can guarantee that the database will be Microsoft SQL Server (2000 or later). It has support for POCO (persistence ignorance), stored procedures, lazy loading, and concurrency management, and it works well with SOA (n-tier) architectures.

Do I use LINQ to SQL in new projects?

I Do ;)

Microsoft is not going to stop including LINQ to SQL in the .NET framework until they are convinced EF is a good migration target for all the current LINQ to SQL users. That day has not arrived. Therefore, I believe I have plenty of time to be productive with LINQ to SQL before I must make a change.

The question is, “Who is adding new features to LINQ to SQL?” The answer is a product called Plinqo, created by the makers of the code-generation tool, Code Smith. The purpose of Plinqo is to generate LINQ to SQL entities that replace those created when you add a dbml file to a Visual Studio project. In fact, Plinqo will generate the dbml file for you, placing each entity in a separate .cs file under a common folder. Actually, Plinqo creates two files: one for the code-generated entity, and another for your own custom metadata that will not be overwritten by the code-generator (for example, attributes that can drive a dynamic data web site).

While Plinqo generates code that is better organized and easier to read, its power lies in the extensions it provides, such as manager and query classes, a build-in rules engine, audit trail, caching, cloning and detaching entities. It also de-normalizes many-to-many relationships and takes advantage of improvements to the DataContract attributes for .NET 3.5 SP1 (avoiding cyclic references and the need for the “unidirectional” serialization option). In addition, Plinqo will create enums instead of entities for tables with lookup values.

But wait, there’s more! Plinqo has actually enabled batch updates and deletes, eliminating possible round-trips when calling SubmitChanges to process updated entities. Wow, now that is something I had been hoping Microsoft would give us in the next version. But thanks to Plinqo, I won’t have to hold my breath waiting for Microsoft, which has stopped adding new features to LINQ to SQL. Lastly, Plinqo also enables batch queries and the ability to process multiple result sets from stored procedures.

And to top it off, Plinqo has templates to create an ADO.NET Data Services layer that exposes entities via a REST-ful web service. There’s even a quick start template that will create both the service and a dynamic data web client in a matter of seconds.

So before you decide to give up on LINQ to SQL, check out Plinqo to get a fresh option for using LINQ to SQL in real-world applications. They’re even offering a free CodeSmith license if you mention Plinqo in a blog or tweet.

Popularity: 2% [?]

Share

Detect duplicate C# code

Detect duplicate C# code with Clone Detective for Visual Studio 2008

This is a killer add-in for Visual Studio that detects all that copy & paste coding your coworkers have been doing (‘cause of course you would never do that). Long live the DRY principle!

Clone Detective is a Visual Studio integration that allows you to analyze C# projects for source code that is duplicated somewhere else. Having duplicates can easily lead to inconsistencies and often is an indicator for poorly factored code.

For more details please see the Videos page.

ScreenshotSmall.png

Clone Detective uses ConQAT to perform the clone detection.

conqat_logo_wide_tum.png
 

Popularity: 6% [?]

Share

String Basics in .NET

I’ve used the snippet of code at the end of this article twice in the last week to clear up some misunderstandings about strings in .NET.

System.String is a reference type in .NET. Don’t let anyone mislead you into thinking otherwise. You’ll hear people saying strings “act like value types”, but this doesn’t mean the runtime makes a copy of the string during assignment operations, and it doesn’t make a copy of a string when passing the string as a parameter.

The equality operator and String.Equals method compare the values of two string objects, and you won’t find a property or method on System.String with the ability to modify the contents of a string – only return a new string object. Because of these two behaviors we sometimes say strings have value type semantics (they feel like value types), but strings are reference types in the runtime. An assignment operation does not copy a string, but assigns a reference. The value given to a string parameter in a method call is the reference, not a copy of the string’s value.

 

using System;

 

class Class1

{

[STAThread]

static void Main(string[] args)

{

 

string s1 = "Hello";

string s2 = s1;

 

// this test will compare the values of the strings

// result will be TRUE since both s1 and s2

// refer to a string with the value "Hello"

 

bool result = String.Equals(s1, s2);

Console.WriteLine("String.Equals(s1, s2) = {0}", result);

 

// next we will check identity

// ReferenceEquals will return true if both parameters

// point to the same object

// result will be TRUE -both s1 and s2reference

// the same object.

// strings are reference types

// there is no copy made on assignment (s2 = s1)

 

result = Object.ReferenceEquals(s1, s2);

Console.WriteLine("Object.ReferenceEquals(s1, s2) = {0}", result);

 

// now we will make a copy of the string

 

s2 = String.Copy(s1);

 

// compare string values again

// result will be TRUE – both s1 and s2

// refer tostrings with the value of "Hello"

 

result = String.Equals(s1, s2);

Console.WriteLine("String.Equals(s1, s2) = {0}", result);

 

// check identity again

// result will be FALSE

// s1 and s2 point to different object instancesbecause we forced a copy

 

result = Object.ReferenceEquals(s1, s2);

Console.WriteLine("Object.ReferenceEquals(s1, s2) = {0}", result);

}

}

The sample code in this post demonstrates that the run time maintains a string intern pool. The intern pool allows sharing of string instances. Interning is primarily a memory optimization, but can also be a performance optimization in some unique scenarios.

The runtime will store strings literals in the intern pool. For example:

 

using System;

 

class Class1

{

    [STAThread]

    static void Main(string[] args)

    {

        string s1 = "bbb";

        string s2 = "bbb";

        Console.WriteLine("{0},{1}", s1, s2);

    }

}

 

If you look at the IL code for the above program, you might be tempted to think we are dealing with two different string instances. In other words, s1 and s2 will point to different string objects.

 

  IL_0000:  ldstr      "bbb"

  IL_0005:  stloc.0

  IL_0006:  ldstr      "bbb"

  IL_000b:  stloc.1

 

This is not the case, as the following program will demonstrate.

 

using System;

 

class Class1

{       

    [STAThread]

    static void Main(string[] args)

    {          

 

        string s1 = "bbbbbb";

        string s2 = "bbbbbb";

 

        // this expression returns true

        // both string variables reference the

        // same interned string

 

        bool b = Object.ReferenceEquals(s1, s2);

        Console.WriteLine(b);

 

        // create a new string with the same value

        // as the above: "bbbbbb"

 

        string s3 = new string(‘b’, 6);

 

        // this expression returns false

        // even though s3 references "bbbbbb",

        // it’s not the same string instance

        // referenced by s1,s2

 

        b = Object.ReferenceEquals(s1, s3);

        Console.WriteLine(b);

 

        // See if "bbbbbb" is already interned by

        // checking the reference returned by Intern

 

        string s4 = String.Intern(s3);

 

        // this expression returns true

        // s4 is pointing to the same object as s1,s2

 

        b = Object.ReferenceEquals(s1, s4);

        Console.WriteLine(b);

    }

}

 

Popularity: 3% [?]

Share

Extract links & Automate download using C# AutoIt

I’m sure you all are aware of rapidshare. Most of the time these downloads links are spread across the website which makes it very difficult to get them.  So, Instead of wasting time in downloading each link at a time, why not extract these links and store in some file ( may be text file ) and then use some script to do this dirty work.

Here is the C# code to extract from any url


 

HttpWebRequest request;
HttpWebResponse response;
Stream s;
string strPath = Application.StartupPath + @"\Extract.txt";
TextWriter tsw = new StreamWriter(strPath, true);
List<string> lst = new List<string>();
// create a request to the url 
request = (HttpWebRequest)WebRequest.Create("http://somewebsite.com");
// get the response 
response = (HttpWebResponse)request.GetResponse();
// get the stream of data and read into a string 
s = response.GetResponseStream();
string strContents = new StreamReader(s).ReadToEnd();
Regex r = new
    Regex("href\\s*=\\s*(?:(?:\\\"(?<url>[^\\\"]*)\\\")|(?>[^\\s]* ))");
MatchCollection mc1 = r.Matches(strContents);
foreach (Match m1 in mc1)
{
    Group grp = m1.Groups[1];
    string strRSLink = grp.Value;
    strRSLink =
    Regex.Replace(strRSLink, @"(.*)(\.)(html)$", "$1", RegexOptions.IgnoreCase);
    if (Regex.IsMatch(strRSLink, @"http://rapidshare.com", RegexOptions.IgnoreCase))
    {
        if (!lst.Exists(i => i.Equals(strRSLink)))
            lst.Add(strRSLink);
    }
}
foreach (var item in lst)
{
    tsw.WriteLine(item);
}
tsw.Close();


And then you can use AutoIt scripting language to automate the download using any download manager. I’m using Internet download manager which is one of the best donwload manager tool.

AutoIt (and AutoItX) v3.3.0.0 released (24th December, 2008).AutoIt v3 is a freeware BASIC-like scripting language designed for automating the Windows GUI and general scripting. It uses a combination of simulated keystrokes, mouse movement and window/control manipulation in order to automate tasks in a way not possible or reliable with other languages (e.g. VBScript and SendKeys). AutoIt is also very small, self-contained and will run on all versions of Windows out-of-the-box with no annoying "runtimes" required! .

Just install it and use the following AutoIt script to automate the download. Here is the code


 

Local $program = @ProgramFilesDir & '\Internet Download Manager\IDMan.exe'
Local $file = @DesktopDir & '\Autoit\RapidLinks.txt'
Local $h_file
Local $url
Local $cnt = 0

        $h_file = FileOpen($file, 0)
        If $h_file = -1 Then
                SetError(1)
        EndIf

        Run($program)
        While 1
                $url = FileReadLine($h_file)
                If @error = -1 Then ExitLoop

                If $cnt = 2 Then
                        Sleep(240000)
                        $cnt = 0
                EndIf

                ;MsgBox(0,"URL",$url)
                WinWait("Internet Download Manager 5.15")

                If Not WinActive("Internet Download Manager 5.15") Then _
                        WinActivate("Internet Download Manager 5.15")

                WinWaitActive("Internet Download Manager 5.15")
                Send("!ta")

                WinWait("Enter new address to download")

                If Not WinActive("Enter new address to download") Then _
                        WinActivate("Enter new address to download")

                WinWaitActive("Enter new address to download")
                Send($url)
                Send("!k")

                WinWait("Download File Info")

                If Not WinActive("Download File Info") Then _
                        WinActivate("Download File Info")

                WinWaitActive("Download File Info")
                Send("!s")
                $cnt += 1
                Sleep(5000)

        WEnd

        FileClose($h_file)

Popularity: 4% [?]

Share

How to get return value from stored procedure ?

Recently one of my friend asked me to review his code to see why he was not able to get the return value from stored procedure.

With the stored procedure, he was returning 1 in the stored procedure if the operation doesn’t succeed. He was executing the command via IDBCommand.ExecuteNonQuery() and then check the return value to see how many records were affected.  Apparently ExecuteNonQuery only returns the number of affected rows on SELECT, INSERT and DELETE statements; for everything else it returns -1.  So, here is what I suggested him to get a return value from a stored procedure.

 

Let’s assume a simplistic stored procedure as follows:

ALTER PROC usp_TestReturnOnly
AS
BEGIN
      RETURN 1

END

You can’t use ExecuteScalar to get the returned value, and ExecuteNonQuery will always return -1.  To get the value back, you need to add a return value parameter to the command.  The name of the parameter is not important.  The C# data access code to get the value returned by that procedure will be as follows:

private int ExecuteStoredProcedure(string strStoredProcedureName)
{
   SqlConnection sCon= new SqlConnection(strConnectionString);
 
   // Command – specify as StoredProcedure
   SqlCommand sCmd= new SqlCommand(strStoredProcedureName, sCon);
   sCmd.CommandType = CommandType.StoredProcedure;
 
   // Return value as parameter
   SqlParameter spReturnValue = new SqlParameter("returnValue", SqlDbType.Int);
   spReturnValue .Direction = ParameterDirection.ReturnValue;
   sCmd.Parameters.Add(spReturnValue );
 
    // Execute the stored procedure
   sCon.Open();
   sCmd.ExecuteNonQuery();
   sCon.Close();
 
   return Convert.ToInt32(spReturnValue .Value);
}

 

 

 

 

Popularity: 2% [?]

Share

Free C# and VB Coding Standards

Clint Edmonson has gifted us for the holidays with free coding standards documents for C# and VB.

I totally agree when he said

“It doesn’t matter what the standards are, as long as you have them and everyone agrees to adhere to them!” 

[ GET THEM HERE ]

Popularity: 2% [?]

Share

VS 2010 and .NET 4.0

Visual Studio 2010 and .NET Framework 4.0 CTP Feedback

______________________________________________________________ Visual Studio 2010 & .Net Framework 4.0 Logo ______________________________________________________________

 

 

Popularity: 1% [?]

Share