December 2008 Entries

C# uses special escape sequences within a string to signify that what follows is to be treated differently.  The special character is the backslash \.  This character says to treat whatever follows it as though it were part of the string itself. 

string msg = "Spot the dog said: \" get that dog bone\"";  // knowing this the following is good syntax:

Spot the dog said: "get that dog bone" //output

List of C# Escape Sequences

\"  Display a double quotation mark
\'   Display a single quotation mark.
\\  Display a backslash.
\0  Null (non-printing).
\a  Alarm (beep terminal alarm).
\b  Backspace (back up one character position).
\f   Form feed (advance to next page).
\n  Newline (advance to next line).
\r  Carriage return (move to left margin).
\t  Tab (advance one tab space, often eight characters).
\v  Vertical tab.


C# provides a way to avoid 'escaping' characters in strings.  You can use the verbatim string literal character @ to tell VS.NET to build the string exactly as it appears.
string msg = @"go to c:\temp"; // this would work

The verbatim string can be used to allow a single string to span more than one line i.e.

string msg = @"this is great
                        to be under
                        the sun";

The default installation folder C:\Program Files\Microsoft Enterprise Library 4.1 - October 2008

  • Bin - contains the binaries you can use in the application.  Also the configuration editor EntLibConfig.exe which can be used to create and edit configuration files for EntLib
  • Docs - documentation
  • Src - contains the installer file for the Enterprise Library source file
  • Visual Studio Integration - contains binaries that make the configuration Editor available in Visual Studio

The installer also puts the original source code in C:\EntLib41Src

  • bin - contains the same as the bin above
  • Blocks - contains a solution that houses all 42 Enterprise Library projects. There is also a second solution that additionally contains unit test projects and the actual unit tests to verify correct working of Enterprise Library as you change it. This is a great value that allows you to feel comfortable editing this pile of code while being able to prove you have not broken anything
  • Lib - contains object builder and unity binaries that you can use in your application independent of EntLib
  • Quick Starts - contains sample code in both C# and VB.NET that you can use to see available functionality of EntLib and how to use it in your own applications.
  • Scripts - contains batch files to amongst others compile EntLib from the source, register assemblies and to install Northwind database for the quick starts

Enteprise Library 4.1 can be found http://msdn.microsoft.com/en-us/library/dd203099.aspx

category: Enterprise Library

Instead of the following typical property setter/getter

private string courseName;
pubic string CourseName{
   get { return courseName;}
   set { courseName = value;}
}

 

//Auto-Implemented property implicitly creates an instance variable for property CourseName
public string CourseName {get; set;}

  • unable to use the private variable for this property (hidden from developer)
  • developer can only reference within the class via CourseName 

This is a reasonable approach for quick prototyping of properties only.

