Posted by: sandeep | May 22, 2009

WMI query to get files from a folder

just change following ObjectQuery part in code of WMI Process

This query will get all dlls in c:\windows\system32 but not in subdirectories

System.Management.ObjectQuery oQuery = new
System.Management.ObjectQuery(“Select
* from CIM_DataFile where Drive=’c:’ and Path=’\\\\windows\\\\system32\\\\’ and
Extension=’dll’”
);

Note the number of  ‘\’ in query variable Path otherwise you’ll get the error as:

An unhandled exception of type ‘System.Management.ManagementException’ occurred in System.Management.dll

Additional information: Invalid query

Even though ProcessStartInfo has one more parameter for arguments it was not working but using following code it works fine.

System.Diagnostics.ProcessStartInfo psinfo;

System.Diagnostics.Process pro = new System.Diagnostics.Process ();

psinfo = new System.Diagnostics.ProcessStartInfo(“cmd”,“/c chkdsk c: “);


pro.StartInfo = psinfo;

pro.Start ();

Once I need to write a code which has scenario like depending on various selection call, the specific function.
There were more than 40 functions from which only one will be called. All these 40 function were defined in different classes.
Easy to write normal code in if-else loops but got second opinion.

Reflection is the best way suggested by a techie friend for this case and it worked gr8. Here the function names can be retrieved from web.config file, no need to recompile if the name of the function to call is changed

The following function accepts the name of the class which has the function defined in it, then name of the function to execute and the client’s name. I am assuming that the types or classes are defined in the same assembly. If it is different then dynamicExecution function can be further parameterized for Path\name of the assembly. Also the function parameters’ array can parameterized if the functions to execute have different number of parameters.

Also this answers, How to create instance of class from string

Here is the code………..

private void btnExecute_Click(object sender, System.EventArgs e)
{

// If the user is Japanese
dynamicExecution( “MyNameSpace.MyClass”, “OhaioGozaimasu”,”SayuriSan”);

// If the user is English
dynamicExecution( “MyNameSpace.MyClass”, “GoodMorning”,”Alice”);

// If the user is Indian
dynamicExecution( “MyNameSpace.MyClass35″, “Suprabhat”,”3sha”);
}

private void dynamicExecution(string ClassName,string FunctionName, string ClientName )
{
// Following code creates the instance of class dynamically and executes the function

// You will need the instance of assembly which has the class to be instatiated

// System.Reflection.Assembly.LoadFrom() this also can be used

System.Reflection.Assembly assembly = System.Reflection.Assembly.GetEntryAssembly();

Object [] para = new Object[1]; // array for parameters of the function

para[0]= ClientName ; // single parameter in this case

// Create instance of the class Dynamically

// CreateInstance requires FullPath i.e. with root namespace and sub namespaces of the type

object dynMyClass = assembly.CreateInstance(ClassName);

// Well this is easy!

dynMyClass.GetType().GetMethod(FunctionName).Invoke(dynMyClass,para);

}



// This is a sample class
class MyClass
{
public MyClass(){}
public void GoodMorning(string name)
{
MessageBox.Show(“Good Morning ” + name + “!”);
}
public void OhaioGozaimasu(string name)
{
MessageBox.Show(name + “, Ohaio Gozaimasu!”);
}
}

The WMI technique is very powerful for system related activities. They provide operating system interface.

The following code can be used to close instance of visual studio on remote machine provided you have access to it. It kills the instance of it. This way you can make your colleague frustrated.

// connection will required user having access to remote m/c

System.Management.ConnectionOptions
conO =
new System.Management.ConnectionOptions();

conO.Username = "DOMAIN\\sandeep";
conO.Password =
"*******";

System.Management.ManagementScope
oMs =
new System.Management.ManagementScope(@"\\<remoteMachineName>\root\cimv2",conO);

//get all the Processes running on remote m/c

System.Management.ObjectQuery oQuery = new System.Management.ObjectQuery("Select
* from Win32_Process"
);

//Execute the query

System.Management.ManagementObjectSearcher oSearcher = new System.Management.ManagementObjectSearcher(oMs,oQuery);

//Get the results

System.Management.ManagementObjectCollection oReturnCollection = oSearcher.Get();

//loop through found process and terminate

foreach (System.Management.ManagementObject oReturn in oReturnCollection)
{
string[] argList = new string[] { string.Empty };

//Name of process
if (oReturn["Name"].ToString().ToLower() == "devenv.exe")
{
object[] obj = new object[] { 0 };
oReturn.InvokeMethod(
"Terminate", obj);
}
}

Posted by: sandeep | April 8, 2008

Hey, Scripting Guy!

The Following Table Summarize the various settings required to implement impersonation in ASP.NET

Anonymous Access
(IIS)
Authentication Type
(IIS)
impersonate (Web.config) Impersonated User
WindowsIdentity.GetCurrent().Name

