Click here to Skip to main content
15,887,331 members
Home / Discussions / C#
   

C#

 
AnswerRe: How to solve"Cross thread operation not valid" error when programming with C#.net Pin
Luc Pattyn6-Apr-07 4:39
sitebuilderLuc Pattyn6-Apr-07 4:39 
QuestionError in saving excel file Pin
Manish_Home5-Apr-07 19:32
Manish_Home5-Apr-07 19:32 
AnswerRe: Error in saving excel file Pin
roel_v5-Apr-07 21:22
roel_v5-Apr-07 21:22 
QuestionDatatable Pin
AnhTin5-Apr-07 18:46
AnhTin5-Apr-07 18:46 
AnswerRe: Datatable Pin
_mubashir5-Apr-07 20:53
_mubashir5-Apr-07 20:53 
AnswerRe: Datatable Pin
Harini N K6-Apr-07 0:32
Harini N K6-Apr-07 0:32 
QuestionHelp!!! Declare a varied-length array of structures and the use of marshalling? Pin
peary5-Apr-07 18:21
peary5-Apr-07 18:21 
AnswerRe: Help!!! Declare a varied-length array of structures and the use of marshalling? Pin
Luc Pattyn6-Apr-07 4:50
sitebuilderLuc Pattyn6-Apr-07 4:50 
Hi,

when the API expects an array of structs, with unknown array length, one way to get
it working is:
- use IntPtr
- cast it while calling Marshal.PtrToStructure

The following class uses these techniques when calling NetWkstaGetInfo():

#if !NET11 && !NET20
#error "Missing version of .NET Framework (define one of NET11, NET20)"
#endif

using System;
using System.DirectoryServices;			// DirectoryEntry
using System.Management;
using System.Net;						// DNS
using System.Runtime.InteropServices;	// DllImport
using System.Threading;

using LP_Core;

namespace LP_Platform {
	/// <summary>
	/// LP_Workgroup scans the network for machines in a workgroup.
	/// It uses Active Directory on the host machine.
	/// </summary>
	public class LP_Workgroup {
		//====================================================================================
		// class constants
		//====================================================================================
		/// <summary>logging object</summary>
		protected static ILP_Environment env=LP_Environment.GetEnvironment();

		//====================================================================================
		// object variables
		//====================================================================================
		protected string name;

		public LP_Workgroup() : this(null) {}

		public LP_Workgroup(string name) {
			if (name==null) {
				name="<unknown>";
				IntPtr buf;
				int result=NetWkstaGetInfo(null, 100, out buf);
				env.log(0,"NetWkstaGetInfo result="+result);
				if (result==0) {
					WKSTA_INFO_100 info=(WKSTA_INFO_100)Marshal.PtrToStructure(buf, typeof(WKSTA_INFO_100));
					name=info.wki100_langroup;
					env.log(0,"LP_Workgroup: workgroup="+name);
				}
				if (buf!=IntPtr.Zero) NetApiBufferFree(buf);
				result=NetWkstaUserGetInfo(null, 1, out buf);
				env.log(0,"NetWkstaUserGetInfo result="+result);
				if (result==0) {
					WKSTA_USER_INFO_1 info=(WKSTA_USER_INFO_1)Marshal.PtrToStructure(buf, typeof(WKSTA_USER_INFO_1));
					string s1=info.wkui1_username;
					env.log(0,"LP_Workgroup: username="+s1);
					string s2=info.wkui1_logon_domain;
					env.log(0,"LP_Workgroup: logon domain="+s2);
					string s3=info.wkui1_oth_domains;
					env.log(0,"LP_Workgroup: other domains="+s3);
					string s4=info.wkui1_logon_server;
					env.log(0,"LP_Workgroup: logon server="+s4);
				}
				if (buf!=IntPtr.Zero) NetApiBufferFree(buf);
			}
			this.name=name;
		}

		public string Name {get {return name;}}

