Fetch Email Address for SentOnBehalfOfName in outlook 2007 VSTO code - vsto

I am developing Outlook 2007 VSTO addin. I need to fetch the email address specified in from section like given below:
info#xyz.com; on behalf of; KANxyz SAXYZ [saxyz7#gmail.com]
I need to fetch [saxyz7#gmail.com] in code. But I just get SentOnBehalfOfName property that only returns the name (in this case "KANxyz SAXYZ").
try
{
Outlook.Selection objSelection = null;
// Get the Application object
Microsoft.Office.Interop.Outlook.Application application = Globals.ThisAddIn.Application;
try
{
var window = application.ActiveWindow();
try
{
objSelection = application.ActiveExplorer().Selection;
}
catch (System.Exception ex)
{
//Ignore; NULL check below will branch out
}
objMail = default(Outlook.MailItem);
try
{
objMail = objSelection[1];
}
catch (Exception ex)
{
}
if ((objMail != null) && !string.IsNullOrEmpty(objMail.SenderEmailAddress))
{
email = objMail.SenderEmailAddress;
emailFrom = objMail.SentOnBehalfOfName;
}
}
catch { }
if ((objMail == null) || string.IsNullOrEmpty(objMail.SenderEmailAddress))
{
// Get the active Inspector object and check if is type of MailItem
Microsoft.Office.Interop.Outlook.Inspector inspector = application.ActiveInspector();
if (inspector != null)
{
mailItem = inspector.CurrentItem as Microsoft.Office.Interop.Outlook.MailItem;
if (mailItem != null)
{
email = mailItem.SenderEmailAddress;
emailFrom = objMail.SentOnBehalfOfName;
}
}
}
}
catch (Exception ex){ }

Related

Best way to find all Outlook calendars in all accounts

I have an application that uses the COM interface to communicate with Outlook.
I have a dropdown box, which has all the calendars from all the accounts.
There are some reported cases, where using exchange and Outlook 2010, the application hangs when loading the list of calendars. Could it be, that it has something to do with the code (shown below) or an anti-virus blocking the access for the address information?
It randomly fails for some Exchange accounts.
private void AppLoad(object sender, EventArgs e)
{
Outlook.Application msOutlook = new Outlook.Application();
Outlook.NameSpace session = msOutlook.Session;
Outlook.Stores stores = session.Stores;
foreach (Outlook.MAPIFolder folder in session.Folders)
{
GetFolders(folder, msOutlook);
}
if(calendarSelector.Items.Count==0)
{
StoreAndCalendar ci = new StoreAndCalendar();
ci.Text = "Default";
ci.Account = "Noaccount";
ci.Storename = "Noaccount";
ci.Value = "Noaccount";
calendarSelector.Items.Add(ci);
}
else
{
try
{
calendarSelector.SelectedIndex = 0;
}
catch { }
}
//preselect default calendar and account
GetDefaultCalendarAndAccount();
}
public void GetFolders(Outlook.MAPIFolder folder, Outlook.Application app)
{
if (folder.Folders.Count == 0)
{
if (folder.DefaultItemType == Outlook.OlItemType.olAppointmentItem)
{
StoreAndCalendar ci = new StoreAndCalendar();
Outlook.Account acc = GetAccountForFolder(folder, app);
if (acc != null)
{
if (!folder.FullFolderPath.Contains("Deleted"))
{
ci.Text = folder.Name + " - " + acc.DisplayName;
ci.Account = acc.DisplayName;
ci.Storename = acc.UserName;
ci.Value = folder.Name;
calendarSelector.Items.Add(ci);
}
}
}
}
else
{
if (folder.DefaultItemType == Outlook.OlItemType.olAppointmentItem)
{
StoreAndCalendar ci = new StoreAndCalendar();
Outlook.Account acc = GetAccountForFolder(folder, app);
if (acc != null)
{
if (!folder.FullFolderPath.Contains("Deleted"))
{
ci.Text = folder.Name + " - " + acc.DisplayName;
ci.Account = acc.DisplayName;
ci.Storename = acc.UserName;
ci.Value = folder.Name;
calendarSelector.Items.Add(ci);
}
}
}
foreach (Outlook.MAPIFolder subFolder in folder.Folders)
{
GetFolders(subFolder, app);
}
}
}
Outlook.Account GetAccountForFolder(Outlook.MAPIFolder folder, Outlook.Application app)
{
// Obtain the store on which the folder resides.
Outlook.Store store = folder.Store;
// Enumerate the accounts defined for the session.
foreach (Outlook.Account account in app.Session.Accounts)
{
// Match the DefaultStore.StoreID of the account
// with the Store.StoreID for the currect folder.
if (account.DeliveryStore.StoreID == store.StoreID)
{
// Return the account whose default delivery store
// matches the store of the given folder.
return account;
}
}
// No account matches, so return null.
return null;
}
public void GetDefaultCalendarAndAccount()
{
try
{
Outlook.Application OutlookApp = new Outlook.Application();
Outlook.NameSpace ns;
Outlook.MAPIFolder defaultfolder;
Outlook.Account defaultaccount;
ns = OutlookApp.Session;
ns.SendAndReceive(false);
defaultfolder = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar);
defaultaccount = GetAccountForFolder(defaultfolder, OutlookApp);
String defaultaccandfold = defaultfolder.Name + " - " + defaultaccount.DisplayName;
int index = 0;
for (int i = 0; i < calendarSelector.Items.Count; i++)
{
string value = calendarSelector.GetItemText(calendarSelector.Items[i]);
if (value == defaultaccandfold)
{
calendarSelector.SelectedIndex = index;
}
index++;
}
}
catch { }
}
What is the best way of going through the accounts, and all of their subfolders, listing all the valid calendars?
Also, selecting the default calendar: is that the way it has to be done?
Thank you!
You're on target as to the best approach. But some suggestions:
There's no need to iterate through Accounts, just parse Stores
Don't process Stores for non-email Store objects, like SharePoint Lists and Internet Calendars (unless you want those kinds of Calendars)
Don't use foreach loops with the Outlook Object Model, use for loops so you can explicitly call Marshal.ReleaseComObject on every variable that references an Outlook object
Your call to NameSpace.SendAndReceive is probably unnecessary and could be causing some delays

