dotnet thoughts 

a dotnet developer's technical blog

FileNot Found exception – Application_Error event in Global.asax

Today I got a problem from my colleague, that he is getting FileNot Found exception in Application Error event in Global.asax, which is used to log application errors. But the application was working fine and good. We thought it may be because of missing images that was referring in Stylesheets. But all the image references are valid and we couldn’t find any issue. We couldn’t find anything suspicious in stack trace.

Stack Trace from the exception

at System.Web.StaticFileHandler.GetFileInfo(String virtualPathWithPathInfo, String physicalPath, HttpResponse response)
at System.Web.StaticFileHandler.ProcessRequestInternal(HttpContext context)
at System.Web.DefaultHttpHandler.BeginProcessRequest(HttpContext context, AsyncCallback callback, Object state)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

After doing some search we got an option where we can find the file causing the exception. We created a string variable and put a break point over there and debugged the code. It will display the filename causing the exception. In our case it was a HTML file which was used in a Javascript to set an IFRAME source, unfortunately the developer who copied the script missed the HTML and it was causing the exception.

Here is the code.

void Application_Error(object sender, EventArgs e)
{
Exception err = Server.GetLastError();
//Insert a break point and run in debug mode.
string fileName = Context.Request.FilePath;
 Application["UnhandledException"] = err;
}

Selecting controls using LINQ

One of my colleague asked how to get all the text boxes with no text entered in Windows form without using a For Loop. I thought of writing it with LINQ. And here is my implementation.

 var controls = from control in this.Controls
                           select control;

But this will generate a compile time error – Could not find an implementation of the query pattern for source type ‘System.Windows.Forms.Control.ControlCollection’. ‘Select’ not found. Consider explicitly specifying the type of the range variable ‘control’. But the error was self explanatory, I need to specify the type of the control. And here is the modified version.

var controls = from Control control in this.Controls
                           select control;

And if you want to select specific type of controls you need to apply a where condition.

var textboxes = from Control textbox in this.Controls
                where textbox is TextBox
                select textbox;

There is some other inbuilt operators is also available to select specific controls, like OfType()

var textboxes = from textbox in this.Controls.OfType<TextBox>()
                select textbox;

In this method we don’t need to specify the type of the control in the from statement. And one of interesting LINQ extension method is the Cast<> method, which helps to enable the standard query operators to be invoked on non-generic collections by supplying the necessary type information. You can get more information from here.

Dropdownlist FindByText Problem

Today one of my colleague talked about a simple basic issue with Dropdownlist, the FindByText() method works as case sensitive. Because of this issue, we are getting some exceptions. So I starting looking for alternatives and one way I found it looping the items and compare it. Like the following.

this.ddlItems.SelectedIndex = -1;
foreach (ListItem item in this.ddlItems.Items)
{
    if (item.Text.Equals("Item", StringComparison.CurrentCultureIgnoreCase))
    {
        item.Selected = true;
        break;
    }
}

It is a nice option, I rewrote it as an extension method and works fine. Later I thought of wrting more generic FindByTextMethod() and here the extension method.

/// <summary>
/// Searches the Collection of ListItem with a ListItem.Text property contains the specified text
/// </summary>
/// <param name="items"></param>
/// <param name="text">The text to search for.</param>
/// <param name="stringComparison">One of the System.StringComparison values.</param>
/// <returns>ListItem if the collection contains the text, null otherwise.</returns>
public static ListItem FindByText(this ListItemCollection items,
    string text,
    StringComparison comparisonType)
{
    ListItem result = items.OfType<ListItem>().
        FirstOrDefault(_string => _string.Text.Equals(text, comparisonType));
    return result;
}

And you can use it like this

this.ddlItems.Items.FindByText("Item", StringComparison.CurrentCultureIgnoreCase).Selected = true;

Happy Coding ;)

Implementing Print using C#

The first assignment I got from my lead in my previous company was to create Print option to the accounting package we were working. The application was developed in VB 6.0. And we were used batch files and command prompt for printing accounting related documents from the application. Few days back one of colleague asked how we can print from C#, he was developing an accounting package for his uncle. I said something like we need to use PrintDocument class for that, but I couldn’t give him a sample code. Today I got some free time in Office so I thought about implementing printing from C#. Here is a simple implementation, which displays a Print Dialog, and based on the settings, it will print the contents of the textbox.

