Outllook item get - outlook-2007

how to get current item of outlook 2007 in asp.net c#
here is some code which get all mails
Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook._NameSpace ns = null;
Microsoft.Office.Interop.Outlook.MailItem item = null;
Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;
Microsoft.Office.Interop.Outlook.MAPIFolder subFolder = null;
try
{
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
ns.Logon(null,null,false, false);
inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
//subFolder =inboxFolder.Folders["inbox"]; //inboxFolder.Folders[1]; also works
//Console.WriteLine("Folder Name: {0}, EntryId: {1}", subFolder.Name, subFolder.EntryID);
//Console.WriteLine("Num Items: {0}", subFolder.Items.Count.ToString());
for (int i = 1; i <= inboxFolder.Items.Count; i++)
{
item = (Microsoft.Office.Interop.Outlook.MailItem)inboxFolder.Items[i];
// System.Windows.Forms.MessageBox.Show("Item: {0} {1}", i.ToString());
//Console.WriteLine("Subject: {0}", item.Subject);
//Console.WriteLine("Sent: {0} {1}", item.SentOn.ToLongDateString(), item.SentOn.ToLongTimeString());
//Console.WriteLine("Categories: {0}", item.Categories);
//Console.WriteLine("Body: {0}", item.Body);
//Console.WriteLine("HTMLBody: {0}", item.HTMLBody);
// System.Windows.Forms.MessageBox.Show(" Subject: " + item.Subject + " TO: " + item.To + " " + item.Body);
System.Windows.Forms.MessageBox.Show( i.ToString());
}
System.Windows.Forms.MessageBox.Show(" Subject: " + item.Subject + " TO: " + item.To + " " + item.Body);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

Explorer object has a property - Selection which contaisn all the items selected in the active explorer.You can check this property to determine the current item in Outlook.
Outlook.Explorer currentExplorer = this.ActiveExplorer();
if (this.ActiveExplorer().Selection.Count > 0){
Object selObject = this.ActiveExplorer().Selection[1];
if (selObject is Outlook.MailItem)
{
Outlook.MailItem mailItem =
(selObject as Outlook.MailItem);
itemMessage ="The item is an e-mail message." +
" The subject is " + mailItem.Subject + ".";
}
}
This link might help you.

Related

through exception in mvc on send email

I want to send email from an excel file.
When It get wrong email address it stop sending.
I want it send all email and at last show me wrong email that isn't able to send.
This my code for read Excel file:
if (!string.IsNullOrWhiteSpace(excel))
{
var src = excel;
DataSet ds = new DataSet();
string fileExtension = System.IO.Path.GetExtension(Server.MapPath("~/") + src);
if (fileExtension == ".xls" || fileExtension == ".xlsx")
{
string fileLocation = Server.MapPath("~/") + src;
string excelConnectionString = string.Empty;
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
if (fileExtension == ".xls")
{
excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
excelConnection.Open();
DataTable dt = new DataTable();
dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheets = new String[dt.Rows.Count];
int t = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[t] = row["TABLE_NAME"].ToString();
t++;
}
OleDbConnection excelConnection1 = new OleDbConnection(excelConnectionString);
string query = string.Format("Select * from [{0}]", excelSheets[0]);
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
{
dataAdapter.Fill(ds);
}
}
if (fileExtension.ToString().ToLower().Equals(".xml"))
{
string fileLocation = Server.MapPath("~/") + src;
if (System.IO.File.Exists(fileLocation))
{
System.IO.File.Delete(fileLocation);
}
Request.Files["FileUpload"].SaveAs(fileLocation);
XmlTextReader xmlreader = new XmlTextReader(fileLocation);
// DataSet ds = new DataSet();
ds.ReadXml(xmlreader);
xmlreader.Close();
}
And this is code for send email:
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string excelname = "";
if (lang == "1")
{
excelname = "<div style='text-align:right;'>" + ds.Tables[0].Rows[i][0].ToString() + "<br/>" + ds.Tables[0].Rows[i][1].ToString() + "</div>";
}
else
{
excelname = "<div style='text-align:left;'>" + ds.Tables[0].Rows[i][0].ToString() + "<br/>" + ds.Tables[0].Rows[i][1].ToString() + "</div>";
}
exceltotal = excelname + text + newslink + attach;
//sender
message = string.Format(body, img, exceltotal, title, prehead, senderemail);
MailMessage email = new MailMessage();
email.To.Add(ds.Tables[0].Rows[i][2].ToString());
email.From = new MailAddress(senderemail);
email.Subject = maintitle;
email.Body = message + makedelivey(ds.Tables[0].Rows[i][2].ToString(), maintitle);
email.BodyEncoding = System.Text.Encoding.UTF8;
email.IsBodyHtml = true;
SmtpClient ssmtp = new SmtpClient();
ssmtp.Host = server;
ssmtp.Port = port;
ssmtp.UseDefaultCredentials = false;
ssmtp.Credentials = new System.Net.NetworkCredential(senderemail, senderpassword);
ssmtp.EnableSsl = false;
ssmtp.Send(email);
exceltotal = "";
message = "";
}
It read a text file and add some value from excel or database base on user selection.
I couldn't find line of code which sends email. But wherever you are sending the email inside the loop, make sure you enclose that code in try catch block. This ensures even if a mail send operation is failed, the error is handled and goes on with other mails. You can include your consolidate and formatting of failures issues in catch block.
var consolidateErrors = string.Empty;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Try
{
//Mail sending logic here
}
Catch(Exception ex)
{
consolidateErrors += YourErrorDetails;
}
}

