Home

Getting All Users in a Computer

Download The Project

Sometimes you need to retrieve users from Active Directory,this application come in handy there.

First we'll create a class to process WinApi calls.This Class has been written by  Michael Bright in 2003.Since then i've been using this code and extending it for network related needs.

 

using System;
using System.Runtime.InteropServices;

 

namespace GettingAllUsers
{

public class NetworkAPI
{

// USER_INFO_1 - Strucutre to hold obtained user information
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct USER_INFO_1
{
public string usri1_name; 
public string usri1_password; 
public int usri1_password_age; 
public int usri1_priv; 
public string usri1_home_dir; 
public string comment; 
public int usri1_flags; 
public string usri1_script_path;
} 

// USER_INFO_0 - Structure to hold Just Usernames
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct USER_INFO_0
{
public String Username;
}

// NetUserAdd - To Add Users to a local machine or Network
[DllImport("Netapi32.dll")]
public extern static int NetUserAdd([MarshalAs(UnmanagedType.LPWStr)] string servername, int level, ref USER_INFO_1 buf, int parm_err);

// NetUserDel - To delete Users from a local machine or Network
[DllImport("Netapi32.dll")]
public extern static int NetUserDel([MarshalAs(UnmanagedType.LPWStr)] string servername, [MarshalAs(UnmanagedType.LPWStr)] string username);

// NetUserGetInfo - Returns to a struct Information about the specified user
[DllImport("Netapi32.dll")]
public extern static int NetUserGetInfo([MarshalAs(UnmanagedType.LPWStr)] string servername,[MarshalAs(UnmanagedType.LPWStr)] string username,int level,out IntPtr bufptr);

// NetUserSetInfo - Allows us to modify User information
[DllImport("Netapi32.dll")]
public extern static int NetUserSetInfo([MarshalAs(UnmanagedType.LPWStr)] string servername,[MarshalAs(UnmanagedType.LPWStr)] string username,int level,ref USER_INFO_1 buf, int error);

// NetUserChangePassword - Allows us to change a users password providing we have it
[DllImport("Netapi32.dll")]
public extern static int NetUserChangePassword([MarshalAs(UnmanagedType.LPWStr)] string domainname,[MarshalAs(UnmanagedType.LPWStr)] string username,[MarshalAs(UnmanagedType.LPWStr)] string oldpassword,[MarshalAs(UnmanagedType.LPWStr)] string newpassword);

// NetUserEnum - Obtains a list of all users on local machine or network
[DllImport("Netapi32.dll")]
public extern static int NetUserEnum(string servername, int level, int filter, out IntPtr bufptr, int prefmaxlen, out int entriesread, out int totalentries, out int resume_handle);

// NetAPIBufferFree - Used to clear the Network buffer after NetUserEnum
[DllImport("Netapi32.dll")]
public extern static int NetApiBufferFree(IntPtr Buffer);

public NetworkAPI()
{
//
// TODO: Add constructor logic here
//
}
}
}

 

Add a ListBox in your form and then,
Later inside your main application create a function for enumerations:

 

public void EnumerateUsers()
{
int EntriesRead;
int TotalEntries;
int Resume;
listBox1.Items.Clear();

IntPtr bufPtr;

NetworkAPI.NetUserEnum(null, 0, 2, out bufPtr, -1, out EntriesRead, out TotalEntries, out Resume);

if (EntriesRead > 0)
{
NetworkAPI.USER_INFO_0[] Users = new NetworkAPI.USER_INFO_0[EntriesRead];
IntPtr iter = bufPtr;
for (int i = 0; i < EntriesRead; i++)
{
Users[i] = (NetworkAPI.USER_INFO_0)Marshal.PtrToStructure(iter, typeof(NetworkAPI.USER_INFO_0));
iter = (IntPtr)((int)iter + Marshal.SizeOf(typeof(NetworkAPI.USER_INFO_0)));
listBox1.Items.Add(Users[i].Username);

}
NetworkAPI.NetApiBufferFree(bufPtr);
}
listBox1.SelectedIndex = 0;


}




Now just call EnumerateUsers inside Form_Load to populate them in your listbox at startup


private void Form1_Load(object sender, EventArgs e)
{
EnumerateUsers();
}

 

 

And run it!


 

 





 

 

 

 

 

 

 

 

 

 

 

Hope that helps!

Task Dialogs in C#

Download The Project
 

Task Dialogs are elevated dialogs as you're familiar with after you installed an application telling you if it was installed correctly.

This is called Task Dialog and its a part of WindowsAPICodePack, available for download from: http://archive.msdn.microsoft.com/WindowsAPICodePack/


What we're going to do in this article is to create a Task Dialog with customizable texts and a hyperlink that opens your webpage using Process.

The application will look like this(its a localized Windows 7 by the way):

 

 



 

 

 

 

 

 

