private static void Main(string[] args) { //ExchangeService service = new ExchangeService(); ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1, TimeZoneInfo.Local) { UseDefaultCredentials = true }; service.AutodiscoverUrl(@"*****@*****.**"); Task newTask = new Task(service); newTask.Contacts.Add("*****@*****.**"); newTask.DueDate = DateTime.Now.AddDays(1); newTask.PercentComplete = 48; newTask.StartDate = DateTime.Now; newTask.Status = TaskStatus.InProgress; //newTask.TotalWork = 50; newTask.Body = "Hello"; newTask.Subject = "Test Issue Task"; newTask.ReminderDueBy = newTask.DueDate.Value; IList<Task> items = new List<Task>(); items.Add(newTask); FolderId id = new FolderId(WellKnownFolderName.Tasks); //service.CreateItems(items, id, null, null); }
/// <summary> /// Binds to an existing calendar folder and loads the specified set of properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to use to bind to the calendar folder.</param> /// <param name="id">The Id of the calendar folder to bind to.</param> /// <param name="propertySet">The set of properties to load.</param> /// <returns>A CalendarFolder instance representing the calendar folder corresponding to the specified Id.</returns> public static new CalendarFolder Bind( ExchangeService service, FolderId id, PropertySet propertySet) { return service.BindToFolder<CalendarFolder>(id, propertySet); }
/// <summary> /// /// </summary> /// <param name="syncState">The optional sync state representing the point in time when the folder was last synced. null indicates the earliest possible time.</param> /// <param name="folderId"></param> public FolderSyncState(string syncState, FolderId folderId) { this._SyncState = syncState; if (folderId == null) throw new ArgumentException("folderId"); this._TargetFolderId = folderId; }
/// <summary> /// Method is returning Folder object from WellKnownFolderName enum. /// </summary> /// <param name="wellKnownFolderName">WellKnownFolderName for which Folder object needs to be returned.</param> /// <param name="ewsSession">ExchangeService session context.</param> /// <returns></returns> public static Folder GetWellKnownFolder(WellKnownFolderName wellKnownFolderName, ExchangeService ewsSession) { FolderId wellKnownFolderId = new FolderId(wellKnownFolderName); Folder wellKnownFolder = Folder.Bind(ewsSession, wellKnownFolderId); return wellKnownFolder; }
/// <summary> /// Binds to an existing calendar folder and loads its first class properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to use to bind to the calendar folder.</param> /// <param name="id">The Id of the calendar folder to bind to.</param> /// <returns>A CalendarFolder instance representing the calendar folder corresponding to the specified Id.</returns> public static new CalendarFolder Bind(ExchangeService service, FolderId id) { return CalendarFolder.Bind( service, id, PropertySet.FirstClassProperties); }
static void Main(string[] args) { var service = new ExchangeService(); service.Credentials = new NetworkCredential("your mail address", "your password"); try { service.Url = new Uri("http://exchange01/ews/exchange.asmx"); } catch (AutodiscoverRemoteException ex) { Console.WriteLine(ex.Message); } FolderId inboxId = new FolderId(WellKnownFolderName.Inbox, "<<e-mail address>>"); var findResults = service.FindItems(inboxId, new ItemView(10)); foreach (var message in findResults.Items) { var msg = EmailMessage.Bind(service, message.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments)); foreach (Attachment attachment in msg.Attachments) { if (attachment is FileAttachment) { FileAttachment fileAttachment = attachment as FileAttachment; // Load the file attachment into memory and print out its file name. fileAttachment.Load(); var filename = fileAttachment.Name; bool b; b = filename.Contains(".csv"); if (b == true) { bool a; a = filename.Contains("meteo"); if (a == true) { var theStream = new FileStream("C:\\data\\attachments\\" + fileAttachment.Name, FileMode.OpenOrCreate, FileAccess.ReadWrite); fileAttachment.Load(theStream); theStream.Close(); theStream.Dispose(); } } } else // Attachment is an item attachment. { // Load attachment into memory and write out the subject. ItemAttachment itemAttachment = attachment as ItemAttachment; itemAttachment.Load(); } } } }
public FolderId CreateChildFolder(IFolderDataBase folderData, FolderId parentFolderId) { Folder folder = new Folder(CurrentExchangeService); folder.DisplayName = folderData.DisplayName; folder.FolderClass = folderData.FolderType; folder.Save(parentFolderId); return FindFolder(folderData, parentFolderId); }
/// <summary> /// Initializes a new instance of FolderIdWrapper. /// </summary> /// <param name="folderId">The FolderId object providing the Id.</param> internal FolderIdWrapper(FolderId folderId) { EwsUtilities.Assert( folderId != null, "FolderIdWrapper.ctor", "folderId is null"); this.folderId = folderId; }
public ReserveRoomResponse Execute(ReserveRoomRequest request) { var response = new ReserveRoomResponse(); try { // Get mailbox info var requestMailboxInfo = new GetMailboxInfo.GetMailboxInfoRequest( email: request.MailboxEmail); var responseMailboxInfo = new GetMailboxInfo().Execute(requestMailboxInfo); if (!responseMailboxInfo.Success) { response.ErrorMessage = responseMailboxInfo.ErrorMessage; return response; } // Connect to Exchange var service = ExchangeServiceConnector.GetService(request.MailboxEmail); var mbx = new Mailbox(request.MailboxEmail); FolderId fid = new FolderId(WellKnownFolderName.Calendar, mbx); //CalendarFolder calendar = CalendarFolder.Bind(service, fid, new PropertySet(FolderSchema.ManagedFolderInformation, FolderSchema.ParentFolderId, FolderSchema.ExtendedProperties)); // Create appointment var appointment = new Appointment(service); appointment.Subject = "Impromptu Meeting"; appointment.Body = "Booked via Conference Room app."; appointment.Start = DateTime.Now; appointment.End = DateTime.Now.AddMinutes(request.BookMinutes); appointment.Location = responseMailboxInfo.DisplayName; appointment.Save(fid, SendInvitationsMode.SendToNone); // Verify saved Item item = Item.Bind(service, appointment.Id, new PropertySet(ItemSchema.Subject)); if (item == null) { response.ErrorMessage = "Error saving appointment to calendar."; return response; } else { response.AppointmentId = appointment.Id; response.Success = true; } } catch (Exception e) { response.ErrorMessage = e.ToString(); return response; } return response; }
/// <summary> /// Attempts to get Id of Conflicts folder /// If the value can not be obtained, the method returns <c>null</c>.</summary> /// <param name="exchangeService">Exchange service.</param> /// <returns>Id of this folder, or <c>null</c>.</returns> public Exchange.FolderId GetConflictsFolderId(Exchange.ExchangeService exchangeService) { var rootFolderId = Exchange.Folder.Bind(exchangeService, Exchange.WellKnownFolderName.MsgFolderRoot).Id; Exchange.FolderId syncIssuesFolderId = GetChildIdByName(exchangeService, rootFolderId, "Sync Issues"); if (syncIssuesFolderId == null) { return(null); } return(GetChildIdByName(exchangeService, syncIssuesFolderId, "Conflicts")); }
public virtual UserConfiguration GetFolderAssociatedItem(ExchangeService ewsSession, FolderId faiFolder, EwsFolderAssociateItemType itemType) { try { UserConfiguration userConfig = UserConfiguration.Bind(ewsSession, itemType.ToString(), faiFolder, UserConfigurationProperties.All); return userConfig; } catch (Exception) { throw; } }
/// <summary> /// Returns Id of first child folder by name and root folder id. /// If the value can not be obtained, the method returns <c>null</c>.</summary> /// <param name="exchangeService">Exchange service.</param> /// <param name="parentId">Root folder Id.</param> /// <param name="childName">Display name of the finding folder.</param> /// <returns>Id of child folder, or <c>null</c>.</returns> private Exchange.FolderId GetChildIdByName(Exchange.ExchangeService exchangeService, Exchange.FolderId parentId, string childName) { Exchange.SearchFilter filter = new Exchange.SearchFilter .IsEqualTo(Exchange.FolderSchema.DisplayName, childName); var result = exchangeService.FindFolders(parentId, filter, new Exchange.FolderView(1)); if (!result.Folders.Any()) { return(null); } return(result.Folders[0].Id); }
/// <summary> /// Send message. /// </summary> /// <param name="parentFolderId">The parent folder id.</param> /// <param name="messageDisposition">The message disposition.</param> private async System.Threading.Tasks.Task InternalSend(FolderId parentFolderId, MessageDisposition messageDisposition) { this.ThrowIfThisIsAttachment(); if (this.IsNew) { if ((this.Attachments.Count == 0) || (messageDisposition == MessageDisposition.SaveOnly)) { await this.InternalCreate( parentFolderId, messageDisposition, null); } else { // If the message has attachments, save as a draft (and add attachments) before sending. await this.InternalCreate( null, // null means use the Drafts folder in the mailbox of the authenticated user. MessageDisposition.SaveOnly, null); await this.Service.SendItem(this, parentFolderId); } } else { // Regardless of whether item is dirty or not, if it has unprocessed // attachment changes, process them now. // Validate and save attachments before sending. if (this.HasUnprocessedAttachmentChanges()) { this.Attachments.Validate(); await this.Attachments.Save(); } if (this.PropertyBag.GetIsUpdateCallNecessary()) { await this.InternalUpdate( parentFolderId, ConflictResolutionMode.AutoResolve, messageDisposition, null); } else { await this.Service.SendItem(this, parentFolderId); } } }
/// <summary> /// Sets the read state of items in the specified conversation. Calling this method results in a call to EWS. /// </summary> /// <param name="contextFolderId">The Id of the folder items must belong to in order for their read state to /// be set. If contextFolderId is null, the read states of items across the entire mailbox are set.</param> /// <param name="isRead">if set to <c>true</c>, conversation items are marked as read; otherwise they are /// marked as unread.</param> public void SetReadStateForItemsInConversation( FolderId contextFolderId, bool isRead) { this.Service.SetReadStateForItemsInConversations( new KeyValuePair <ConversationId, DateTime?>[] { new KeyValuePair <ConversationId, DateTime?>( this.Id, this.GlobalLastDeliveryTime) }, contextFolderId, isRead)[0].ThrowIfNecessary(); }
/// <summary> /// Copies items in the specified conversation to a specific folder. Calling this method results in a call to EWS. /// </summary> /// <param name="contextFolderId">The Id of the folder items must belong to in order to be copied. If contextFolderId /// is null, items across the entire mailbox are copied.</param> /// <param name="destinationFolderId">The Id of the destination folder.</param> public void CopyItemsInConversation( FolderId contextFolderId, FolderId destinationFolderId) { this.Service.CopyItemsInConversations( new KeyValuePair <ConversationId, DateTime?>[] { new KeyValuePair <ConversationId, DateTime?>( this.Id, this.GlobalLastDeliveryTime) }, contextFolderId, destinationFolderId)[0].ThrowIfNecessary(); }
/// <summary> /// Deletes items in the specified conversation. /// Calling this method results in a call to EWS. /// </summary> /// <param name="contextFolderId">The Id of the folder items must belong to in order to be deleted. If contextFolderId is /// null, items across the entire mailbox are deleted.</param> /// <param name="deleteMode">The deletion mode.</param> public void DeleteItems( FolderId contextFolderId, DeleteMode deleteMode) { this.Service.DeleteItemsInConversations( new KeyValuePair <ConversationId, DateTime?>[] { new KeyValuePair <ConversationId, DateTime?>( this.Id, this.GlobalLastDeliveryTime) }, contextFolderId, deleteMode)[0].ThrowIfNecessary(); }
/// <summary> /// Moves items in the specified conversation to a specific folder. /// Calling this method results in a call to EWS. /// </summary> /// <param name="contextFolderId">The Id of the folder items must belong to in order to be moved. If contextFolderId is null, /// items across the entire mailbox are moved.</param> /// <param name="destinationFolderId">The Id of the destination folder.</param> public async System.Threading.Tasks.Task MoveItemsInConversation( FolderId contextFolderId, FolderId destinationFolderId) { (await this.Service.MoveItemsInConversations( new KeyValuePair <ConversationId, DateTime?>[] { new KeyValuePair <ConversationId, DateTime?>( this.Id, this.GlobalLastDeliveryTime) }, contextFolderId, destinationFolderId).ConfigureAwait(false))[0].ThrowIfNecessary(); }
public void accessShared() { ServicePointManager.ServerCertificateValidationCallback = m_UrlBack.CertificateValidationCallBack; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2); // Get the information of the account. service.Credentials = new WebCredentials(EMAIL_ACCOUNT, EMAIL_PWD); // Set the url of server. if (!AutodiscoverUrl(service, EMAIL_ACCOUNT)) { return; } var mb = new Mailbox(SHARED_MAILBOX); var fid1 = new FolderId(WellKnownFolderName.Inbox, mb); // Add a search filter that searches on the body or subject. List<SearchFilter> searchFilterCollection = new List<SearchFilter>(); searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, SUBJECT_KEY_WORD)); SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchFilterCollection.ToArray()); // Create a view with a page size of 10. var view = new ItemView(10); // Identify the Subject and DateTimeReceived properties to return. // Indicate that the base property will be the item identifier view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.DateTimeReceived); // Order the search results by the DateTimeReceived in descending order. view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending); // Set the traversal to shallow. (Shallow is the default option; other options are Associated and SoftDeleted.) view.Traversal = ItemTraversal.Shallow; String[] invalidStings = { "\\", ",", ":", "*", "?", "\"", "<", ">", "|" }; PropertySet itemPorpertySet = new PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.MimeContent); FindItemsResults<Item> findResults = service.FindItems(fid1, searchFilter, view); foreach (Item item in findResults.Items) { EmailMessage email = EmailMessage.Bind(service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments)); email.Load(itemPorpertySet); string emailBody = email.Body.ToString(); } }
/// <summary> /// <see cref="ExchangeSyncProvider.EnumerateChanges"/> /// </summary> public override IEnumerable <IRemoteItem> EnumerateChanges(SyncContext context) { base.EnumerateChanges(context); var result = new List <IRemoteItem>(); if (!UserSettings.ImportActivities) { return(result); } var folders = new List <Exchange.Folder>(); Exchange.FolderId trashFolderId = Exchange.Folder.Bind( Service, Exchange.WellKnownFolderName.DeletedItems, Exchange.BasePropertySet.IdOnly).Id; if (UserSettings.ImportActivitiesAll) { Exchange.Folder rootFolder = Exchange.Folder.Bind(Service, Exchange.WellKnownFolderName.MsgFolderRoot); folders.GetAllFoldersByFilter(rootFolder); folders.Add(rootFolder); } else { folders = SafeBindFolders(Service, UserSettings.RemoteFolderUIds.Keys, context); } Exchange.SearchFilter itemsFilter = GetItemsSearchFilters(); SyncItemSchema schema = FindSchemaBySyncValueName(typeof(ExchangeTask).Name); foreach (Exchange.Folder folder in folders) { if (folder.Id.Equals(trashFolderId)) { continue; } var itemView = new Exchange.ItemView(PageItemCount); Exchange.FindItemsResults <Exchange.Item> itemCollection; do { itemCollection = folder.ReadItems(itemsFilter, itemView); foreach (Exchange.Item item in itemCollection) { Exchange.Task task = ExchangeUtility.SafeBindItem <Exchange.Task>(Service, item.Id); if (task != null) { var remoteItem = new ExchangeTask(schema, task, TimeZone); result.Add(remoteItem); } } } while (itemCollection.MoreAvailable); } return(result); }
/// <summary> /// Binds to an existing user configuration and loads the specified properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to which the user configuration is bound.</param> /// <param name="name">The name of the user configuration.</param> /// <param name="parentFolderId">The Id of the folder containing the user configuration.</param> /// <param name="properties">The properties to load.</param> /// <returns>A user configuration instance.</returns> public static UserConfiguration Bind( ExchangeService service, string name, FolderId parentFolderId, UserConfigurationProperties properties) { UserConfiguration result = service.GetUserConfiguration( name, parentFolderId, properties); result.isNew = false; return(result); }
public int GetPendingMessagesCount() { try { var inbox = new ex.FolderId(ex.WellKnownFolderName.Inbox, new ex.Mailbox(Config["NOME_CAIXA"])); var itemView = new ex.ItemView(Config["QTD_EMAILS_RECUPERAR"].To(10)); var items = GetExchangeService(Username, Password).FindItems(inbox, itemView); return(items.Count()); } catch { Instance = null; throw; } }
/// <summary> /// This function retuns the mail items for the given folder and for the date /// </summary> /// <param name="service"></param> /// <param name="folderId"></param> /// <param name="lastSyncDate"></param> /// <returns></returns> public FindItemsResults<Item> RetrieveMailItems(ref ExchangeService service, FolderId folderId, DateTime lastSyncDate) { //email view var emailView = new ItemView(int.MaxValue) { PropertySet = BasePropertySet.IdOnly }; //search filter collection var searchFilterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And) { new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, lastSyncDate) }; //retrieve var items = service.FindItems(folderId, searchFilterCollection, emailView); return items; }
/// <summary> /// Sets the read state of items in the specified conversation. Calling this method results in a call to EWS. /// </summary> /// <param name="contextFolderId">The Id of the folder items must belong to in order for their read state to /// be set. If contextFolderId is null, the read states of items across the entire mailbox are set.</param> /// <param name="isRead">if set to <c>true</c>, conversation items are marked as read; otherwise they are /// marked as unread.</param> /// <param name="suppressReadReceipts">if set to <c>true</c> read receipts are suppressed.</param> public async System.Threading.Tasks.Task SetReadStateForItemsInConversation( FolderId contextFolderId, bool isRead, bool suppressReadReceipts) { (await this.Service.SetReadStateForItemsInConversations( new KeyValuePair <ConversationId, DateTime?>[] { new KeyValuePair <ConversationId, DateTime?>( this.Id, this.GlobalLastDeliveryTime) }, contextFolderId, isRead, suppressReadReceipts).ConfigureAwait(false))[0].ThrowIfNecessary(); }
/// <summary> /// Sets the retention policy of items in the specified conversation. Calling this method results in a call to EWS. /// </summary> /// <param name="contextFolderId">The Id of the folder items must belong to in order for their retention policy to /// be set. If contextFolderId is null, the retention policy of items across the entire mailbox are set.</param> /// <param name="retentionPolicyType">Retention policy type.</param> /// <param name="retentionPolicyTagId">Retention policy tag id. Null will clear the policy.</param> public async System.Threading.Tasks.Task SetRetentionPolicyForItemsInConversation( FolderId contextFolderId, RetentionType retentionPolicyType, Guid?retentionPolicyTagId) { (await this.Service.SetRetentionPolicyForItemsInConversations( new KeyValuePair <ConversationId, DateTime?>[] { new KeyValuePair <ConversationId, DateTime?>( this.Id, this.GlobalLastDeliveryTime) }, contextFolderId, retentionPolicyType, retentionPolicyTagId).ConfigureAwait(false))[0].ThrowIfNecessary(); }
/// <summary> /// Sets the retention policy of items in the specified conversation. Calling this method results in a call to EWS. /// </summary> /// <param name="contextFolderId">The Id of the folder items must belong to in order for their retention policy to /// be set. If contextFolderId is null, the retention policy of items across the entire mailbox are set.</param> /// <param name="retentionPolicyType">Retention policy type.</param> /// <param name="retentionPolicyTagId">Retention policy tag id. Null will clear the policy.</param> public void SetRetentionPolicyForItemsInConversation( FolderId contextFolderId, RetentionType retentionPolicyType, Guid?retentionPolicyTagId) { this.Service.SetRetentionPolicyForItemsInConversations( new KeyValuePair <ConversationId, DateTime?>[] { new KeyValuePair <ConversationId, DateTime?>( this.Id, this.GlobalLastDeliveryTime) }, contextFolderId, retentionPolicyType, retentionPolicyTagId)[0].ThrowIfNecessary(); }
public static void Subscribe(Node doclibrary, ExchangeService service) { if (service == null) return; var address = doclibrary["ListEmail"] as string; if (string.IsNullOrEmpty(address)) return; var mailbox = new Mailbox(address); var folderId = new FolderId(WellKnownFolderName.Inbox, mailbox); var servicePath = string.Format(Configuration.PushNotificationServicePath, doclibrary.Path); var watermark = ExchangeHelper.GetWaterMark(doclibrary); var ps = service.SubscribeToPushNotifications(new List<FolderId> { folderId }, new Uri(servicePath), Configuration.StatusPollingIntervalInMinutes, watermark, EventType.NewMail); var loginfo = string.Concat(" - Path:",doclibrary.Path, ", Email:", address, ", Watermark:", watermark, ", SubscriptionId:", ps.Id); Logger.WriteInformation("Exchange subscription" + loginfo, ExchangeHelper.ExchangeLogCategory); // persist subscription id to doclib, so that multiple subscriptions are handled correctly var user = User.Current; try { AccessProvider.Current.SetCurrentUser(User.Administrator); var retryCount = 3; while (retryCount > 0) { try { doclibrary["ExchangeSubscriptionId"] = ps.Id; doclibrary.Save(); break; } catch (NodeIsOutOfDateException) { retryCount--; doclibrary = Node.LoadNode(doclibrary.Id); } } } finally { AccessProvider.Current.SetCurrentUser(user); } }
/// <summary> /// Clear flags for conversation items. Calling this method results in a call to EWS. /// </summary> /// <param name="contextFolderId">The Id of the folder items must belong to in order to be unflagged. If contextFolderId is /// null, flags for items in conversation across the entire mailbox are cleared.</param> public void ClearItemFlags(FolderId contextFolderId) { Flag flag = new Flag() { FlagStatus = ItemFlagStatus.NotFlagged }; this.Service.SetFlagStatusForItemsInConversations( new KeyValuePair <ConversationId, DateTime?>[] { new KeyValuePair <ConversationId, DateTime?>( this.Id, this.GlobalLastDeliveryTime) }, contextFolderId, flag)[0].ThrowIfNecessary(); }
/// <summary> /// Binds to an existing user configuration and loads the specified properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to which the user configuration is bound.</param> /// <param name="name">The name of the user configuration.</param> /// <param name="parentFolderId">The Id of the folder containing the user configuration.</param> /// <param name="properties">The properties to load.</param> /// <returns>A user configuration instance.</returns> public static async Task <UserConfiguration> Bind( ExchangeService service, string name, FolderId parentFolderId, UserConfigurationProperties properties, CancellationToken token = default(CancellationToken)) { UserConfiguration result = await service.GetUserConfiguration( name, parentFolderId, properties, token); result.isNew = false; return(result); }
/// <summary> /// Clear flags for conversation items. Calling this method results in a call to EWS. /// </summary> /// <param name="contextFolderId">The Id of the folder items must belong to in order to be unflagged. If contextFolderId is /// null, flags for items in conversation across the entire mailbox are cleared.</param> public async System.Threading.Tasks.Task ClearItemFlags(FolderId contextFolderId) { Flag flag = new Flag() { FlagStatus = ItemFlagStatus.NotFlagged }; (await this.Service.SetFlagStatusForItemsInConversations( new KeyValuePair <ConversationId, DateTime?>[] { new KeyValuePair <ConversationId, DateTime?>( this.Id, this.GlobalLastDeliveryTime) }, contextFolderId, flag).ConfigureAwait(false))[0].ThrowIfNecessary(); }
public IEnumerable <MailMessage> GetPendingMessages() { var inbox = new ex.FolderId(ex.WellKnownFolderName.Inbox, new ex.Mailbox(Config["NOME_CAIXA"])); var itemView = new ex.ItemView(Config["QTD_EMAILS_RECUPERAR"].To(10)) { PropertySet = new ex.PropertySet(ex.BasePropertySet.IdOnly, ex.ItemSchema.Subject, ex.ItemSchema.DateTimeReceived) }; itemView.OrderBy.Add(ex.ItemSchema.DateTimeReceived, ex.SortDirection.Ascending); var findResults = GetExchangeService(Username, Password).FindItems(inbox, itemView); var items = GetExchangeService(Username, Password).BindToItems(findResults.Select(item => item.Id), new ex.PropertySet(ex.BasePropertySet.FirstClassProperties, ex.EmailMessageSchema.From, ex.EmailMessageSchema.ToRecipients, ex.ItemSchema.Attachments, ex.EmailMessageSchema.CcRecipients, ex.EmailMessageSchema.BccRecipients, ex.ItemSchema.Body, ex.ItemSchema.DateTimeCreated, ex.ItemSchema.DateTimeReceived, ex.ItemSchema.DateTimeSent, ex.ItemSchema.DisplayCc, ex.ItemSchema.DisplayTo, ex.ItemSchema.Subject)); foreach (var item in items) { yield return(ParseItem(item)); var ea = new OnMessageReadEventArgs(); if (OnMessageRead != null) { OnMessageRead(this, ea); if (ea.Cancel) { continue; } } GetExchangeService(Username, Password).DeleteItems(new[] { item.Item.Id }, ex.DeleteMode.MoveToDeletedItems, null, null); } }
/// <summary> /// Create a PostItem response. /// </summary> /// <param name="parentFolderId">The parent folder id.</param> /// <param name="messageDisposition">The message disposition.</param> /// <returns>Created PostItem.</returns> internal PostItem InternalCreate(FolderId parentFolderId, MessageDisposition? messageDisposition) { ((ItemId)this.PropertyBag[ResponseObjectSchema.ReferenceItemId]).Assign(this.referenceItem.Id); List<Item> items = this.Service.InternalCreateResponseObject( this, parentFolderId, messageDisposition); PostItem postItem = EwsUtilities.FindFirstItemOfType<PostItem>(items); // This should never happen. If it does, we have a bug. EwsUtilities.Assert( postItem != null, "PostReply.InternalCreate", "postItem is null. The CreateItem call did not return the expected PostItem."); return postItem; }
/// <summary> /// Create a PostItem response. /// </summary> /// <param name="parentFolderId">The parent folder id.</param> /// <param name="messageDisposition">The message disposition.</param> /// <returns>Created PostItem.</returns> internal PostItem InternalCreate(FolderId parentFolderId, MessageDisposition?messageDisposition) { ((ItemId)this.PropertyBag[ResponseObjectSchema.ReferenceItemId]).Assign(this.referenceItem.Id); List <Item> items = this.Service.InternalCreateResponseObject( this, parentFolderId, messageDisposition); PostItem postItem = EwsUtilities.FindFirstItemOfType <PostItem>(items); // This should never happen. If it does, we have a bug. EwsUtilities.Assert( postItem != null, "PostReply.InternalCreate", "postItem is null. The CreateItem call did not return the expected PostItem."); return(postItem); }
/// <summary> /// Create item. /// </summary> /// <param name="parentFolderId">The parent folder id.</param> /// <param name="messageDisposition">The message disposition.</param> /// <param name="sendInvitationsMode">The send invitations mode.</param> internal void InternalCreate( FolderId parentFolderId, MessageDisposition?messageDisposition, SendInvitationsMode?sendInvitationsMode) { this.ThrowIfThisIsNotNew(); this.ThrowIfThisIsAttachment(); if (this.IsNew || this.IsDirty) { this.Service.CreateItem( this, parentFolderId, messageDisposition, sendInvitationsMode.HasValue ? sendInvitationsMode : this.DefaultSendInvitationsMode); this.Attachments.Save(); } }
/// <summary> /// Saves the user configuration. Calling this method results in a call to EWS. /// </summary> /// <param name="name">The name of the user configuration.</param> /// <param name="parentFolderId">The Id of the folder in which to save the user configuration.</param> public async System.Threading.Tasks.Task Save(string name, FolderId parentFolderId, CancellationToken token = default(CancellationToken)) { EwsUtilities.ValidateParam(name, "name"); EwsUtilities.ValidateParam(parentFolderId, "parentFolderId"); parentFolderId.Validate(this.service.RequestedServerVersion); if (!this.isNew) { throw new InvalidOperationException(Strings.CannotSaveNotNewUserConfiguration); } this.parentFolderId = parentFolderId; this.name = name; await this.service.CreateUserConfiguration(this, token); this.isNew = false; this.ResetIsDirty(); }
/// <summary> /// Saves the user configuration. Calling this method results in a call to EWS. /// </summary> /// <param name="name">The name of the user configuration.</param> /// <param name="parentFolderId">The Id of the folder in which to save the user configuration.</param> public void Save(string name, FolderId parentFolderId) { EwsUtilities.ValidateParam(name, "name"); EwsUtilities.ValidateParam(parentFolderId, "parentFolderId"); parentFolderId.Validate(this.service.RequestedServerVersion); if (!this.isNew) { throw new InvalidOperationException(Strings.CannotSaveNotNewUserConfiguration); } this.parentFolderId = parentFolderId; this.name = name; this.service.CreateUserConfiguration(this); this.isNew = false; this.ResetIsDirty(); }
/// <summary> /// Create item. /// </summary> /// <param name="parentFolderId">The parent folder id.</param> /// <param name="messageDisposition">The message disposition.</param> /// <param name="sendInvitationsMode">The send invitations mode.</param> internal async System.Threading.Tasks.Task InternalCreate( FolderId parentFolderId, MessageDisposition?messageDisposition, SendInvitationsMode?sendInvitationsMode, CancellationToken token) { this.ThrowIfThisIsNotNew(); this.ThrowIfThisIsAttachment(); if (this.IsNew || this.IsDirty) { await this.Service.CreateItem( this, parentFolderId, messageDisposition, sendInvitationsMode.HasValue?sendInvitationsMode : this.DefaultSendInvitationsMode, token); await this.Attachments.Save(); } }
/// <summary> /// Load from XML. /// </summary> /// <param name="reader">The reader.</param> internal override void InternalLoadFromXml(EwsServiceXmlReader reader) { base.InternalLoadFromXml(reader); this.folderId = new FolderId(); this.folderId.LoadFromXml(reader, reader.LocalName); reader.Read(); this.ParentFolderId = new FolderId(); this.ParentFolderId.LoadFromXml(reader, XmlElementNames.ParentFolderId); switch (this.EventType) { case EventType.Moved: case EventType.Copied: reader.Read(); this.oldFolderId = new FolderId(); this.oldFolderId.LoadFromXml(reader, reader.LocalName); reader.Read(); this.OldParentFolderId = new FolderId(); this.OldParentFolderId.LoadFromXml(reader, reader.LocalName); break; case EventType.Modified: reader.Read(); if (reader.IsStartElement()) { reader.EnsureCurrentNodeIsStartElement(XmlNamespace.Types, XmlElementNames.UnreadCount); this.unreadCount = int.Parse(reader.ReadValue()); } break; default: break; } }
public IEnumerable<MailMessage> GetPendingMessages() { ex.FolderId inbox = new ex.FolderId(ex.WellKnownFolderName.Inbox, new ex.Mailbox(_config["NOME_CAIXA"])); ex.ItemView itemView = new ex.ItemView(_config["QTD_EMAILS_RECUPERAR"].To<int>(10)); itemView.PropertySet = new ex.PropertySet(ex.BasePropertySet.IdOnly, ex.ItemSchema.Subject, ex.ItemSchema.DateTimeReceived); itemView.OrderBy.Add(ex.ItemSchema.DateTimeReceived, ex.SortDirection.Ascending); ex.FindItemsResults<ex.Item> findResults = GetExchangeService(this.Username, this.Password).FindItems(inbox, itemView); ex.ServiceResponseCollection<ex.GetItemResponse> items = GetExchangeService(this.Username, this.Password).BindToItems(findResults.Select(item => item.Id), new ex.PropertySet(ex.BasePropertySet.FirstClassProperties, ex.EmailMessageSchema.From, ex.EmailMessageSchema.ToRecipients, ex.EmailMessageSchema.Attachments, ex.EmailMessageSchema.CcRecipients, ex.EmailMessageSchema.BccRecipients, ex.EmailMessageSchema.Body, ex.EmailMessageSchema.DateTimeCreated, ex.EmailMessageSchema.DateTimeReceived, ex.EmailMessageSchema.DateTimeSent, ex.EmailMessageSchema.DisplayCc, ex.EmailMessageSchema.DisplayTo, ex.EmailMessageSchema.Subject)); foreach (ex.GetItemResponse item in items) { yield return ParseItem(item); OnMessageReadEventArgs ea = new OnMessageReadEventArgs(); if (OnMessageRead != null) { OnMessageRead(this, ea); if (ea.Cancel) continue; } GetExchangeService(this.Username, this.Password).DeleteItems(new ex.ItemId[] { item.Item.Id }, ex.DeleteMode.MoveToDeletedItems, null, null); } }
/// <summary> /// Flag conversation items as complete. Calling this method results in a call to EWS. /// </summary> /// <param name="contextFolderId">The Id of the folder items must belong to in order to be flagged as complete. If contextFolderId is /// null, items in conversation across the entire mailbox are marked as complete.</param> /// <param name="completeDate">The complete date (can be null).</param> public async System.Threading.Tasks.Task FlagItemsComplete( FolderId contextFolderId, DateTime?completeDate) { Flag flag = new Flag() { FlagStatus = ItemFlagStatus.Complete }; if (completeDate.HasValue) { flag.CompleteDate = completeDate.Value; } (await this.Service.SetFlagStatusForItemsInConversations( new KeyValuePair <ConversationId, DateTime?>[] { new KeyValuePair <ConversationId, DateTime?>( this.Id, this.GlobalLastDeliveryTime) }, contextFolderId, flag).ConfigureAwait(false))[0].ThrowIfNecessary(); }
/// <summary> /// Return the FolderID of a sub-folder within a given parent folder. /// </summary> /// <param name="WebService">Exchange Web Service instance to use</param> /// <param name="BaseFolderId">FolderID of the prent folder</param> /// <param name="FolderName">Name of the folder to find</param> /// <returns>FolderID of the matching folder (or null if not found)</returns> public static FolderId FindFolder(ExchangeService WebService, FolderId BaseFolderId, string FolderName) { // Retrieve a list of folders (paged by 10) FolderView folderView = new FolderView(10, 0); // Set base point of offset. folderView.OffsetBasePoint = OffsetBasePoint.Beginning; // Set the properties that will be loaded on returned items (display namme & folder ID) folderView.PropertySet = new PropertySet(FolderSchema.DisplayName, FolderSchema.Id); FindFoldersResults folderResults; do { // Get the folder at the base level. folderResults = WebService.FindFolders(BaseFolderId, folderView); // Iterate over the folders, until we find one that matches what we're looking for. foreach (Folder folder in folderResults) { // Found it - return if (String.Compare(folder.DisplayName, FolderName, StringComparison.OrdinalIgnoreCase) == 0) { return folder.Id; } } // If there's more folders, get them ... if (folderResults.NextPageOffset.HasValue) { folderView.Offset = folderResults.NextPageOffset.Value; } } while (folderResults.MoreAvailable); // If we got here, we didn't find it, so return null. return null; }
/// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param> /// <returns> /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false. /// </returns> /// <exception cref="T:System.NullReferenceException">The <paramref name="obj"/> parameter is null.</exception> public override bool Equals(object obj) { if (object.ReferenceEquals(this, obj)) { return(true); } else { FolderId other = obj as FolderId; if (other == null) { return(false); } else if (this.FolderName.HasValue) { if (other.FolderName.HasValue && this.FolderName.Value.Equals(other.FolderName.Value)) { if (this.Mailbox != null) { return(this.Mailbox.Equals(other.Mailbox)); } else if (other.Mailbox == null) { return(true); } } } else if (base.Equals(other)) { return(true); } return(false); } }
/// <summary> /// Flag conversation items as complete. Calling this method results in a call to EWS. /// </summary> /// <param name="contextFolderId">The Id of the folder items must belong to in order to be flagged as complete. If contextFolderId is /// null, items in conversation across the entire mailbox are marked as complete.</param> /// <param name="completeDate">The complete date (can be null).</param> public void FlagItemsComplete( FolderId contextFolderId, DateTime?completeDate) { Flag flag = new Flag() { FlagStatus = ItemFlagStatus.Complete }; if (completeDate.HasValue) { flag.CompleteDate = completeDate.Value; } this.Service.SetFlagStatusForItemsInConversations( new KeyValuePair <ConversationId, DateTime?>[] { new KeyValuePair <ConversationId, DateTime?>( this.Id, this.GlobalLastDeliveryTime) }, contextFolderId, flag)[0].ThrowIfNecessary(); }
public void DeleteFolder(FolderId findFolderId, DeleteMode deleteMode) { Folder folder = Folder.Bind(CurrentExchangeService, findFolderId); folder.Delete(deleteMode); }
public static string UploadItemPost(string ServerVersion, FolderId ParentFolderId, CreateActionType oCreateActionType, string sItemId, string sFile) { try { string sResponseText = string.Empty; System.Net.HttpWebRequest oHttpWebRequest = null; EwsProxyFactory.CreateHttpWebRequest(ref oHttpWebRequest); string EwsRequest = string.Empty; if (oCreateActionType != CreateActionType.CreateNew) { EwsRequest = TemplateEwsRequests.UploadItems_Update; if (oCreateActionType == CreateActionType.Update) EwsRequest = EwsRequest.Replace("##CreateAction##", "Update"); else EwsRequest = EwsRequest.Replace("##CreateAction##", "UpdateOrCreate"); EwsRequest = EwsRequest.Replace("##ItemId##", sItemId); } else { EwsRequest = TemplateEwsRequests.UploadItems_CreateNew; EwsRequest = EwsRequest.Replace("##CreateAction##", "CreateNew"); } EwsRequest = EwsRequest.Replace("##RequestServerVersion##", ServerVersion); EwsRequest = EwsRequest.Replace("##ParentFolderId_Id##", ParentFolderId.UniqueId); string sBase64Data = string.Empty; sBase64Data = FileHelper.GetBinaryFileAsBase64(sFile); System.Diagnostics.Debug.WriteLine("sBase64: " + sBase64Data); // Convert byte array to base64 EwsRequest = EwsRequest.Replace("##Data##", sBase64Data); //ShowTextDocument oForm = new ShowTextDocument(); //oForm.txtEntry.WordWrap = false; //oForm.Text = "Info"; //oForm.txtEntry.Text = EwsRequest; //oForm.ShowDialog(); // Now inject the base64 body into the stream: byte[] bytes = Encoding.UTF8.GetBytes(EwsRequest); oHttpWebRequest.ContentLength = bytes.Length; using (Stream requestStream = oHttpWebRequest.GetRequestStream()) { requestStream.Write(bytes, 0, bytes.Length); requestStream.Flush(); requestStream.Close(); } // Get response HttpWebResponse oHttpWebResponse = (HttpWebResponse)oHttpWebRequest.GetResponse(); StreamReader oStreadReader = new StreamReader(oHttpWebResponse.GetResponseStream()); sResponseText = oStreadReader.ReadToEnd(); if (oHttpWebResponse.StatusCode == HttpStatusCode.OK) { string responseCode = GetFirstResponseCode(sResponseText); if (responseCode != "NoError") { string messageText = GetFirstMessageText(sResponseText); LogWriter.Instance.WriteLine("Import ftstream failed with error stream, the detail of response is:"); LogWriter.Instance.WriteLine(sResponseText); return messageText; } else { return string.Empty; } } else { LogWriter.Instance.WriteLine("Import ftstream failed with error response status code, the detail of response is:"); LogWriter.Instance.WriteLine(sResponseText); return oHttpWebResponse.StatusCode.ToString(); } } catch(Exception e){ LogWriter.Instance.WriteException(typeof(ExportUploadHelper), e); return e.Message; } }
private string FreeRoom(string roomName) { // ToDo: error stategy to be implemented // log into Officee 365 ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010); //service.Credentials = new WebCredentials("*****@*****.**", "Passw0rd!"); service.Credentials = new WebCredentials("*****@*****.**", "Passw0rd!"); //service.Credentials = new WebCredentials("*****@*****.**", ""); service.UseDefaultCredentials = false; service.AutodiscoverUrl("*****@*****.**", RedirectionUrlValidationCallback); //EmailMessage email = new EmailMessage(service); //email.ToRecipients.Add("*****@*****.**"); //email.Subject = "HelloWorld"; //email.Body = new MessageBody("This is the first email I've sent by using the EWS Managed API."); //email.Send(); // GetRoomLists EmailAddressCollection roomGroup = service.GetRoomLists(); // GetRooms(roomGroup) Collection<EmailAddress> rooms = service.GetRooms(roomGroup[0]); string response = "No meeting room found"; //if the room.Address matchaes the one you are looking for then foreach (EmailAddress room in rooms) { if (room.Name == roomName) { Mailbox mailBox = new Mailbox(room.Address, "Mailbox"); //Mailbox mailBox = new Mailbox("*****@*****.**", "Mailbox"); // Create a FolderId instance of type WellKnownFolderName.Calendar and a new mailbox with the room's address and routing type FolderId folderID = new FolderId(WellKnownFolderName.Calendar, mailBox); // Create a CalendarView with from and to dates DateTime start = DateTime.Now.ToUniversalTime().AddHours(-8); DateTime end = DateTime.Now.ToUniversalTime().AddHours(5); //end.AddHours(3); CalendarView calendarView = new CalendarView(start, end); // Call findAppointments on FolderId populating CalendarView FindItemsResults<Appointment> appointments = service.FindAppointments(folderID, calendarView); // Iterate the appointments if (appointments.Items.Count == 0) response = "The room is free"; else { DateTime appt = appointments.Items[0].Start; TimeSpan test = DateTime.Now.Subtract(appt); int t = (int)Math.Round(Convert.ToDecimal(test.TotalMinutes.ToString())); if (test.TotalMinutes < 0) response = "a meeting is booked at this time"; else response = "the room is free for " + t.ToString() + "minutes"; } Console.WriteLine(response); } } return response; }
/// <summary> /// Sends this e-mail message and saves a copy of it in the specified folder. SendAndSaveCopy does not work if the /// message has unsaved attachments. In that case, the message must first be saved and then sent. Calling this method /// results in a call to EWS. /// </summary> /// <param name="destinationFolderId">The Id of the folder in which to save the copy.</param> public void SendAndSaveCopy(FolderId destinationFolderId) { EwsUtilities.ValidateParam(destinationFolderId, "destinationFolderId"); this.InternalSend(destinationFolderId, MessageDisposition.SendAndSaveCopy); }
/// <summary> /// Tries to read element from XML. /// </summary> /// <param name="reader">The reader.</param> /// <returns>True if element was read.</returns> internal override bool TryReadElementFromXml(EwsServiceXmlReader reader) { switch (reader.LocalName) { case XmlElementNames.AssignCategories: this.assignCategories.LoadFromXml(reader, reader.LocalName); return(true); case XmlElementNames.CopyToFolder: reader.ReadStartElement(XmlNamespace.NotSpecified, XmlElementNames.FolderId); this.copyToFolder = new FolderId(); this.copyToFolder.LoadFromXml(reader, XmlElementNames.FolderId); reader.ReadEndElement(XmlNamespace.NotSpecified, XmlElementNames.CopyToFolder); return(true); case XmlElementNames.Delete: this.delete = reader.ReadElementValue <bool>(); return(true); case XmlElementNames.ForwardAsAttachmentToRecipients: this.forwardAsAttachmentToRecipients.LoadFromXml(reader, reader.LocalName); return(true); case XmlElementNames.ForwardToRecipients: this.forwardToRecipients.LoadFromXml(reader, reader.LocalName); return(true); case XmlElementNames.MarkImportance: this.markImportance = reader.ReadElementValue <Importance>(); return(true); case XmlElementNames.MarkAsRead: this.markAsRead = reader.ReadElementValue <bool>(); return(true); case XmlElementNames.MoveToFolder: reader.ReadStartElement(XmlNamespace.NotSpecified, XmlElementNames.FolderId); this.moveToFolder = new FolderId(); this.moveToFolder.LoadFromXml(reader, XmlElementNames.FolderId); reader.ReadEndElement(XmlNamespace.NotSpecified, XmlElementNames.MoveToFolder); return(true); case XmlElementNames.PermanentDelete: this.permanentDelete = reader.ReadElementValue <bool>(); return(true); case XmlElementNames.RedirectToRecipients: this.redirectToRecipients.LoadFromXml(reader, reader.LocalName); return(true); case XmlElementNames.SendSMSAlertToRecipients: EmailAddressCollection smsRecipientCollection = new EmailAddressCollection(XmlElementNames.Address); smsRecipientCollection.LoadFromXml(reader, reader.LocalName); this.sendSMSAlertToRecipients = ConvertSMSRecipientsFromEmailAddressCollectionToMobilePhoneCollection(smsRecipientCollection); return(true); case XmlElementNames.ServerReplyWithMessage: this.serverReplyWithMessage = new ItemId(); this.serverReplyWithMessage.LoadFromXml(reader, reader.LocalName); return(true); case XmlElementNames.StopProcessingRules: this.stopProcessingRules = reader.ReadElementValue <bool>(); return(true); default: return(false); } }
private static webServiceData.Appointment searchAppointmentByFilter(SchedulingInfo schedulingInfo, webServiceData.ExchangeService service, string appointmentID) { RvLogger.DebugWrite("enter searchAppointmentByFilter=============="); List<webServiceData.SearchFilter> searchORFilterCollection = new List<webServiceData.SearchFilter>(); if (null != appointmentID) searchORFilterCollection.Add(new webServiceData.SearchFilter.IsEqualTo(webServiceData.EmailMessageSchema.Id, new webServiceData.ItemId(appointmentID))); else { searchORFilterCollection.Add(new webServiceData.SearchFilter.IsEqualTo(webServiceData.EmailMessageSchema.Subject, schedulingInfo.subject)); searchORFilterCollection.Add(new webServiceData.SearchFilter.IsEqualTo(webServiceData.EmailMessageSchema.From, schedulingInfo.delegatorEmailAddr)); searchORFilterCollection.Add(new webServiceData.SearchFilter.IsGreaterThan(webServiceData.EmailMessageSchema.LastModifiedTime, DateTime.UtcNow.AddHours(-25))); if (!string.IsNullOrEmpty(schedulingInfo.storeEntryId)) searchORFilterCollection.Add(new webServiceData.SearchFilter.IsEqualTo(webServiceData.EmailMessageSchema.StoreEntryId, schedulingInfo.storeEntryId)); if (!string.IsNullOrEmpty(schedulingInfo.conversationKey)) searchORFilterCollection.Add(new webServiceData.SearchFilter.IsEqualTo(webServiceData.EmailMessageSchema.ConversationId, schedulingInfo.conversationKey)); } RvLogger.DebugWrite("enter searchAppointmentByFilter==============1"); webServiceData.SearchFilter searchFilter = new webServiceData.SearchFilter.SearchFilterCollection(webServiceData.LogicalOperator.And, searchORFilterCollection.ToArray()); RvLogger.DebugWrite("enter searchAppointmentByFilter==============2 " + schedulingInfo.delegatorEmailAddr); webServiceData.Mailbox mailBox = new webServiceData.Mailbox(schedulingInfo.delegatorEmailAddr); RvLogger.DebugWrite("enter searchAppointmentByFilter==============3"); webServiceData.FolderId folderID = new webServiceData.FolderId(webServiceData.WellKnownFolderName.Calendar, mailBox); //No need to set mail since the service already know it. //webServiceData.FolderId folderID = new webServiceData.FolderId(webServiceData.WellKnownFolderName.Calendar); RvLogger.DebugWrite("enter searchAppointmentByFilter==============4"); webServiceData.FindItemsResults<webServiceData.Item> results = service.FindItems( folderID, searchFilter, new webServiceData.ItemView(100)); RvLogger.DebugWrite("enter searchAppointmentByFilter==============5"); RvLogger.DebugWrite("results searchAppointmentByFilter==============" + (null == results.Items ? "0" : "" + results.Items.Count)); foreach (webServiceData.Item item in results) { try { webServiceData.Appointment appointment = (webServiceData.Appointment)item; if (string.IsNullOrEmpty(schedulingInfo.location)) schedulingInfo.location = ""; if (string.IsNullOrEmpty(appointment.Location)) appointment.Location = ""; if (schedulingInfo.location == appointment.Location && schedulingInfo.startDate.ToUniversalTime().Equals(appointment.Start.ToUniversalTime()) && schedulingInfo.endDate.ToUniversalTime().Equals(appointment.End.ToUniversalTime())) { RvLogger.DebugWrite("lastModifiedTime1===================" + appointment.LastModifiedTime); return appointment; } } catch (ScopiaMeetingAddInException ex) { throw ex; } } return null; }
public Item MoveMessage(FolderId destination) { return _message.Move(destination); }
/// <summary> /// Sends this response and saves a copy in the specified folder. Calling this method results in a call to EWS. /// </summary> /// <param name="destinationFolderId">The Id of the folder in which to save the copy of the message.</param> public System.Threading.Tasks.Task SendAndSaveCopy(FolderId destinationFolderId) { EwsUtilities.ValidateParam(destinationFolderId, "destinationFolderId"); return(this.InternalCreate(destinationFolderId, MessageDisposition.SendAndSaveCopy)); }
/// <summary> /// Tries to read element from XML. /// </summary> /// <param name="reader">The reader.</param> /// <returns>True if element was read.</returns> internal override bool TryReadElementFromXml(EwsServiceXmlReader reader) { switch (reader.LocalName) { case XmlElementNames.AssignCategories: this.assignCategories.LoadFromXml(reader, reader.LocalName); return true; case XmlElementNames.CopyToFolder: reader.ReadStartElement(XmlNamespace.NotSpecified, XmlElementNames.FolderId); this.copyToFolder = new FolderId(); this.copyToFolder.LoadFromXml(reader, XmlElementNames.FolderId); reader.ReadEndElement(XmlNamespace.NotSpecified, XmlElementNames.CopyToFolder); return true; case XmlElementNames.Delete: this.delete = reader.ReadElementValue<bool>(); return true; case XmlElementNames.ForwardAsAttachmentToRecipients: this.forwardAsAttachmentToRecipients.LoadFromXml(reader, reader.LocalName); return true; case XmlElementNames.ForwardToRecipients: this.forwardToRecipients.LoadFromXml(reader, reader.LocalName); return true; case XmlElementNames.MarkImportance: this.markImportance = reader.ReadElementValue<Importance>(); return true; case XmlElementNames.MarkAsRead: this.markAsRead = reader.ReadElementValue<bool>(); return true; case XmlElementNames.MoveToFolder: reader.ReadStartElement(XmlNamespace.NotSpecified, XmlElementNames.FolderId); this.moveToFolder = new FolderId(); this.moveToFolder.LoadFromXml(reader, XmlElementNames.FolderId); reader.ReadEndElement(XmlNamespace.NotSpecified, XmlElementNames.MoveToFolder); return true; case XmlElementNames.PermanentDelete: this.permanentDelete = reader.ReadElementValue<bool>(); return true; case XmlElementNames.RedirectToRecipients: this.redirectToRecipients.LoadFromXml(reader, reader.LocalName); return true; case XmlElementNames.SendSMSAlertToRecipients: EmailAddressCollection smsRecipientCollection = new EmailAddressCollection(XmlElementNames.Address); smsRecipientCollection.LoadFromXml(reader, reader.LocalName); this.sendSMSAlertToRecipients = ConvertSMSRecipientsFromEmailAddressCollectionToMobilePhoneCollection(smsRecipientCollection); return true; case XmlElementNames.ServerReplyWithMessage: this.serverReplyWithMessage = new ItemId(); this.serverReplyWithMessage.LoadFromXml(reader, reader.LocalName); return true; case XmlElementNames.StopProcessingRules: this.stopProcessingRules = reader.ReadElementValue<bool>(); return true; default: return false; } }
/// <summary> /// Writes to Xml. /// </summary> /// <param name="writer">The writer.</param> /// <param name="xmlNamespace">The XML namespace.</param> /// <param name="name">The user configuration name.</param> /// <param name="parentFolderId">The Id of the folder containing the user configuration.</param> internal static void WriteUserConfigurationNameToXml( EwsServiceXmlWriter writer, XmlNamespace xmlNamespace, string name, FolderId parentFolderId) { EwsUtilities.Assert( writer != null, "UserConfiguration.WriteUserConfigurationNameToXml", "writer is null"); EwsUtilities.Assert( name != null, "UserConfiguration.WriteUserConfigurationNameToXml", "name is null"); EwsUtilities.Assert( parentFolderId != null, "UserConfiguration.WriteUserConfigurationNameToXml", "parentFolderId is null"); writer.WriteStartElement(xmlNamespace, XmlElementNames.UserConfigurationName); writer.WriteAttributeValue(XmlAttributeNames.Name, name); parentFolderId.WriteToXml(writer); writer.WriteEndElement(); }
public FolderId FindFolder(IFolderDataBase folderData, FolderId parentFolderId, int findCount = 0) { FolderView view = new FolderView(1); view.PropertySet = new PropertySet(BasePropertySet.IdOnly); view.Traversal = FolderTraversal.Shallow; SearchFilter filter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, folderData.DisplayName); FindFoldersResults results = CurrentExchangeService.FindFolders(parentFolderId, filter, view); if (results.TotalCount > 1) { throw new InvalidOperationException("Find more than 1 folder."); } else if (results.TotalCount == 0) { if (findCount > 3) { return null; } Thread.Sleep(500); return FindFolder(folderData, parentFolderId, ++findCount); } else { foreach (var result in results) { return result.Id; } throw new InvalidOperationException("Thread sleep time is too short."); } }
private void OnStartAfter() { string sMailBox = System.String.Empty; string sMailServerUrl = System.String.Empty; string sUser = System.String.Empty; string sPassword = System.String.Empty; string sDomain = System.String.Empty; string sFolderRoot = System.String.Empty; int iItemsProccesing = 0; int iScanDelay = 0; Boolean bFolderDestDomain = false; Boolean bDestinationFileFormatLong = false; Boolean bProcessingFileToLog = false; if (!EventLog.SourceExists(sSource)) EventLog.CreateEventSource(sSource, sLog); sEvent = "Service started"; EventLog.WriteEntry(sSource, sEvent); try { sMailBox = ConfigurationManager.AppSettings["MailBox"]; sMailServerUrl = ConfigurationManager.AppSettings["MailServerUrl"]; sUser = ConfigurationManager.AppSettings["User"]; sPassword = ConfigurationManager.AppSettings["Password"]; sDomain = ConfigurationManager.AppSettings["Domain"]; sFolderRoot = ConfigurationManager.AppSettings["FolderRoot"]; iItemsProccesing = Convert.ToInt32(ConfigurationManager.AppSettings["ItemsProccesing"]); // How much emails retrieve to view iScanDelay = Convert.ToInt32(ConfigurationManager.AppSettings["ScanDelay"]); // Delay between scan Inbox bFolderDestDomain = Convert.ToBoolean(ConfigurationManager.AppSettings["FolderDestinationNameWithDomain"]); bDestinationFileFormatLong = Convert.ToBoolean(ConfigurationManager.AppSettings["DestinationFileFormatLong"]); // bProcessingFileToLog = Convert.ToBoolean(ConfigurationManager.AppSettings["ProcessingFileToLog"]); // sEvent = "MailBox=" + sMailBox + "\n" + "MailServerUrl=" + sMailServerUrl + "\n" + "User="******"\n" + "Domain=" + sDomain + "\n" + "FolderRoot=" + sFolderRoot + "\n" + "ItemsProccesing=" + iItemsProccesing + "\n" + "ScanDelay=" + iScanDelay + "\n" + "FolderDestDomain=" + bFolderDestDomain + "\n" + "DestinationFileFormatLong=" + bDestinationFileFormatLong + "\n" + "ProcessingFileToLog=" + bProcessingFileToLog; EventLog.WriteEntry(sSource, sEvent); } catch (Exception e) { EventLog.WriteEntry(sSource, e.Message, EventLogEntryType.Warning, 234); } ////////////////////; // Boolean bItemDelete = false; string sFilePath = System.String.Empty; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); ServicePointManager.ServerCertificateValidationCallback = (obj, certificate, chain, errors) => true; service.Credentials = new System.Net.NetworkCredential(sUser, sPassword, sDomain); Uri uriMailServerUrl = new Uri(sMailServerUrl); service.Url = uriMailServerUrl; FolderId InboxId = new FolderId(WellKnownFolderName.Inbox, sMailBox); FindItemsResults<Item> findResults = null; while (true) { try { findResults = service.FindItems(InboxId, new ItemView(iItemsProccesing)); } catch (Exception e) { sEvent = "Exchange Server:" +e.Source + ":" + e.Message; EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Warning, 234); } if (findResults != null) { foreach (Item message in findResults.Items) { bItemDelete = true; if (message.HasAttachments) { EmailMessage emailMessage = EmailMessage.Bind(service, message.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments)); #if DEBUG sEvent = "Debug event Subject: " + message.Subject + " Date: " + message.DateTimeReceived; EventLog.WriteEntry(sSource, sEvent ); #endif emailMessage.Load(); string sSenderAdddress = emailMessage.From.Address; String sFolderPath = GetPath(bFolderDestDomain, message.DateTimeReceived, sFolderRoot, sSenderAdddress); foreach (Attachment attachment in emailMessage.Attachments) { FileAttachment fileAttachment = attachment as FileAttachment; if (bDestinationFileFormatLong) { string sNewFileName = AttachFileName(fileAttachment.Name, message.DateTimeReceived); sFilePath = sFolderPath + sNewFileName; } else { sFilePath = sFolderPath + fileAttachment.Name; } if (bProcessingFileToLog) { sEvent = "File stored path=" + sFilePath; EventLog.WriteEntry(sSource, sEvent); } try { fileAttachment.Load(sFilePath); } catch (System.UnauthorizedAccessException e) { sEvent = e.Source + ":" + e.Message; EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Warning, 234); bItemDelete = false; } catch (Exception e) { sEvent = e.Source + ":" + e.Message; EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Warning, 234); bItemDelete = false; } } } // Move processed item to \Deleted items if (bItemDelete) message.Delete(DeleteMode.MoveToDeletedItems); } } System.Threading.Thread.Sleep(iScanDelay); } }
/// <summary> /// Loads from json. /// </summary> /// <param name="jsonProperty">The json property.</param> /// <param name="service">The service.</param> internal override void LoadFromJson(JsonObject jsonProperty, ExchangeService service) { foreach (string key in jsonProperty.Keys) { switch (key) { case XmlElementNames.AssignCategories: this.assignCategories.LoadFromJson(jsonProperty.ReadAsJsonObject(key), service); break; case XmlElementNames.CopyToFolder: this.copyToFolder = new FolderId(); this.copyToFolder.LoadFromJson( jsonProperty.ReadAsJsonObject(key), service); break; case XmlElementNames.Delete: this.delete = jsonProperty.ReadAsBool(key); break; case XmlElementNames.ForwardAsAttachmentToRecipients: this.forwardAsAttachmentToRecipients.LoadFromJson(jsonProperty.ReadAsJsonObject(key), service); break; case XmlElementNames.ForwardToRecipients: this.forwardToRecipients.LoadFromJson(jsonProperty.ReadAsJsonObject(key), service); break; case XmlElementNames.MarkImportance: this.markImportance = jsonProperty.ReadEnumValue <Importance>(key); break; case XmlElementNames.MarkAsRead: this.markAsRead = jsonProperty.ReadAsBool(key); break; case XmlElementNames.MoveToFolder: this.moveToFolder = new FolderId(); this.moveToFolder.LoadFromJson( jsonProperty.ReadAsJsonObject(key), service); break; case XmlElementNames.PermanentDelete: this.permanentDelete = jsonProperty.ReadAsBool(key); break; case XmlElementNames.RedirectToRecipients: this.redirectToRecipients.LoadFromJson(jsonProperty.ReadAsJsonObject(key), service); break; case XmlElementNames.SendSMSAlertToRecipients: EmailAddressCollection smsRecipientCollection = new EmailAddressCollection(XmlElementNames.Address); smsRecipientCollection.LoadFromJson(jsonProperty.ReadAsJsonObject(key), service); this.sendSMSAlertToRecipients = ConvertSMSRecipientsFromEmailAddressCollectionToMobilePhoneCollection(smsRecipientCollection); break; case XmlElementNames.ServerReplyWithMessage: this.serverReplyWithMessage = new ItemId(); this.serverReplyWithMessage.LoadFromJson(jsonProperty.ReadAsJsonObject(key), service); break; case XmlElementNames.StopProcessingRules: this.stopProcessingRules = jsonProperty.ReadAsBool(key); break; default: break; } } }
/// <summary> /// Create response object. /// </summary> /// <param name="parentFolderId">The parent folder id.</param> /// <param name="messageDisposition">The message disposition.</param> /// <returns>A list of items that were created or modified as a results of this operation.</returns> internal List<Item> InternalCreate(FolderId parentFolderId, MessageDisposition? messageDisposition) { ((ItemId)this.PropertyBag[ResponseObjectSchema.ReferenceItemId]).Assign(this.referenceItem.Id); return this.Service.InternalCreateResponseObject( this, parentFolderId, messageDisposition); }
public List<Folder> GetChildFolder(string parentFolderId) { const int pageSize = 100; int offset = 0; bool moreItems = true; List<Folder> result = new List<Folder>(); var parentFolder = new FolderId(parentFolderId); //var parentFolderObj = Folder.Bind(CurrentExchangeService, parentFolder); // return GetChildFolder(parentFolderObj); while (moreItems) { FolderView oView = new FolderView(pageSize, offset, OffsetBasePoint.Beginning); oView.PropertySet = FolderPropertySet; FindFoldersResults findResult = CurrentExchangeService.FindFolders(parentFolder, oView); result.AddRange(findResult.Folders); if (!findResult.MoreAvailable) moreItems = false; if (moreItems) offset += pageSize; } return result; }
/// <summary> /// Binds to an existing user configuration and loads the specified properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to which the user configuration is bound.</param> /// <param name="name">The name of the user configuration.</param> /// <param name="parentFolderId">The Id of the folder containing the user configuration.</param> /// <param name="properties">The properties to load.</param> /// <returns>A user configuration instance.</returns> public static UserConfiguration Bind( ExchangeService service, string name, FolderId parentFolderId, UserConfigurationProperties properties) { UserConfiguration result = service.GetUserConfiguration( name, parentFolderId, properties); result.isNew = false; return result; }