dotnet thoughts 

a dotnet developer's technical blog

Reviewing uCertify 70-513-CSharp MCTS exam prepkit

I have got a offer from them to review their PrepKit for MCTS 70-513, C#.NET 4 WCF Development(which you can find here) and I have accepted that challenge. Initially it looks fully-featured and with a nice UI, I haven’t had the time to make a few tests and that’s what counts most, so I’ll leave any further review opinions for later. As soon as I am done with the full review I will post it for you all.

How to use Linq for paging a generic collection

Yesterday one of my friend asked me about implementing client side paging. I provided the solution using LINQ paging. Already I have a post which talks about implementing Custom Paging in DataRepeater using C# and SQL Server, but this is using the generic collection. It is using Skip() and Take() extention methods.

var pageNumber = 3;
var pageSize = 20;
//users is the generic list of custom user objects.
var list = users.Skip((pageNumber - 1) * pageSize).Take(pageSize);

Happy Programming :)

How to start a Process as administrator mode in C#

Long back I wrote a post on how to create UAC Compatible applications in .NET. In that UAC will be applicable for the whole application. Today I got a scenario like I want to install a Windows service from my application, but I don’t want to enable UAC for the whole application. I am using the Process.Start() method for invoking the sc.exe. As I am not running that application as Administrator, I was getting an Access Denied message. Then I figured out the solution with Verb property of ProcessStartInfo. Simply set the Verb property of ProcessStartInfo as “runas”, this will popup the UAC dialog, before starting the application. If the user press Yes, it will launch the application otherwise it will throw a WIN32Exception.

var processStartInfo = new ProcessStartInfo(@"C:\Windows\Notepad.exe");
processStartInfo.Verb = "runas";
try
{
    Process.Start(processStartInfo);
}
catch (Win32Exception ex)
{
    MessageBox.Show(ex.ToString(), "Run As",
        MessageBoxButtons.OK, MessageBoxIcon.Error);
}

You can also check the OS platform also, this is required only if you are using Vista or Windows 7. You can check this using Environment.OSVersion.Version.Major, if it is more than 6, it is Vista or above.

if (Environment.OSVersion.Version.Major >= 6)
{
    processStartInfo.Verb = "runas";
}

Happy Programming :)

How to get the current battery level in C#

Today I found one blogpost related to how to get laptop battery level. But it was using WMI, and it was slow. Then after searching in MSDN, I found PowerStatus class, which is part of System.Windows.Forms namespace, which can be used to get the battery level. Here is a simple implementation, which shows battery status as well as system connected to AC power.

And here is the code snippet.

PowerStatus p = SystemInformation.PowerStatus;
progressBar1.Value = (int)(p.BatteryLifePercent * 100);
label1.Text = string.Format("{0}%", (p.BatteryLifePercent * 100));
radioButton1.Checked = p.PowerLineStatus == PowerLineStatus.Online;
radioButton2.Checked = p.PowerLineStatus == PowerLineStatus.Offline;
radioButton3.Checked = p.PowerLineStatus == PowerLineStatus.Unknown;

And here is the application running on my laptop

Current Battery Status

Current Battery Status

Happy Coding

Drive combo box in C#

As most of the .Net developers, I am also started my development career with VB6. :) VB6 comes with few file system controls, like DriveListbox, DirectoryListbox, FileListbox etc. But in .Net framework didn’t support these controls. Here is a solution for creating a drive listbox(it is not a listbox, it is dropdown list).

Drive Combo box in C#

Drive Combo box in C#

The drive information can be retrieved using DriveInfo.GetDrives() method. And for getting the corresponding icons for drive letters, I am using the SHGetFileInfo WIN32 API call.

Here is the implementation.

private void Form1_Load(object sender, EventArgs e)
{
    comboBox1.DrawMode = DrawMode.OwnerDrawFixed;
    comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
    comboBox1.DrawItem += new DrawItemEventHandler(comboBox1_DrawItem);

    var drives = DriveInfo.GetDrives()
        .Where(drive => drive.Name != string.Empty).ToArray();
    comboBox1.Items.AddRange(drives);
}

And here is the DrawItem event

private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    if (e.Index != -1)
    {
        e.DrawBackground();
        var icon = GetIcon(comboBox1.Items[e.Index].ToString());
        e.Graphics.DrawIcon(icon, 3, e.Bounds.Top);
        e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(),
            comboBox1.Font, Brushes.Black, icon.Width + 2, e.Bounds.Top);
        e.DrawFocusRectangle();
    }
}

And here is the GetIcon method and API declaration.

private const uint SHGFI_ICON = 0x100;
private const uint SHGFI_LARGEICON = 0x0;
private const uint SHGFI_SMALLICON = 0x1;

[DllImport("shell32.dll")]
private static extern IntPtr SHGetFileInfo(string pszPath,
                            uint dwFileAttributes,
                            ref SHFILEINFO psfi,
                            uint cbSizeFileInfo,
                            uint uFlags);
[StructLayout(LayoutKind.Sequential)]
private struct SHFILEINFO
{
    public IntPtr hIcon;
    public IntPtr iIcon;
    public uint dwAttributes;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
    public string szDisplayName;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
    public string szTypeName;
};

private Icon GetIcon(string fileName)
{
    IntPtr hImgSmall;
    SHFILEINFO shinfo = new SHFILEINFO();
    hImgSmall = SHGetFileInfo(fileName, 0, ref shinfo,
                (uint)Marshal.SizeOf(shinfo),
                    SHGFI_ICON |
                    SHGFI_SMALLICON);
    return Icon.FromHandle(shinfo.hIcon);
}

This implementation is using normal Combobox, you can do same thing by extending Combobox. So that it can be used in any project without any dependency.

« Newer PostsOlder Posts »