Main |
How to add an event source |
|
By using System.Diagnostics namespace (that provides classes to interact with system processes, event logs,
and performance counters) we have access to:
-
EventLog - functionality to write to event logs, read event log entries, and create and delete event logs and event sources on the network.
- EventLogEntry - single record in the event log.
By using EventLog, we can interact with Windows event logs - access or customize Windows event logs, which record information about important software or hardware events.
Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAdd.Click
Dim objApplicationLog As EventLog
Dim SourceName As String
SourceName = txtSourceName.Text
If SourceName = "" Then
MessageBox.Show("Enter Event Source Name", _
"Add Event Source", _
MessageBoxButtons.OK, _
MessageBoxIcon.Asterisk)
txtSourceName.Focus()
Exit Sub
End If
objApplicationLog = New EventLog()
If Not EventLog.SourceExists(SourceName) Then
EventLog.CreateEventSource(SourceName, SourceName)
objApplicationLog.Source = SourceName
objApplicationLog.WriteEntry(SourceName, "Source Added...")
Else
MessageBox.Show("Event Source Name [" & SourceName & "] already exists!", _
"Add Event Source", _
MessageBoxButtons.OK, _
MessageBoxIcon.Exclamation)
End If
End Sub
Where:
- EventLog.Source - Gets or sets the source name to register and use when writing to the event log.
- EventLog.SourceExists() - Searches a computer's registry for a given event source -
whether an event source is registered on the computer (local or remote).
- EventLog.CreateEventSource() - Establishes an application as able to write event information to a particular log on the system.
If you do not specify a log name when calling CreateEventSource(),
your source will be registered to the Application log.
If you specify the name of a log that does not exist, the system creates a custom event log for you and
registers the Source to that log.
- EventLog.WriteEntry() - Writes an entry in the event log.
In this example, using objApplicationLog.WriteEntry(SourceName, "Source Added..."),
application Writes an information type entry with the "Source Added..." message text to the event log,
using SourceName as the specified registered event source.
|
|
|
|
How to write to Windows Event Log:
In this example, by using System.Diagnostics namespace, application can write to EventLog - generate entries in Windows Event Log.
Application can only receive event notifications when entries are written on the local computer
and cannot receive notifications for entries written on remote computers.
()
When form loads, application populates list of available Windows Event Log names on a computer and Event Types:
private void frmTestWatcher_Load(object sender, EventArgs e)
{
//populate with event log names:
foreach (EventLog eventLog in EventLog.GetEventLogs())
{ cboEventLogList.Items.Add(eventLog.Log ); }
cboEventTypeList.Items.Add("Information");
cboEventTypeList.Items.Add("Error");
cboEventTypeList.Items.Add("Warning");
}
..., then, upon user clicking on "Generate Entry" button:
private void cmdGenerateEntry_Click(object sender, EventArgs e)
{
//
//... check user input ...
//
//generate event:
EventLog eventLog = new EventLog(cboEventLogList.Text);
eventLog.Source = txtSourceName.Text;
eventLog.WriteEntry(txtMessage.Text, ConvertEventType(cboEventTypeList.Text));
eventLog.Close();
}
where ConvertEventType() function:
private EventLogEntryType ConvertEventType(string eventType)
{
switch (cboEventTypeList.Text)
{
case "Information": return EventLogEntryType.Information; break;
case "Error": return EventLogEntryType.Error; break;
case "Warning": return EventLogEntryType.Warning; break;
}
return EventLogEntryType.Information;
}
|
|
How to monitor and react to event log changes
In this example, by using System.Diagnostics namespace, application "attaches" itself to monitor for EventLog changes.
EventLog.EntryWritten event - Occurs when an entry is written to an event log on the local computer.
Application can only receive event notifications when entries are written on the local computer
and cannot receive notifications for entries written on remote computers.
()
To get event notifications, application sets EnableRaisingEvents to true.
|
|
Private m_ApplicationLog As EventLog
Private m_SystemLog As EventLog
...
m_ApplicationLog = New EventLog()
m_ApplicationLog.Log = "Application"
AddHandler m_ApplicationLog.EntryWritten, AddressOf ApplicationLog_OnEntryWritten
m_ApplicationLog.EnableRaisingEvents = True
m_SystemLog = New EventLog()
m_SystemLog.Log = "System"
AddHandler m_SystemLog.EntryWritten, AddressOf SystemLog_OnEntryWritten
m_SystemLog.EnableRaisingEvents = True
...
Public Sub ApplicationLog_OnEntryWritten(ByVal [source] As Object, ByVal e As EntryWrittenEventArgs)
Try
'.... handle Application event log change
Catch err As Exception
End Try
End Sub
Public Sub SystemLog_OnEntryWritten(ByVal [source] As Object, ByVal e As EntryWrittenEventArgs)
Try
'.... handle System event log change
'
Catch err As Exception
End Try
End Sub
Where:
AddHandler m_ApplicationLog.EntryWritten, AddressOf ApplicationLog_OnEntryWritten
identifies the method that will handle the EventLog change event.
ApplicationLog_OnEntryWritten() - The event handler is called whenever the EventLog change event occurs.
|
|
|
|
How to check for Shared Open Files - WMI connections made easy in .NET - Get System Information Using WMI in .NET - NET Framework's Windows Management Instrumentation (WMI) services allows ...:
(see Win32_ConnectionShare class)
|
|
Using Computer Management management console:
Code bellow produces:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim query As ManagementObjectSearcher = _
New ManagementObjectSearcher(New SelectQuery("Win32_ConnectionShare"))
Dim management_object As ManagementObject
For Each management_object In query.Get()
Dim objAntecedent As ManagementObject = _
New ManagementObject(management_object("Antecedent").ToString)
Dim objDependent As ManagementObject = _
New ManagementObject(management_object("Dependent").ToString)
MessageBox.Show(management_object("Antecedent") & vbCrLf & _
management_object("Dependent") & vbCrLf & _
"Open Files : [" & objDependent("NumberOfFiles").ToString & "]" & vbCrLf & _
"Local Path : [" & objAntecedent("Path") & "]")
Next
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim objWindows As Object = GetObject("WinNT://./LanManServer")
Dim objRsc As Object
For Each objRsc In objWindows.Resources
MessageBox.Show(objRsc.Path)
Next
End Sub
|
|
|
|
How to enumerate running processes using WMI and Win32_Process class - WMI connections made easy in .NET - Get System Information Using WMI in .NET - NET Framework's Windows Management Instrumentation (WMI) services allows ...:
()
|
|
Using Win32_Process and WMI:
Win32_Process Class
The Win32_Process WMI class represents a process on an operating system.
class Win32_Process : CIM_Process
{
string Caption;
string CommandLine;
string CreationClassName;
datetime CreationDate;
string CSCreationClassName;
string CSName;
string Description;
string ExecutablePath;
uint16 ExecutionState;
string Handle;
uint32 HandleCount;
datetime InstallDate;
uint64 KernelModeTime;
uint32 MaximumWorkingSetSize;
uint32 MinimumWorkingSetSize;
string Name;
string OSCreationClassName;
string OSName;
uint64 OtherOperationCount;
uint64 OtherTransferCount;
uint32 PageFaults;
uint32 PageFileUsage;
uint32 ParentProcessId;
uint32 PeakPageFileUsage;
uint64 PeakVirtualSize;
uint32 PeakWorkingSetSize;
uint32 Priority;
uint64 PrivatePageCount;
uint32 ProcessId;
uint32 QuotaNonPagedPoolUsage;
uint32 QuotaPagedPoolUsage;
uint32 QuotaPeakNonPagedPoolUsage;
uint32 QuotaPeakPagedPoolUsage;
uint64 ReadOperationCount;
uint64 ReadTransferCount;
uint32 SessionId;
string Status;
datetime TerminationDate;
uint32 ThreadCount;
uint64 UserModeTime;
uint64 VirtualSize;
string WindowsVersion;
uint64 WorkingSetSize;
uint64 WriteOperationCount;
uint64 WriteTransferCount;
};
where
Caption - Short description of an object�a one-line string.
ExecutablePath - Path to the executable file of the process. (Example: C:\WINDOWS\EXPLORER.EXE)
ProcessId - Global process identifier that is used to identify a process.
The value is valid from the time a process is created until it is terminated.
public static ArrayList GetProcessList()
{
ArrayList processList = new ArrayList();
SelectQuery selectQuery = new SelectQuery("select * from Win32_Process");
using(ManagementObjectSearcher searcher = new ManagementObjectSearcher(selectQuery))
{
ManagementObjectCollection processes = searcher.Get();
foreach(ManagementObject process in processes)
{
if (process.Properties["ExecutablePath"].Value != null)
{
string processCaption = process.Properties["Caption"].Value.ToString();
string processExePath = process.Properties["ExecutablePath"].Value.ToString();
//int processID = Convert.ToInt32(process.Properties["ProcessId"].Value.ToString());
string processID = process.Properties["ProcessId"].Value.ToString();
processList.Add(new ProcessData(processCaption, processExePath, processID));
}
}
}
processList.Sort(new ProcessDataComparer());
return processList;
}
where supporting classes are:
//ProcessData class
class ProcessData
{
public string Caption = "";
public string ExePath = "";
public string ProcessID = "0";
public ProcessData(string processCaption, string processExePath, string processID)
{
Caption = processCaption;
ExePath = processExePath;
ProcessID = processID;
}
}
//for sorting:
class ProcessDataComparer : System.Collections.IComparer
{
public int Compare(Object processData1, Object processData2)
{
return String.Compare(((ProcessData)processData1).Caption, ((ProcessData)processData2).Caption);
}
}
|
|
NetworkCredential - How to Connect to "Secured" web service - Web Service requires authentication:
Web service's virtual directory under IIS can be configured with Basic Authentication or
Integrated Windows Authentication.
- With Basic Authentication -
the caller must configure the proxy and provide credentials in the form of a user name and password.
The proxy then transmits them with each Web service request through that proxy.
The credentials are transmitted in plaintext and therefore you should only use Basic authentication with SSL.
- With Integrated Windows Authentication - the caller is authenticated with/by
Kerberos or NTLM authentication depending on the client and server environment.
Accessing secure web services/web pages require use of NetworkCredential class.
NetworkCredential (system.Net namespace) class provides credentials for password-based authentication
schemes such as Basic, Digest, NTLM, and Kerberos authentication.
...
Dim objNetworkCredential As System.Net.NetworkCredential = _
New System.Net.NetworkCredential(NetworkUserName, _
NetworkUserPwd, _
NetworkDomain)
objSQLWebServiceManager = New siccolo.Siccolo()
objSQLWebServiceManager.Credentials = objNetworkCredential
objSQLWebServiceManager.PreAuthenticate = True
...
But, if you're using web application
(such as Siccolo Web Client for PocketPC, SmartPhone, Blackberry, iPhone, Palm, Symbian),
and you need connect to a "secured" web service with Integrated Windows or Basic authentication set, then on your web client
...
objSQLWebServiceManager = New siccolo.Siccolo()
objSQLWebServiceManager.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials
objSQLWebServiceManager.PreAuthenticate = True
...
Because web browser will prompt user for a domain/user name/password if needed.
|
|
|
|
Open Dataset from Text File - How to Connect Dataset to a Text File:
Using .NET Dataset we can connect to Text File (with using schema.ini) and load data from text file into ListView or GridView:
...
string textFilePath = @"c:\test_to_load.txt";
DataSet dataTextFile = new DataSet("textfile");
if ( ! LoadTextFile ( textFilePath, dataTextFile, out errorInfo) )
{
MessageBox.Show("Failed to load text file:\n" + errorInfo,
"Load Text File");
return;
}
else
{
MessageBox.Show("File Loaded:\nTables:" + dataTextFile.Tables.Count.ToString()
+ "\nRows:" + dataTextFile.Tables[0].Rows.Count.ToString() ,
"Load Text File");
}
...
where LoadTextFile() method:
private bool LoadTextFile( string textFilePath, DataSet dataToLoad, out string errorInfo )
{
errorInfo = String.Empty;
try
{
string textFileFolder = ( new System.IO.FileInfo (textFilePath)).DirectoryName;
string textConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + textFileFolder + ";" +
"Extended Properties=\"text;\";" ;
//from using System.Data.OleDb:
OleDbConnection textConnection = new OleDbConnection (textConnectionString);
textConnection.Open();
textFilePath = (new System.IO.FileInfo(textFilePath)).Name;
string selectCommand = "select * from " + textFilePath;
//open command:
OleDbCommand textOpenCommand = new OleDbCommand(selectCommand);
textOpenCommand.Connection = textConnection;
OleDbDataAdapter textDataAdapter = new OleDbDataAdapter( textOpenCommand );
int rows = textDataAdapter.Fill(dataToLoad);
textConnection.Close();
textConnection.Dispose();
return true;
}
catch (Exception ex_load_text_file)
{
errorInfo = ex_load_text_file.Message;
return false;
}
}
|
|
showModalDialog problem - javascript problem - open webform with client script but cant close it...
When you use showModalDialog() to open a "pop-up" dialog window, and then trying to use JavaScript method within the "pop-up" window,
browser opens a new window with "javascript:" as an URL address...
Using <base target="_self" /> and <iframe> element helps .
For example, in your "parent" page:
...
<body style="width:400px">
...
...
<script language=javascript>
function open_appointment_list(client_id)
{
var url = 'appointment_list_frame.aspx?clientid=' + client_id;
var settings = 'dialogHeight:430px;dialogWidth:650px;status=no;'
var result = window.showModalDialog(url,null,settings);
while (result == 1 )
{
result = window.showModalDialog(url,null,settings);
}
}
</script>
...
...
| |