Event Log message entry format - c#

Im trying to get entries from Event Viewer. Im getting data now, but theres ome parsin I need to know if possible. First the example:
Console.WriteLine("[Index]\t\t" + entry.Index +
"\n[EventID]\t" + entry.InstanceId +
"\n[TimeWritten]\t" + entry.TimeWritten +
"\n[MachineName]\t" + entry.MachineName +
"\n[Source]\t" + entry.Source +
"\n[UserName]\t" + entry.UserName +
"\n[Message]\t" + entry.Message +
"\n---------------------------------------------------\n");
}
OUTPUT
[EventID] 4719
[TimeWritten] 8/20/2014 5:31:46 PM
[MachineName] pcname
[Source] Microsoft-Windows-Security-Auditing
[UserName]
[Message] System audit policy was changed.
Subject:
**Security ID:** S-1-5-18
Account Name: pcname$
**Account Domain:** WORKGROUP
Logon ID: 0x3e7
Audit Policy Change:
Category: %%8273
Subcategory: %%12544
Subcategory GUID: {0CCE9215-69AE-11D9-BED3-505054503030}
Changes: %%8449, %%8451
Now what I want is to get particular pieces of information on the message like
**Security ID:** **Account Domain:**.
Theres some method that allow me to extract only this from [message]??

You can try this:
string[] mMessage = e.Entry.Message.Split(new string[] { "\r\n" }, StringSplitOptions.None);
for (i=0; i<=mMessage.count; i++)
{
if (mMessage[i] == "Account Domain")
{
Console.WriteLine(mMessage[i]);
}
}

Related

Adding users to ZKTeco access door using Push SDK

I'm trying to add users to the Door Access Control Device: "inBio 260"
I'm told I need to use the Push/Pull SDK to do that.
public bool AddUser(User u) {
return axCZKEM1.SSR_SetDeviceData(machineNumber, "user", u + "\r\n", "");
}
class User {
...
public override string ToString()
{
return
"CardNo=" + ID + "\t" +
"Pin=" + Pin + "\t" +
"Name=" + Name + "\t" +
"Password=" + Password + "\t" +
"StartTime=" + StartTime + "\t" +
"EndTime=" + EndTime;
}
}
public bool AddFingerprint(Fingerprint p)
{
return
IsPinValid(p.Pin) &&
p.Template != null &&
p.Template.Length > 100 &&
axCZKEM1.SSR_SetDeviceData(machineNumber, "templatev10", p + "\r\n", "");
}
}
class Fingerprint {
...
public override string ToString()
{
int size = Convert.FromBase64String(Template).Length;
return
"Size=" + size +
"\tPin=" + Pin +
"\tFingerID=" + FingerID +
"\tValid=1\tTemplate=" + Template +
"\tEndTag=" + EndTag;
}
}
I use "ZKAccess 3.5" to check and I find the users I added and everything seems fine.
But suddenly the machine will report 0 valid fingerprints. And the doors won't open.
Calling AddFingerprint to restore the lost fingerprint returns a false "true", i.e. nothing was added and the machine still has 0 fingerprints left.
Note: ZKAccess is limited to 2000 users, I added 2600+ users.
Update: ZKAccess has 2654 users in its database, clicking sync to device only restores the 900 users that where added using ZKAccess itself (foul play suspected).
Update: I confused push & pull sdk, they are not the same. PullSDK is free, push SDK is private to ZKTeco
ZKAccess3.5 deleted all data because the limit of the free version was exceeded.
EDIT: Just for anyone looking for an answer, Push sdk is a private sdk used only by ZKteco. Pull sdk how ever is free but has no documentation. I wrote a wrapper in C#: code

How to get the current project name in C# code?