Having Trouble with ObjectInputStream/OutputStream

I am having trouble with my programs ability to save my Maps to a file. Here are my two methods for writing and reading my maps and arraylist.
Here is my read method:
private void getData() throws IOException, ClassNotFoundException {
File f_Instructors = new File(PSLTrackerInfo.file + "instructors.brent");
File f_Students = new File(PSLTrackerInfo.file + "students.brent");
File f_Times = new File(PSLTrackerInfo.file + "times.brent");
if (f_Instructors.exists()) {
try (ObjectInputStream in = new ObjectInputStream(new
BufferedInputStream(new FileInputStream(f_Instructors)))) {
//Add theList back in
if (in.readObject() != null) {
TreeMap<Instructor, Set<Student>> read = null;
while(in.available() > 0) {
read = (TreeMap<Instructor, Set<Student>>)
in.readObject();
}
if (read != null) {
for (Instructor key : read.keySet()) {
System.out.println(key);
Set<Student> values = read.get(key);
PSLTrackerInfo.addInstructor(key, values);
}
System.out.println("Instructors Found! Reading...");
} else {
System.out.println("No instructor data saved.1");
}
} else {
System.out.println("No instructor data saved.2");
}
in.close();
}
}
//Add times back in
if (f_Times.exists()) {
try (ObjectInputStream in = new ObjectInputStream(new
BufferedInputStream(new FileInputStream(f_Times)))) {
if (in.readObject() != null) {
TreeMap<Student, ArrayList<Date>> readTimes = null;
while(in.available() > 0) {
readTimes = (TreeMap<Student, ArrayList<Date>>) in.readObject();
}
if (readTimes != null) {
for (Student key : readTimes.keySet()) {
System.out.println(key);
ArrayList<Date> values = readTimes.get(key);
PSLTrackerInfo.addTimes(key, values);
}
System.out.println("Dates Found! Reading...");
} else {
System.out.println("No dates saved.");
}
} else {
System.out.println("No dates saved.");
}
in.close();
}
}
//Add newStudents back in
if (f_Students.exists()) {
try (ObjectInputStream in = new ObjectInputStream(new
BufferedInputStream(new FileInputStream(f_Students)))) {
if (in.readObject() != null) {
ArrayList<Student> readStudents = null;
while (in.available() > 0) {
readStudents = (ArrayList<Student>) in.readObject();
}
if (readStudents != null) {
PSLTrackerInfo.setTheList(readStudents);
}
System.out.println("New students found! Reading...");
} else {
System.out.println("No new students data saved.");
}
in.close();
}
}
}
And Here is my Writing method:
private void saveData() {
System.out.println("Saving Data...");
File f_Instructors = new File(PSLTrackerInfo.file + "instructors.brent");
File f_Students = new File(PSLTrackerInfo.file + "students.brent");
File f_Times = new File(PSLTrackerInfo.file + "times.brent");
ObjectOutputStream out_Instructors = null;
ObjectOutputStream out_Students = null;
ObjectOutputStream out_Times = null;
try {
out_Instructors = new ObjectOutputStream(new
BufferedOutputStream(new FileOutputStream(f_Instructors)));
out_Students = new ObjectOutputStream(new
BufferedOutputStream(new FileOutputStream(f_Students)));
out_Times = new ObjectOutputStream(new
BufferedOutputStream(new FileOutputStream(f_Times)));
out_Instructors.writeObject(PSLTrackerInfo.getMap());
out_Times.writeObject(PSLTrackerInfo.getTimes());
out_Students.writeObject(PSLTrackerInfo.getList());
out_Instructors.flush();
out_Students.flush();
out_Times.flush();
out_Instructors.close();
out_Students.close();
out_Times.close();
} catch (IOException ex) {
Logger.getLogger(PrivateLessonsTrackerGUI.class.getName())
.log(Level.SEVERE, null, ex);
}
System.exit(0);
}
Sorry if it is a little confusing I have 3 files to save 3 different objects, if there is a way to save it into one file let me know but I just was getting a lot of errors that I couldn't figure out how to solve so this is what I ended up doing. Thanks for any help given.
To EJP: I tried this
TreeMap<Instructor, Set<Student>> read = null;
try {
read = (TreeMap<Instructor, Set<Student>>)
in.readObject();
} catch (EOFException e) {
System.out.println("Caught EOFException!");
}
And even when there was data in it when it was written to the file, I got an EOFException everytime.
readObject() doesn't return null unless you wrote a null. If you're using that as a test for end of stream, it is invalid. The correct technique is to catch EOFException.
You are calling it and throwing away the result if it isn't null, and then calling it again. The second call will throw EOFException if there isn't another object in the file. It won't give you the same result as the first call. It's a stream.
available() is also not a valid test for end of stream. That's not what it's for. See the Javadoc. Again, the correct technique with readObject() is to catch EOFException.

