Archive

Posts Tagged ‘C#.Net’

Create UAC Compatible applications in .NET

September 1st, 2010 Anuraj P No comments

In my last project I got an opportunity to make my application compatible with Windows Vista and Windows 7. The main issue I faced was UAC; User Account Control (UAC) which introduced with the launch of Windows Vista; this provides users a better and safer computing experience. If UAC enabled, Windows will prompt every time when Applications try to access File System, like writing / creating Files in Program Files Folder, Windows Folder etc. (It’s not a best practice to write / create files in System directories like Windows, Program Files etc.). It’s also not a best practice to ask the customer to disable the UAC and run the application. The alternate is to make the application compatible with UAC, so that when the customer runs the application the system will prompts the UAC dialog, and run the application with Administrator privileges.
The procedure to make the application compatible with UAC is simple.

  1. Right-click project and add a new item.
  2. From the Add New Item box select Application Manifest File.
  3. In the manifest file un-comment the following line:
    <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
    

Build your application. And when the build is complete you will see the security shield icon accompanying your application icon.

Security shield icon accompanying application icon

Security shield icon accompanying application icon

A dialogue box appears in front of the user to run the application with full administrative privileges.

UAC Dialog box when double clicking on the Application

UAC Dialog box when double clicking on the Application

How to disable Close button of Windows Forms Application

August 25th, 2010 Anuraj P No comments

We can disable the close button of a Windows Form in three ways

  1. Set controlbox property to false – It is most easy way to do this. But it also hides the Minimize and Maximize buttons.
  2. Using WIN32 API – Using Win32 API, we are getting the system menu and removes the close menu item using Remove menu item.
    Here is the Code.

    const int MF_BYPOSITION = 0x400;
    [DllImport("User32")]
    private static extern int RemoveMenu(IntPtr hMenu, int nPosition, int wFlags);
    [DllImport("User32")]
    private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
    [DllImport("User32")]
    private static extern int GetMenuItemCount(IntPtr hWnd);
    
    //In the Form load event
    IntPtr hMenu = GetSystemMenu(this.Handle, false);
    int menuItemCount = GetMenuItemCount(hMenu);
    RemoveMenu(hMenu, menuItemCount - 1, MF_BYPOSITION);
    

    And here is the screenshot

    Using WIN32 API

    Using WIN32 API

  3. By Overriding the CreateParams property – The CreateParams property gets the required creation parameters when the control handle is created. By overriding the property we are removing the close button. You can get more information about CreateParams in MSDN
    Here is the code.

    private const int CS_CLOSE = 0x200;
    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams parms = base.CreateParams;
            parms.ClassStyle |= CS_CLOSE;  //
            return parms;
        }
    }
    

    And here is the screenshot

    By Overriding CreateParams property

    By Overriding CreateParams property

    All of above three methods will work fine. But if you are using Windows 7 none of the above will work or OS will override all these.

    Windows 7 - Close Window

    Windows 7 - Close Window

Tuple in .NET Framework 4.0

August 19th, 2010 Anuraj P No comments

Another new feature in the .NET 4 Framework is support for tuple,which are similar to anonymous classes that you can create on the fly. A tuple is a data structure used in many functional and dynamic languages, such as F# and Iron Python. By providing common tuple types in the BCL, we are helping to better facilitate language interoperability. Many programmers find tuple to be convenient, particularly for returning multiple values from methods.

Here is a code which uses a function that returns two values.

class Program
{
    static void Main(string[] args)
    {
        //Getting the values from the Tuple Function
        Tuple<string, string> details = GetDetails();
        Console.WriteLine("FirstName : {0}, LastName :{1}", details.Item1, details.Item2);
        Console.Read();
    }
    //Tuple function, which reads two values from
    //user and returns to the main
    static Tuple<string, string> GetDetails()
    {
        Console.Write("Enter First Name:");
        string _firstName = Console.ReadLine();
        Console.Write("Enter Last Name:");
        string _lastName = Console.ReadLine();
        return new Tuple<string, string>(_firstName, _lastName);
    }
}

You can find more details about Tuples in MSDN : Tuple Class

Categories: .Net, .Net 4.0 Tags: , , , ,

Operator overloading in C#

August 14th, 2010 Anuraj P No comments

Long back one of my cousins Rajesh gives me an introduction to Operator overloading in C++, but at that time I was VB 6.0 guy and I didn’t give much importance to it. But yesterday I got a chance to work on some sample applications where I tried operator overloading on C#.

I overloaded the + operator for adding two persons objects, and here is the code.

//Person class.
public class Person
{
    //Name of the Person
    public string Name
    {
        get;
        set;
    }
    //Operator overloading.
    public static Person operator +(Person first, Person second)
    {
        //Returning person, by adding the Names.
        return new Person()
        {
            Name = first.Name + " " + second.Name
        };
    }
}

And here is the void Main()

static void Main(string[] args)
{
Person firstPerson = new Person()
    {
        Name = "Person 1"
    };

Person secondPerson = new Person()
    {
        Name = "Person 2"
    };
    //Adding Person objects
Person resultPerson = firstPerson + secondPerson;
    //It will return Person 1 Person 2
Console.WriteLine(resultPerson.Name);
}

You can find Operator Overloading Tutorial in MSDN

Categories: .Net, .Net 3.0 / 3.5 Tags: , ,

Dropdownlist FindByText Problem

July 15th, 2010 Anuraj P No comments

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#

July 8th, 2010 Anuraj P No comments

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;
        }
    }
}