/// <summary> /// Display the DelegateDialog for the current mailbox. /// </summary> /// <param name="sender">The parameter is not used.</param> /// <param name="e">The parameter is not used.</param> private void MnuDelegateInformation_Click(object sender, EventArgs e) { NameResolutionCollection names = null; // Attempt to resolve the Act As account name. If there is only one // hit from ResolveNames then assume it is the right one. if (this.CurrentAppSettings != null) { if (this.CurrentAppSettings.AuthenticationMethod == RequestedAuthType.oAuth) { names = this.CurrentService.ResolveName(this.CurrentAppSettings.MailboxBeingAccessed); } else { names = this.CurrentService.ResolveName(this.CurrentService.GetActAsAccountName()); } } else { names = this.CurrentService.ResolveName(this.CurrentService.GetActAsAccountName()); //this.CurrentAppSettings.MailboxBeingAccessed; } if (names.Count == 1) { DialogResult res = DelegateDialog.ShowDialog( this.CurrentService, new Mailbox(names[0].Mailbox.Address)); } else { DialogResult res = DelegateDialog.ShowDialog(this.CurrentService); } }
static Dictionary <string, Folder> GetSharedCalendarFolders(ExchangeService service, String searchIn = "My Calendars") { Dictionary <String, Folder> rtList = new Dictionary <string, Folder>(); FolderId rfRootFolderid = new FolderId(WellKnownFolderName.Root);//, mbMailboxname FolderView fvFolderView = new FolderView(1000); SearchFilter sfSearchFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "Common Views"); FindFoldersResults ffoldres = service.FindFolders(rfRootFolderid, sfSearchFilter, fvFolderView); if (ffoldres.Folders.Count == 1) { PropertySet psPropset = new PropertySet(BasePropertySet.FirstClassProperties); ExtendedPropertyDefinition PidTagWlinkAddressBookEID = new ExtendedPropertyDefinition(0x6854, MapiPropertyType.Binary); ExtendedPropertyDefinition PidTagWlinkFolderType = new ExtendedPropertyDefinition(0x684F, MapiPropertyType.Binary); ExtendedPropertyDefinition PidTagWlinkGroupName = new ExtendedPropertyDefinition(0x6851, MapiPropertyType.String); psPropset.Add(PidTagWlinkAddressBookEID); psPropset.Add(PidTagWlinkFolderType); ItemView iv = new ItemView(1000); iv.PropertySet = psPropset; iv.Traversal = ItemTraversal.Associated; SearchFilter cntSearch = new SearchFilter.IsEqualTo(PidTagWlinkGroupName, searchIn); FindItemsResults <Item> fiResults = ffoldres.Folders[0].FindItems(cntSearch, iv); foreach (Item itItem in fiResults.Items) { try { object GroupName = null; object WlinkAddressBookEID = null; if (itItem.TryGetProperty(PidTagWlinkAddressBookEID, out WlinkAddressBookEID)) { byte[] ssStoreID = (byte[])WlinkAddressBookEID; int leLegDnStart = 0; String lnLegDN = ""; for (int ssArraynum = (ssStoreID.Length - 2); ssArraynum != 0; ssArraynum--) { if (ssStoreID[ssArraynum] == 0) { leLegDnStart = ssArraynum; lnLegDN = System.Text.Encoding.ASCII.GetString(ssStoreID, leLegDnStart + 1, (ssStoreID.Length - (leLegDnStart + 2))); ssArraynum = 1; } } NameResolutionCollection ncCol = service.ResolveName(lnLegDN, ResolveNameSearchLocation.DirectoryOnly, true); if (ncCol.Count > 0) { FolderId SharedCalendarId = new FolderId(WellKnownFolderName.Calendar, ncCol[0].Mailbox.Address); Folder SharedCalendaFolder = Folder.Bind(service, SharedCalendarId); rtList.Add(ncCol[0].Mailbox.Address, SharedCalendaFolder); } } } catch (Exception exception) { Console.WriteLine(exception.Message); } } } return(rtList); }
/// <summary> /// Initializes a new instance of the <see cref="NameResolution"/> class. /// </summary> /// <param name="owner">The owner.</param> internal NameResolution(NameResolutionCollection owner) { EwsUtilities.Assert( owner != null, "NameResolution.ctor", "owner is null."); this.owner = owner; }
public static data.ScheduleData LoadResouceCallendar(string ResourceName) { ExchangeService service = ExchangeHelper.GetExchangeServiceConnection(); SetExchangeServiceHttpHeader(service, "X-AnchorMailbox", MailBoxAddress); PropertySet psPropset = new PropertySet(BasePropertySet.FirstClassProperties); ExtendedPropertyDefinition PidTagWlinkAddressBookEID = new ExtendedPropertyDefinition(0x6854, MapiPropertyType.Binary); ExtendedPropertyDefinition PidTagWlinkFolderType = new ExtendedPropertyDefinition(0x684F, MapiPropertyType.Binary); psPropset.Add(PidTagWlinkAddressBookEID); psPropset.Add(PidTagWlinkFolderType); NameResolutionCollection resolve = service.ResolveName(ResourceName, ResolveNameSearchLocation.DirectoryOnly, false, psPropset); FindItemsResults <Appointment> findResults = null; if (resolve.Count > 0) { try { SetExchangeServiceHttpHeader(service, "X-AnchorMailbox", resolve[0].Mailbox.Address); // service.HttpHeaders.Add("X-AnchorMailbox", resolve[0].Mailbox.Address); FolderId SharedCalendarId = new FolderId(WellKnownFolderName.Calendar, resolve[0].Mailbox.Address); CalendarFolder cf = CalendarFolder.Bind(service, SharedCalendarId); findResults = LoadResouceCallendar(cf); } catch (Microsoft.Exchange.WebServices.Data.ServiceResponseException ex) { Trace.TraceError("Error reading calendar for resource {0} ErrMsg: {1}", ResourceName, ex.Message); throw ex; } //Folder SharedCalendaFolder = Folder.Bind(service, SharedCalendarId); } else { throw new ApplicationException(String.Format("Error resolving resource name in GAL: {0}", ResourceName)); } if (findResults != null && findResults.TotalCount > 0) { service.LoadPropertiesForItems(from Item item in findResults select item, new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.Location, AppointmentSchema.Subject, AppointmentSchema.Categories, OnlineMeetingExternalLink, AppointmentSchema.IsAllDayEvent, AppointmentSchema.Sensitivity, AppointmentSchema.Organizer)); } return(new data.ScheduleData { RoomId = ResourceName, Schedule = ConvertToSerializable(findResults, ResourceName) }); /* PropertySet props = new PropertySet(); * CalendarFolder.Bind(service,WellKnownFolderName.Calendar,)*/ }
/// <summary> /// Initializes a new instance of the <see cref="ResolveNamesResponse"/> class. /// </summary> /// <param name="service">The service.</param> internal ResolveNamesResponse(ExchangeService service) : base() { EwsUtilities.Assert( service != null, "ResolveNamesResponse.ctor", "service is null"); this.resolutions = new NameResolutionCollection(service); }
//gavdcodeend 05 //gavdcodebegin 06 static void FindContactsByPartialName(ExchangeService ExService) { NameResolutionCollection resolvedNames = ExService.ResolveName("Mymiddle"); foreach (NameResolution oneName in resolvedNames) { Console.WriteLine("Name: " + oneName.Mailbox.Name); Console.WriteLine("Email: " + oneName.Mailbox.Address); Console.WriteLine("Id: " + oneName.Mailbox.Id); } }
/// <summary> /// Get the availability information basing the emailaddresses and the date /// </summary> static void GetAvailabilityResults(ExchangeService service, String currentAddress) { do { Console.WriteLine("Please input the user identity you want to get the " + "availability details:"); String inputInfo = Console.ReadLine(); Console.WriteLine("Please input the start date:"); String startDate = Console.ReadLine(); Console.WriteLine("Please input the end date:"); String endDate = Console.ReadLine(); if (!String.IsNullOrWhiteSpace(inputInfo)) { // You can input the "EXIT" to exit. if (inputInfo.ToUpper().CompareTo("EXIT") == 0) { return; } String[] identities = inputInfo.Split(','); List <String> emailAddresses = new List <String>(); foreach (String identity in identities) { NameResolutionCollection nameResolutions = service.ResolveName(identity, ResolveNameSearchLocation.DirectoryOnly, true); if (nameResolutions.Count != 1) { Console.WriteLine("{0} is invalid user identity.", identity); } else { String emailAddress = nameResolutions[0].Mailbox.Address; emailAddresses.Add(emailAddress); } } if (emailAddresses.Count > 0) { GetAvailabilityDetails(service, startDate, endDate, emailAddresses.ToArray()); } } else { // We can also directly press Enter to get the availability details of the // login account. GetAvailabilityDetails(service, startDate, endDate, currentAddress); } Console.WriteLine(); } while (true); }
//Faz uma busca no Exchange pelo legacyDN e retorna o emailAddress public string ConvertLegacyExchangeDNToSmtpAddress(EmailAddress email, ExchangeService svc) { string smtp = null; string legacyDN = email.Address; NameResolutionCollection col = null; col = svc.ResolveName(email.Name, ResolveNameSearchLocation.DirectoryOnly, true); if (col.Count != 0) { smtp = col[0].Mailbox.Address; } return(smtp); }
public string GetUserDisplayName(string email) { lock (exService) { try { NameResolutionCollection ncCol = exService.ResolveName(email, ResolveNameSearchLocation.DirectoryOnly, true); return(ncCol[0].Contact.DisplayName); } catch { } return(string.Empty); } }
private void button1_Click(object sender, EventArgs e) { NameResolutionCollection nameResolutions = service.ResolveName( "<group_name>", ResolveNameSearchLocation.DirectoryOnly, true); foreach (NameResolution nameResolution in nameResolutions) { ExpandGroupResults groupResults = service.ExpandGroup(nameResolution.Mailbox.Address); foreach (EmailAddress member in groupResults.Members) { Console.WriteLine(member.Name + " <" + member.Address + ">"); } } }
private void mnuUserSettingsUserOofSettings_Click(object sender, EventArgs e) { NameResolutionCollection names = null; try { this.Cursor = Cursors.WaitCursor; // If there is no CurrentService then we can't do anything if (this.CurrentService == null) { return; } if (this.CurrentAppSettings != null) { if (this.CurrentAppSettings.AuthenticationMethod == RequestedAuthType.oAuth) { names = this.CurrentService.ResolveName(this.CurrentAppSettings.MailboxBeingAccessed); } else { // Attempt to resolve the Act As account name. If there is only one // hit from ResolveNames then assume it is the right one. names = this.CurrentService.ResolveName(this.CurrentService.GetActAsAccountName()); } } else { names = this.CurrentService.ResolveName(this.CurrentService.GetActAsAccountName()); } } finally { this.Cursor = Cursors.Default; } if (names != null && names.Count == 1) { OofForm.ShowDialog( this.CurrentService, new Mailbox(names[0].Mailbox.Address)); } else { OofForm.ShowDialog(this.CurrentService); } }
private static void ResolveName(ExchangeService service, string NameToResolve) { // Identify the mailbox folders to search for potential name resolution matches. List <FolderId> folders = new List <FolderId>() { new FolderId(WellKnownFolderName.Contacts) }; // Search for all contact entries in the default mailbox Contacts folder and in Active Directory Domain Services. This results in a call to EWS. NameResolutionCollection coll = service.ResolveName(NameToResolve, folders, ResolveNameSearchLocation.ContactsThenDirectory, false); foreach (NameResolution nameRes in coll) { Console.WriteLine("Contact name: " + nameRes.Mailbox.Name); Console.WriteLine("Contact e-mail address: " + nameRes.Mailbox.Address); Console.WriteLine("Mailbox type: " + nameRes.Mailbox.MailboxType); } }
public static NameResolutionCollection DoResolveName(string strResolve) { NameResolutionCollection ncCol = null; try { ncCol = exService.ResolveName(strResolve, ResolveNameSearchLocation.DirectoryOnly, true); } catch (ServiceRequestException ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error when attempting to resolve the name for " + strResolve + ":"); Console.WriteLine(ex.Message); Console.ResetColor(); return(null); } return(ncCol); }
public bool ResolveName(string Email) { ConnectToServer(); if (service == null) { return(false); } List <FolderId> folders = new List <FolderId>() { new FolderId(WellKnownFolderName.Contacts) }; NameResolutionCollection coll = service.ResolveName(Email, folders, ResolveNameSearchLocation.ContactsThenDirectory, false); if (coll.Count != 0) { return(true); } return(false); }
private string ResolveRecipients(string[] unresolvedRecipients, EmailAddressCollection emailAddressCollection) { string resolvedRecipients = string.Empty; foreach (string recipient in unresolvedRecipients) { try { NameResolutionCollection nameResolutionCollection = exchangeService.ResolveName(recipient); if (nameResolutionCollection != null) { if (nameResolutionCollection.Count == 1) { if (nameResolutionCollection[0].Mailbox != null) { emailAddressCollection.Add(nameResolutionCollection[0].Mailbox.Address); } resolvedRecipients += nameResolutionCollection[0].Mailbox.Address + "; "; } else { if (errorRecipients.Contains(recipient)) { errorRecipients.Add(recipient); } } } } catch { if (errorRecipients.Contains(recipient)) { errorRecipients.Add(recipient); } } } return(resolvedRecipients); }
private void GetCalendarEvents(ExchangeService service) { // Use a view to retrieve calendar events within 60 days from today DateTime startDate = DateTime.Now.AddDays(-60); DateTime endDate = DateTime.Now.AddDays(60); Mailbox userMailbox = new Mailbox(Resources.EWSUserMailbox); FolderId calendar = new FolderId(WellKnownFolderName.Calendar, userMailbox); CalendarView cView = new CalendarView(startDate, endDate); cView.PropertySet = new PropertySet(AppointmentSchema.ICalUid, AppointmentSchema.Organizer, AppointmentSchema.Subject, AppointmentSchema.Location, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.LegacyFreeBusyStatus, AppointmentSchema.AppointmentState, AppointmentSchema.IsCancelled, AppointmentSchema.IsAllDayEvent); FindItemsResults <Item> items = null; items = service.FindItems(calendar, cView); // Set up a datatable to store appointments DataTable appointmentsData = new DataTable("Appointments"); // ICalUid Column DataColumn iCalUidColumn = new DataColumn(); iCalUidColumn.DataType = Type.GetType("System.String"); iCalUidColumn.ColumnName = "ICalUid"; appointmentsData.Columns.Add(iCalUidColumn); // Account name column DataColumn accountNameColumn = new DataColumn(); accountNameColumn.DataType = Type.GetType("System.String"); accountNameColumn.ColumnName = "AccountName"; appointmentsData.Columns.Add(accountNameColumn); // Subject column DataColumn subjectColumn = new DataColumn(); subjectColumn.DataType = Type.GetType("System.String"); subjectColumn.ColumnName = "Subject"; appointmentsData.Columns.Add(subjectColumn); // Location column DataColumn locationColumn = new DataColumn(); locationColumn.DataType = Type.GetType("System.String"); locationColumn.ColumnName = "Location"; appointmentsData.Columns.Add(locationColumn); // Start time column DataColumn startTimeColumn = new DataColumn(); startTimeColumn.DataType = Type.GetType("System.DateTime"); startTimeColumn.ColumnName = "StartTime"; appointmentsData.Columns.Add(startTimeColumn); // End time column DataColumn endTimeColumn = new DataColumn(); endTimeColumn.DataType = Type.GetType("System.DateTime"); endTimeColumn.ColumnName = "EndTime"; appointmentsData.Columns.Add(endTimeColumn); // Status column DataColumn statusColumn = new DataColumn(); statusColumn.DataType = Type.GetType("System.String"); statusColumn.ColumnName = "Status"; appointmentsData.Columns.Add(statusColumn); // Appointment State column DataColumn appointmentStateColumn = new DataColumn(); appointmentStateColumn.DataType = Type.GetType("System.Int32"); appointmentStateColumn.ColumnName = "AppointmentState"; appointmentsData.Columns.Add(appointmentStateColumn); // Is Cancelled Column DataColumn isCancelledColumn = new DataColumn(); isCancelledColumn.DataType = Type.GetType("System.Boolean"); isCancelledColumn.ColumnName = "IsCancelled"; appointmentsData.Columns.Add(isCancelledColumn); // Is All Day Event Column DataColumn isAllDayEventColumn = new DataColumn(); isAllDayEventColumn.DataType = Type.GetType("System.Boolean"); isAllDayEventColumn.ColumnName = "IsAllDayEvent"; appointmentsData.Columns.Add(isAllDayEventColumn); // ChangeKey Column DataColumn changeKeyColumn = new DataColumn(); changeKeyColumn.DataType = Type.GetType("System.String"); changeKeyColumn.ColumnName = "ChangeKey"; appointmentsData.Columns.Add(changeKeyColumn); // UniqueId Column DataColumn uniqueIdColumn = new DataColumn(); uniqueIdColumn.DataType = Type.GetType("System.String"); uniqueIdColumn.ColumnName = "UniqueID"; appointmentsData.Columns.Add(uniqueIdColumn); List <ResolvedEmailAddress> resolvedEmailAddresses = new List <ResolvedEmailAddress>(); int i = 0; using (SqlBulkCopy bulkCopy = new SqlBulkCopy(Resources.SqlConnectionString, SqlBulkCopyOptions.KeepNulls & SqlBulkCopyOptions.KeepIdentity)) { bulkCopy.BatchSize = items.Count(); bulkCopy.DestinationTableName = "dbo.TimeOffCalendarTemp"; bulkCopy.ColumnMappings.Clear(); bulkCopy.ColumnMappings.Add("ICalUid", "ICalUid"); bulkCopy.ColumnMappings.Add("AccountName", "AccountName"); bulkCopy.ColumnMappings.Add("Subject", "Subject"); bulkCopy.ColumnMappings.Add("Location", "Location"); bulkCopy.ColumnMappings.Add("StartTime", "StartTime"); bulkCopy.ColumnMappings.Add("EndTime", "EndTime"); bulkCopy.ColumnMappings.Add("Status", "Status"); bulkCopy.ColumnMappings.Add("AppointmentState", "AppointmentState"); bulkCopy.ColumnMappings.Add("IsCancelled", "IsCancelled"); bulkCopy.ColumnMappings.Add("IsAllDayEvent", "IsAllDayEvent"); bulkCopy.ColumnMappings.Add("ChangeKey", "ChangeKey"); bulkCopy.ColumnMappings.Add("UniqueID", "UniqueID"); foreach (Item item in items) { try { i++; DataRow appointmentRow = appointmentsData.NewRow(); EmailAddress accountName = null; ItemId itemId = null; string iCalUid, subject, location = null; DateTime startTime, endTime = new DateTime(); LegacyFreeBusyStatus status = new LegacyFreeBusyStatus(); int appointmentState; bool isCancelled, isAllDayEvent; item.TryGetProperty(AppointmentSchema.ICalUid, out iCalUid); if (iCalUid != null) { appointmentRow["ICalUid"] = iCalUid; } item.TryGetProperty(AppointmentSchema.Organizer, out accountName); if (accountName != null) { if (resolvedEmailAddresses.Where(re => re.EWSAddress == accountName.Address).Count() < 1) { NameResolutionCollection nd = service.ResolveName(accountName.Address); if (nd.Count > 0) { ResolvedEmailAddress resAddress = new ResolvedEmailAddress { EWSAddress = accountName.Address, SMTPAddress = nd[0].Mailbox.Address }; resolvedEmailAddresses.Add(resAddress); appointmentRow["AccountName"] = resAddress.SMTPAddress; } } else { ResolvedEmailAddress resAddress = resolvedEmailAddresses.First(re => re.EWSAddress == accountName.Address); appointmentRow["AccountName"] = resAddress.SMTPAddress; } } item.TryGetProperty(AppointmentSchema.Subject, out subject); if (subject != null) { appointmentRow["Subject"] = subject; } item.TryGetProperty(AppointmentSchema.Location, out location); if (location != null) { appointmentRow["Location"] = location; } item.TryGetProperty(AppointmentSchema.Start, out startTime); if (startTime != null) { appointmentRow["StartTime"] = startTime; } item.TryGetProperty(AppointmentSchema.End, out endTime); if (endTime != null) { appointmentRow["EndTime"] = endTime; } item.TryGetProperty(AppointmentSchema.LegacyFreeBusyStatus, out status); if (status != null) { appointmentRow["Status"] = status; } item.TryGetProperty(AppointmentSchema.AppointmentState, out appointmentState); appointmentRow["AppointmentState"] = appointmentState; item.TryGetProperty(AppointmentSchema.IsCancelled, out isCancelled); appointmentRow["IsCancelled"] = isCancelled; item.TryGetProperty(AppointmentSchema.IsAllDayEvent, out isAllDayEvent); appointmentRow["IsAllDayEvent"] = isAllDayEvent; itemId = item.Id; appointmentRow["ChangeKey"] = itemId.ChangeKey; appointmentRow["UniqueID"] = itemId.UniqueId; appointmentsData.Rows.Add(appointmentRow); int percentComplete = 0; if (items.Count() > 0) { percentComplete = ((i + 1) * 100 / items.Count()); } else { percentComplete = 100; } UpdateProgress(percentComplete); } catch (Exception ex) { Util.LogError("GetCalendarEvents failed with message: " + ex.Message); } } bulkCopy.WriteToServer(appointmentsData); using (SqlConnection conn = new SqlConnection(Resources.SqlConnectionString)) { using (SqlCommand command = new SqlCommand(Resources.MergeStoredProcedureName, conn) { CommandType = CommandType.StoredProcedure }) { conn.Open(); command.ExecuteNonQuery(); } } } }
protected override void LoadContents() { if (txtName.Text.Length == 0) { return; } ResolveNameSearchLocation oResolveNameSearchLocation = ResolveNameSearchLocation.ContactsThenDirectory; switch (cmboResolveNameSearchLocation.Text) { case "DirectoryOnly": oResolveNameSearchLocation = ResolveNameSearchLocation.DirectoryOnly; break; case "DirectoryThenContacts": oResolveNameSearchLocation = ResolveNameSearchLocation.ContactsThenDirectory; break; case "ContactsOnly": oResolveNameSearchLocation = ResolveNameSearchLocation.ContactsOnly; break; case "ContactsThenDirectory": oResolveNameSearchLocation = ResolveNameSearchLocation.DirectoryThenContacts; break; } NameResolutionCollection oNameResolutionCollection = CurrentService.ResolveName( txtName.Text, oResolveNameSearchLocation, chkReturnContactDetails.Checked, PropertySet.FirstClassProperties ); Dictionary <string, string> itemIdToDisplayName = new Dictionary <string, string>(); ItemId[] toLookup = oNameResolutionCollection .Where(nr => nr.Contact == null && nr.Mailbox.Id != null) .Select(nr => nr.Mailbox.Id) .ToArray(); if (toLookup.Length > 0) { var itemsWithDisplayNames = CurrentService.BindToItems(toLookup, new PropertySet(BasePropertySet.IdOnly, ContactSchema.DisplayName)); foreach (GetItemResponse resp in itemsWithDisplayNames) { if (resp.Result != ServiceResult.Error && resp.Item != null && resp.Item.TryGetProperty(ContactSchema.DisplayName, out string displayName)) { itemIdToDisplayName[resp.Item.Id.UniqueId] = displayName; } } } // Load new results foreach (NameResolution name in oNameResolutionCollection) { int rowIdx = ContentsGrid.Rows.Add(); DataGridViewRow row = ContentsGrid.Rows[rowIdx]; string displayName = null; if (name.Contact != null) { name.Contact.TryGetProperty(ContactSchema.DisplayName, out displayName); } if (displayName == null && name.Mailbox.Id != null) { itemIdToDisplayName.TryGetValue(name.Mailbox.Id.UniqueId, out displayName); } if (displayName != null) { row.Cells[colNameDisplayName].Value = displayName; } row.Cells[colNameMailboxName].Value = name.Mailbox.Name; row.Cells[colNameAddress].Value = name.Mailbox.Address; row.Cells[colNameMailboxType].Value = name.Mailbox.MailboxType; row.Cells[colNameRoutingType].Value = name.Mailbox.RoutingType; if (name.Mailbox.Id != null) { row.Cells[colNameUniqueId].Value = name.Mailbox.Id.UniqueId; row.Cells[colNameContentId].Value = name.Mailbox.Id.UniqueId; } if (name.Contact != null && name.Contact.TryGetProperty(ContactSchema.DirectoryId, out string directoryId)) { row.Cells[colNameDirectoryId].Value = directoryId; row.Cells[colNameContentId].Value = directoryId; } row.Tag = name; } }
static void Main(string[] args) { string strAcct = ""; string strTenant = ""; string strEmailAddr = ""; bool bMailbox = false; NameResolutionCollection ncCol = null; List <string> strCalList = new List <string>(); List <Item> CalItems = null; List <Item> PurgeItems = null; int cRestoredItems = 0; string strStartDate = ""; if (args.Length > 0) { for (int i = 0; i < args.Length; i++) { if (args[i].ToUpper() == "-M" || args[i].ToUpper() == "/M") // mailbox mode - use impersonation to get to another mailbox { if (args[i + 1].Length > 0) { strEmailAddr = args[i + 1]; bMailbox = true; } else { Console.WriteLine("Please enter a valid SMTP address for the mailbox."); ShowHelp(); return; } } if (args[i].ToUpper() == "-S" || args[i].ToUpper() == "/S") // Choose a Start Date instead of using 24 hours { if (args[i + 1].Length > 0) { strStartDate = args[i + 1]; bStartDate = true; } else { Console.WriteLine("Please enter a valid Date."); ShowHelp(); return; } } if (args[i].ToUpper() == "-?" || args[i].ToUpper() == "/?") // display command switch help { ShowInfo(); ShowHelp(); return; } } } if (bStartDate) { try { dtStartDate = DateTime.Parse(strStartDate); } catch (Exception ex) { if (ex.Message == "String was not recognized as a valid DateTime.") { Console.WriteLine("Date Format was incorrect. Please enter a valid Date.\r\n"); ShowHelp(); return; } else { Console.WriteLine("Error with Entered Date. Please try again."); Console.WriteLine(ex.Message + "\r\n"); ShowHelp(); return; } } } strStartDate = dtStartDate.ToString(); ShowInfo(); exService = new ExchangeService(ExchangeVersion.Exchange2013_SP1); exService.UseDefaultCredentials = false; Console.Write("Press <ENTER> to enter credentials."); Console.ReadLine(); Console.WriteLine(); AuthenticationResult authResult = GetToken(); if (authResult != null) { exService.Credentials = new OAuthCredentials(authResult.AccessToken); strAcct = authResult.UserInfo.DisplayableId; } else { return; } strTenant = strAcct.Split('@')[1]; exService.Url = new Uri(strSrvURI + "/ews/exchange.asmx"); if (bMailbox) { ncCol = DoResolveName(strEmailAddr); exService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, strEmailAddr); } else { ncCol = DoResolveName(strAcct); } if (ncCol == null) { // Didn't get a NameResCollection, so error out. Console.WriteLine(""); Console.WriteLine("Exiting the program."); return; } if (ncCol[0].Contact != null) { strDisplayName = ncCol[0].Contact.DisplayName; strEmailAddr = ncCol[0].Mailbox.Address; Console.WriteLine("Will attempt restore from Purges folder for " + strDisplayName); } else { Console.WriteLine("Will attempt restore from Purges folder for " + strAcct); } Console.WriteLine("==============================================================\r\n"); // Get Calendar items Console.WriteLine("Connecting to Calendar and retreiving items."); CalItems = GetItems(exService, "Calendar"); if (CalItems != null) { string strCount = CalItems.Count.ToString(); Console.WriteLine("Creating Calendar items list for " + strCount + " items.\r\n"); foreach (Appointment appt in CalItems) { strCalList.Add(GetPropsLine(appt)); //strGlobalObjID + "," + strSubject + "," + strStartWhole + "," + strEndWhole + "," + strOrganizerAddr + "," + strRecurring } } else { return; } // Get Purges items if (bStartDate) { Console.WriteLine("Connecting to Purges folder and retreiving purged Calendar items starting from " + strStartDate + "."); } else { Console.WriteLine("Connecting to Purges folder and retreiving purged Calendar items from the last 24 hours."); } PurgeItems = GetItems(exService, "Purges"); if (PurgeItems != null) { if (PurgeItems.Count > 0) { Console.WriteLine("Checking " + PurgeItems.Count.ToString() + " items from Purges against the existing Calendar items list.\r\n"); foreach (Appointment appt in PurgeItems) { string strPurged = GetPropsLine(appt); bool bRestore = true; foreach (string strCalItem in strCalList) { if (strPurged == strCalItem) { bRestore = false; } } if (bRestore) { string strStart = ""; string strEnd = ""; try { strStart = appt.Start.ToString(); } catch { strStart = "Cannot Retrieve or Not Set."; } try { strEnd = appt.End.ToString(); } catch { strEnd = "Cannot Retrieve or Not Set."; } Console.WriteLine("Recovering item:"); Console.WriteLine(appt.Subject + " | Location: " + appt.Location + " | Start Time: " + strStart + " | End Time: " + strEnd); appt.Move(fldCal.Id); cRestoredItems++; strCalList.Add(strPurged); // this one has been moved back, so add it to the list in case there is another older one } } } else { if (bStartDate) { Console.WriteLine("There were no Calendar items sent to the Purges folder since " + strStartDate + ".\r\n"); } else { Console.WriteLine("There were no Calendar items sent to the Purges folder in the last 24 hours.\r\n"); } } } else { return; } string strItemCount = ""; if (cRestoredItems == 1) { strItemCount = "1 item"; } else { strItemCount = cRestoredItems.ToString() + " items"; } Console.WriteLine("========================"); Console.WriteLine("Complete. Restored " + strItemCount + " from Purges back to Calendar."); Console.WriteLine("========================"); }
/// <summary> /// Call ResolveName and display results /// </summary> private void btnGo_Click(object sender, EventArgs e) { try { this.Cursor = Cursors.WaitCursor; //NameResolutionCollection oNameResolutionCollection = this.CurrentService.ResolveName( // txtName.Text, // ResolveNameSearchLocation.DirectoryThenContacts, // chkReturnContactDetails.Checked // ); ResolveNameSearchLocation oResolveNameSearchLocation = ResolveNameSearchLocation.ContactsThenDirectory; switch (cmboResolveNameSearchLocation.Text) { case "DirectoryOnly": oResolveNameSearchLocation = ResolveNameSearchLocation.DirectoryOnly; break; case "DirectoryThenContacts": oResolveNameSearchLocation = ResolveNameSearchLocation.ContactsThenDirectory; break; case "ContactsOnly": oResolveNameSearchLocation = ResolveNameSearchLocation.ContactsOnly; break; case "ContactsThenDirectory": oResolveNameSearchLocation = ResolveNameSearchLocation.DirectoryThenContacts; break; } NameResolutionCollection oNameResolutionCollection = this.CurrentService.ResolveName( txtName.Text, oResolveNameSearchLocation, chkReturnContactDetails.Checked ); // Clear out previous results lstNames.Items.Clear(); // Load new results foreach (NameResolution name in oNameResolutionCollection) { ListViewItem item = new ListViewItem(); item.Text = name.Mailbox.Name; item.Tag = name; item.SubItems.Add(name.Mailbox.Address); item.SubItems.Add(name.Mailbox.RoutingType); if (name.Mailbox.Id != null) { item.SubItems.Add(name.Mailbox.Id.UniqueId); } else { item.SubItems.Add(""); } lstNames.Items.Add(item); } // Select the first result by default if (lstNames.Items.Count > 0) { this.lstNames.Items[0].Selected = true; this.lstNames.Focus(); } // Pressing <enter> will now execute the OK button this.AcceptButton = this.btnOK; } finally { this.Cursor = Cursors.Default; } }
static void Main(string[] args) { string strAcct = ""; string strTenant = ""; string strEmailAddr = ""; bool bMailbox = false; NameResolutionCollection ncCol = null; Folder fldCal = null; if (args.Length > 0) { for (int i = 0; i < args.Length; i++) { if (args[i].ToUpper() == "-M" || args[i].ToUpper() == "/M") // mailbox mode - use impersonation to get to another mailbox { if (args[i + 1].Length > 0) { strEmailAddr = args[i + 1]; bMailbox = true; } else { Console.WriteLine("Please enter a valid SMTP address for the mailbox."); ShowHelp(); return; } } if (args[i].ToUpper() == "-R" || args[i].ToUpper() == "/R") { if (args[i + 1].Contains("@")) // checking ot see if the next param is an email address { Console.WriteLine("You must use the -M switch with an smtp address to connect to that mailbox."); ShowHelp(); return; } else { bRestore = true; } } if (args[i].ToUpper() == "-?" || args[i].ToUpper() == "/?") // display command switch help { ShowInfo(); ShowHelp(); return; } } } ShowInfo(); exService = new ExchangeService(ExchangeVersion.Exchange2013_SP1); exService.UseDefaultCredentials = false; Console.Write("Press <ENTER> to enter credentials."); Console.ReadLine(); Console.WriteLine(); AuthenticationResult authResult = GetToken(); if (authResult != null) { exService.Credentials = new OAuthCredentials(authResult.AccessToken); strAcct = authResult.UserInfo.DisplayableId; } else { return; } strTenant = strAcct.Split('@')[1]; exService.Url = new Uri(strSrvURI + "/ews/exchange.asmx"); if (bMailbox) { ncCol = DoResolveName(strEmailAddr); exService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, strEmailAddr); } else { ncCol = DoResolveName(strAcct); } if (ncCol == null) { // Didn't get a NameResCollection, so error out. Console.WriteLine(""); Console.WriteLine("Exiting the program."); return; } if (ncCol[0].Contact != null) { strDisplayName = ncCol[0].Contact.DisplayName; strEmailAddr = ncCol[0].Mailbox.Address; if (!bRestore) { Console.WriteLine("Backing up Calendar for " + strDisplayName); } else { Console.WriteLine("Restoring Calendar for " + strDisplayName); } } else { if (!bRestore) { Console.WriteLine("Backing up Calendar for " + strAcct); } else { Console.WriteLine("Restoring Calendar for " + strAcct); } } // Get or create the backup folder... GetBackupFld(); // Get or create the Restore folder if (bRestore) { GetRestoreFld(); } else { // Get the Calendar folder try { Console.WriteLine("Connecting to the Calendar."); fldCal = Folder.Bind(exService, WellKnownFolderName.Calendar, new PropertySet(PropertySet.IdOnly)); } catch (ServiceResponseException ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(""); Console.WriteLine("Could not connect to this user's mailbox or calendar."); Console.WriteLine(ex.Message); Console.ResetColor(); return; } } if (!bRestore) { // now go get the items and copy them to the backup folder. Console.WriteLine("Copying all items from Calendar to the CalBackup folder."); CopyItems(fldCal, fldCalBackup); Console.WriteLine("\r\n"); Console.WriteLine("==============================================================="); Console.WriteLine("Copied " + cItems.ToString() + " items to the CalBackup folder."); Console.WriteLine("==============================================================="); } else { Console.WriteLine("Restoring items to the CalRestore folder."); CopyItems(fldCalBackup, fldCalRestore); Console.WriteLine("\r\n"); Console.WriteLine("=================================================================="); Console.WriteLine("Restored " + cItems.ToString() + " items to the CalRestore folder."); Console.WriteLine("=================================================================="); } //Console.Write("Press a key to exit"); //Console.Read(); return; }
static void Main(string[] args) { string strAcct = ""; string strTenant = ""; string strEmailAddr = ""; DateTime dtNow = DateTime.MinValue; string strFileName = ""; string strDate = ""; bool bRet = true; //List<Item> CalItems = null; if (args.Length > 0) { for (int i = 0; i < args.Length; i++) { if (args[i].ToUpper() == "-L" || args[i].ToUpper() == "/L") // list mode pulls in a list of SMTP addresses - will connect to each of them. { if (args[i + 1].Length > 0) { strListFile = args[i + 1]; if (File.Exists(strListFile)) { bListMode = true; } else { Console.WriteLine("Could not find the file " + strListFile + "."); ShowHelp(); return; } } } if (args[i].ToUpper() == "-M" || args[i].ToUpper() == "/M") // move mode to move problem items out to the CalVerifier folder { bMoveItems = true; } if (args[i].ToUpper() == "-V" || args[i].ToUpper() == "/V") // include tracing, verbose mode. { bVerbose = true; } if (args[i].ToUpper() == "-?" || args[i].ToUpper() == "/?") // display command switch help { ShowHelp(); return; } } } ShowInfo(); exService = new ExchangeService(ExchangeVersion.Exchange2013_SP1); exService.UseDefaultCredentials = false; /*if (bVerbose) * { * exService.TraceEnabled = true; * exService.TraceFlags = TraceFlags.All; * }*/ if (bListMode) { Console.Write("Press <ENTER> to enter credentials for the ServiceAccount."); } else { Console.Write("Press <ENTER> to enter credentials for the Mailbox."); } Console.ReadLine(); Console.WriteLine(); AuthenticationResult authResult = GetToken(); if (authResult != null) { exService.Credentials = new OAuthCredentials(authResult.AccessToken); strAcct = authResult.UserInfo.DisplayableId; } else { return; } strTenant = strAcct.Split('@')[1]; exService.Url = new Uri(strSrvURI + "/ews/exchange.asmx"); NameResolutionCollection ncCol = null; if (bListMode) // List mode { rgstrMBX = File.ReadAllLines(strListFile); foreach (string strSMTP in rgstrMBX) { CreateLogFile(); LogInfo(); strDupCheck = new List <string>(); strGOIDCheck = new List <string>(); ncCol = DoResolveName(strSMTP); if (ncCol == null || ncCol.Count == 0) { // Didn't get a NameResCollection, so error out. Console.WriteLine(""); Console.WriteLine("Check the SMTP addresses in the list file - there was a problem resolving against the directory."); Console.WriteLine("SMTP Address: " + strSMTP); Console.WriteLine("Exiting the program."); return; // look at just skipping to the next one here... } if (ncCol[0].Contact != null) { strDisplayName = ncCol[0].Contact.DisplayName; DisplayAndLog("Processing Calendar for " + strDisplayName); } else { DisplayAndLog("Processing Calendar for " + strSMTP); } exService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, strSMTP); // Should only do this if the switch was set. if (bMoveItems) { CreateErrFld(); string strFldID = fldCalVerifier.Id.ToString(); } strSMTPAddr = strSMTP.ToUpper(); bRet = ProcessCalendar(exService); /*if (CalItems != null) * { * string strCount = CalItems.Count.ToString(); * DisplayAndLog("Found " + strCount + " items"); * DisplayAndLog(""); * Console.WriteLine("Processing items..."); * } * else * { * return; // could not connect, error is displayed to user already. * } * * int i = 0; * int n = 0; * foreach (Appointment appt in CalItems) * { * i++; * if (i % 5 == 0) * { * Console.SetCursorPosition(0, Console.CursorTop); * Console.Write(""); * Console.Write(cSpin[n % 4]); * n++; * } * ProcessItem(appt); * iCheckedItems++; * }*/ DisplayAndLog("\r\n"); DisplayAndLog("==============================================================="); DisplayAndLog("Checked " + iCheckedItems.ToString() + " items."); DisplayAndLog("Found " + iErrors.ToString() + " errors and " + iWarn.ToString() + " warnings."); DisplayAndLog("===============================================================\r\n"); outLog.Close(); dtNow = DateTime.Now; strDate = dtNow.ToShortDateString(); strDate = strDate.Replace('/', '-'); strFileName = strAppPath + strDate + "_" + strSMTPAddr + "_CalVerifier.log"; if (File.Exists(strFileName)) { File.Delete(strFileName); } File.Move(strLogFile, strFileName); ResetGlobals(); } Console.WriteLine(""); Console.WriteLine("Please check " + strAppPath + " for the CalVerifier logs."); } else // single mailbox mode { CreateLogFile(); LogInfo(); strDupCheck = new List <string>(); strGOIDCheck = new List <string>(); ncCol = DoResolveName(strAcct); if (ncCol == null || ncCol.Count == 0) { // Didn't get a NameResCollection, so error out. Console.WriteLine(""); Console.WriteLine("Could not resolve address " + strAcct + " against the directory."); Console.WriteLine("Exiting the program."); return; } if (ncCol[0].Contact != null) { strDisplayName = ncCol[0].Contact.DisplayName; strEmailAddr = ncCol[0].Mailbox.Address; DisplayAndLog("Processing Calendar for " + strDisplayName); } else { DisplayAndLog("Processing Calendar for " + strAcct); } strSMTPAddr = strEmailAddr.ToUpper(); // Should only do this if the switch was set. if (bMoveItems) { CreateErrFld(); string strFldID = fldCalVerifier.Id.ToString(); } bRet = ProcessCalendar(exService); /*if (CalItems != null) * { * string strCount = CalItems.Count.ToString(); * DisplayAndLog("Found " + strCount + " items"); * DisplayAndLog(""); * Console.WriteLine("Processing items "); * } * else * { * return; // could not connect, error is displayed to user already. * } * * int i = 0; * int n = 0; * foreach (Appointment appt in CalItems) * { * i++; * if (i % 5 == 0) * { * Console.SetCursorPosition(0,Console.CursorTop); * Console.Write(""); * Console.Write(cSpin[n % 4]); * n++; * } * ProcessItem(appt); * iCheckedItems++; * }*/ DisplayAndLog("\r\n"); DisplayAndLog("==============================================================="); DisplayAndLog("Checked " + iCheckedItems.ToString() + " items."); DisplayAndLog("Found " + iErrors.ToString() + " errors and " + iWarn.ToString() + " warnings."); DisplayAndLog("==============================================================="); outLog.Close(); dtNow = DateTime.Now; strDate = dtNow.ToShortDateString(); strDate = strDate.Replace('/', '-'); strFileName = strAppPath + strDate + "_" + strSMTPAddr + "_CalVerifier.log"; if (File.Exists(strFileName)) { File.Delete(strFileName); } File.Move(strLogFile, strFileName); Console.WriteLine(""); Console.WriteLine("Please check " + strAppPath + " for " + strDate + "_" + strSMTPAddr + "_CalVerifier.log for more information."); } DisplayPrivacyInfo(); }
protected void Page_Load(object sender, EventArgs e) { if (Request.QueryString["EmployeeId"] != null) { if (!IsPostBack) { EmployeeView view = new EmployeeMapper().Get(new EmployeeEntity() { Id = Convert.ToInt32(Request.QueryString["EmployeeId"]) }); if (view.Id != 0) { EmployeeNameLabel.Text = view.ToString(); JobTitleAndUnitLabel.Text = view.Job + " at " + view.OrganizationalUnit; EmployeeNoLabel.InnerText = view.EmployeeNo; PersonalNoLabel.InnerText = view.PersonalNumber; DateOfBirthLabel.InnerText = view.DateOfBirth.ToShortDateString(); GenderLabel.InnerText = view.Gender.ToString(); CountryLabel.InnerText = view.Country; NationalityNoLabel.InnerText = view.Nationality; CityLabel.InnerText = view.City; tMobilePhoneLabel.InnerText = view.MobilePhone; WorkEmailLabel.InnerText = view.WorkEmail; } else { Response.Redirect("List.aspx"); } } else { if (userTextBox.Text != "") { //PrincipalContext ctx = new PrincipalContext(ContextType.Domain); //UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, userTextBox.Text); //if (user != null) //{ // if (user.UserPrincipalName != null) // { // EmailAddressTextBox.Text = user.UserPrincipalName; // } //} //else //{ // EmailAddressTextBox.Text = ""; //} // Get the number of items in the Contacts folder. To keep the response smaller, request only the TotalCount property. ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010); service.Url = new Uri(@"https://mail.kpaonline.org/EWS/Exchange.asmx"); service.Credentials = new NetworkCredential("*****@*****.**", "Passsygtech456"); System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object sender1, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); }; NameResolutionCollection nameResolutions = service.ResolveName( userTextBox.Text, ResolveNameSearchLocation.DirectoryOnly, true); foreach (NameResolution nameResolution in nameResolutions) { EmailAddressTextBox.Text = nameResolution.Mailbox.Address; } } } } }
// Test this Calendar Item's properties. public static void ProcessItem(Appointment appt) { // populate the values for the properties try { if (appt.Size > 0) { if (bVerbose) { outLog.WriteLine("Calling to Get Readable Properties from the following item."); } GetPropsReadable(appt); } else { DisplayAndLog("Appointment item not valid - continuing..."); return; } } catch { DisplayAndLog("Getting props failed or item is NULL - continuing..."); return; } string strLogItem = "Problem item: " + strSubject + " | " + strLocation + "| " + strStartWhole + " | " + strEndWhole; if (bVerbose) { string strItemsChecked = (iCheckedItems + 1).ToString(); outLog.WriteLine("Checking item " + strItemsChecked + ": " + strSubject + " | " + strStartWhole + "|" + strEndWhole); } foreach (string strVal in appt.Categories) { if (strVal.ToUpper() == "HOLIDAY") { return; // we will skip testing holiday items since they are imported and should be okay } } List <string> strErrors = new List <string>(); bool bErr = false; bool bWarn = false; bool bOrgTest = true; DateTime dtStart = DateTime.MinValue; DateTime dtEnd = DateTime.MinValue; int iDel = 0; int iMod = 0; int iExcept = 0; string strRecurStart = ""; string strRecurEnd = ""; DateTime dtRecurStart = DateTime.MinValue; DateTime dtRecurEnd = DateTime.MinValue; // parse the recurrence blob and get useful stuff out of it if (!string.IsNullOrEmpty(strRecurBlob)) { GetRecurData(strRecurBlob); if (!(string.IsNullOrEmpty(strRecurDelInstCount) && !(string.IsNullOrEmpty(strRecurModInstCount)))) { iDel = int.Parse(strRecurDelInstCount); iMod = int.Parse(strRecurModInstCount); iExcept = iDel - iMod; strRecurExceptCount = iExcept.ToString(); } if (!(string.IsNullOrEmpty(strRecurStartDate) && !(string.IsNullOrEmpty(strRecurStartTime)))) { strRecurStart = strRecurStartDate + " " + strRecurStartTime; dtRecurStart = DateTime.Parse(strRecurStart); } if (!(string.IsNullOrEmpty(strRecurEndDate) && !(string.IsNullOrEmpty(strRecurEndTime)))) { strRecurEnd = strRecurEndDate + " " + strRecurEndTime; dtRecurEnd = DateTime.Parse(strRecurEnd); } } string strOrganizerSMTP = ""; string strMbxSMTP = strSMTPAddr; // get the SMTP address of the Organizer by doing Resolve Name on the X500 address. if (!(string.IsNullOrEmpty(strOrganizerAddr))) { NameResolutionCollection ncCol = null; try { ncCol = Utils.exService.ResolveName(strOrganizerAddr); } catch (ServiceRequestException ex) { strErrors.Add(" Error when attempting to resolve the name for " + strOrganizerAddr + ":"); strErrors.Add(" " + ex.Message); iWarn++; } if (ncCol.Count > 0 && !string.IsNullOrEmpty(ncCol[0].Mailbox.Address)) { strOrganizerSMTP = ncCol[0].Mailbox.Address; } else { bOrgTest = false; strOrganizerSMTP = strOrganizerAddr; } } else { strOrganizerAddr = ""; } // now really actually start testing props if (string.IsNullOrEmpty(strSubject)) { bWarn = true; strErrors.Add(" WARNING: Subject is empty/missing."); iWarn++; strSubject = ""; } else // need to remove commas for logging purposes { if (strSubject.Contains(",")) { strSubject = strSubject.Replace(',', '_'); } } if (string.IsNullOrEmpty(strEndWhole)) { bErr = true; strErrors.Add(" ERROR: Missing required End Time property."); iErrors++; } else // not empty/missing, but might still have problems { dtEnd = DateTime.Parse(strEndWhole); if (TimeCheck(dtEnd)) { bErr = true; strErrors.Add(" ERROR: End Time is not set correctly."); iErrors++; } } if (string.IsNullOrEmpty(strStartWhole)) { bErr = true; strErrors.Add(" ERROR: Missing required Start Time property."); iErrors++; } else // not empty/missing, but might still have problems { dtStart = DateTime.Parse(strStartWhole); if (dtEnd < dtStart) { bErr = true; strErrors.Add(" ERROR: Start Time is greater than the End Time."); iErrors++; } if (TimeCheck(dtStart)) { bErr = true; strErrors.Add(" ERROR: Start Time is set to an invalid value."); iErrors++; } } if (string.IsNullOrEmpty(strOrganizerAddr)) { if (int.Parse(strApptStateFlags) > 0) // if no Organizer Address AND this is a meeting then that's bad. { bErr = true; strErrors.Add(" ERROR: Missing required Organizer Address property."); iErrors++; } strOrganizerAddr = ""; } if (string.IsNullOrEmpty(strRecurring)) { bErr = true; strErrors.Add(" ERROR: Missing required Recurring property."); iErrors++; strRecurring = "MISSING"; } if (string.IsNullOrEmpty(strLocation)) { strLocation = ""; } else { if (strLocation.Contains(",")) { strLocation = strLocation.Replace(',', '_'); } } // check for duplicate calendar items string strDupLine = strSubject + "," + strLocation + "," + strOrganizerAddr + "," + strRecurring + "," + strStartWhole + "," + strEndWhole; if (strDupCheck.Count > 0) { bool bAdd = true; foreach (string str in strDupCheck) { string strSubj = str.Split(',')[0]; string strStart = str.Split(',')[4]; string strEnd = str.Split(',')[5]; if (str == strDupLine) { bErr = true; strErrors.Add(" ERROR: Duplicate Items."); strErrors.Add(" This Item: " + strSubject + " | " + strStartWhole + " | " + strEndWhole); strErrors.Add(" Other Item: " + strSubj + " | " + strStart + " | " + strEnd); iErrors++; bAdd = false; } } if (bAdd) { strDupCheck.Add(strDupLine); } } else { strDupCheck.Add(strDupLine); } if (string.IsNullOrEmpty(strDeliveryTime)) { if (int.Parse(strApptStateFlags) > 0) // single Appt might not need Delivery time. { bErr = true; strErrors.Add(" ERROR: Missing required Delivery Time property."); iErrors++; } } // Do some tests if the item is a recurring item if (strRecurring.ToUpper() == "TRUE") { if (iMod > iDel) { bErr = true; strErrors.Add(" ERROR: Recurrence Data is corrupt."); iErrors++; } if (TimeCheck(dtRecurStart)) { bErr = true; strErrors.Add(" ERROR: Recurrence Start Time is set to an invalid value."); iErrors++; } if (TimeCheck(dtRecurEnd)) { bErr = true; strErrors.Add(" ERROR: Recurrence End Time is set to an invalid value."); iErrors++; } iRecurItems++; if (iRecurItems == 1299) { bErr = true; strErrors.Add(" ERROR: Reached limit of 1300 Recurring Appointments. Delete some older recurring appointments to correct this."); iErrors++; } if (iRecurItems == 1250) { bWarn = true; strErrors.Add(" WARNING: Approaching limit of 1300 Recurring Appointments. Delete some older recurring appointments to correct this."); iWarn++; } } if (dtStart < dtOld) { if (!(strAllDay.ToUpper() == "TRUE")) { bErr = true; strErrors.Add(" ERROR: Start time set previous to 1990."); iErrors++; } else { bWarn = true; strErrors.Add(" WARNING: All day event set with event date before 1990."); iWarn++; } } if (dtStart > dtFuture) { if (!(strAllDay.ToUpper() == "TRUE")) { bErr = true; strErrors.Add(" ERROR: Start time set after the year 2100."); iErrors++; } else { bWarn = true; strErrors.Add(" WARNING: All day event set with event date after 2100."); iWarn++; } } if (string.IsNullOrEmpty(strSenderName)) { if (int.Parse(strApptStateFlags) > 0) // if no Sender Name AND this is a meeting then that's bad. { bErr = true; strErrors.Add(" ERROR: Missing required Sender Name property."); iErrors++; } } if (string.IsNullOrEmpty(strSenderAddr)) { if (int.Parse(strApptStateFlags) > 0) // if no Sender Address AND this is a meeting then that's bad. { bErr = true; strErrors.Add(" ERROR: Missing required Sender Address property."); iErrors++; } } if (string.IsNullOrEmpty(strMsgClass)) { bErr = true; strErrors.Add(" ERROR: Missing required Message Class property."); iErrors++; } else { bool bFound = false; foreach (string strClass in calMsgClasses) { if (strClass == strMsgClass) { bFound = true; break; // if one of the known classes then all is good. } } if (!bFound) { if (!(strMsgClass.Contains("IPM.Appointment"))) { bErr = true; strErrors.Add(" ERROR: Unknown or incorrect Message Class " + strMsgClass + " is set on this item."); iErrors++; } else { bWarn = true; strErrors.Add(" WARNING: Unknown Message Class " + strMsgClass + " is set on this item."); iWarn++; } } } if (iExcept >= 25) { bWarn = true; strErrors.Add(" WARNING: Meeting has " + strRecurExceptCount + " exceptions which may indicate a problematic long-running recurring meeting."); iWarn++; } if (!(string.IsNullOrEmpty(strMsgSize))) { int iSize = int.Parse(strMsgSize); string strNum = ""; if (iSize >= 52428800) { strNum = "50M"; } else if (iSize >= 26214400) { strNum = "25M"; } else if (iSize >= 10485760) { strNum = "10M"; } if (iSize >= 10485760) // if >= 10M then one of the above is true... { bWarn = true; iWarn++; if (strHasAttach.ToUpper() == "TRUE" && strRecurring.ToUpper() == "TRUE") { strErrors.Add(" WARNING: Message size exceeds " + strNum + " which may indicate a problematic long-running recurring meeting."); } else if (strHasAttach.ToUpper() == "TRUE") { strErrors.Add(" WARNING: Message size exceeds " + strNum + " but is not set as recurring. Might have large and/or many attachments."); } else { strErrors.Add(" WARNING: Message size exceeds " + strNum + " but has no attachments. Might have some large problem properties."); } } } if (string.IsNullOrEmpty(strApptStateFlags)) // { bErr = true; strErrors.Add(" ERROR: Missing required Appointment State property."); iErrors++; } else { // check for meeting hijack items switch (strApptStateFlags) { case "0": // Non-meeting appointment { //single appointment I made in my Calendar break; } case "1": // Meeting and I am the Organizer { if (!string.IsNullOrEmpty(strOrganizerAddr) && !string.IsNullOrEmpty(strOrganizerSMTP)) { if (!(strOrganizerSMTP.ToUpper() == strMbxSMTP)) // this user's email should match with the Organizer. If not then error. { if (bOrgTest) { bErr = true; strErrors.Add(" ERROR: Organizer properties are in conflict."); strErrors.Add(" Organizer Address: " + strOrganizerAddr); strErrors.Add(" Appt State: " + strDisplayName + " is the Organizer"); iErrors++; } else { bWarn = true; strErrors.Add(" WARNING: Organizer properties might be in conflict."); strErrors.Add(" Organizer Address: " + strOrganizerAddr); strErrors.Add(" Appt State: " + strDisplayName + " is the Organizer"); strErrors.Add(" If the address above is one of the proxyAddresses for " + strDisplayName + " then all is good."); iWarn++; } } } break; } case "2": // Received item - shouldn't be in this state { bErr = true; strErrors.Add(" ERROR: Appointment State is an incorrect value."); iErrors++; break; } case "3": // Meeting item that I received - I am an Attendee { if (!string.IsNullOrEmpty(strOrganizerAddr) && !string.IsNullOrEmpty(strOrganizerSMTP)) { if (strOrganizerSMTP.ToUpper() == strMbxSMTP) // this user's email should NOT match with the Organizer. If it does then error. { if (bOrgTest) { bErr = true; strErrors.Add(" ERROR: Organizer properties are in conflict."); strErrors.Add(" Organizer Address: " + strOrganizerAddr); strErrors.Add(" Appt State: " + strDisplayName + " is an Attendee"); iErrors++; } else { bWarn = true; strErrors.Add(" WARNING: Organizer properties might be in conflict."); strErrors.Add(" Organizer Address: " + strOrganizerAddr); strErrors.Add(" Appt State: " + strDisplayName + " is an Attendee"); strErrors.Add(" If the address above is NOT a proxyAddress for " + strDisplayName + " then all is good."); iWarn++; } } } break; } default: // nothing else matters yet - can add later if needed { break; } } } if (string.IsNullOrEmpty(strTZDefStart)) { if (strRecurring.ToUpper() == "TRUE") { bErr = true; strErrors.Add(" ERROR: Missing required Timezone property."); iErrors++; } } // GlobalObjectID check if (int.Parse(strApptStateFlags) > 0) /// Global Obj IDs count when it's an actual Meeting, not single Appt. { bool bAdd = true; if (string.IsNullOrEmpty(strGlobalObjID)) { bErr = true; strErrors.Add(" ERROR: No GlobalObjectID property detected on this meeting item."); iErrors++; } if (string.IsNullOrEmpty(strCleanGlobalObjID)) { bErr = true; strErrors.Add(" ERROR: No CleanGlobalObjectID property detected on this meeting item."); iErrors++; } if (!(string.IsNullOrEmpty(strGlobalObjID)) || (!(string.IsNullOrEmpty(strCleanGlobalObjID)))) // if both are empty then don't bother testing { string strGOIDs = strGlobalObjID + "," + strCleanGlobalObjID + "," + strSubject + "," + strStartWhole + "," + strEndWhole; if (strGOIDCheck.Count > 0) { foreach (string str in strGOIDCheck) { string strGOID = str.Split(',')[0]; string strCleanGOID = str.Split(',')[1]; string strSubj = str.Split(',')[2]; string strStart = str.Split(',')[3]; string strEnd = str.Split(',')[4]; if (strGOID == strGlobalObjID && strCleanGOID == strCleanGlobalObjID) { bErr = true; strErrors.Add(" ERROR: Duplicate GlobalObjectID properties detected on two items."); strErrors.Add(" This item: " + strSubject + " | " + strStartWhole + " | " + strEndWhole); strErrors.Add(" Other item: " + strSubj + " | " + strStart + " | " + strEnd); iErrors++; bAdd = false; } else if (strGOID == strGlobalObjID) { if (!(string.IsNullOrEmpty(strGlobalObjID))) { bErr = true; strErrors.Add(" ERROR: Duplicate GlobalObjectID prop detected on two items."); strErrors.Add(" This item: " + strSubject + " | " + strStartWhole + " | " + strEndWhole); strErrors.Add(" Other item: " + strSubj + " | " + strStart + " | " + strEnd); iErrors++; } bAdd = false; } else if (strCleanGOID == strCleanGlobalObjID) { if (!(string.IsNullOrEmpty(strCleanGlobalObjID))) { bErr = true; strErrors.Add(" ERROR: Duplicate CleanGlobalObjectID prop detected on two items."); strErrors.Add(" This item: " + strSubject + " | " + strStartWhole + " | " + strEndWhole); strErrors.Add(" Other item: " + strSubj + " | " + strStart + " | " + strEnd); iErrors++; } bAdd = false; } } if (bAdd) { strGOIDCheck.Add(strGOIDs); } } else { strGOIDCheck.Add(strGOIDs); } } } // // Now do the reporting and moving of items as needed // if (bErr || bWarn) { outLog.WriteLine(strLogItem); // AND log out each line in the List of errors foreach (string strLine in strErrors) { outLog.WriteLine(strLine); } outLog.WriteLine(""); } // Move items to CalVerifier folder if error is flagged and in "move" mode if (bMoveItems && bErr) { appt.Move(fldCalVerifier.Id); } ResetProps(); // reset the properties for each item. }
ExchangeResult ExecuteOperation(EmailOperation operation, string address, Dictionary <string, bool> processed = null) { // create processed addresses dictionary if it does not exist if (processed == null) { processed = new Dictionary <string, bool>(); } // dont reprocess this address if we have already processed it if (processed.ContainsKey(address)) { return(null); } // try to find a mailbox for the address on one of the tenants ExchangeService service = null; EmailAddress mailbox = null; foreach (WebCredentials cred in credentials) { service = new ExchangeService(); service.Credentials = cred; service.Url = new Uri(ConfigurationManager.AppSettings["url"]); try { NameResolutionCollection results = service.ResolveName("smtp:" + address); if (results.Count > 0) { mailbox = results[0].Mailbox; break; } } catch (Exception e) { return(new ExchangeResult(address, StatusCode.Error, "Failed to resolve name: " + e.Message)); } } // if we did not find a mailbox for the address on any of the tenants then report recipient not found if (mailbox == null) { return(new ExchangeResult(address, StatusCode.RecipientNotFound, "recipient not found")); } // add resolved address to processed list to prevent reprocessing processed.Add(mailbox.Address, true); // if this mailbox is a group/distribution list if (mailbox.MailboxType == MailboxType.PublicGroup) { // attempt to expand the group ExpandGroupResults group = null; try { group = service.ExpandGroup(mailbox.Address); } catch (Exception e) { // report failure to expand group if an exception occurs during expansion return(new ExchangeResult(mailbox.Address, StatusCode.Error, "Failed to expand group: " + e.Message)); } // for every member in the group ExchangeResult result = new ExchangeResult(); foreach (EmailAddress member in group.Members) { // recursively execute operation and log results result.Log(ExecuteOperation(operation, member.Address, processed)); } // return the results return(result); } // if this is just a regular mailbox else if (mailbox.MailboxType == MailboxType.Mailbox) { // set impersonation to the mailbox address service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, mailbox.Address); // attempt to get some info to see if impersonation worked try { DateTime?dt = service.GetPasswordExpirationDate(mailbox.Address); } catch (Exception e) { // if we were unable to impersonate the user then report error return(new ExchangeResult(mailbox.Address, StatusCode.Error, "impersonation failed: " + e.Message)); } // delete email if operation is delete if (operation == EmailOperation.Delete) { try { // find all instances of the email with message_id in the mailbox FolderView folderView = new FolderView(int.MaxValue); folderView.PropertySet = new PropertySet(BasePropertySet.IdOnly, FolderSchema.DisplayName); folderView.Traversal = FolderTraversal.Shallow; SearchFilter folderFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "AllItems"); FindFoldersResults folders = service.FindFolders(WellKnownFolderName.Root, folderFilter, folderView); SearchFilter filter = new SearchFilter.IsEqualTo(EmailMessageSchema.InternetMessageId, message_id); ItemView view = new ItemView(int.MaxValue); view.PropertySet = new PropertySet(BasePropertySet.IdOnly); view.Traversal = ItemTraversal.Shallow; List <ItemId> items = new List <ItemId>(); foreach (Item item in service.FindItems(folders.Folders[0].Id, filter, view)) { items.Add(item.Id); } // if no instances of the email were found in the mailbox then report message_id not found if (items.Count == 0) { return(new ExchangeResult(mailbox.Address, StatusCode.MessageNotFound, "message_id not found")); } // delete all found instances of the email with message_id from the mailbox foreach (ServiceResponse response in service.DeleteItems(items, DeleteMode.SoftDelete, null, null)) { // if we failed to delete an instance of the email then report an error if (response.Result != ServiceResult.Success) { string message = "failed to delete email: " + response.ErrorCode + " " + response.ErrorMessage; return(new ExchangeResult(mailbox.Address, StatusCode.Error, message)); } } } catch (Exception e) { //report any errors we encounter return(new ExchangeResult(mailbox.Address, StatusCode.Error, "failed to delete email: " + e.Message)); } } // recover email if operation is recover else if (operation == EmailOperation.Restore) { try { // find all instances of the email with message_id in the recoverable items folder SearchFilter filter = new SearchFilter.IsEqualTo(EmailMessageSchema.InternetMessageId, message_id); ItemView view = new ItemView(int.MaxValue); view.PropertySet = new PropertySet(BasePropertySet.IdOnly); view.Traversal = ItemTraversal.Shallow; List <ItemId> items = new List <ItemId>(); foreach (Item item in service.FindItems(WellKnownFolderName.RecoverableItemsDeletions, filter, view)) { items.Add(item.Id); } // if no instances of the email with message_id were found in the recoverable items folder of the mailbox if (items.Count == 0) { // report message_id not found return(new ExchangeResult(mailbox.Address, StatusCode.MessageNotFound, "message_id not found")); } // move every instance of the email with message_id in the recoverable items folder to the inbox foreach (ServiceResponse response in service.MoveItems(items, new FolderId(WellKnownFolderName.Inbox))) { // if we failed to move an instance of the email to the inbox then report an error if (response.Result != ServiceResult.Success) { string message = "failed to recover email: " + response.ErrorCode + " " + response.ErrorMessage; return(new ExchangeResult(mailbox.Address, StatusCode.Error, message)); } } } catch (Exception e) { // report any errors we encounter return(new ExchangeResult(mailbox.Address, StatusCode.Error, "failed to recover email: " + e.Message)); } } // report successful operation return(new ExchangeResult(mailbox.Address, StatusCode.Success, "success")); } // report that the mailbox type is not one of the supported types return(new ExchangeResult(mailbox.Address, StatusCode.Error, "Unsupported mailbox type: " + mailbox.MailboxType.ToString())); }