Sharepoint 2010 EventReceiver for SPFolder adding

I have a document library in which we have added a custom folder content type in order to keep the Folder Owner in a custom field.
Now I am asked to set the default value of the "Add new" form to the Parent Folder Owner. I have tried this code below but the event fires after saving the new Folder. Could anyone pls help me? How can I set this default value before opening the form?
public override void ItemAdding(SPItemEventProperties properties)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
try
{
this.EventFiringEnabled = false;
base.ItemAdding(properties);
if (properties.List.RootFolder.Name == "Documents")
{
SPWeb web = properties.List.ParentWeb;
SPList List = properties.List;
SPField fld = List.Fields["Folder Owner"];
SPUser usr = web.CurrentUser;
SPFieldUserValue curUser = new SPFieldUserValue();
curUser.LookupId = usr.ID;
SPFolder parentFolder = web.GetFolder(properties.AfterUrl.Substring(0,properties.AfterUrl.LastIndexOf("/")));
if (parentFolder.Item["Folder Owner"] == null)
{
fld.DefaultValue = curUser.ToString();
}
else
{
fld.DefaultValue = parentFolder.Item["Folder Owner"].ToString();
}
fld.Update();
List.Update();
}
}
catch (Exception)
{
}
finally
{
this.EventFiringEnabled = true;
}
});
}

How to search file from a document library using client object model sharepoint 2010

