using System;
using System.Security.Principal;
WindowsIdentity wi = WindowsIdentity.GetCurrent();
WindowsPrincipal wp = new WindowsPrincipal(wi);
if (wp.IsInRole(WindowsBuiltInRole.Administrator))
{
//Console.WriteLine("Admin");
Console.WriteLine(WindowsBuiltInRole.Administrator.ToString());
}
Friday, July 31, 2009
Tuesday, July 14, 2009
Understand foreach statement
In order an class support foreach statement, it should support GetEnumerator(), MoveNext(), Reset(), Current() Method.
The interface IEnumerator has the method of MoveNext(), Reset(), Current(), and the interface IEnumerable has the method GetEnumerator().
The ICollection, IList interface are derived from IEnumerable and support GetEnumerator() method.
so,
public class MyClass: ICollection, IEnumerator
{}
MyClass A=new MyClass()
foreach(object a in A)....
So ICollection, IList only will not ensure that your collection class support foreach iteration.
We can write MoveNext(), Reset(), Current() in our custom class to support foreach:
class MyIterator
{
int _count;
public MyIterator(int count)
{
_count=count;
}
public string Current { get { return "Hello World!"; } }
public bool MoveNext()
{
if(_count-- > 0)
return true;
return false;
}
}
Class MyCollection
{
public MyIterator GetEnumerator() { return new MyIterator(3); }
}
class Program
{
static void Main(string[] args)
{
foreach (string value in new MyCollection())
Console.WriteLine(value);
}
}
The interface IEnumerator has the method of MoveNext(), Reset(), Current(), and the interface IEnumerable has the method GetEnumerator().
The ICollection, IList interface are derived from IEnumerable and support GetEnumerator() method.
so,
public class MyClass: ICollection, IEnumerator
{}
MyClass A=new MyClass()
foreach(object a in A)....
So ICollection, IList only will not ensure that your collection class support foreach iteration.
We can write MoveNext(), Reset(), Current() in our custom class to support foreach:
class MyIterator
{
int _count;
public MyIterator(int count)
{
_count=count;
}
public string Current { get { return "Hello World!"; } }
public bool MoveNext()
{
if(_count-- > 0)
return true;
return false;
}
}
Class MyCollection
{
public MyIterator GetEnumerator() { return new MyIterator(3); }
}
class Program
{
static void Main(string[] args)
{
foreach (string value in new MyCollection())
Console.WriteLine(value);
}
}
Tuesday, June 30, 2009
Use of BCP Utility
The syntax is:
bcp {[[database_name.][schema].]{table_name | view_name} | "query"}
{in | out | queryout | format} data_file
[-m max_errors] [-f format_file] [-x] [-e err_file]
[-F first_row] [-L last_row] [-b batch_size]
[-n] [-c] [-N] [-w] [-V (70 | 80 | 90 )]
[-q] [-C { ACP | OEM | RAW | code_page } ] [-t field_term]
[-r row_term] [-i input_file] [-o output_file] [-a packet_size]
[-S server_name[\instance_name]] [-U login_id] [-P password]
[-T] [-v] [-R] [-k] [-E] [-h"hint [,...n]"]
for examle:
Export:
run cmd:
bcp "select * from db.dbo.table where ..." queryout "\\..." -Ssever -Uuser -Ppass -c
or we can also use exec master..xp_cmdshell to run it.
if table use "out" option instead of queryout
bcp
Import:
declare @bcp as varchar(200)
set @bcp = 'bcp DBname.dbo.tablename in \\server\filepath\tmpTestFile.txt -c -t : -r # -Sserver -Ulogin -Ppassword -F2
exec master..xp_cmdshell @bcp
or:
exec master.dbo.xp_cmdshell 'bcp AdventureWorks.dbo.test_import in c:\temp\employee.txt -S localhost\SQLExpress -T -c -t ""'
For Example, we can write C# code:
using System;
using System.Diagnostics;
using (Process p = new Process())
{
p.StartInfo.FileName = "bcp";
p.StartInfo.Arguments = "databasename .dbo.tablename in myoutput.txt -Sservername -Usa -Ppass -c -t| -F2";
p.Start();
p.WaitForExit();
}
//Note -t| is delimeter is pipe, -F2 is import from line 2
We can specify the output txt format when use bcp ... out in command line.
When input to db from a txt file, we can write the format file by ourselves:
For example, we have a pipe delimited txt file with txt format like the following.
(file name is C:\mybcp.txt)
ID|Name|Age|Sex
1|Jerry|30|Male
2|Lina|15|Female
3|Jay|88|Male
4|Eric|30|NoRecord
5|Someone|40|NoRecord
We can write the format file (C:\mybcptest.fmt) use txt pad:
9.0
4
1 SQLCHAR 0 100 "|" 1 ID SQL_Latin1_General_CP1_CI_AS
2 SQLCHAR 0 100 "|" 2 DBColumn1 SQL_Latin1_General_CP1_CI_AS
3 SQLCHAR 0 100 "|" 3 Age SQL_Latin1_General_CP1_CI_AS
4 SQLCHAR 0 100 "\r\n" 4 SourceID SQL_Latin1_General_CP1_CI_AS
Notice the 9.0 is the bcp version, we can use command bcp -v to check the bcp version.
4 means the columns in txt files
After create the format files, we can impot the txt files to database, use command:
bcp mydb.dbo.MyClassmates in C:\mybcp.txt -SMyServer -USa -Ppass -fC:\mybcptest.fmt
bcp {[[database_name.][schema].]{table_name | view_name} | "query"}
{in | out | queryout | format} data_file
[-m max_errors] [-f format_file] [-x] [-e err_file]
[-F first_row] [-L last_row] [-b batch_size]
[-n] [-c] [-N] [-w] [-V (70 | 80 | 90 )]
[-q] [-C { ACP | OEM | RAW | code_page } ] [-t field_term]
[-r row_term] [-i input_file] [-o output_file] [-a packet_size]
[-S server_name[\instance_name]] [-U login_id] [-P password]
[-T] [-v] [-R] [-k] [-E] [-h"hint [,...n]"]
for examle:
Export:
run cmd:
bcp "select * from db.dbo.table where ..." queryout "\\..." -Ssever -Uuser -Ppass -c
or we can also use exec master..xp_cmdshell to run it.
if table use "out" option instead of queryout
bcp
Import:
declare @bcp as varchar(200)
set @bcp = 'bcp DBname.dbo.tablename in \\server\filepath\tmpTestFile.txt -c -t : -r # -Sserver -Ulogin -Ppassword -F2
exec master..xp_cmdshell @bcp
or:
exec master.dbo.xp_cmdshell 'bcp AdventureWorks.dbo.test_import in c:\temp\employee.txt -S localhost\SQLExpress -T -c -t ""'
For Example, we can write C# code:
using System;
using System.Diagnostics;
using (Process p = new Process())
{
p.StartInfo.FileName = "bcp";
p.StartInfo.Arguments = "databasename .dbo.tablename in myoutput.txt -Sservername -Usa -Ppass -c -t| -F2";
p.Start();
p.WaitForExit();
}
//Note -t| is delimeter is pipe, -F2 is import from line 2
We can specify the output txt format when use bcp ... out in command line.
When input to db from a txt file, we can write the format file by ourselves:
For example, we have a pipe delimited txt file with txt format like the following.
(file name is C:\mybcp.txt)
ID|Name|Age|Sex
1|Jerry|30|Male
2|Lina|15|Female
3|Jay|88|Male
4|Eric|30|NoRecord
5|Someone|40|NoRecord
We can write the format file (C:\mybcptest.fmt) use txt pad:
9.0
4
1 SQLCHAR 0 100 "|" 1 ID SQL_Latin1_General_CP1_CI_AS
2 SQLCHAR 0 100 "|" 2 DBColumn1 SQL_Latin1_General_CP1_CI_AS
3 SQLCHAR 0 100 "|" 3 Age SQL_Latin1_General_CP1_CI_AS
4 SQLCHAR 0 100 "\r\n" 4 SourceID SQL_Latin1_General_CP1_CI_AS
Notice the 9.0 is the bcp version, we can use command bcp -v to check the bcp version.
4 means the columns in txt files
After create the format files, we can impot the txt files to database, use command:
bcp mydb.dbo.MyClassmates in C:\mybcp.txt -SMyServer -USa -Ppass -fC:\mybcptest.fmt
Monday, June 22, 2009
Debug and Trace
Calling Trace class executes in both debug and release build type, while using Debug only execute in debug mode.
So the following code in Debug and Release build type has different output:
using System;
using System.Diagnostics;
Debug.Listeners.Add(new ConsoleTraceListener());
Debug.AutoFlush = true;
Debug.WriteLine("This is Debug");
Trace.WriteLine("This is Trace");
Console.WriteLine("This is Console");
In Debug build type, output is:
This is Debug
This is Trace
This is Console
In Release build type, output is
This is Debug
This is Console
So the following code in Debug and Release build type has different output:
using System;
using System.Diagnostics;
Debug.Listeners.Add(new ConsoleTraceListener());
Debug.AutoFlush = true;
Debug.WriteLine("This is Debug");
Trace.WriteLine("This is Trace");
Console.WriteLine("This is Console");
In Debug build type, output is:
This is Debug
This is Trace
This is Console
In Release build type, output is
This is Debug
This is Console
Wednesday, June 17, 2009
Reading and Writing Event Log
In my computer, right click manage, we can see the events logs by event viewer. The majory types of the event log are: system, security and application types.
In order an application program writing events to the Event log, the application need to be register as an Evnet Source. We can use Regedit.exe to register manually: locate the registry subkey: HKEY_LOCAL_MACHINE\SYSTEM|CurrentControlSet\Services\Eventlog\Application, right click the Application subkey, and click New and type the event source name.
We can also use EventLog object to register event source, read and write to event logs. Reference the name space, System.Diagnostics, the code can be like:
1. Register Application EventLog Source:
if(!EventLog.SourceExists("My Application"))
EventLog.CreateEventSource("My Application","Application");
or:
if(!EventLog.Exists("My Log"))
EventLog.CreateEventSource("My App","My Log");
2. Log Events
We can use EventLog.WriteEntry() method and specify the message, type, eventID,category, rawData. The code sample like:
EventLog myLog=new EventLog("Application");
//Notice this parameter can also be "System",
//"Security", so we can also read/write
//systme and security logs.
myLog.Source="My Application";
myLog.WriteEntry("Could not connect",EventLogEntryType.Error, 1001,1);
3. Read Events
We can also create EventLog instance and access the EventLog.Entries Collection:
EventLog myLog=new EventLog("Application");
foreach(EventLogEntry entry in myLog.Entries)
Console.WriteLine(entry.Message);
In order an application program writing events to the Event log, the application need to be register as an Evnet Source. We can use Regedit.exe to register manually: locate the registry subkey: HKEY_LOCAL_MACHINE\SYSTEM|CurrentControlSet\Services\Eventlog\Application, right click the Application subkey, and click New and type the event source name.
We can also use EventLog object to register event source, read and write to event logs. Reference the name space, System.Diagnostics, the code can be like:
1. Register Application EventLog Source:
if(!EventLog.SourceExists("My Application"))
EventLog.CreateEventSource("My Application","Application");
or:
if(!EventLog.Exists("My Log"))
EventLog.CreateEventSource("My App","My Log");
2. Log Events
We can use EventLog.WriteEntry() method and specify the message, type, eventID,category, rawData. The code sample like:
EventLog myLog=new EventLog("Application");
//Notice this parameter can also be "System",
//"Security", so we can also read/write
//systme and security logs.
myLog.Source="My Application";
myLog.WriteEntry("Could not connect",EventLogEntryType.Error, 1001,1);
3. Read Events
We can also create EventLog instance and access the EventLog.Entries Collection:
EventLog myLog=new EventLog("Application");
foreach(EventLogEntry entry in myLog.Entries)
Console.WriteLine(entry.Message);
Thursday, May 14, 2009
Use ServiceController to Start or Stop a Service
Reference the System.ServiceProcess.dll first, and use the namespace System.ServiceProcess:
We write the code sample as the following:
using System;
using System.ServiceProcess;
class Program
{
static void Main(string[] args)
{
ServiceController sc = new ServiceController("Server");
string svStatus = sc.Status.ToString();
if (svStatus == "Stopped")
{ sc.Start(); }
if (svStatus == "Running")
{ sc.Stop(); }
}
}
We write the code sample as the following:
using System;
using System.ServiceProcess;
class Program
{
static void Main(string[] args)
{
ServiceController sc = new ServiceController("Server");
string svStatus = sc.Status.ToString();
if (svStatus == "Stopped")
{ sc.Start(); }
if (svStatus == "Running")
{ sc.Stop(); }
}
}
Tuesday, May 5, 2009
Use ThreadPool to Queue Work Items
Example:
using System.Threading;
static void Main(string[] args)
{
WaitCallback callback=new WaitCallback(SomeMethod);
ThreadPool.QueueUserWorkItem(callback, "Hi");
ThreadPool.QueueUserWorkItem(callback, "Good Morning");
ThreadPool.QueueUserWorkItem(callback, "Good Bye");
}
static void SomeMethod(object state)
{
string greetingText=(string)state;
Console.Write(geetingText);
}
The step here is Use WaitCallBack delegate to call SomeMethod() and use ThreadPool static method to queue up serverl calls, parameter/object can be passed.
using System.Threading;
static void Main(string[] args)
{
WaitCallback callback=new WaitCallback(SomeMethod);
ThreadPool.QueueUserWorkItem(callback, "Hi");
ThreadPool.QueueUserWorkItem(callback, "Good Morning");
ThreadPool.QueueUserWorkItem(callback, "Good Bye");
}
static void SomeMethod(object state)
{
string greetingText=(string)state;
Console.Write(geetingText);
}
The step here is Use WaitCallBack delegate to call SomeMethod() and use ThreadPool static method to queue up serverl calls, parameter/object can be passed.
Subscribe to:
Posts (Atom)