Odd or Even? (C#)

by Vitaly Zayko 24. February 2010 21:15

How to quickly determine is given number odd or even? There are several simple methods.

Here is the first one:

 

 public bool IsEven(int i)
 {
     return (i & 1) == 0;
 }

And the second:

 public bool IsEven(int i)
 {
     return (i % 2) == 0;
 }

 

Technorati Tags:
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:

Code Snippets

Another way to get path to a running assembly or how to get list of command line arguments in a non console App?

by Vitaly Zayko 23. December 2009 16:58

There is an another way how to get path to a running assembly from itself besides I mentioned here. Use this simple snippet:

string[] cmd = Environment.GetCommandLineArgs();
string path_to_assembly = cmd[0];
/* cmd[1] and above contains command line arguments is any */

Resulting array is at least one element length or longer. First element of this array always contains path to the assembly. As a side effect – you can get command line params beginning from second element.

Unfortunately doesn’t work in .NET Compact Framework.

Technorati Tags: ,
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:

Code Snippets

Adding /r/n in .NET (C#)

by Vitaly Zayko 30. November 2009 16:05

When your App outputs some text, you probably will want to split your strings by adding carriage return. Of course, you can declare this as a constant string: private const string CRLF = "/r/n";

or use predefined constant from Environment: Environment.NewLine

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:

Code Snippets

Using Windows 7 Jump List in Visual Studio 2010 Beta 2

by Vitaly Zayko 2. November 2009 20:48

If you are on Windows 7, you probably have noticed about new feature – Windows 7 Jump List. If you right-click on an App icon (let say – Internet Explorer) you will see additional menu items which you as a programmer can handle in your solutions. If you are on Visual Studio 2008, the only way is to use an additional Windows API Code Pack for Microsoft .NET Framework. But there is a modern way for Visual Studio 2010 (at least for WPF):

  • Open App.xaml file of your App
  • Add reference to JumpList as shown below:

<Application x:Class="WpfApplication1.App"

             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

             StartupUri="MainWindow.xaml">

    <Application.Resources>    

    </Application.Resources>

    <!-- Add reference to JumpList here: -->

    <JumpList.JumpList>

        <JumpList ShowFrequentCategory="True" ShowRecentCategory="True">

            <JumpTask Title="Notepad"

                      Description="Open Notepad"

                      ApplicationPath="notepad.exe"

                      IconResourcePath="notepad.exe"/>

        </JumpList>

    </JumpList.JumpList>

</Application>

Technorati Tags: ,,
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags: , ,

Code Snippets | Visual Studio Tip

Detect how many CPUs (or cores) available on a system? (C#)

by Vitaly Zayko 21. July 2009 11:30

Quite important to be prepared for the Parallel Computing.
This will show you how lucky your system is Smile:

int cpu = System.Environment.ProcessorCount;

Greetings!

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:

Code Snippets

C#: How To Disable Windows Screensaver programmatically?

by Vitaly Zayko 18. May 2009 15:22

In some cases you may want to prevent Windows screensaver from running. For example, when a customer watch video or does VoIP call, his mouse and keyboard activities are low.

I didn’t find a managed function in .NET Framework but fortunately we can make it through PInvoke.

1. Add PInvoke namespace:

using System.Runtime.InteropServices;

2. Import SystemParametersInfo function and its enums as below:

public enum SPI : uint
{
   SPI_GETSCREENSAVEACTIVE = 0x0010,
   SPI_SETSCREENSAVEACTIVE = 0x0011
}
public enum SPIF : uint
{
   None = 0x00,
   SPIF_UPDATEINIFILE = 0x01,
   SPIF_SENDCHANGE = 0x02,
   SPIF_SENDWININICHANGE = 0x02
}
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SystemParametersInfo(SPI uiAction, uint uiParam, ref uint pvParam, SPIF fWinIni);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SystemParametersInfo(SPI uiAction, uint uiParam, uint pvParam, SPIF fWinIni);

3. You may want to check is screensaver enabled by Control panel setting or not:

uint vParam = 0;
if (SystemParametersInfo(SPI.SPI_GETSCREENSAVEACTIVE, 0, ref vParam, SPIF.None))
{
   if (vParam == 1)
       MessageBox.Show("Screensaver is enabled");
   else
        MessageBox.Show("Screensaver is disabled");
}
else
    MessageBox.Show("Error!");

4. And finally - disable it:

if (SystemParametersInfo(SPI.SPI_SETSCREENSAVEACTIVE, 0, 0, SPIF.None))
{
   MessageBox.Show("Screensaver has been disabled");
}
else
    MessageBox.Show("Error!");

5. Don’t forget to re-enable if it was enabled initially:

SystemParametersInfo(SPI.SPI_SETSCREENSAVEACTIVE, 1, 0, SPIF.None);
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:

Code Snippets

How to send HTML e-mail with an image embedded in its body? (C#)

by Vitaly Zayko 20. February 2009 13:56

I’m trying to cover two common questions in one post:

  1. How to send an HTML message by SMTP?
  2. How to embed a picture into its body?

Follow the C# code below.

// Use AlternateView to create HTML body ("cid:image" - here we place the image):
using(AlternateView htmlView = AlternateView.CreateAlternateViewFromString(
   "This is an <b>Html</b> e-mail message with <i>embedded image</i> below\r\n<img src='cid:image'>",
   null, "text/html"))
{
   // Create LinkedResource to specify an embedded image:
    using (LinkedResource image = new LinkedResource("c:\\IMAGE.jpg"))
   {
       // ContentId should be equals to the CID that we specified above
        image.ContentId = "image";
       htmlView.LinkedResources.Add(image);

       mail.AlternateViews.Add(htmlView);

       // Create SmtpClient as reqular:
        SmtpClient smtp = new SmtpClient("mail.zayko.net");

       // Set Credential if needed:
        smtp.Credentials = new System.Net.NetworkCredential("mailusername", "mailpassword");

       // ...and here we go:
        smtp.Send(mail);
   }
}

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:

Code Snippets

How to lock workstation programmatically? (C#)

by Vitaly Zayko 13. January 2009 15:48
There is no such .NET function (or at least I didn’t find). Fortunately we can use PInvoke instead.
Use this function to lock workstation’s display to protect from unauthorized use. Result of this function is the same as pressing Ctrl+Alt+Del.
  1. Add namespace at the top of your code:
    	using System.Runtime.InteropServices;
    	
  2. Declare PInvoke:
    	[DllImport("user32.dll", SetLastError = true)]
    	
    	static extern bool LockWorkStation();
    	
  3. Call this function like this:
    	if (!LockWorkStation())
    	
    	   throw new Win32Exception(Marshal.GetLastWin32Error());
    	
    	
    	
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:

Code Snippets

How to get some User environment information? (C#)

by Vitaly Zayko 24. December 2008 15:50

Use System.Environment namespace to get lot of information about your user. Just few examples:

 

string userName = System.Environment.UserName;
string machineName = System.Environment.MachineName;
OperatingSystem osVersion = System.Environment.OSVersion;
string userDomainName = System.Environment.UserDomainName;

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:

Code Snippets

How to get list of removable drives installed on a computer? (C#)

by Vitaly Zayko 16. December 2008 12:32

First of all add reference to System.Management sysm assembly.
Then run something like this:

1:/// <summary>
2:/// Retuns list of all Removable drives aailable
3:/// </summary>
4:/// <param name="UsbDrives">Structure to store drive names (e.g. "D:", "E:" etc.</param>
5:/// <returns>true if at least one removable is available</returns>
6:public bool GetRemovableDisks(out IList<string> UsbDrives)
7:{
8:   // Add System.Management reference. Then
9:    bool result = false;
10:   UsbDrives = new List<string>();
11:   using (System.Management.ManagementClass managementClass = new System.Management.ManagementClass("Win32_Diskdrive"))
12:   {
13:       using (System.Management.ManagementObjectCollection driveCollection = managementClass.GetInstances())
14:       {
15:           foreach(System.Management.ManagementObject driveObject in driveCollection)
16:               foreach (System.Management.ManagementObject drivePartition in driveObject.GetRelated("Win32_DiskPartition"))
17:                   foreach (System.Management.ManagementBaseObject logicalDisk in drivePartition.GetRelated("Win32_LogicalDisk"))
18:                   {
19:                       string drive = (logicalDisk["Name"]).ToString();
20:                       string driveDescription = logicalDisk.Properties["Description"].Value.ToString();
21:                       if (driveDescription.Equals("Removable Disk", StringComparison.InvariantCultureIgnoreCase))
22:                       {
23:                           UsbDrives.Add(drive);
24:                           result = true;
25:                       }
26:                   } 
27:       }
28:   }
29:   return result;
30:}
31:
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:

Code Snippets

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

Calendar

<<  March 2010  >>
MoTuWeThFrSaSu
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar

About the author

Vitaly Zayko

Senior Software Developer / Team Lead / Product Manager

Moscow, Russia