		public void Scan(LPW_ProgressMessage msg) {
			msg.Title="Searching machines in workgroup "+name;
			env.alert(msg);
			env.outputBegin();
			LP_CancellableThread thread=new LP_CancellableThread(msg);
			thread.Start(new LP_ObjectHandler(scanner), msg);
		}

		// Scan the active directory to find all computers in the workgroup,
		// and to identify their IP address(es) and MAC address(es).
		// inspired by http://www.codeproject.com/cs/internet/host_info_within_network.asp
		private void scanner(object arg) {
			LPW_ProgressMessage msg=arg as LPW_ProgressMessage;
			env.output("Searching machines in workgroup "+name);
			DirectoryEntry domainEntry=new DirectoryEntry("WinNT://"+name);
			domainEntry.Children.SchemaFilter.Add("computer");
			int NAMELEN=0;
			foreach(DirectoryEntry machine in domainEntry.Children) {
				int i=machine.Name.Length+1;
				if (i>NAMELEN) NAMELEN=i;
			}
			foreach(DirectoryEntry machine in domainEntry.Children) {
				msg.Progress(1);
				string machineName=machine.Name;
				string longname=machineName.PadRight(NAMELEN);
				env.log(0,"machineName="+machineName);
				IPHostEntry hostEntry=null;
				try {
#if NET11
					hostEntry=Dns.GetHostByName(machineName);
#elif NET20
					hostEntry=Dns.GetHostEntry(machineName);
#endif
				} catch(Exception exc) {
					env.output("    "+longname+" unable to connect ("+exc.Message+")");
				}
				if (hostEntry!=null) {
					IPAddress[] IPAS=hostEntry.AddressList;
					foreach(IPAddress IPA in IPAS) {
						msg.Progress(1);
						string IP=" IP="+IPA.ToString().PadRight(16);
						env.log(0, IP);
						byte[] ab=new byte[6];
						int len=ab.Length;
						// now get Physical Address; the simple way would be
						//int r=SendARP((int)IPA.Address, 0, ab, ref len);
						// but this is obsolete since .NET 2.0; hence:
						byte[] b=IPA.GetAddressBytes();
						int IPAadr=(((((b[0]<<8)|b[1])<<8)|b[2])<<8)|b[3];
						int r=SendARP(IPAadr, 0, ab, ref len);
						string MAC=" MAC="+BitConverter.ToString(ab, 0, 6);
						env.log(0, MAC);
						env.output("    "+longname+IP+MAC);
						longname=" ".PadRight(NAMELEN);
					}			
				}
			}
#if true
			env.output("All entries");
			domainEntry=new DirectoryEntry("WinNT://"+name);
			//domainEntry=new DirectoryEntry("WinNT://");
			//domainEntry.Children.SchemaFilter.Add("WLAN");
			DirectoryEntries children=domainEntry.Children;
			foreach(DirectoryEntry entry in domainEntry.Children) {
				try {
					env.output("    properties of "+entry.Name);
					// this code fails when NETDISK300 is switched on
					PropertyCollection props=entry.Properties;
					foreach(string s in props.PropertyNames) {
						object obj=props[s].Value;
						env.output("        "+s+"="+obj.ToString());
					}
				} catch(Exception exc) {
					env.output("        Exception: "+exc.Message);
				}
			}
#endif
			aha();
			env.outputEnd();
			//Thread.Sleep(5000);
			msg.Done(true);
		}

		public void aha() {
			env.output("PRINTERS");
			ManagementScope mgmtscope=new ManagementScope(@"\root\cimv2");
			mgmtscope.Connect();
			ManagementObjectSearcher objsearcher=new ManagementObjectSearcher(
				"Select * from Win32_Printer");
			foreach(ManagementObject printer in objsearcher.Get()) {
				//if(printer["WorkOffline"].ToString().Equals("true"))
				string printername=printer["Name"].ToString();
				env.output("    "+printername);
				foreach(PropertyData pd in printer.Properties) {
					env.output("        "+pd.Name+"="+pd.Value);
				}
			}
		}