First of all create a new windows forms application.

Then add these references:

Microsoft.WindowsAPICodePack.dll

which can be found on your extracted archive after you downloaded it:

..\Windows API Code Pack 1.1\Windows API Code Pack 1.1\binaries\Microsoft.WindowsAPICodePack.dll

 
After that create a TaskDialogCommandLink variable:

TaskDialogCommandLink link = null;



This will help us to access it from another event to open your website.

 

Now lets keep going...

Create a TaskDialog variable

  

TaskDialog dia = new TaskDialog();



This is the Dialog Window we wish to create.Here we created it actually

 


Lets play with its properties by adding more functionality to it:

dia.Cancelable = true;
dia.InstructionText = "Friend Request"; 
dia.StandardButtons = TaskDialogStandardButtons.Yes | TaskDialogStandardButtons.No;



Cancelable means we can close/cancel the dialog if we want.
InstructionText is the above text inside the dialog.You can give it a general name like Friend Request,Mail Sent,Password Changed and goes on...
StandardButtons are as you can see,added two of them;


Now lets play with CommandLink:

link = new TaskDialogCommandLink("http://www.iersoy.com","Anonymous just added you as Friend in Facebook!","Do you accept?");
link.UseElevationIcon = true;
link.Enabled = true;
link.Click+=new EventHandler(link_Click);



Here we created a Hyperlink alike structure that uses Elevation icon and raised an event when clicked on it

public void link_Click(object sender, EventArgs e)
{
Process.Start(link.Name);
}



as i told before we created commandlink to access from an event.That event is this Click event.We access links name to view it on a webbrowser.i added my own blog,you can change it later,depends on you.

And lets finalize this application:

dia.Controls.Add(link); 
dia.DetailsExpanded = false;
dia.DetailsExpandedText = "Annonymous is a world-wide hacktivist group";
dia.ExpansionMode = TaskDialogExpandedDetailsLocation.ExpandFooter; 
dia.Caption = "Information!";
dia.Show();




we're adding this link to Task Dialog so that we can see it.We also assign false to DetailsExpanded to make it look like real windows 7 Task Dialogs.And we're adding some text regarding information about Anonymous.it displays when you expand the detail icon
And finally we show it to the user:

 Run and you'll see similar effecti've shown as a screenshot above

Hope it helps,and you use it in your applications.

Get All Instances of SQL Server in C#

Download The Project

If you're writing a Database Manager application or simply want to retrieve all the instances,this trick might come in handy.

We'll be using SQL SMO(SQL Management Objects)

First of All you need to add reference to Microsoft.SqlServer.smo.dll file which is located in:

For 64-bit Windows 7:
[Your drive]:\Program Files (x86)\Microsoft SQL Server\100\SDK\Assemblies\Microsoft.SqlServer.Smo.dll

For 32-bit Windows 7:
[Your drive]:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\Microsoft.SqlServer.Smo.dll

 

Now that we've added it to our project,we can start coding!

Add a ListBox control to your project:

DataTable dataTable = SmoApplication.EnumAvailableSqlServers(true);
listBox1.ValueMember = "Name";
listBox1.DataSource = dataTable;



By running this code alone,you'll get all the available sql servers inside your listbox control.

 

 

 




 

 

 

 

 

 

 

 

 

 

Ok lets develop it further.Lets see what databases our instances have

So to do this,you need to add another ListBox.Then in your listbox1's selectedindexchanged event you need to check which server selected.So you need to create a server object first.

After this,you'll iterate through this server to populate all the databases in newly created listbox.

Here is the code to do that:

 

 

listBox2.Items.Clear();
if (listBox1.SelectedIndex != -1)
{
string serverName = listBox1.SelectedValue.ToString();
Server server = new Server(serverName);
try
{
foreach (Database database in server.Databases)
{
listBox2.Items.Add(database.Name);
}
}
catch (Exception ex)
{
string exception = ex.Message;
}
}

 

 


After we run the project we'll be getting our Databases.

 

 

 

 

 

 

 

 

 

 

Hope it helps! 

Get All Installed Printers in C#

Download The Project

Assuming you need to retrieve all installed printers,you can do it by using PrinterSettings class

This class locates in System.Drawing.Printing namespace

so you need to add reference System.Drawing and then import it with using statement:


using System.Drawing.Printing;




To get all the printers available,you need to iterate the string values through PrinterSettings

 

For example:

Add a ListBox to your windows application and then use foreach statement for iteration:

foreach (string printname in PrinterSettings.InstalledPrinters)
{
listBox1.Items.Add(printname);
}

 

This will show you all the available Printers installed on your computer as seen below:



 

 

 

 

 

 

 

 

Because i've not installed any physical printers on my computer it shows the printer services. 

Get All Installed Fonts in C#

Download The Project
 