I want to send an email to myself when an exception is thrown. Using StackFrame object, I am able to get File Name, Class Name and even class method that throw the Exception, but I also need to know the project name as many of my ASP.NET project has the same file name, class name and method.
This is my code:
public static string JndGetEmailTextForDebuggingExceptionError(this Exception Ex)
{
StackFrame sf = Ex.JndGetStackFrame();
string OutputHTML = "<i><b><u>For Developer Use Only: </u></b></i>" + "<br>" +
"<br>" +
"Project Name: " + HttpContext.Current.ApplicationInstance.GetType().Assembly.GetName().Name + "<br>" + //Under discussion
"File Name: " + sf.GetFileName() + "<br>" +
"Class Name: " + sf.GetMethod().DeclaringType + "<br>" +
"Method Name: " + sf.GetMethod() + "<br>" +
"Line Number: " + sf.GetFileLineNumber() + "<br>" +
"Line Column: " + sf.GetFileColumnNumber() + "<br>" +
"Error Message: " + Ex.Message + "<br>" +
"Inner Message : " + Ex.InnerException.Message + "<br>";
return OutputHTML;
}
Thanks ALL.
You can use Assembly.GetCallingAssembly if you have your logging code in a separate library assembly, and call directly from your ASP.NET assembly to your library, and you mark the method so that it won't be inlined:
[MethodImpl(MethodImplOptions.NoInlining)]
public static string JndGetEmailTextForDebuggingExceptionError(this Exception Ex)
{
StackFrame sf = Ex.JndGetStackFrame();
string OutputHTML = "<i><b><u>For Developer Use Only: </u></b></i>" + "<br>" +
"<br>" +
"Project Name: " + Assembly.GetCallingAssembly().GetName().Name + "<br>" +
"File Name: " + sf.GetFileName() + "<br>" +
"Class Name: " + sf.GetMethod().DeclaringType + "<br>" +
"Method Name: " + sf.GetMethod() + "<br>" +
"Line Number: " + sf.GetFileLineNumber() + "<br>" +
"Line Column: " + sf.GetFileColumnNumber() + "<br>" +
"Error Message: " + Ex.Message + "<br>" +
"Inner Message : " + Ex.InnerException.Message + "<br>";
return OutputHTML;
}
On any entry points in your library that can end up wanting to log the project name, you'd have to record the calling assembly and mark it NoInlining, then pass that around internally.
If you're using .NET 4.5, there's an alternative way to do this: CallerFilePath. It has the same restrictions on entry points, and it returns the source path on your machine instead of the assembly name (which is probably less useful), but it's easier to know that it'll work (because it compiles it, just like optional parameters are compiled in), and it allows inlining:
public static string JndGetEmailTextForDebuggingExceptionError
(this Exception Ex, [CallerFilePath] string filePath = "")
{
StackFrame sf = Ex.JndGetStackFrame();
string OutputHTML = "<i><b><u>For Developer Use Only: </u></b></i>" + "<br><br>" +
"Source File Path: " + filePath + "<br>" +
...
For anyone looking for an ASP.NET Core compatible solution, the following should work;
System.Reflection.Assembly.GetEntryAssembly().GetName().Name
.NET Core API Reference
This ought to be enough
string projectName = Assembly.GetCallingAssembly().GetName().Name;
Edit* If you are running this from another assembly then you should use GetCallingAssembly instead.
You can use
HttpContext.Current.ApplicationInstance.GetType().Assembly.GetName().Name
If this returns App_global.asax...., change it to
HttpContext.Current.ApplicationInstance.GetType().BaseType.Assembly.GetName().Name
If you aren't running in an HTTP request, you will need some way to get ahold of the HttpContext.
This will return different results if you're in a Web Site project (as opposed to Web Application).
You can also use HttpRuntime.AppDomainAppPath to get the physical path on disk to the deployed site; this will work everywhere.
Reflection is the best way to find out product name,company name version like information.
public static string ProductName
{
get
{
AssemblyProductAttribute myProduct =(AssemblyProductAttribute)AssemblyProductAttribute.GetCustomAttribute(Assembly.GetExecutingAssembly(),
typeof(AssemblyProductAttribute));
return myProduct.Product;
}
}
And Another way like get direct project name
string projectName=System.IO.Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location).ToString();
Just adding my answer here.
For those who work with multiple Dlls in their projects, the correct answer is:
string projectName = Assembly.GetExecutingAssembly().FullName.Split(',')[0];

ActiveDirectory Domain Description?

I'm trying to get some details about the current systems Domain.
I've been able to find the Name, DomainMode and ForstMode by using the following code:
System.DirectoryServices.ActiveDirectory.Domain domain = System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain();
Console.WriteLine("Domain: " + domain.Name);
Console.WriteLine("Domain Mode: " + domain.DomainMode);
Console.WriteLine("Forest Mode: " + domain.Forest.ForestMode);
However, I cannot seem to figure out how to get the domains description. Screenshot of what I am looking for:
Any suggestions on how I can go about getting this? I don't see any attributes on the Domain object that seems to represent it.
Figured it out. Along with the description I was also able to get the SID using the following code:
using (System.DirectoryServices.ActiveDirectory.Domain domain = System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain())
{
using (DirectoryEntry directoryEntry = domain.GetDirectoryEntry())
{
Console.WriteLine("Domain: " + domain.Name);
Console.WriteLine("Domain Mode: " + domain.DomainMode);
Console.WriteLine("Forest Mode: " + domain.Forest.ForestMode);
var sidInBytes = directoryEntry.Properties["objectSID"].Value as byte[];
var sid = new SecurityIdentifier(sidInBytes, 0);
Console.WriteLine("Domain SID: " + sid.ToString());
Console.WriteLine("Description: " + directoryEntry.Properties["description"].Value as string);
}
}