Reading Windows event log using JNA provides me only part of the description available in Event Veiwer

This is my code Provide me details where am going wrong so that am
getting only the part of the description available
========================================================================
http://code.dblock.org/jna-reading-windows-event-log-entries-in-java
#SuppressWarnings("unused")
public void testReadEventLogEntries() throws CharacterCodingException {
final Charset charset = Charset.forName("UTF-8");
Charset iso88591charset = Charset.forName("ISO-8859-1");
final CharsetEncoder encoder = charset.newEncoder();
final CharsetDecoder decoder = charset.newDecoder();
int i = 0;// loop contro variable
String type = null; // Type of the event
String user = null;
String str[] = { "System", "Application" };
while (i < 2) {
System.out.println("\n\n" + str[i]);
HANDLE h = Advapi32.INSTANCE.OpenEventLog(null, str[i]);
IntByReference pnBytesRead = new IntByReference();
IntByReference pnMinNumberOfBytesNeeded = new IntByReference();
Memory buffer = new Memory(1024 * 64);
IntByReference pOldestRecord = new IntByReference();
int dwRecord = pOldestRecord.getValue();
int rc = 0;
while (true) { // Travesing the read log records
if (!Advapi32.INSTANCE.ReadEventLog(h,
WinNT.EVENTLOG_SEQUENTIAL_READ
| WinNT.EVENTLOG_FORWARDS_READ, 0, buffer,
(int) buffer.size(), pnBytesRead,
pnMinNumberOfBytesNeeded)) {
rc = Kernel32.INSTANCE.GetLastError();
if (rc == W32Errors.ERROR_INSUFFICIENT_BUFFER) {
buffer = new Memory(pnMinNumberOfBytesNeeded.getValue());
continue;
}
break;
}
int dwRead = pnBytesRead.getValue();
Pointer pevlr = buffer;
while (dwRead > 0) {
EVENTLOGRECORD record = new EVENTLOGRECORD(pevlr);
EventLogRecord event = new EventLogRecord(pevlr);
org.hyperic.sigar.win32.EventLogRecord sigar;
EventLog log = new EventLog();
if (record.EventType.intValue() == 1)
type = "Error";
else if (record.EventType.intValue() == 10)
type = "Failure Audit";
else if (record.EventType.intValue() == 8)
type = "Sucess Audit";
else if (record.EventType.intValue() == 4)
type = "Information";
else
type = "Warning";
ByteBuffer names = pevlr
.getByteBuffer(
record.size(),
(record.UserSidLength.intValue() != 0 ? record.UserSidOffset
.intValue() : record.StringOffset
.intValue())
- record.size());
names.position(0);
CharBuffer namesBuf = names.asCharBuffer();
String[] splits = namesBuf.toString().split("\0");
if (record.UserSidLength.intValue() != 0) {
ByteBuffer usersid = pevlr.getByteBuffer(
record.UserSidOffset.intValue(),
record.UserSidLength.intValue());
usersid.position(0);
CharBuffer sidBuf = usersid.asCharBuffer();
String[] sp = sidBuf.toString().split("\0");
// System.out.println(sp[0] + sp[1] + sp[2]);
/*
* dst.get user= new String(dst);
*/
} else {
user = "N/A";
}
System.out.println(type + "\t" + toDate(record) + "\t"
+ event.getSource() + "\t" + record.EventCategory
+ "\t" + record.EventID.shortValue() + "\t" + user
+ "\t" + splits[1]);
ByteBuffer strings = pevlr.getByteBuffer(
record.StringOffset.longValue(),
record.DataOffset.intValue()
- record.StringOffset.intValue());
CharBuffer stringsBuf = strings.asCharBuffer();
System.out.println("Desc: " + stringsBuf.toString());
dwRecord++;
dwRead -= record.Length.intValue();
pevlr = pevlr.share(record.Length.intValue());
}
}
i++;
}
}
// Method to convert the timestamp to formated date
public Date toDate(EVENTLOGRECORD record) {
Timestamp stamp = new Timestamp(record.TimeWritten.longValue() * 1000);
Date date = new Date(stamp.getTime());
return date;
}
}
Finally I figured out the solution....The description returned by the
above code is just the insertion strings needed to build the message.
Instead of using jna I used WMI which is simple to use and more handy
/**
* #param args
*/
public static void main(String[] args) throws COMException {
String computerName = ".";
String userName = "";
String password = "";
String namespace = "root/cimv2";
String Message = "";
String queryProcessor = "Select * from Win32_NTLogEvent where Logfile='System'or Logfile='Application'";
DispatchPtr dispatcher = null;
try {
ISWbemLocator locator = new ISWbemLocator(
"WbemScripting.SWbemLocator");
ISWbemServices wbemServices = locator.ConnectServer(computerName,
namespace, userName, password, "", "", 0, dispatcher);
ISWbemObjectSet wbemObjectSet = wbemServices.ExecQuery(
queryProcessor, "WQL", 0, null);
DispatchPtr[] results = new DispatchPtr[wbemObjectSet.getCount()];
IUnknown unknown = wbemObjectSet.get_NewEnum();
IEnumVariant enumVariant = (IEnumVariant) unknown
.queryInterface(IEnumVariant.class);
enumVariant.Next(wbemObjectSet.getCount(), results);
for (int i = 0; i < results.length; i++) {
ISWbemObject wbemObject = (ISWbemObject) results[i]
.queryInterface(ISWbemObject.class);
if (wbemObject.get("Message") != null) {
Message = (String) wbemObject.get("Message");
} else {
Message = "The description for Event ID ("
+ wbemObject.get("EventCode")
+ " ) in Source ( "
+ wbemObject.get("SourceName")
+ ") cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details.";
}
System.out.println(wbemObject.get("Logfile") + "\t"
+ wbemObject.get("Type") + "\t"
+ toDate(wbemObject.get("TimeGenerated").toString())
+ "\t"
+ toTime(wbemObject.get("TimeGenerated").toString())
+ "\t" + wbemObject.get("EventCode") + "\t"
+ wbemObject.get("ComputerName") + "\t" + Message);
// System.out.println(wbemObject.GetObjectText_(0));
}
} catch (COMException e) {
e.printStackTrace();
}
}
public static String toDate(String time) throws COMException {
String date = time.substring(6, 8) + "-" + time.substring(4, 6) + "-"
+ time.substring(0, 4);
return date;
}
public static String toTime(String time) throws COMException {
String Generatedtime = time.substring(8, 10) + ":"
+ time.substring(10, 12) + ":" + time.substring(12, 14) + ":"
+ time.substring(16, 21) + "-" + "GMT" + time.substring(21, 25);
return Generatedtime;
}