If you need to retrieve all the fonts installed on your environment,you just need InstalledFontCollection class.This class is a collection of storing all the installed fonts and enabled you to populate them via iteration.

To get all the installed fonts ,we need first add reference to System.Drawing and then import it in our project with using statement:


using System.Drawing.Text;




This will let us use InstalledFontCollection class:

Now lets build a sample.

 

 


Create a windows forms,add a listbox and then add these codes:

 

 

using (InstalledFontCollection col = new InstalledFontCollection())
{
foreach (FontFamily fa in col.Families)
{
listBox1.Items.Add(fa.Name);
} 
}

 




After we run,we'll be populating them:

 




 

 

 

 

 

 

 

 

 

 

 

 

 


Hope that helps!

Running Single Instance of the Application

You've built an application and would like it to run a single instance.

Here comes Mutex to the rescue!
 

bool isMutexOwned;
Mutex mut=null;



Then create a Mutex instance and control this Mutex via isMutexOwned boolean var.

 

 

using(Mutex mut=new Mutex(true,"My Mutex",out isMutexOwned))
{
if(isMutexOwned)
{
//Do Something...Mutex is owned by the application
}
else
{
//Mutex isnt owned.So other instances can run.
}
}

public void ReleaseMut()
{
mut.ReleaseMutex();
}

 

Add a Button Click event and raise ReleaseMut function.See what happens.



After that another instance of application will now run.

Hope that helps

Dynamically Call a Function

As you well know, "dynamic" keyword was introduced in .NET 4.0.


While we use dynamic,the c# compiler will not know whether it exists or not.it'll be created & executed in runtime.

 

To call a function dynamically, all you have to do is creating an instance of the class you're in and call the function using the dynamic instance created

 

For example we have a class and a function:

class Ersoy
{
    public void Display_Name(string name1)
    {
       Messagebox.Show(name1); 
    }
}



We can load a functional dynamically by using:

 

class Ersoy
{
   public void Create_Dynamic()
   {
     dynamic ersinstant=new Ersoy();
     ersinstant.Display_Name("Ibrahim");
   }
   public void Display_Name(string name1)
   {
     Messagebox.Show(name1); 
   }
}

 



After running we'll be displaying our name.


Hope that helps

Unloading Assemblies in C#

If you've created an Application Domain and want to unload all the assemblies loaded within,there is no way to unload Assembly themselves.But you can unload Application Domain you've just created.


In addition to that one;

You cannot unload the default Application Domain CLR created on its own.And unloading can differ from the assemblies being used and the unload events these assemblies have.It can take some time.

 

To Unload an Application Domain all you need to do is calling Unload function.


A sample code can help you understand:


AppDomain myDom=AppDomain.Create("Ibrahims Domain");

//Here assuming you loaded your assemblies

//To unload AppDomain call Unload Function

AppDomain.Unload(myDom);

// The Application Domain we've just created is now no more as the assemblies with it.



After Unloading Application Domain object,we've also unloaded all the assemblies loaded within.

 

Hope that helps

Getting All Colors in XNA

 

To display all the colors,i've used combobox from windows controls


First of all we need to get the Type of Color:

Type structType = typeof(Color);



Then we use PropertyInfo to get all the controls:

  

PropertyInfo[] fields = structType.GetProperties();


The reason why we didnt use FieldInfo instead of PropertyInfo is Each color is actually Property and have fields like R,G,B,A.

 

So we iterated through PropertyInfo and populated our combobox object


 

foreach (PropertyInfo field in fields)
{
cbo.Items.Add(field.Name);
}

 

 


When we run it,we'll be getting extra useless items:
 

XNAColors1.png


 

 

 

 

So what to do?


I've written a simple iteration to remove these useless items:


for (int a = 0; a <= 5; a++)
{
cbo.Items.RemoveAt(0);
}

 


it removes the first 6 items from the list.

Simple but useful.As it seems:

 

XNAColors2.png


 

 

 

 

So? 

Our work is done here.We got our Colors populated.

Hope it helps

 

BigInteger in C#

The max value for an integer(int64) is "9223372036854775807" (According to my calculation)

But you can calculate greater numbers using BigInteger.

To get started;

First you must add reference to System.Numerics.


 Given the code below; simply multiplies 2 int64 numbers:

 

BigInteger big = BigInteger.Multiply(Int64.MaxValue,Int64.MaxValue);
textBox3.Text = big.ToString();

 

And result is:



85070591730234615847396907784232501249  (a 38-digit number)


You can use BigInteger to calculate big numbers.


Hope it helps



Türkiye'nin en doğru, dolu dolu ve hatasız anlatımları ile teknik yazılarına, makalelerine, video'larına, 
seminerlerine, forum sayfasına ve sektörün önde gelenlerine ulaşabileceğiniz teknik topluluğu, MSHOWTO