Allowed NA false Machine_name\ASPNET
Allowed NA true Machine_name\IUSR_Machine_name
Not Allowed Integrated false Machine_name\ASPNET
Not Allowed Integrated true Domain\User
Not Allowed Basic false Machine_name\ASPNET
Not Allowed Basic true Login box will appear to enter
username & password. Grant access only for valid username-password.
Note :
ü If valid username/password is provided in web config, in identity tag, then
provided userid will be final impersonated user.

ü
Integrated authentication type will always override the Basic.
Posted by: sandeep | June 7, 2007

Special accounts in windows

Name Full Name Description
IUSR_machineName
Internet Guest Account Built-in account for anonymous
access to Internet Information Services
IWAM_machineName
Launch IIS
Process Account
Built-in account for Internet
Information Services to start out of process applications
ASPNET ASP.NET
Machine Account
Account used for running the
ASP.NET worker process (aspnet_wp.exe)

Following code retreives the parameters sent. Also we can use page’s Request object directly which exposes most of the properties but not all like username, password. The password value is set only when application uses IIS basic authentication.

string[] allKeys = this.Request.Params.AllKeys;
int count = allKeys.Length-1;
while( count >= 0)
{
Response.Write(allKeys[count]+ ” = “+
this.Request.Params[allKeys[count]].ToString() + System.Web.UI.Html32TextWriter.TagLeftChar + “br”+System.Web.UI.Html32TextWriter.TagRightChar);
count–;
}

The output is as follows (useful parameters are marked in bold)

HTTP_USER_AGENT = Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705;
.NET CLR 1.1.4322)
HTTP_HOST = localhost
HTTP_ACCEPT_LANGUAGE = en-us
HTTP_ACCEPT_ENCODING = gzip, deflate
HTTP_ACCEPT = */*
HTTP_CONNECTION = Keep-Alive
URL = /WebApplication1/WebForm1.aspx
SERVER_SOFTWARE = Microsoft-IIS/5.1
SERVER_PROTOCOL = HTTP/1.1
SERVER_PORT_SECURE = 0
SERVER_PORT = 80
SERVER_NAME = localhost
SCRIPT_NAME = /WebApplication1/WebForm1.aspx
REQUEST_METHOD = GET
REMOTE_PORT = 1052
REMOTE_HOST = 127.0.0.1
REMOTE_ADDR = 127.0.0.1
QUERY_STRING =
PATH_TRANSLATED = c:\inetpub\wwwroot\WebApplication1\WebForm1.aspx
PATH_INFO = /WebApplication1/WebForm1.aspx

LOCAL_ADDR = 127.0.0.1
INSTANCE_META_PATH = /LM/W3SVC/1
INSTANCE_ID = 1
HTTPS_SERVER_SUBJECT =
HTTPS_SERVER_ISSUER =
HTTPS_SECRETKEYSIZE =
HTTPS_KEYSIZE =
HTTPS = off
GATEWAY_INTERFACE = CGI/1.1
CONTENT_TYPE =
CONTENT_LENGTH = 0
CERT_SUBJECT =
CERT_SERVER_SUBJECT =
CERT_SERVER_ISSUER =
CERT_SERIALNUMBER =
CERT_SECRETKEYSIZE =
CERT_KEYSIZE =
CERT_ISSUER =
CERT_FLAGS =
CERT_COOKIE =
REMOTE_USER =
LOGON_USER =
AUTH_PASSWORD =
AUTH_USER =
AUTH_TYPE =
APPL_PHYSICAL_PATH = c:\inetpub\wwwroot\WebApplication1\

APPL_MD_PATH = /LM/W3SVC/1/Root/WebApplication1
ALL_RAW = Connection: Keep-Alive Accept: */* Accept-Encoding: gzip, deflate
Accept-Language: en-us Host: localhost User-Agent: Mozilla/4.0 (compatible;
MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)
ALL_HTTP = HTTP_CONNECTION:Keep-Alive HTTP_ACCEPT:*/*
HTTP_ACCEPT_ENCODING:gzip, deflate HTTP_ACCEPT_LANGUAGE:en-us
HTTP_HOST:localhost HTTP_USER_AGENT:Mozilla/4.0 (compatible; MSIE 6.0; Windows
NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)
ASP.NET_SessionId = vc51gu45yek45zecmsjezf45

Posted by: sandeep | May 11, 2007

How to compare versions of two Assemblies?

We can make use of System.Version class.

int check;

System.Version version = new Version(“1.1.234.999″);

check = version.CompareTo(new Version(“1.1.234.998″)); //check will be 1

check = version.CompareTo(new Version(“1.1.234.999″)); //check will be 0

check = version.CompareTo(new Version(“1.1.234.1000″)); //check will be -1

Posted by: sandeep | February 15, 2007

Hello World! Not everything in life is WYSIWYG

I am Sandeep Bharati from Pune currently with TCS. Sandeep Bharti

technologies: c#,vb.net, ASP.NET, web services, XML, .Net Framework, WMI scripting.


Drop a comment if you find this useful or have any doubt!!

Categories