I tried to print the document based on the ForeColor of the TextBox, but it was throwing some error, I couldn’t resolve itIts fixed. :) Source code is pretty self-explanatory. Happy Printing.

private int startIndex = 0;
private void printToolStripMenuItem_Click(object sender, EventArgs e)
{
    PrintDocument printDocument = new PrintDocument();
    //Print Options dialog.
    using (PrintDialog printDialog = new PrintDialog())
    {
        printDialog.ShowHelp = false;
        printDialog.ShowNetwork = false;
        printDialog.Document = printDocument;
        printDialog.AllowPrintToFile = true;
        //As its a simple text file, disabling the advanced options.
        printDialog.AllowCurrentPage = false;
        printDialog.AllowSelection = false;
        printDialog.AllowSomePages = false;
        //Display XP Style Print Dialog
        printDialog.UseEXDialog = true;
        if (printDialog.ShowDialog(this) == DialogResult.OK)
        {
            //Assigning the Printer settings to the Document.
            printDocument.PrinterSettings = printDialog.PrinterSettings;
            printDocument.PrintPage += new PrintPageEventHandler(printDocument_PrintPage);
            //Number of copies
            for (int i = 0; i < printDialog.PrinterSettings.Copies; i++)
            {
                startIndex = 0;
                //Print method call.
                printDocument.Print();
            }
        }
    }
}

And here is the Print Page event.

protected void printDocument_PrintPage(object sender, PrintPageEventArgs e)
{
    //Setting the color as Black.
    Brush brush = Brushes.Black;
    //Setting color dynamically
    //Brush brush = new SolidBrush(this.txtEditor.ForeColor);
    int lineCounter = 0;
    float lineTop = 0;
    //Looping throught each line in the textbox.
    for (int lineIndex = startIndex; lineIndex < this.txtEditor.Lines.Length; lineIndex++)
    {
        string line = this.txtEditor.Lines[lineIndex];
        lineCounter++;
        //Writing the line to the document.
        lineTop = e.MarginBounds.Top + lineCounter * this.txtEditor.Font.Size;
        e.Graphics.DrawString(line,
            this.txtEditor.Font,
            brush,
            e.MarginBounds.Left,
            lineTop);
        //Checking for more pages.
        if (lineTop > e.MarginBounds.Bottom)
        {
            startIndex = lineIndex;
            e.HasMorePages = true;
            return;
        }
    }
}

How to use Stored Procedures in Entity Framework

In the current project we are using Entity Framework for database operations. Entity Framework comes with Visual Studio SP1, which helps you to map tables / views / procedures as entities in C# / VB Code. You can find more details about EF from here : http://msdn.microsoft.com/en-us/library/bb399572.aspx. In this post I am explaining how to use Stored Procedures in Entity Framework.

  1. Add the Stored Procedure to the Entity Model Designer using Update Model From Database Option.
  2. Add Procedure

    Add Procedure

  3. If you are added successfully, you can get the procedure in Model Browser.
  4. Model Browser

    Model Browser

  5. Right click on the Procedure name and select Create Function Import.
  6. Create Function Import

    Create Function Import

  7. It will popups a Windows with Stored Procedure Name, Function Import Name and Return Type. If the procedure returns nothing, you can choose none. If the procedure is returns single value, like UserId, Number Of Rows etc, then you can choose scalar option, where you need to specify the return type. And if the procedure is returns Table or Number of Rows, you need to choose the last option Entities, which will allow to select entities created in the Model as the Output. Sometimes we need to create a View in the DB and need to import it in the Model, so that we can use the View as the return type entity. Select the appropriate return type and click Ok. You can use this in code. In this code I am using a View to return the selected users.
Add Function Import dialog

Add Function Import dialog


using (SampleEntities context = new SampleEntities())
{
/*
* Thanks to Barry Soetoro.
* I was not calling the GetAllUsers function.
List<Users> Users = null;
Users = (from user in context.Users
             select user).ToList();
this.dataGridView1.DataSource = Users;
*/
//Updated Version.
IEnumerable<UsersView> userview = context.GetAllUsers();
this.dataGridView1.DataSource = userview;
}

This will display list of Users in the DataGridView. Happy Coding :)

Older Posts »