How can I get a list Local Windows Users (Only the Users that appear in the windows Logon Screen)

How can I get a list of Local Windows Users (Only the Users that appear in the windows Logon Screen)
I have tried many methods using Windows Principle library & WMI Select commands. I keep getting Administrator, Guest & some other bizarre accounts (VUSRNEIL-DELL, $HOMEGROUPUSER, ASPNET...etc.)
Neither of these 3 user accounts appear on the Logon screen. How can I Differentiate between these user types?
I am coding in C#
Just add a reference to System.Management in a Console Application and try this code:
using System;
using System.Management;
using System.Linq;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
ManagementObjectSearcher usersSearcher = new ManagementObjectSearcher(#"SELECT * FROM Win32_UserAccount");
ManagementObjectCollection users = usersSearcher.Get();
var localUsers = users.Cast<ManagementObject>().Where(
u => (bool)u["LocalAccount"] == true &&
(bool)u["Disabled"] == false &&
(bool)u["Lockout"] == false &&
int.Parse(u["SIDType"].ToString()) == 1 &&
u["Name"].ToString() != "HomeGroupUser$");
foreach (ManagementObject user in localUsers)
{
Console.WriteLine("Account Type: " + user["AccountType"].ToString());
Console.WriteLine("Caption: " + user["Caption"].ToString());
Console.WriteLine("Description: " + user["Description"].ToString());
Console.WriteLine("Disabled: " + user["Disabled"].ToString());
Console.WriteLine("Domain: " + user["Domain"].ToString());
Console.WriteLine("Full Name: " + user["FullName"].ToString());
Console.WriteLine("Local Account: " + user["LocalAccount"].ToString());
Console.WriteLine("Lockout: " + user["Lockout"].ToString());
Console.WriteLine("Name: " + user["Name"].ToString());
Console.WriteLine("Password Changeable: " + user["PasswordChangeable"].ToString());
Console.WriteLine("Password Expires: " + user["PasswordExpires"].ToString());
Console.WriteLine("Password Required: " + user["PasswordRequired"].ToString());
Console.WriteLine("SID: " + user["SID"].ToString());
Console.WriteLine("SID Type: " + user["SIDType"].ToString());
Console.WriteLine("Status: " + user["Status"].ToString());
}
Console.ReadKey();
}
}
}
If you're using WMI to query Win32_UserAccount you can display only items that meet following conditions:
Property AccountType has the UF_NORMAL_ACCOUNT flag.
Property Disabled is false.
Property Lockout is false.
Property LocalAccount is true.
Property SIDType is SidTypeUser.
If you can't use WMI (or you do not want to use it) then you have to do a little bit more work, basically you have to use NetGroupGetUsers function to enumerate all users. See this article on CodeProject for an example.
If you want to use a wrappered solution, NuGet has the "Continuous.Management" package - which is an open source project: https://github.com/jarzynam/continuous
This will give you a list of all user accounts, their domain, full name and SID.
wmic useraccount get domain,name,sid

Facebook C# SDK get user language/region

I'm using the Facebook C# SDK. How can I get language of the user, so I can display all messages accordingly without forcing the user to choose his preferred language manually?
If you are developing a web app, then you can use Accept-Language Http header to detect the language
EDIT 1
For winforms application, you can use System.Globalization.CultureInfo.CurrentCulture.Name .
EDIT2
To get the locale using FB REST API :
dynamic fbResult = new Uri("https://graph.facebook.com/AngelaMerkel?access_token=AAABkECTD......").GetDynamicJsonObject();
Console.WriteLine(
fbResult.locale ?? "-" + " > " + //<----
fbResult.location.country + " " + //<----
fbResult.location.city + " " + //<----
fbResult.name + " " +
fbResult.gender + " " +
fbResult.link + " " +
fbResult.updated_time);
You can find info about my extension method GetDynamicJsonObject here

Categories