Exception Management Application Block with MVC - asp.net-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);
}

Related

Selenium grid error : Session [(null externalkey)] not available and is not among the last 1000 terminated sessions

We are executing multiple test cases in selenium grid where hub is connected to 2 machines, but every time I am running the grid, I get an error.
Error creating a webdriver. Exception message:
Session [(null externalkey)] not available and is not among the last 1000 terminated sessions.
Active sessions are[]
Command duration or timeout: 0 milliseconds
Code:
private static List<WebDriver> m_listOfWebDrivers = Collections.synchronizedList(new ArrayList<WebDriver>());
private static ThreadLocal<WebDriver> m_driverForThread = new ThreadLocal<WebDriver>() {
#Override
protected WebDriver initialValue() {
WebDriver driver = null;
try {
driver = loadDesktopDriver();
} catch (Exception e) {
e.printStackTrace();
}
Log.info("Initializing Webdriver");
m_listOfWebDrivers.add(driver);
return driver;
}
};
protected static WebDriver loadDesktopDriver() throws Exception {
WebDriver driver = null;
Log.debug("Get Driver for Browser : " + m_browser);
try {
if (!m_runOnBrowserStack && null == m_browser) {
throw new IllegalArgumentException("Browser value should be provided for test");
}
driver = getNewDriver(m_browser, "", "", m_context);
**driver.manage().timeouts().implicitlyWait(50000, TimeUnit.MILLISECONDS);** /* this was added later, still didnt work*/
} catch (Exception e) {
Log.fatal("Error creating a webdriver. Exception message : " + e.getMessage());
throw e;
}
return driver;
}
public static WebDriver getNewDriver(String browserName, String browserVersion, String platform,
ITestContext context)
throws IOException, ComboBoxElementException, TextBoxElementException, ElementException, PageException {
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.BROWSER, Level.ALL);
/**
* These capabilities will need to be re assigned according to the
* browser we are going to be launched. This is required in case of
* running on Grid only but keeping it same normal execution to avoid
* code redundancy.
*/
DesiredCapabilities desiredCapabilities = null;
if (m_runOnBrowserStack) {
desiredCapabilities = new DesiredCapabilities();
JSONObject envs = (JSONObject) m_bsConfig.get("environment");
String bsEnvironment = context.getCurrentXmlTest().getParameter("bsEnvironment");
String testName = context.getCurrentXmlTest().getName();
Log.info("Environmnet details for Test [" + testName + "] is : " + bsEnvironment);
if (null == bsEnvironment)
throw new PageException(
"Environment name does not present in XML or not passed from CLI : " + bsEnvironment);
Map<String, String> envCapabilities = (Map<String, String>) envs.get(bsEnvironment);
if (null == envCapabilities)
throw new PageException("Environment name does not present in Config file : " + bsEnvironment);
Iterator<Entry<String, String>> it = envCapabilities.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, ?> pair = (Map.Entry<String, ?>) it.next();
desiredCapabilities.setCapability(pair.getKey().toString(), pair.getValue().toString());
}
Map<String, String> commonCapabilities = (Map<String, String>) m_bsConfig.get("capabilities");
it = commonCapabilities.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, ?> pair = (Map.Entry<String, ?>) it.next();
if (desiredCapabilities.getCapability(pair.getKey().toString()) == null) {
desiredCapabilities.setCapability(pair.getKey().toString(), pair.getValue().toString());
}
}
browserName = (String) desiredCapabilities.getCapability("browser");
}
DriverSupportedBrowsers driverType = DriverSupportedBrowsers.valueOf(browserName.toUpperCase());
if (null != m_gridUrl && !m_gridUrl.isEmpty()) {
m_gridUrl += "/wd/hub";
}
switch (driverType) {
case CHROME:
String chromeDriverPath = driverHome + File.separator + FrameworkConstants.chromeDriverExeName;
if (m_runOnBrowserStack || CommonHelper.isFileExists(chromeDriverPath)) {
if (!m_runOnBrowserStack)
desiredCapabilities = DesiredCapabilities.chrome();
desiredCapabilities.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
options.addArguments("--disable-extensions");
// To start browser in private mode
// options.addArguments("incognito");
desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, options);
System.setProperty("webdriver.chrome.driver", chromeDriverPath);
if (null != m_gridUrl && !m_gridUrl.isEmpty()) {// for runs on
// grid
return new RemoteWebDriver(new URL(m_gridUrl), desiredCapabilities);
} else
return new RemoteWebDriver(service.getUrl(), desiredCapabilities); /* The code fails here generally with the failure*/
} else {
throw new FileNotFoundException(
"Chrome Driver path : " + chromeDriverPath + "\n\"" + FrameworkConstants.chromeDriverExeName
+ "\" not found in driver home path declared in System Environment Variable \""
+ driverHome + "\"");
}
#Parameters({ "bsEnvironment" })
#BeforeMethod(alwaysRun = true)
public void initialize(ITestContext context, Method method, #Optional String bsEnvironment)
throws IOException {
String customer = context.getCurrentXmlTest().getParameter("customer");
String testName = context.getCurrentXmlTest().getName();
setTestName(testName);
String methodName = "";
m_testMethod = method.getName();
methodName = testName + "_" + method.getName() + "_" + customer;
CommonHelper.renameRetryLog(m_logDir, methodName);
Log.setLog(m_logDir, methodName);
m_context = context;
if (m_runOnBrowserStack) {
if (null == context.getCurrentXmlTest().getParameter("bsEnvironment")
|| context.getCurrentXmlTest().getParameter("bsEnvironment").isEmpty()) {
Log.info("Adding bsEnvironment parameter for run on BrowserStack");
context.getCurrentXmlTest().addParameter("bsEnvironment", bsEnvironment);
}
}
try {
WebDriver driver = getDriverInstanceForThread();
if (null == driver)
throw new PageException("Driver is null. Initialization problem!!");
// Logging browser name and version parameters, driver and thread
// instances
String browserName = null;
String browserVersion = null;
try {
Capabilities webDriverCapablities = ((RemoteWebDriver) driver).getCapabilities();
browserName = webDriverCapablities.getBrowserName();
browserVersion = webDriverCapablities.getVersion();
} catch (ClassCastException e) {
Log.error("Unable to cast driver to RemoteWebdriver");
browserName = m_browser;
browserVersion = "NA";
}
Log.info("\n ****************** START OF TEST CASE " + method.getName() + " " + customer + ":"
+ browserName + ":" + browserVersion + "\t THREAD:" + Thread.currentThread().getId()
+ "\t WEBDRIVER:" + driver + " ****************** \n");
// driver.manage().timeouts().pageLoadTimeout(CommonConstants.PAGE_LOAD_WAIT_SEC,
// TimeUnit.SECONDS);
if (null != m_gridUrl) {
// Log the remote node ip address where the test is running
Log.info("Remote Node IP: " + CommonHelper.getIPOfRemoteNode(driver));
}
} catch (Exception e) {
e.printStackTrace();
Log.warn(e.getMessage());
}
The CMD is triggered for Node giving timeout and browser timeout:
java -Dwebdriver.chrome.driver=D:/imp/iTAF_Driver_Home/chromedriver.exe -jar selenium-server-standalone-3.3.1.jar -port 5554 -role node -hub http://10.18.15.168:5550/grid/register -timeout 86400 -browserTimeout 86000
This issue is a recurring error.

Changing synchronous call to async await(Asynchronous ) MvC controller

I am new to C# Asp.net mvc asynchronous programming. I need to uplaod vidoe to my server but it video upload is locked when I uploading the video. I can not do another tasks in parallel. I have tried like this but it is not working.
public async Task<ActionResult> upload()
{
if (Request.Files.Count > 0)
{
int chunk = Request["chunk"] != null ?
int.Parse(Request["chunk"]) : 0;
string fileName = Request["name"] != null ? Request["name"] :
string.Empty;
string upath = "";
if (Request.Headers["UName"] != null)
upath = Request.Headers["UName"].ToString();
//if (CloudSettings.EnableCloudStorage && upath != "")
// _fileName = upath.Substring(0, 3) + "-" + _fileName; // void duplication in cloud storage
long AlbumID = 0;
if (Request.Headers["MediaID"] != null)
AlbumID = Convert.ToInt64(Request.Headers["MediaID"]);
string uploadPath = "";
// default path
if (upath == "")
uploadPath = UrlConfig.Published_Video_Path(); // direct upload to published area
else
uploadPath = UrlConfig.Published_Video_Path(upath); // source video path
FileStream fs;
using (fs = new FileStream(Path.Combine(uploadPath, fileName), chunk == 0 ? FileMode.Create : FileMode.Append))
{
byte[] buffer = new byte[Request.Files[0].InputStream.Length];
await Request.Files[0].InputStream.ReadAsync(buffer, 0, buffer.Length);
await fs.WriteAsync(buffer, 0, buffer.Length);
}
string url = "";
string filetype = System.IO.Path.GetExtension(fileName);
string fileIndex = fileName.Replace(filetype, "");
string elementid = UtilityBLL.ReplaceSpaceWithHyphin(fileIndex);
//eturn fileName; // "Success";
return this.Content("{\"jsonrpc\" : \"2.0\", \"result\" : \"OK\", \"id\" : \"id\", \"fname\" : \"" + fileName + "\", \"url\" : \"" + url + "\", \"filetype\" : \"" + filetype + "\", \"filename\" : \"" + fileName + "\", \"fileIndex\" : \"" + fileIndex + "\", \"eleid\" : \"" + elementid + "\"}", "text/plain");
}
else
{
return this.Content("failed", "text/plain");
}
}

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;
}

How To Get Value From DB While Editting Entry with Null value

Error Message:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
I want to get Image Url from database if fileupload has null value(not change).
I mean if i change smallImage and not change LargeImage,then it should get largeImage value from DB.
[HttpPost]
public ActionResult Edit(Blog blog, HttpPostedFileBase smallImage, HttpPostedFileBase largeImage)
{
if (ModelState.IsValid)
{
if (smallImage != null)
{
blog.SmallImage = smallImage.ContentLength + "_" + smallImage.FileName;
string filepath = Path.Combine(Server.MapPath("~/Content/Blog/"), smallImage.ContentLength + "_" + smallImage.FileName);
smallImage.SaveAs(filepath);
}
else
{
blog.SmallImage = db.Blogs.Find(blog.ID).SmallImage;
}
if (largeImage != null)
{
blog.LargeImage = largeImage.ContentLength + "_" + largeImage.FileName;
string filepath = Path.Combine(Server.MapPath("~/Content/Blog/"), largeImage.ContentLength + "_" + largeImage.FileName);
largeImage.SaveAs(filepath);
}
else
{
blog.LargeImage = db.Blogs.Find(blog.ID).LargeImage;
}
blog.PostDate = Convert.ToDateTime(DateTime.Now.ToShortDateString());
db.Entry(blog).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(blog);
}
Thank you.
You are both loading a copy of the blog
db.Blogs.Find(blog.ID)
and attaching another with the same id to the context
db.Entry(blog).State = EntityState.Modified;
meaning you have 2 copies of the same blog in the context (not allowed).
I'd recommend the replacing the one posted back with a viewmodel instead, something like
public ActionResult Edit(BlogViewModel viewModel, HttpPostedFileBase smallImage, HttpPostedFileBase largeImage)
{
if (!ModelState.IsValid)
{
return View(viewModel);
}
var blog = db.Blogs.Find(viewModel.ID);
if (smallImage != null)
{
blog.SmallImage = smallImage.ContentLength + "_" + smallImage.FileName;
string filepath = Path.Combine(Server.MapPath("~/Content/Blog/"), smallImage.ContentLength + "_" + smallImage.FileName);
smallImage.SaveAs(filepath);
}
if (largeImage != null)
{
blog.LargeImage = largeImage.ContentLength + "_" + largeImage.FileName;
string filepath = Path.Combine(Server.MapPath("~/Content/Blog/"), largeImage.ContentLength + "_" + largeImage.FileName);
largeImage.SaveAs(filepath);
}
blog.Title = viewModel.Title;
blog.Body = viewModel.Body; //etc
db.SaveChanges();
return RedirectToAction("Index");
}
Looks like issue here is that you load same blog twice.
Load it once instead, something like this:
Blog existingBlog = db.Blogs.Find(blog.ID);
if (smallImage != null)
{
blog.SmallImage = smallImage.ContentLength +
"_" + smallImage.FileName;
string filepath = Path.Combine(Server.MapPath("~/Content/Blog/"),
smallImage.ContentLength + "_" + smallImage.FileName);
smallImage.SaveAs(filepath);
}
else
{
blog.SmallImage = existingBlog.SmallImage;
}
if (largeImage != null)
{
blog.LargeImage = largeImage.ContentLength + "_" +
largeImage.FileName;
string filepath = Path.Combine(Server.MapPath("~/Content/Blog/"),
largeImage.ContentLength + "_" +
largeImage.FileName);
largeImage.SaveAs(filepath);
}
else
{
blog.LargeImage = existingBlog.LargeImage;
}

Outllook item get

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.

Resources