Details...

  • an anonymous type declaration begins with the new keyword followed by a member-initialzer list in braces {}
  • the compiler generates a new class definition that contains the properties specified in the new member-initializer list
  • all properties of an anonymous type are public and immutable
  • anonymous type properties are read-only (you cannot modify a properties value once the object is created)
  • each properties type is inferred from the values assigned to it
  • the compiler defines a ToString method that returns comma-separated list of property-name = value pairs
  • Equals method compares the properties of two or more anonymous types
  • Examples...

    //Create a 'person' object using an anonymous type
    var bob = new { Name = "Bob", Age = 37 };

    bob in this case is the anonymous type and the types of the properties are inferred by the value assigned.

    //display information (note here however that the ToString is not required as a ToString method is automatically defined and is the anonymous type)
    Console.WriteLine("Bob:" + bob.ToString());

    //the ToString() method would output the following
    Bob: { Name = Bob, Age = 37 }


    var steve = new { Name = "Steve", Age = 36 };

    //the compiler is able to recognize the anonymous type for bob and steve are identical and of the same class by the fact that the properties and types were identical for both bob and steve

    //the anonymous type also creates an equals method that is capable of comparing all objects of this anonymous type (so name and age properties will be compared)
    Console.WriteLine(bob.Equals(steve) ? "equal" : "not equal"));

    The output from the is "not equal".

    I have a generic function in one of my helper libraries that allows me to open a new browser window when a button is selected.  The button posts back to the server runs some code and opens a new window.  I often use this sort of thing on a reporting page allowing me to post some search criteria and open a new window (a pdf report).

    I found this type of helper function useful however I found that I was losing my CSS after the postback.

    To avoid losing the css keep the following in mind:

    • ensure that your css files are include declaratively in your aspx page (not through code behind)
    • use Page.ClientScript.RegisterStartupScript(this.GetType(),”name”,script); (Not Response.Write)

    The end helper function looks something like the following:

        /// <summary>

        /// redirect to a new page from codebehind

        /// </summary>   

        static public void RedirectToNewWindow(string url, System.Web.UI.Page page) {       

            string script = "<script>window.open('" + url + "');</script>";

            page.ClientScript.RegisterStartupScript(page.GetType(), "redirectscript",script);       

        }

    Often we test web services by either locally on our workstations or remoting to the server and accessing the asmx page.  If you try to access the asmx remotely however you are not given the option to test the server (by using the server url address).  By adding the following code the <system.web> section of asmx web site web.config you can now test your services remotely.

    <webServices>
            <protocols>
                <add name="HttpSoap12"/>
                <add name="HttpSoap"/>
                <add name="HttpGet"/>
                <add name="HttpPost"/>
            </protocols>
    </webServices>

    The above code addresses the issue related to "The test form is only available for requests from the local machine." error message.

    category: Asp.Net

    I was looking for some utility that would take a very long string and convert it to vb.net or c# with line continuation(s) characters. String literals to the rescue.  C# supports two forms of string literals: regular string literals and verbatim string literals. 

    A regular string literal consists of zero or more characters enclosed in double quotes, as in "hello", and may include both simple escape sequences (such as \t for the tab character) and hexadecimal and Unicode escape sequences.  In c# regular strings can only span multiple lines with syntax similar to the following:

    string sql = “SELECT customer “ +
                      “FROM customers “ +
                      “WHERE custId=10”;


    A verbatim string literal consists of an @ character followed by a double-quote character, zero or more characters, and a closing double-quote character. A simple example is @"hello". In a verbatim string literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote-escape-sequence. In particular, simple escape sequences and hexadecimal and Unicode escape sequences are not processed in verbatim string literals.

    The above sample can be replaced with the ‘literal’ designated by the @ symbol as follows:

    string sql = @“SELECT
                      FROM customers
                      WHERE custId=10”;

    I have been chasing an issue for quite a while where the query would timeout when executed from an ASP.NET interface.  If I ran that exact same query through Query Analyzer the results would be returned in less than 2 seconds. 

    I have for a while been struggling with why it is different between those two interfaces.  I thought about connection pooling issues, command time outs and connection timeouts and was focused on that for a while.  Even after extending those values from the default the query would still time out.  It was often I would see an exception similar to

    ---------------------------

    SQL Exception Information:
    ErrorId: -2
    Message: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
    Line Number: 0
    Procedure:
    ---------------------------

    To put this post in the proper context think about one of your application search stored procedures.  The interface shows a dozen or more optional textboxes for user entry to narrow down the results.  The stored procedure in this case often has many parameters that could be used with the actual query.  This is the case for the query that I am discussing herein.

    When you execute a stored procedure for the first time the query processor constructs a query plan based on the the state of the statistics and the input parameters.  So, the query plan is created upon first execution and is cached in case some other invocation of the same stored procedure comes along before the cache is cleared.  So, when executing through the web interface SQL Server is using the same execution plan that was created by the prior user.  This can look significantly different between users and what parameters they provide before they run the search.

    So, to have SQL Server generate a new query plan upon each execution the "WITH RECOMPILE" can be used.  By adding this parameter SQL Server regardless of the parameters passed in it will create a new optimal plan.

    i.e.
    Create Procedure dbo.GetCustomers
                @LastName varchar(200),
                @FirstName varchar(200),
                .... 
    WITH RECOMPILE AS
      BEGIN

      END

    New in SQL Server 2005 it has a new RECOMPILE query hint option (see also OPTIMIZE FOR for can take advantage for local parameters also).  More information regarding these options can be found by researching 'parameter sniffing' problems' related to query execution.  So with 2005 instead of just using the WITH RECOMPILE (available in both 2000 and 2005) option at the stored procedure level you have more granular control at SQL level within the stored procedure.  By this I mean you can have some SQL statements within a stored procedure that use a common execution plan (ep) while others within the same stored procedure can create new optimal ep's upon each execution.

    i.e. SQL 2005 option
    Create Procedure dbo.GetCustomers
                @LastName varchar(200),
                @FirstName varchar(200),
                .... 
    AS
      BEGIN
          Query 1
          Query 2 OPTION(RECOMPILE)
          Query 3 OPTION(RECOMPILE)
          Query 4 
      END

    So when would use the recompile feature?  When you feel it would be inefficient to reuse a previously cached execution plan you should consider using it.

    The only aspect of this problem that still I have not found confirmation on is why it behaved differently in SQL Server Query Analyzer OR from within VS.NET.  I am tending to think that the optimal plan was generated each time from within those interfaces while when running from the ASP.NET web application it was using one that was cached on the server.  If anyone knows the answer to this I would very much like to know.

    category: SQL Server

    Getting the w3wp.exe ProcessID for Attach to Process

    Open command prompt and type iisapp.vbs 

    Attach a debugger to your code

      • The code you are using to debug must be exactly the same as the executing assembly. This often catches people out in SharePoint development as the assembly SharePoint is using is often in a different location than the default build directory (i.e. in the bin directory in IIS or in the GAC). You may want to include a post build script to copy your assembly to the correct location to help automate this process. Also be careful when debugging assemblies that are in the GAC as you may need to do an iisreset to ensure ASP.NET uses the latest version of your assembly.
      • The .pdb file needs to be in the same directory as the assembly to see line numbers. This is easy if you are using the bin directory of the website (recommended when developing), but you cannot copy these files directly into the GAC. You can get around this with the following steps:

        • Map a network drive to the GAC (C:\WINDOWS\assembly) folder. This allows you to see the actual folder structure and copy files into the folders as they appear on disk (opposed to the shell that is shown when browsing directly).
        • Copy the .pdb file into your assembly folder in the GAC_MSIL subfolder so that it sits next to the assembly dll.
      • Activate features through the UI if you want to debug feature receivers. If you use the stsadm command line tool to automate feature deployment the w3wp process will be recycled so any debuggers will be detached. Activating these through the central admin or the site features page will ensure the w3wp process is running.

     Use Debug and Trace statements

    System.Diagnostics.Debug and Trace statements are another great way of tracking down errors in your code. As Debug calls are removed from release builds, these can be used extensively to help track down errors in development. To view these you can use tools such as DebugView to view messages on local or remote machines

    Use Try-Catch statements

    As with standard ASP.NET applications, Try-Catch statements can help catch and log error messages that occur in your code. This can be combined with Debug and Trace statements to view or log errors, or display meaningful messages to the user. For example in a web control you might do the following:

    protected override void Render(HtmlTextWriter writer)
    {
      try
      {
         // code that might cause an error
      }
      catch
      {
         Trace.Write(ex);
         writer.Write(ex.Message);
      }
    }

    View the SharePoint Logs

    The raw SharePoint log files are extremely cluttered and hard to use but there is an alternative. The LogViewer feature on CodePlex lets you easily select a log file and view a filtered display of the items you are interested in.

    You can also tweak the information that is written to the SharePoint logs via the Diagnostic Logging link under Logging and Reporting in the operations section of Central Administration.

    If when using Windows Sharepoint Services you are unable to retract or execute jobs seen through the management interface using the following commands can help to manually list and remove and redeploy solutions.

    To see a list of all solutions on the server
    stsadm.exe -o enumsolutions

    To see a list of all deployments
    stsadm.exe -o enumdployments

    To cancel a deployment
    stsadm.exe -o canceldeployment -id {guid}

    To execute scheduled jobs
    stsadm.exe -o execadmsvcjobs

    Error: "the solution cannot be removed when a job is scheduled or is running" < use the above commands to execute jobs that are scheduled

    I am using something like the following when removing and deploying web parts (notice the execadmsvcjobs)

    stsadm.exe -o retractsolution -name webPart.wsp -immediate -url {http://...} 
    stsadm.exe -o execadmsvcjobs
    stsadm.exe -o deletesolution -name webPart.wsp -override
    stsadm.exe -o addsolution -filename webPart.wsp
    stsadm.exe -o deploysolution -name webPart.wsp -immediate -allowgacdeployment -url {http://...} -force
    stsadm.exe -o execadmsvcjobs


    About Me

    An engineer by training and a software developer at heart. My techniques and approaches meld engineering approaches with software technology.

    Core to these principles is a systematic approach to the development of software with a strong lifecycle and process management emphasis through adoption of mature technologies.

    Ten years designing heavy structural steel and concrete structures and 12 years in the software development profession have embedded strong project management and business knowledge in my approaches.

    Subscribe to Rss Feed


    Follow me on twitter @dyardy