At the moment i am struggling to programatically enable the search functionality to search file from a document library using client object model sharepoint 2010,
Can you please help me with the code
Thanks
Kajal
List list = clientcontext.Web.Lists.GetByTitle(ListName);
clientcontext.Load(list);
clientcontext.ExecuteQuery();
FileCollection files = list.RootFolder.Files;
clientcontext.Load(files);
clientcontext.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.File file in files)
{
if(file.Name == txtSearch)
{
// your logic
}
}
private string searchDoc(string name)
{
try
{
ClientContext clientContext = new ClientContext("YOUR SERVER");
SP.List oList = clientContext.Web.Lists.GetByTitle("YOUR DOC");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = #"<View Scope='Recursive'/>";
Microsoft.SharePoint.Client.ListItemCollection collListItem1 = oList.GetItems(camlQuery);
clientContext.Load(collListItem1, items => items.Include(item => item.DisplayName, item => item["Comments"]));
clientContext.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem oListItem1 in collListItem1)
{
if (oListItem1.DisplayName == name)
{
XXXXXXXXXXXXXX
}
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message, "Exception");
}
}
Recursive's search!

java mail keeping Transport object connected

How do i keep the java mail transport object alive or connected.
I have written this in my code in a simple class file inside a web application : -
#Resource(name = "myMailServer")
private Session mailSession;
Transport transport ;
public boolean sendMail(String recipient, String subject, String text) {
boolean exe = false;
Properties p = new Properties();
String username = "someone#gmail.com";
String password = "password";
InitialContext c = null;
try
{
c = new InitialContext();
mailSession = (javax.mail.Session) c.lookup("java:comp/env/myMailServer");
}
catch(NamingException ne)
{
ne.printStackTrace();
}
try
{
Message msg = new MimeMessage(mailSession);
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(recipient, false));
msg.setSubject(subject);
msg.setText(text);
msg.setHeader("MIME-Version" , "1.0" );
msg.setHeader("Content-Type" , "text/html" );
msg.setHeader("X-Mailer", "Recommend-It Mailer V2.03c02");
msg.saveChanges();
//Transport.send(msg);
if(transport == null) {
transport = mailSession.getTransport("smtps");
System.out.println("" + transport.isConnected());
if(!transport.isConnected()) {
transport.connect(username, password);
}
}
transport.sendMessage(msg, msg.getAllRecipients());
exe = true;
}
catch (AddressException e)
{
e.printStackTrace();
exe = false;
}
catch (MessagingException e)
{
e.printStackTrace();
exe = false;
}
finally {
/*try {
if(transport != null)
transport.close();
}
catch(MessagingException me) {
me.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}*/
}
return exe;
}
the full code here
Now everytime i run this code it takes some time to connect with the mail server
and the line
System.out.println("" + transport.isConnected());
prints a false
How do i retain the object transport as it does gets null and into the block
if(transport == null) {
or the transport object remains connected...
Thanks
Pradyut
the code should be....
with a static initialization of transport object
without any problems but can be good with a function
static Transport getTransport() method
#Resource(name = "myMailServer")
private Session mailSession;
static Transport transport ;
public boolean sendMail(String recipient, String subject, String text) {
boolean exe = false;
Properties p = new Properties();
String username = "someone#gmail.com";
String password = "password";
InitialContext c = null;
try
{
c = new InitialContext();
mailSession = (javax.mail.Session) c.lookup("java:comp/env/myMailServer");
}
catch(NamingException ne)
{
ne.printStackTrace();
}
try
{
Message msg = new MimeMessage(mailSession);
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(recipient, false));
msg.setSubject(subject);
msg.setText(text);
msg.setHeader("MIME-Version" , "1.0" );
msg.setHeader("Content-Type" , "text/html" );
msg.setHeader("X-Mailer", "Recommend-It Mailer V2.03c02");
msg.saveChanges();
//Transport.send(msg);
if(transport == null) {
transport = mailSession.getTransport("smtps");
}
if(!transport.isConnected()) {
transport.connect(username, password);
}
transport.sendMessage(msg, msg.getAllRecipients());
exe = true;
}
catch (AddressException e)
{
e.printStackTrace();
exe = false;
}
catch (MessagingException e)
{
e.printStackTrace();
exe = false;
}
finally {
/*try {
if(transport != null)
transport.close();
}
catch(MessagingException me) {
me.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}*/
}
return exe;
}
Thanks
Regards
Pradyut