		[DllImport("Netapi32.dll", ExactSpelling=true)]
		public static extern int NetWkstaGetInfo(
			string servername,			// LPWSTR
			int level,					// DWORD
			out IntPtr buf				// WKSTA_INFO_100 wksta	// LPBYTE*
			);

		[DllImport("Netapi32.dll", ExactSpelling=true)]
		public static extern int NetWkstaUserGetInfo(
			string reserved,			// LPWSTR
			int level,					// DWORD
			out IntPtr buf				// WKSTA_USER_INFO_1101 wksta	// LPBYTE*
			);

		[DllImport("Netapi32.dll", ExactSpelling=true)]
		public static extern int NetApiBufferFree(IntPtr buf);

		[DllImport("iphlpapi.dll", ExactSpelling=true)]
		public static extern int SendARP( int DestIP, int SrcIP, [Out] byte[] pMacAddr, ref int PhyAddrLen);

		[StructLayout(LayoutKind.Sequential)]
			public struct WKSTA_INFO_100 {
			public int wki100_platform_id;			// DWORD
			[MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
			public string wki100_computername;		// LPWSTR
			[MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
			public string wki100_langroup;			// LPWSTR
			public int wki100_ver_major;			// DWORD
			public int wki100_ver_minor;			// DWORD
		}

		[StructLayout(LayoutKind.Sequential)]
			public struct WKSTA_USER_INFO_1 {
			[MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
			public string wkui1_username;
			[MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
			public string wkui1_logon_domain;
			[MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
			public string wkui1_logon_server;
			[MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
			public string wkui1_oth_domains;
		}
	}
}


Smile | :)

Luc Pattyn

[My Articles]

QuestionC# Pin
rednexhex5-Apr-07 16:59
rednexhex5-Apr-07 16:59 
AnswerRe: C# Pin
Sathesh Sakthivel5-Apr-07 17:12
Sathesh Sakthivel5-Apr-07 17:12 
AnswerRe: C# Pin
Rudolf Jan6-Apr-07 0:30
Rudolf Jan6-Apr-07 0:30 
QuestionCall an Executable from C# with Administrative rights Pin
ke3p_up5-Apr-07 16:40
ke3p_up5-Apr-07 16:40 
AnswerRe: Call an Executable from C# with Administrative rights Pin
shrinerainxp5-Apr-07 21:26
shrinerainxp5-Apr-07 21:26 
GeneralRe: Call an Executable from C# with Administrative rights Pin
ke3p_up5-Apr-07 22:41
ke3p_up5-Apr-07 22:41 
Questionsockets question Pin
dino20945-Apr-07 15:45
dino20945-Apr-07 15:45 
QuestionGeneric collection classes with Hashtable Pin
sreecahitu5-Apr-07 13:38
sreecahitu5-Apr-07 13:38 
AnswerRe: Generic collection classes with Hashtable Pin
roel_v5-Apr-07 21:04
roel_v5-Apr-07 21:04 
AnswerRe: Generic collection classes with Hashtable Pin
roel_v5-Apr-07 21:07
roel_v5-Apr-07 21:07 
QuestionHow to empty a Text file? Pin
Khoramdin5-Apr-07 12:50
Khoramdin5-Apr-07 12:50 
AnswerRe: How to empty a Text file? Pin
Luc Pattyn5-Apr-07 12:57
sitebuilderLuc Pattyn5-Apr-07 12:57 
AnswerRe: How to empty a Text file? Pin
Rudolf Jan6-Apr-07 0:32
Rudolf Jan6-Apr-07 0:32 
Questionopen OR run File Pin
TAREQ F ABUZUHRI5-Apr-07 12:28
TAREQ F ABUZUHRI5-Apr-07 12:28 
AnswerRe: open OR run File Pin
Luc Pattyn5-Apr-07 12:37
sitebuilderLuc Pattyn5-Apr-07 12:37 
QuestionHex String Pin
AAKAra5-Apr-07 11:37
AAKAra5-Apr-07 11:37 
AnswerRe: Hex String Pin
Luc Pattyn5-Apr-07 12:44
sitebuilderLuc Pattyn5-Apr-07 12:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.