Showing posts with label C# Using. Show all posts
Showing posts with label C# Using. Show all posts

25 November 2008

C# WMI Startup Programs, List Startup Applications with ManagementClass

It is possible to list Startup Programs of operating system in C#.

With the use of ManagementClass, a few lines of code will give us this list.
The WMI classes are easy to use such these operations.
  • Add reference System.Management to your project.
  • Add the following code to your code file.
  • using System.Management;
    using System.Management.Instrumentation;
  • Add the code below to list the startup application assigned in os.
  •  ManagementClass mangnmt =
    new ManagementClass("Win32_StartupCommand");

    ManagementObjectCollection mcol = mangnmt.GetInstances();

    foreach (ManagementObject strt in mcol)
    {
    Console.WriteLine("Application Name: "
    + strt["Name"].ToString());

    Console.WriteLine("Application Location: "
    + strt["Location"].ToString());

    Console.WriteLine("Application Command: "
    + strt["Command"].ToString());

    Console.WriteLine("User: " + strt["User"].ToString());
    }

List Autorun programs in C#

C# a generic error occurred in GDI+ Solution

A generic error occurred in GDI+
I encountered this error while I was working with images,
when I try to save image file with EncoderParameter and ImageCodecInfo classes in C#.

This problem is mostly occurred for the security reasons,
you may not enough permission to write file and so on.
Here is solution.
  • Create a System.IO.MemoryStream object.
  • Create a System.IO.FileStream object
  • Save image into MemoryStream
  • Read bytes[] from the MemoryStream
  • Save the image file with FileStream
And Here is the C# sample code;
using System.Drawing.Imaging;
using System.Drawing;
using System.IO;

public static void SaveJpeg
(string path, Image img, int quality)
{
EncoderParameter qualityParam
= new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);

ImageCodecInfo jpegCodec
= GetEncoderInfo(@"image/jpeg");

EncoderParameters encoderParams
= new EncoderParameters(1);

encoderParams.Param[0] = qualityParam;

System.IO.MemoryStream mss = new System.IO.MemoryStream();

System.IO.FileStream fs
= new System.IO.FileStream(path, System.IO.FileMode.Create
, System.IO.FileAccess.ReadWrite);

img.Save(mss, jpegCodec, encoderParams);
byte[] matriz = mss.ToArray();
fs.Write(matriz, 0, matriz.Length);

mss.Close();
fs.Close();
}
Do not forget to close streams, other wise you will get a out of memory error.

C# ASP.NET MySQL Connection Tutorial with MySQL Connector

In order to connect to MySQL Server with .NET in C# or ASP.NET does not matter actually,
  • You need to download MySQL Connector/Net .
  • After you add a reference to your project, it is probably in C:\Program Files\MySQL\MySQL Connector Net 5.0.7\Binaries\.NET 2.0 folder, add the MySql.Data.dll file as a reference.
  • Make your connection string, the following code will shows a standard MySQL connection string.

using MySql.Data.MySqlClient;
public static string GetConnectionString()
{
string connStr =
String.Format("server={0};user id={1}; password={2};
database=yourdb; pooling=false", "yourserver",
"youruser", "yourpass");

return connStr;
}
  • Then create an instance from MySql.Data.MySqlClient.MySqlConnection as shown below.
  •  MySql.Data.MySqlClient.MySqlConnection mycon
    = new MySqlConnection( GetConnectionString());
  • Then Try to open the MySQL connection.
  • if(mycon .State != ConnectionState.Open)
    try
    {
    mycon .Open();
    }
    catch (MySqlException ex)
    {
    throw (ex);
    }
So simple as you see, It is always better to do this in data access layer also called DAL.
Connect Mysql in C# and ASP.NET.

C# How To Get Computer IP Address IPHostEntry

To get the IP address of the local machine in C#,
using system.net
namespace.

From IPHostEntry class, we get the list in a string array.
 using System.Net;

Private string GetIP()
{
string strHostName = "";
strHostName = System.Net.Dns.GetHostName();

IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);

IPAddress[] addr = ipEntry.AddressList;

return addr[addr.Length-1].ToString();

}
Read IP address of the local computer.

You can check your IP address on myip.help.

C# Regex Time Validation With Regular Expression

In order to check whether an input is a valid time format or not,
regular expressions
can be used to validate the input value.

The sample function below show how to check if the input
is valid time in XX:XX, code is in C#.

This regular expression checks the input for 00:00 to 23:59 is a valid time format.

using System.Text.RegularExpressions;

public bool IsValidTime(string thetime)
{
Regex checktime =
new Regex(@"^(20|21|22|23|[01]d|d)(([:][0-5]d){1,2})$");

return checktime.IsMatch(thetime);
}
Time regular expression used to control time is ^(20|21|22|23|[01]\d|\d)(([:][0-5]\d){1,2})$

Is valid time validation with regular expression in C#.

C# Regex Number Validation With Regular Expression

In order to check whether an input is a valid number or not,
regular expressions
are very easy to use to validate the input value.

The sample function below show how to check if the input is number or not, code is in C#.

using System.Text.RegularExpressions;

public static bool IsItNumber(string inputvalue)
{
Regex isnumber = new Regex("[^0-9]");
return !isnumber.IsMatch(inputvalue);
}
IsItNumber("2"); will return true;
IsItNumber("A"); will return false;

Is number validation with regular expression in C#.

C# Read Windows Logon User Name in WMI

Using the namespace System.Management,
we can easily read the Windows Logon User name.

The WMI (Windows Media Instrumentation)
queries are very similar with the SQL queries.

The sample code below written in C# reads the logon user name.
using System.Management;

public static string logonUser()
{
string _user = string.Empty;
ConnectionOptions co = new ConnectionOptions();
System.Management.ManagementScope ms
= new System.Management.ManagementScope("\" + "localhost" + "rootcimv2", co);

System.Management.ObjectQuery oq =
new System.Management.ObjectQuery("SELECT * FROM Win32_ComputerSystem");
ManagementObjectSearcher query =
new ManagementObjectSearcher(ms, oq);

ManagementObjectCollection queryCollection;
queryCollection = query.Get();

foreach (ManagementObject mo in queryCollection)
{
_userl = mo["UserName"].ToString();
}

char[] charSeparators = new char[] { '' };

int deger = _user.Split(charSeparators, StringSplitOptions.None).Length;
_user= _user.Split(charSeparators, StringSplitOptions.None)[deger - 1];

return _user;
}
Will return the Windows Logon User name. Many other WMI queries are available.