custom exception handling database insert - c#

I hope you understand me
I have 2 questions
1 How do I implement custom exception handling ?
2 I have my this table
ID
ExceptionName
ClassName
MethodName
FieldName
ErrorMessage
I want to record following for a exception to the table :
what was the error page?
what was the error classname?
what was the error method and What was the name of the fieldname ? How can I get Exception details?
Get Class Name and Method Name Where Exception Occurred From Exception Details
MSSQL + C# mvc framework 4.0
thank you

this is the function which you have to call inside your catch block,
public static void LogException(Exception exc, string source)
{
// Include enterprise logic for logging exceptions
// Get the absolute path to the log file
string logFile = "App_Data/ErrorLog.txt";
logFile = HttpContext.Current.Server.MapPath(logFile);
// Open the log file for append and write the log
StreamWriter sw = new StreamWriter(logFile, true);
sw.WriteLine("********** {0} **********", DateTime.Now);
if (exc.InnerException != null)
{
sw.Write("Inner Exception Type: ");
sw.WriteLine(exc.InnerException.GetType().ToString());
sw.Write("Inner Exception: ");
sw.WriteLine(exc.InnerException.Message);
sw.Write("Inner Source: ");
sw.WriteLine(exc.InnerException.Source);
if (exc.InnerException.StackTrace != null)
{
sw.WriteLine("Inner Stack Trace: ");
sw.WriteLine(exc.InnerException.StackTrace);
}
}
sw.Write("Exception Type: ");
sw.WriteLine(exc.GetType().ToString());
sw.WriteLine("Exception: " + exc.Message);
sw.WriteLine("Source: " + source);
sw.WriteLine("Stack Trace: ");
if (exc.StackTrace != null)
{
sw.WriteLine(exc.StackTrace);
sw.WriteLine();
}
sw.Close();
}
refer to the link:http://msdn.microsoft.com/en-us/library/bb397417(v=vs.140).aspx

Related

Decoding JSON command line arguments fails after build but succeeds during debug