"Authorization is required to perform that action" in Google Scripts with no way to give authorization

I am trying to create a sort of middleware so some legacy software I am working on can consume Twitter feeds.
Since Twitter has made API 1.0 obsolete and 1.1 requires OAuth and because for this project I only have client-side scripting available to me, I opted to use a Google script to perform the OAuth negotiation:
Source: http://www.labnol.org/internet/twitter-rss-feeds/27931/
function start() {
// Get your Twitter keys from dev.twitter.com
var CONSUMER_KEY = "-----";
var CONSUMER_SECRET = "----";
// Ignore everything after this line
initialize(CONSUMER_KEY, CONSUMER_SECRET);
}
function initialize(key, secret) {
ScriptProperties.setProperty("TWITTER_CONSUMER_KEY", key);
ScriptProperties.setProperty("TWITTER_CONSUMER_SECRET", secret);
var url = ScriptApp.getService().getUrl();
if (url) {
connectTwitter();
var msg = "";
msg += "Sample RSS Feeds for Twitter\n";
msg += "============================";
msg += "\n\nTwitter Timeline of user #labnol";
msg += "\n" + url + "?action=timeline&q=labnol";
msg += "\n\nTwitter Favorites of user #labnol";
msg += "\n" + url + "?action=favorites&q=labnol";
msg += "\n\nTwitter List labnol/friends-in-india";
msg += "\n" + url + "?action=list&q=labnol/friends-in-india";
msg += "\n\nTwitter Search for New York";
msg += "\n" + url + "?action=search&q=new+york";
msg += "\n\nYou should replace the value of 'q' parameter in the URLs as per requirement.";
msg += "\n\nFor help, please refer to http://www.labnol.org/?p=27931";
MailApp.sendEmail(Session.getActiveUser().getEmail(), "Twitter RSS Feeds", msg);
}
}
function doGet(e) {
var a = e.parameter.action;
var q = e.parameter.q;
var feed;
switch (a) {
case "timeline":
feed = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" + q;
break;
case "search":
feed = "https://api.twitter.com/1.1/search/tweets.json?q=" + encodeString(q);
break;
case "favorites":
feed = "https://api.twitter.com/1.1/favorites/list.json?screen_name=" + q;
break;
case "list":
var i = q.split("/");
feed = "https://api.twitter.com/1.1/lists/statuses.json?slug=" + i[1] + "&owner_screen_name=" + i[0];
break;
default:
feed = "https://api.twitter.com/1.1/statuses/user_timeline.json";
break;
}
var id = Utilities.base64Encode(feed);
var cache = CacheService.getPublicCache();
var rss = cache.get(id);
if ((!rss) || (rss == "undefined")) {
rss = JSONtoRSS(feed, a, q);
cache.put(id, rss, 3600);
}
return ContentService.createTextOutput(rss)
.setMimeType(ContentService.MimeType.RSS);
}
function JSONtoRSS(json, type, key) {
oAuth();
var options = {
"method": "get",
"oAuthServiceName": "twitter",
"oAuthUseToken": "always"
};
try {
var result = UrlFetchApp.fetch(json, options);
if (result.getResponseCode() === 200) {
var tweets = Utilities.jsonParse(result.getContentText());
if (type == "search")
tweets = tweets.statuses;
if (tweets) {
var len = tweets.length;
var rss = "";
if (len) {
rss = '<?xml version="1.0"?><rss version="2.0">';
rss += ' <channel><title>Twitter ' + type + ': ' + key + '</title>';
rss += ' <link>' + htmlentities(json) + '</link>';
rss += ' <pubDate>' + new Date() + '</pubDate>';
for (var i = 0; i < len; i++) {
var sender = tweets[i].user.screen_name;
var tweet = htmlentities(tweets[i].text);
rss += "<item><title>" + sender + ": " + tweet + "</title>";
rss += " <author>" + tweets[i].user.name + " (#" + sender + ")</author>";
rss += " <pubDate>" + tweets[i].created_at + "</pubDate>";
rss += " <guid isPermaLink='false'>" + tweets[i].id_str + "</guid>";
rss += " <link>https://twitter.com/" + sender + "/statuses/" + tweets[i].id_str + "</link>";
rss += " <description>" + tweet + "</description>";
rss += "</item>";
}
rss += "</channel></rss>";
return rss;
}
}
}
} catch (e) {
Logger.log(e.toString());
}
}
function connectTwitter() {
oAuth();
var search = "https://api.twitter.com/1.1/application/rate_limit_status.json";
var options = {
"method": "get",
"oAuthServiceName": "twitter",
"oAuthUseToken": "always"
};
try {
var result = UrlFetchApp.fetch(search, options);
} catch (e) {
Logger.log(e.toString());
}
}
function encodeString(q) {
var str = encodeURIComponent(q);
str = str.replace(/!/g, '%21');
str = str.replace(/\*/g, '%2A');
str = str.replace(/\(/g, '%28');
str = str.replace(/\)/g, '%29');
str = str.replace(/'/g, '%27');
return str;
}
function htmlentities(str) {
str = str.replace(/&/g, "&");
str = str.replace(/>/g, ">");
str = str.replace(/</g, "<");
str = str.replace(/"/g, """);
str = str.replace(/'/g, "'");
return str;
}
function oAuth() {
var oauthConfig = UrlFetchApp.addOAuthService("twitter");
oauthConfig.setAccessTokenUrl("https://api.twitter.com/oauth/access_token");
oauthConfig.setRequestTokenUrl("https://api.twitter.com/oauth/request_token");
oauthConfig.setAuthorizationUrl("https://api.twitter.com/oauth/authorize");
oauthConfig.setConsumerKey(ScriptProperties.getProperty("TWITTER_CONSUMER_KEY"));
oauthConfig.setConsumerSecret(ScriptProperties.getProperty("TWITTER_CONSUMER_SECRET"));
}
I have followed all of the instructions prescribed in the guide including running 'start' twice... and all that does is send my email account an email with the various URLs. When I try to access the URLs provided in the email (and the plan is to drop that URL into our legacy javascript that currently points to the Twitter 1.0 API), i get the error "Authorization is required to perform that action"
I have confirmed countless times that it is set up to "Execute the app as [me]" and "Anyone, even anonymous can access app"
I am not sure what I am missing or what got screwed up.
Turns out, I forgot to set up the callback URL within the Twitter app setup as specified in the source instructions. Oops!
This would explain why it wasn't working even though everything on the Google side was correct.

Parse IMAP message and extract header information

I am trying to extract header and body information from email, the following code retrieves the header and body in their raw form. I have an email object that contains the fields from, subject, date, and body. I would like to extract these values from the email and assign them to the email object. How do I get around it? I have tried several ways like getting the header info and using a streamReader.ReadLine() to get a line but I got illegal path exceptions. I know I can use a library but I need to achieve it this way.
What I mean is this, IMAP command returns header information. And I want to extract subject value, date value, sender e-amil, etc. and assign them to my email objects corresponding values like
emailObject.subject = "subjectValue"
public class Imap
{
static void Main(string[] args)
{
try
{
path = Environment.CurrentDirectory + "\\emailresponse.txt";
if (System.IO.File.Exists(path))
System.IO.File.Delete(path);
sw = new System.IO.StreamWriter(System.IO.File.Create(path));
tcpc = new System.Net.Sockets.TcpClient("imap.gmail.com", 993);
ssl = new System.Net.Security.SslStream(tcpc.GetStream());
ssl.AuthenticateAsClient("imap.gmail.com");
receiveResponse("");
Console.WriteLine("username : ");
username = Console.ReadLine();
Console.WriteLine("password : ");
password = Console.ReadLine();
receiveResponse("$ LOGIN " + username + " " + password + " \r\n");
Console.Clear();
receiveResponse("$ LIST " + "\"\"" + " \"*\"" + "\r\n");
receiveResponse("$ SELECT INBOX\r\n");
receiveResponse("$ STATUS INBOX (MESSAGES)\r\n");
Console.WriteLine("enter the email number to fetch :");
int number = int.Parse(Console.ReadLine());
Console.WriteLine("*************Header************");
Console.WriteLine("");
// receiveResponse("$ FETCH " + number + " body[header]\r\n");
// BODY.PEEK[HEADER.FIELDS (SUBJECT)]
// StringBuilder sb = receiveResponse("$ FETCH " + number + " BODY.PEEK[HEADER.FIELDS (From Subject Date)]\r\n");
StringBuilder sb= receiveResponse("$ FETCH " + number + " body.peek[header]\r\n");
Console.WriteLine(sb);
Console.WriteLine("");
Console.WriteLine("Body");
sb = new StringBuilder();
sb=receiveResponse("$ FETCH " + number + " body[text]\r\n");
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] serverbuff = new Byte[1024];
int count = 0;
string retval = enc.GetString(serverbuff, 0, count);
Console.WriteLine(sb.ToString());
receiveResponse("$ LOGOUT\r\n");
}
catch (Exception ex)
{
Console.WriteLine("error: " + ex.Message);
}
finally
{
if (sw != null)
{
sw.Close();
sw.Dispose();
}
if (ssl != null)
{
ssl.Close();
ssl.Dispose();
}
if (tcpc != null)
{
tcpc.Close();
}
}
Console.ReadKey();
}
static StringBuilder receiveResponse(string command)
{
sb = new StringBuilder();
try
{
if (command != "")
{
if (tcpc.Connected)
{
dummy = Encoding.ASCII.GetBytes(command);
ssl.Write(dummy, 0, dummy.Length);
}
else
{
throw new ApplicationException("TCP CONNECTION DISCONNECTED");
}
}
ssl.Flush();
buffer = new byte[2048];
bytes = ssl.Read(buffer, 0, 2048);
sb.Append(Encoding.ASCII.GetString(buffer));
// Console.WriteLine(sb.ToString());
sw.WriteLine(sb.ToString());
// sb = new StringBuilder();
return sb;
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
}
You said you do not want to use an IMAP library. This means that you will have to implement your own. You should start by reading RFC 3501 because there is no chance you could get the protocol right without reading the docs carefuly. In particular, you're issuing a STATUS command on the currently selected mailbox, which is explicitly forbidden by the protocol specification. The rest of the code supports the assumption that you have not read the RFC yet.

Exception Management Application Block with MVC

I've been scanning forums for an implementation of the Exception Management Application Block (EMAB) in an ASP.NET MVC (MVC3) application.
There's a lot of talk about ELMAH and NLog as well as handling via the global.asax (http://s151.codeinspot.com/q/694875) Vs an ErrorController (http://www.davidjuth.com/asp-net-mvc-error-handler.aspx) approach as well as leveraging the [HandleError] decoration
We are looking at standardising our Exception Management of our MVC apps with EMAB but I can't seem to find any specific examples that provide an all round solution.
Does anyone have any links or can explain exactly how you might utilise EMAB within the MVC framework
I decided on the approach below...
//**In Global.asax
protected void Application_Error(object sender, EventArgs e)
{
Exception originalError = Server.GetLastError();
Exception replacedError;
if (ExceptionPolicy.HandleException(originalError, "Global Policy", out replacedError))
{
Exception ex = replacedError ?? originalError;
if (ex.InnerException != null)
{
ex = ex.InnerException;
}
var httpException = ex as HttpException;
HttpApplication httpApplication = this.Context.ApplicationInstance;
string message = Utility.GetFullMessage(httpApplication, ex, "::");
string messageHtml = Utility.GetFullMessage(httpApplication, ex, "<br/>");
LogEntry logEntry = new LogEntry();
logEntry.EventId = 100;
logEntry.Priority = 2;
logEntry.Message = ex.Message + "::" + message;
Logger.Write(logEntry);
Response.Clear();
Server.ClearError();
var routeData = new RouteData();
routeData.Values["controller"] = "Error";
routeData.Values["action"] = Constants.ErrorGeneralKey; //"General"
routeData.Values["message"] = ex.Message;
routeData.Values["fullMessage"] = messageHtml;
Response.StatusCode = 500;
if (httpException != null)
{
Response.StatusCode = httpException.GetHttpCode();
switch (Response.StatusCode)
{
case 403:
routeData.Values["action"] = "Http403";
break;
case 404:
routeData.Values["action"] = "Http404";
break;
default:
routeData.Values["httpStatusCode"] = Response.StatusCode;
break;
}
}
IController errorController = new ErrorController();
var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
errorController.Execute(rc);
}
}
//**In helper class
public static string GetFullMessage(HttpApplication httpApplication, Exception ex, string delimiter)
{
return "StackTrace: " + ex.StackTrace
+ delimiter + "User: " + ((httpApplication.User == null) ? "<null>" : httpApplication.User.Identity.Name)
+ delimiter + "Data: " + GetExceptionData(ex.Data)
+ delimiter + "Version: " + httpApplication.Request.Browser.Version
+ delimiter + "Browser: " + httpApplication.Request.Browser.Browser
+ delimiter + "Major Version: " + httpApplication.Request.Browser.MajorVersion.ToString()
+ delimiter + "Minor Version: " + httpApplication.Request.Browser.MinorVersion.ToString()
+ delimiter + "Javascript Version: " + httpApplication.Request.Browser.JScriptVersion.ToString()
+ delimiter + "Ecma Script Version: " + httpApplication.Request.Browser.EcmaScriptVersion.ToString()
+ delimiter + "Platform: " + httpApplication.Request.Browser.Platform
+ delimiter + "Source: " + ex.Source
+ delimiter + "Form: " + httpApplication.Request.Form.ToString()
+ delimiter + "QueryString: " + httpApplication.Request.QueryString.ToString()
+ delimiter + "TargetSite: " + ex.TargetSite;
}
//**In Error controller
public ActionResult General(string httpStatusCode, string message, string fullMessage)
{
errorViewModel.RootCause = Enums.RootCause.General;
errorViewModel.HttpStatusCode = httpStatusCode;
errorViewModel.Message = message;
errorViewModel.FullMessage = fullMessage;
return View("Error", errorViewModel);
}
public ActionResult Http404()
{
errorViewModel.RootCause = Enums.RootCause.NotFound;
return View("Error", errorViewModel);
}
public ActionResult Http403()
{
errorViewModel.RootCause = Enums.RootCause.Forbidden;
return View("Error", errorViewModel);
}

Resources