Get other user's Outlook availability information - c#

I am writing an application that creates an overview of peoples Outlook calendars, i.e it will show the amount of unplanned time per week for the coming [n] weeks.
The basics are working, but there's one thing that I am having trouble with. Some users have shared their Outlook calendar in a way so that other users can only see availability information (the time and description of the appointments), but not any details.
I verified this by opening Outlook manually and opening a shared calendar; hovering the mouse over an appointment will show a popup with begin and end time, description and location, but double clicking it gives an error: "You are not authorized to display the calendar, do you want to ask [person] to share it?".
The relevant lines from my code are:
var outlook = new Application();
var mapiNamespace = outlook.GetNamespace("MAPI");
var recipient = mapiNamespace.CreateRecipient("Scott");
recipient.Resolve();
var calendarFolder = mapiNamespace.GetSharedDefaultFolder(recipient, OlDefaultFolders.olFolderCalendar);
var calendarItems = calendarFolder.Items;
Everything I now try to do with calendarItems will raise an exception. For instance, getting Count will raise a TargetInvocationException (The client process failed, but I'm not quite sure about the exact English translation). Calling Sort("[Start]") will raise a COMException with message Unknown property: Start. Both do work for fully shared calendars.
Now, for the overview, all I need is begin and end times, so I don't really want to ask everyone to change their sharing settings, especially when that shouldn't be necessary.
My questions are:
Most important: Is there another way to get availability info that I'm overlooking?
And related: Is Interop still the way to go these days, or are there alternatives? Maybe an Office365 webservice?

Instead of using GetSharedDefaultFolder and accessing the items in that folder, you can use Recipient.FreeBusy method.

Related

How do I access the BusyStatus of a shared outlook calendar with limited permissions?

I am trying to read the AppointmentItem.BusyStatus from a shared calendar with limited access. I can see the BusyStatus for the entire day/week, but do not have access to information like the subject or location of an appointment.
My code looks like the following:
At first, I get the folder in which the shared calendars are stored.
oApp = new Outlook.Application();
mapiNamespace = oApp.GetNamespace("MAPI");
Outlook.Recipient oRep = mapiNamespace.CreateRecipient(oApp.Session.CurrentUser.Name);
calendarsFolder = mapiNamespace.GetSharedDefaultFolder(oRep, Outlook.OlDefaultFolders.olFolderCalendar).Folders;
In the next step, I iterate over all the calendars and their appointment items.
foreach(Outlook.Folder calendar in calendarsFolder){
Console.WriteLine(calendar.Name);
foreach(Outlook.AppointmentItem item in calendar.Items){
Console.WriteLine(item.Start.ToString("dd.MM.yyyy"));
Console.WriteLine(item.BusyStatus);
}
}
This code works just fine on a calendar which grants me full control to read any details the appointment may have. It does not work on the calendar with limited access though. After debugging my code, I found out that the calendar.Items list of this particular calendar is empty, its count is 0. I am assuming this has to do with me not having the proper authorization to retrieve this information, since I could read the subject and location if I got the appointment items. This is just an assumption however, and I am honestly not quite sure what is going on. Do I need an entirely different approach or am I just missing something? I would really appreciated it, if someone could help me out.
Use Recipient.FreeBusy instead - it does not require access rights to the mailbox.

Outlook Interop Exception HRESULT: 0xCA140115

I have some pretty basic code that seems to work for most people but there's at least one workstation that throws this HRESULT code when it runs these couple lines of code:
Outlook.Application _OutlookInstance = new Outlook.Application();
Outlook.Stores stores = _OutlookInstance.Session.Stores;
Any idea what HRESULT code 0xCA140115 is or what it means? I can't find it on MSDN anywhere...
The workstation that experiences the problem is at a remote call center location, so I can't do any immediate testing/debugging, or easily see what is specifically different about this workstation versus the others. I would imagine there might be more workstations at that same call center that could have the error, but this code is still in the testing phase.
Sorry for the delay, but I was able to get through several more iterations of testing and find out what the issue was. First off, my original post was incorrect. The code flow made it seem like the error was happening during those 2 initial lines, but it was actually happening a little later, when I was looping through the stores, like this:
Outlook.Stores stores = _OutlookInstance.Session.Stores;
foreach(Outlook.Store store in stores) // <----- THIS LINE
{
...
}
Each time the user ran this, he would get a different HRESULT error code:
0xCA140115
0xAF64011D
0xC1F4011D
0xC834011D
The only consistent factor was the "4011" in the middle.
When I upped the logging, I could see that the user had 18 mailboxes and the foreach() loop was getting through the first 3 but failing on the 4th. The 4th mailbox was a "Public Folders" store associated to another mailbox that was added in a different way than the rest of the mailboxes (it had something to do with it being an Outlook 365 mailbox that required different authentication).
So essentially it ended up being that any attempt to even touch that particular mailbox/store (including the "store" variable being set) would result in that COM exception.
I was able to work around it by looping through stores via numeric index so that the setting of "store" was inside my try/catch block, like this:
for(int i = 0; i < stores.Count; i++)
{
try
{
Outlook.Store store = stores[i];
...
}
catch(Exception)
{
...
}
}
Now when the loop hit that particular store, I could tell that it was Outlook saying that the server wasn't available, and the store was an online-only store, so the store couldn't be accessed.
I'm still not certain about why the error codes changed each time, but there you have it.

Get Direct Reports from Logged in user from Exchange

I need to get the direct reports from a logged in user (MVC 4)
I don't need the names of the direct reports but I do need their email addresses including their proxy addresses.
So for this reason I need to search through Exchange. I personally have never attempted to search Exchange in the past and everything I find out there tells me how to get from step 8 to the finish line but says nothing about how to go from step 1 to 8.
I can get the current users user name by simply
User.Identity.Name.Replace(#"yourdomain\", "")
and I have found this example which so far is probably the best example I have found
http://msdn.microsoft.com/en-us/library/office/ff184617(v=office.15).aspx
but even with that example the line
Outlook.AddressEntry currentUser =
Application.Session.CurrentUser.AddressEntry;
is not actually getting the current user logged into the site.
I really hope someone out there is familiar with this and can get me past this point.
I reworked the sample from the URL as the following LINQPad 4 query. I've found that LINQPad is a great way to experiment because it is very scripty, allowing quick experimentation, and you can easily view data by using the Dump() extension method. Purchasing intellisense support is totally worthwhile.
Also, I noticed there is a lot of fine print like:
The logged-on user must be online for this method to return an AddressEntries collection; otherwise, GetDirectReports returns a null reference. For production code, you must test for the user being offline by using the _NameSpace.ExchangeConnectionMode property, or the _Account.ExchangeConnectionMode property for multiple Exchange scenarios.
and
If the current user has a manager, GetDirectReports() is called to return an AddressEntries collection that represents the address entries for all the direct reports of user’s manager. If the manager has no direct reports, GetDirectReports returns an AddressEntries collection that has a count of zero.
So there are a lot of assumptions like Exchange is configured properly with Direct Report relationships, and the current user is online...which I believe brings Lync into the equation. Hopefully this LINQPad query will be useful to you. Just copy and paste it into a text editor and name it with the .linq file extension. You'll then be able to open it in LINQPad 4. BTW: You're question caught my attention because there was talk recently at my work of pulling direct reports from Active Directory. I wish I could be more helpful...good luck.
<Query Kind="Program">
<Reference><ProgramFilesX86>\Microsoft Visual Studio 12.0\Visual Studio Tools for Office\PIA\Office15\Microsoft.Office.Interop.Outlook.dll</Reference>
<Reference><ProgramFilesX86>\Microsoft Visual Studio 12.0\Visual Studio Tools for Office\PIA\Office15\Microsoft.Office.Interop.OutlookViewCtl.dll</Reference>
<Namespace>Microsoft.Office.Interop.Outlook</Namespace>
</Query>
void Main()
{
GetManagerDirectReports();
}
// Define other methods and classes here
private void GetManagerDirectReports()
{
var app = new Microsoft.Office.Interop.Outlook.Application();
AddressEntry currentUser = app.Session.CurrentUser.AddressEntry;
if (currentUser.Type == "EX")
{
ExchangeUser manager = currentUser.GetExchangeUser().GetExchangeUserManager();
manager.Dump();
if (manager != null)
{
AddressEntries addrEntries = manager.GetDirectReports();
if (addrEntries != null)
{
foreach (AddressEntry addrEntry in addrEntries)
{
ExchangeUser exchUser = addrEntry.GetExchangeUser();
StringBuilder sb = new StringBuilder();
sb.AppendLine("Name: " + exchUser.Name);
sb.AppendLine("Title: " + exchUser.JobTitle);
sb.AppendLine("Department: " + exchUser.Department);
sb.AppendLine("Location: " + exchUser.OfficeLocation);
sb.Dump();
}
}
}
}
}
I would suggest using EWS Managed API in conjunction with your code to get the direct reports for a user. As Jeremy mentioned in his response that you need to have your direct report relationships already set up. To help you get started, here some steps to get EWS Managed API up and running:
Download the latest version of EWS Managed API
Get started with EWS Managed API client applications to learn about how to reference the assembly, set the service URL, and communicate with EWS.
Start working with your code. If you need some functioning code to get you going, check out the Exchange 2013 101 Code Samples that has some authentication code already written and a bunch of examples you can modify to make your own.
If you have the email address or user name of the current user you can use the ResolveName() method to get to their mailbox to retrieve additional information. Here is an article to help with that method: How to: Resolve ambiguous names by using EWS in Exchange 2013
Essentially you want to get to the point where you can run a command similar to this:
NameResolutionCollection coll = service.ResolveName(NameToResolve, ResolveNameSearchLocation.DirectoryOnly, true, new PropertySet(BasePropertySet.FirstClassProperties));
If you give a unique enough value in the NameToResolve parameter you should only get back one item in the collection. With that, you can look at the direct reports collection within that one item and see not only the names of their direct reports, but their email addresses as well.
I hope this information helps. If this does resolve your problem, please mark the post as answered.
Thanks,
--- Bob ---

Getting attachments from a mail account with .NET

I'd like a free library for .NET to get attachments from an account (such as gMail, or others) via imap4 (not necessarely), and save them in a folder.
Ideally it would allow me to get a list of them, and download only some given ones (filtering by extension, name, and/or size) and be free.
I've already done this with a trial version of EAGetMail, but for the purpose of what i'm trying to attempt buying the unlimited version of this library isn't quite suitable (i didn't know that this functionality itself was one among the ones with limited time).
---[edit - Higuchi]---
I'm using the following code:
Dim cl As New Pop3Client()
cl.UserName = "marcelo.f.ramires#gmail.com"
cl.Password = "mypassword"
cl.ServerName = "pop.gmail.com"
cl.AuthenticateMode = Pop3AuthenticateMode.Pop
cl.Ssl = False
cl.Authenticate() //takes a while, but passes even if there's a wrong password
Dim mg As Pop3Message = cl.GetMessage(1) //gives me an exception: Message = "Pop3 connection is closed"
UPDATE: Setting the port to 995 gives me a "Response TimeOut" exception
As commented, I am having some issues while trying to connect and get the first e-mail. any help ?
Well, I know you specified IMAP4, but I figured I'd offer this anyway in case POP3 is an option, since it's been useful for me:
http://csharpmail.codeplex.com/
This library provides access to POP3 mail, which many e-mail services (including Gmail) do offer in addition to the newer IMAP.
The core class is Pop3Client, which provides access to POP3 functions such as ExecuteList, ExecuteTop, etc. I have used this for specifically what you are asking about -- scanning for and downloading attachments.
If you decide this is something you could use after all and need further guidance, let me know.
UPDATE: In response to your updated question, I have just a few preliminary suggestions:
Consider setting the Pop3Client.Port property to 995. I know this is what Gmail uses for POP3.
The Pop3Client.Authenticate method returns a bool value indicating whether or not authentication was successful. You can check this value after calling the method to know whether it will be possible to progress further.
UPDATE 2: I tried this at home with the following settings and it worked for me:
Using client As New Pop3Client
client.UserName = "username#gmail.com"
client.Password = "[insert password here]"
client.ServerName = "pop.gmail.com"
client.AuthenticateMode = Pop3AuthenticateMode.Pop
client.Ssl = True ' NOTICE: in your example code you have False here '
client.Port = 995
client.Authenticate()
Dim messageList = client.ExecuteList()
Console.WriteLine("# Messages: {0}", messageList.Count)
End Using
Try these settings and see if they work for you.
UPDATE 3: One more thing! Have you made sure to enable POP for your Gmail account? If not, you need to do that!
From your Gmail inbox, click "Settings" (top right).
From the Settings page, click the tab labeled "Forwarding and POP/IMAP."
In the POP Download section, select one of the radio buttons to enable POP mail.
Click "Save Changes" at the bottom.

How do I popup the compose / create mail dialog using the user's default email client?

The use case is simple. At a certain point of time, I need to be able to show the user his familiar compose email dialog (Outlook or other) with
fields like from, to, Subject already filled up with certain application determined values.
The email would also have an attachment along with it.
The mail should not be sent unless the user explicitly okays it.
I did this once back in the ol' VB6 days.. can't figure out how now.. I just remember that it was quite easy.
Managed app, C#, .net 3.0+
Update#1: Yeah seems like mailto removed support for attachments (as a security risk?). I tried
You need to include ShellExecute signature as described here. All I got from this was a 5 SE_ERR_ACCESSDENIED and a 2 just for some variety
string sMailToLink = #"mailto:some.address#gmail.com?subject=Hey&body= yeah yeah yeah";
IntPtr result = ShellExecute(IntPtr.Zero, "open", sMailToLink, "", "", ShowCommands.SW_SHOWNORMAL);
Debug.Assert(result.ToInt32() > 32, "Shell Execute failed with return code " + result.ToInt32());
The same MailtoLink works perfectly with Process.Start... but as long as thou shalt not mention attachments.
System.Diagnostics.Process.Start(sMailToLink);
The other options are using the Outlook Object model to do this.. but I've been told that this requires you to add assembly references based to the exact version of Outlook installed. Also this would blow up if the user doesn't prefer MS for email.
The next option are Mapi and something called Mapi33.. Status still IN PROGRESS. Ears still open to suggestions.
You can create a process object and have it call "mailto:user#example.com?subject=My+New+Subject". This will cause the system to act on the mailto with its default handler, however, while you can set subjects and such this wont handle adding an attachment. I'll freely admit im not entirely sure how you'd go about forcing an attachment without writing some mail plugin.
The process code is:
System.Diagnostics.Process.Start("mailto:user#example.com?subject=My+New+Subject");
It's probably not the most efficient or elegant way, but shelling a "mailto:" link will do what you want, I think.
EDIT: Sorry, left out a very important "not".
Since mailto does not support attachments, and since MAPI is not supported within managed code, your best bet is to write (or have someone write) a small non-managed program to call MAPI functions that you can call with command-line arguments. Pity that .NET does not have a cleaner alternative.
See also : MAPI and managed code experiences?
Could it be that you used the mailto: protocol?
Almost all of what you highlight can be done, but I am quite sure, that you cant do attachments.
Microsoft MailTo Documentation
Starting process with mailto: arguments is the simplest approach. Yet, it does not allow anything more or less complex.
Slightly different approach involves creating email template and then feeding it to the Process.Start:
var client = new SmtpClient();
var folder = new RandomTempFolder();
client.DeliveryMethod =
SmtpDeliveryMethod.SpecifiedPickupDirectory;
client.PickupDirectoryLocation = folder.FullName;
var message = new MailMessage("to#no.net",
"from#no.net", "Subject","Hi and bye");
// add attachments here, if needed
// need this to open email in Edit mode in OE
message.Headers.Add("X-Unsent", "1");
client.Send(message);
var files = folder.GetFiles();
Process.Start(files[0].FullName);
Scenarios for the default email handler:
Outlook express opens
Windows: Outlook - does not handle by default, Outlook Express is called instead
Windows: The Bat! - message is opened for viewing, hit Shift-F6 and Enter to send
I've also tested with Mono and it worked more or less.
Additional details are available in this post: Information integration - simplest approach for templated emails
PS: in the end I went for slightly more complex scenario:
Defined interface IEmailIntegraton
Code above went into the DefaultEmailIntegration
Added implementations for OutlookEmailIntegration (automation) and theBat! email integration (using their template format).
Allowed users of the SmartClient to select their scenario from the drop-down (alternatively this could've been implemented as "Check the system for the default email handler and decide automatically")
You're making the assumption that they will have an email client installed, of course.
The option I've taken in the past (in a corporate environment where everyone has at least one version of Outlook installed) was to use the Outlook interop - you only need to reference the earliest version you need to support.
You could look at P/Invoking MAPISendDocuments (which I'd try and avoid, personally), or the other option would be to create your own "compose" form and use the objects from the System.Net.Mail namespace.
you can use a trick if you intend to use Outlook[this code is based on outlook 2010[v14.0.0.]]
Create Outlook MailItem
and transmit file (ie download)
if user opens the file (.msg) the compose message dialog opens automatically
here is the code ...
Microsoft.Office.Interop.Outlook.Application outapp = new Application();
try
{
_NameSpace np = outapp.GetNamespace("MAPI");
MailItem oMsg = (MailItem)outapp.CreateItem(OlItemType.olMailItem);
oMsg.To = "a#b.com";
oMsg.Subject = "Subject";
//add detail
oMsg.SaveAs("C:\\Doc.msg", OlSaveAsType.olMSGUnicode);//your path
oMsg.Close(OlInspectorClose.olSave);
}
catch (System.Exception e)
{
status = false;
}
finally
{
outapp.Quit();
}
then transmit the file you created say "Doc.msg"
string filename ="Doc.msg";//file name created previously
path = "C:\\" + filename; //full path ;
Response.ContentType="application/outlook";
Response.AppendHeader("Content-Disposition", "filename=\"" + filename + "\"");
FileInfo fl = new FileInfo(path);
Response.AddHeader("Content-Length", fl.Length.ToString());
Response.TransmitFile(path,0,fl.Length);
Response.End();

Categories