I am building a C# application that handles a custom protocol used in my web application.
The links are like:
Print
These are handled using a handler in the windows registry (URL:zebra-wp Protocol):
"C:\Program Files (x86)\[My App Name]\[My App].exe" "%1"
I am running the following code in my app:
class LabelData
{
public string name;
public string barcode;
}
static class Program
{
[STAThread]
static void Main(string[] args)
{
if (args.Length > 0 && args[0].StartsWith("zebra-wp://"))
{
// retrieve data from argument
string argData = args[0].Remove(0, 11);
string decodedJson = "";
try
{
// Undo URL Encoding
decodedJson = WebUtility.UrlDecode(argData);
}
catch (Exception ex)
{
string msg = "Couldn't print label, failed to decode data.";
msg += "\nData: " + argData;
msg += "Error: " + ex.Message;
MessageBox.Show(msg);
Application.Exit();
}
// Unpack JSON string
LabelData decodedData = new LabelData();
try
{
decodedData = JsonConvert.DeserializeObject<LabelData>(decodedJson);
}
catch (Exception ex)
{
string msg = "Couldn't print label, failed to unpack data.";
msg += "\nData: " + decodedJson;
msg += "Error: " + ex.Message;
MessageBox.Show(msg);
Application.Exit();
}
// Do things with object
When I debug the application I enter the link URL into the "Command line arguments" start up option.
The program works as expected and the JSON data is successfully decoded.
When I build and install, the JsonConvert.DeserializeObject function gives me the following error:
Data: {"barcode":"000063","name":"Food Fun - Magnetic Multicultural set"}
Error: Unexpected end while parsing comment. Path '', line 1, position 68.
Is something different about how VS launches an app with command line arguments in debug?
Is there a way to debug the application with the same command line arguments as when I click the URL?
I have found the issue, apparently when passing URI's to custom protocol handlers, Windows adds a trailing forward slash to the URI, checking for this in the code and removing it solves the problem.

How to get an element in FHIR API?

I tried to get the element like Identifier, Location, Period, ... But not working. How can I get it?
My code follow:
static void Main(string[] args)
{
//The fhir server end point address
string ServiceRootUrl = "http://stu3.test.pyrohealth.net/fhir";
//Create a client to send to the server at a given endpoint.
var FhirClient = new Hl7.Fhir.Rest.FhirClient(ServiceRootUrl);
// increase timeouts since the server might be powered down
FhirClient.Timeout = (60 * 1000);
Console.WriteLine("Press any key to send to server: " + ServiceRootUrl);
Console.WriteLine();
Console.ReadKey();
try
{
//Attempt to send the resource to the server endpoint
Hl7.Fhir.Model.Bundle ReturnedSearchBundle = FhirClient.Search<Hl7.Fhir.Model.Patient>(new string[] { "status=planned" });
Console.WriteLine(string.Format("Found: {0} Fhirman patients.", ReturnedSearchBundle.Total.ToString()));
Console.WriteLine("Their logical IDs are:");
foreach (var Entry in ReturnedSearchBundle.Entry)
{
Console.WriteLine("ID: " + Entry.Resource.Id);
Console.WriteLine("ID2: " + Entry.Identifier);
}
Console.WriteLine();
}
catch (Hl7.Fhir.Rest.FhirOperationException FhirOpExec)
{
//Process any Fhir Errors returned as OperationOutcome resource
Console.WriteLine();
Console.WriteLine("An error message: " + FhirOpExec.Message);
Console.WriteLine();
string xml = Hl7.Fhir.Serialization.FhirSerializer.SerializeResourceToXml(FhirOpExec.Outcome);
XDocument xDoc = XDocument.Parse(xml);
Console.WriteLine(xDoc.ToString());
}
catch (Exception GeneralException)
{
Console.WriteLine();
Console.WriteLine("An error message: " + GeneralException.Message);
Console.WriteLine();
}
Console.WriteLine("Press any key to end.");
Console.ReadKey();
}
The result is System.Collections.Generic.List`1[Hl7.Fhir.Model.Identifier]
Your search is for a Patient, which does not have a 'status' search parameter nor field. The server you use eliminates the parameter for the search, and sends back a Bundle with Patients in the entries - this is according to the FHIR specification.
The first line in your foreach (Console.WriteLine("ID: " + Entry.Resource.Id);) will output the technical id of the resource. Since there is no Identifier field on the Entry, I assume your second one actually reads Entry.Resource.Identifier.
The Patient.identifier field is a 0..* list of Identifiers, so you would have to take one of them. The Identifier datatype in turn is a complex datatype, with usually a system and value field filled in. So, you could do something like this - assuming the Identifier list contains an item:
var patient = (Patient)Entry.Resource;
Console.WriteLine($"Patient identifier: {patient.Identifier[0].System} {patient.Identifier[0].Value}");

System.IO.File.Delete throws Arithmetic operation resulted in an overflow

I have this weird error. When I call System.IO.File.Delete(), it throws
JobCleaner.CleanFiles(): Unable to delete file: D:\WorkerData\4\Run128\Run_TEMPLATE_Rail_Scenario_Type35_INFHD2_NO_TAX_NOMEP\out‌​put_panels\FileIndex55.bin
Error: Arithmetic operation resulted in an overflow.
There is no stack trace.
Here is my code:
foreach (string strFile in System.IO.Directory.GetFiles(strFolder))
{
try { System.IO.File.Delete(strFile); }
catch (Exception ex)
{
//Exception here
AddToLog("JobCleaner.CleanFiles(): Error occurred when trying to delete file \"" + strFile + "\".\nError:\n" + ex.Message);
return false;
}
}
Any idea? I tried everything, I check the security on the folder. I enabled "Everyone" with full controls, but still encounter this "Arithmetic operation resulted in an overflow" exception.
Can anyone help, please? I am using Windows 2012 R2 Datacenter to run my application.
I wouldn't expect it to throw an arithmetic exception, but I have observed some weird behavior when you modify an IEnumerable within the foreach that is walking it. Try moving the file listing out of the loop, like this:
string[] files = System.IO.Directory.GetFiles(strFolder);
foreach (string strFile in files)
{
try { System.IO.File.Delete(strFile); }
catch (Exception ex)
{
//Exception here
AddToLog("JobCleaner.CleanFiles(): Error occurred when trying to delete file \"" + strFile + "\".\nError:\n" + ex.Message);
return false;
}
}

ASP.NET can't create Windows Event Log even as Administrator

I'm working on an ASP.NET web application in Visual Studio 2013 and as part of the main error routine, I want it to store the errors in a Windows Event Log. However, every time I run the code, the log never gets created even when I run Visual Studio as Administrator. Would turning off UAC fix this? Code is below. Any help is appreciated. Thanks.
public static void ErrorRoutine(Exception e, string obj, string method)
{
EventLog.Delete("LogName"); // uncomment this line to delete log
EventLog log = new EventLog();
log.Source = "SourceName";
log.Log = "LogName";
if (e.InnerException != null)
{
log.WriteEntry("Error in Models, object = " + obj + ", method = " + method + ", inner exception = " +
e.InnerException.Message, EventLogEntryType.Error);
throw e.InnerException;
}
else
{
log.WriteEntry("Error in Models, object = " + obj + ", method = " + method + ", message = " + e.Message,
EventLogEntryType.Error);
throw e;
}
}
Edit: I get that this is probably not best practice but this project is actually an assignment for college and this is the exact code we were told to write, as well as being told to run VS as Administrator. I just need to find a way to make work really.

Query Active Directory in C#

I am trying to perform a query to Active Directory to obtain all the first names of every user. So I have created a new console application and in my main method have the following code:
try
{
DirectoryEntry myLdapConnection =new DirectoryEntry("virtual.local");
myLdapConnection.Path = "LDAP://DC=virtual,DC=local";
DirectorySearcher search = new DirectorySearcher(myLdapConnection);
search.PropertiesToLoad.Add("cn");
SearchResultCollection allUsers = search.FindAll();
I have added some code to check that the connection is being made and that the path can be found. I also ensure that the Collection is not empty.
//For Debugging
if(DirectoryEntry.Exists(myLdapConnection.Path())
{
Console.WriteLine("Found");
}
else Console.WriteLine("Could Not Find LDAP Connection");
//In my case prints 230
Console.WriteLine("Total Count: " + allUsers.Count);
foreach(SearchResult result in allUsers)
{
//This prints out 0 then 1
Console.WriteLine("Count: " + result.Properties["cn'].Count);
if (result.Properties["cn"].Count > 0) //Skips the first value
{
Console.WriteLine(String.Format("{0,-20} : {1}",
result.Properties["cn"][0].ToString())); //Always fails
}
}
}
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
I have specified in the code, where it prints out the properties, that it always fails. I get a System.FormatException being caught here that states the Index must be greater than zero and less than the size of the argument list.
So in the end I'm not really sure how "result.Properties" works and was wondering if you had any advise on how to fix or troubleshoot the problem.
You are defining two format specifiers {0} and {1} but only specifying one argument.

Categories