public static void MakePublicContactsFolder(Microsoft.Exchange.WebServices.Data.ExchangeService service)
        {
            var folder = new ContactsFolder(service);

            folder.DisplayName = "ZeebregtsCs";
            folder.Save(WellKnownFolderName.Contacts);
        }
Beispiel #2
0
        private static void DisplayContacts(ExchangeService service)
        {
            // Get the number of items in the Contacts folder. To keep the response smaller, request only the TotalCount property.
            ContactsFolder contactsfolder = ContactsFolder.Bind(service,
                                                                WellKnownFolderName.Contacts,
                                                                new PropertySet(BasePropertySet.IdOnly, FolderSchema.TotalCount));

            // Set the number of items to the smaller of the number of items in the Contacts folder or 1000.
            int numItems = contactsfolder.TotalCount < 1000 ? contactsfolder.TotalCount : 1000;

            // Instantiate the item view with the number of items to retrieve from the Contacts folder.
            ItemView view = new ItemView(numItems);

            // To keep the request smaller, send only the display name.
            view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ContactSchema.DisplayName);

            // Retrieve the items in the Contacts folder that have the properties you've selected.
            FindItemsResults <Item> contactItems = service.FindItems(WellKnownFolderName.Contacts, view);

            // Display the display name of all the contacts. (Note that there can be a large number of contacts in the Contacts folder.)
            foreach (Item item in contactItems)
            {
                if (item is Contact)
                {
                    Contact contact = item as Contact;
                    Console.WriteLine(contact.DisplayName);
                }
            }
        }
        public static void MakeFolder(Microsoft.Exchange.WebServices.Data.ExchangeService service)
        {
            ContactsFolder folder = new ContactsFolder(service);

            folder.DisplayName = "syncContacts";
            folder.Save(FindFolder(service));
        }
Beispiel #4
0
    public void ListContacts()
    {
        // Get the number of items in the contacts folder. To limit the size of the response, request only the TotalCount property.
        ContactsFolder contactsfolder = ContactsFolder.Bind(service, WellKnownFolderName.Contacts, new PropertySet(BasePropertySet.IdOnly, FolderSchema.TotalCount));

        // Set the number of items to the number of items in the Contacts folder or 50, whichever is smaller.
        int numItems = contactsfolder.TotalCount < 50 ? contactsfolder.TotalCount : 50;

        // Instantiate the item view with the number of items to retrieve from the Contacts folder.
        ItemView view = new ItemView(numItems);

        // To keep the response smaller, request only the display name.
        view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ContactSchema.DisplayName);

        // Request the items in the Contacts folder that have the properties that you selected.
        FindItemsResults <Item> contactItems = service.FindItems(WellKnownFolderName.Contacts, view);

        // Display the list of contacts. (Note that there can be a large number of contacts in the Contacts folder.)
        foreach (Item item in contactItems)
        {
            if (item is Contact)
            {
                Contact contact = item as Contact;
                Console.WriteLine(contact.DisplayName);
            }
        }
    }
        private static Collection <Folder> GetAllContactsFolders(ExchangeService service)
        {
            // The collection will contain all contact folders.
            Collection <Folder> folders = new Collection <Folder>();

            // Get the root Contacts folder and load all properties. This results in a GetFolder call to EWS.
            ContactsFolder rootContactFolder = ContactsFolder.Bind(service, WellKnownFolderName.Contacts);

            folders.Add(rootContactFolder);
            Console.WriteLine("Added the default Contacts folder to the collection of contact folders.");

            // Find all child folders of the root Contacts folder.
            int        initialFolderSearchOffset = 0;
            const int  folderSearchPageSize      = 100;
            bool       AreMoreFolders            = true;
            FolderView folderView = new FolderView(folderSearchPageSize, initialFolderSearchOffset);

            folderView.Traversal   = FolderTraversal.Deep;
            folderView.PropertySet = new PropertySet(BasePropertySet.IdOnly);

            while (AreMoreFolders)
            {
                try
                {
                    // Find all the child folders of the default Contacts folder. This results in a FindFolder
                    // operation call to EWS.
                    FindFoldersResults childrenOfContactsFolderResults = rootContactFolder.FindFolders(folderView);
                    if (folderView.Offset == 0)
                    {
                        Console.WriteLine("Found {0} child folders of the default Contacts folder.", childrenOfContactsFolderResults.TotalCount);
                    }

                    foreach (Folder f in childrenOfContactsFolderResults.Folders)
                    {
                        ContactsFolder contactFolder = (ContactsFolder)f;
                        // Loads all the properties for the folder. This results in a GetFolder operation call to EWS.
                        contactFolder.Load();
                        Console.WriteLine("Loaded a folder named {0} and added it to the collection of contact folders.", contactFolder.DisplayName);
                        // Add the folder to the collection of contact folders.
                        folders.Add(contactFolder);
                    }

                    // Turn off paged searches if there are no more folders to return.
                    if (childrenOfContactsFolderResults.MoreAvailable == false)
                    {
                        AreMoreFolders = false;
                    }
                    else // Increment the paging offset.
                    {
                        folderView.Offset = folderView.Offset + folderSearchPageSize;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: {0}", ex.Message);
                }
            }

            return(folders);
        }
        internal static string GetContactRecipientIMAddress(string email, UserContext userContext, bool addSipPrefix)
        {
            if (email == null)
            {
                throw new ArgumentNullException("email");
            }
            if (userContext == null)
            {
                throw new ArgumentNullException("userContext");
            }
            string text = null;

            using (ContactsFolder contactsFolder = ContactsFolder.Bind(userContext.MailboxSession, DefaultFolderType.Contacts))
            {
                using (FindInfo <Contact> findInfo = contactsFolder.FindByEmailAddress(email, new PropertyDefinition[0]))
                {
                    if (findInfo.FindStatus == FindStatus.Found)
                    {
                        Contact result = findInfo.Result;
                        result.Load(new PropertyDefinition[]
                        {
                            ContactSchema.IMAddress
                        });
                        text = (result.TryGetProperty(ContactSchema.IMAddress) as string);
                    }
                }
            }
            if (addSipPrefix && !string.IsNullOrEmpty(text) && text.IndexOf("sip:", StringComparison.OrdinalIgnoreCase) != 0)
            {
                text = "sip:" + text;
            }
            return(text);
        }
Beispiel #7
0
        /// <summary>
        ///     Retrieve contact items from the exchange service
        /// </summary>
        /// <returns>FindItemsResults with Item</returns>
        public IEnumerable <Contact> RetrieveContacts(int limit = 100)
        {
            // Limit the properties returned
            // Initialize the calendar folder object with only the folder ID.
            var contactsFolder = ContactsFolder.Bind(Service, WellKnownFolderName.Contacts);
            // Set the amount of contacts to return
            var itemView = new ItemView(limit);

            // For later
            var propertySet = new PropertySet(ItemSchema.Attachments, ContactSchema.GivenName, ContactSchema.Surname, ContactSchema.EmailAddresses);

            // Retrieve a collection of items by using the itemview.
            var itemsList = contactsFolder.FindItems(itemView);

            return(itemsList.OfType <Contact>().Select(item =>
            {
                var contact = Contact.Bind(Service, item.Id, propertySet);
                foreach (var fileAttachment in contact.Attachments.OfType <FileAttachment>())
                {
                    if (!fileAttachment.IsContactPhoto)
                    {
                        continue;
                    }
                    Log.Verbose().WriteLine("Loading contact photo attachment for {1}, {0}", contact.GivenName, contact.Surname);
                    // Load the attachment to access the content.
                    fileAttachment.Load();
                }
                return contact;
            }));
        }
        public static Contact FindContactByDisplayName(ExchangeService service, string DisplayName)
        {
            // Get the number of items in the Contacts folder. To keep the response smaller, request only the TotalCount property.
            ContactsFolder contactsfolder = ContactsFolder.Bind(service,
                                                                WellKnownFolderName.Contacts,
                                                                new PropertySet(BasePropertySet.IdOnly, FolderSchema.TotalCount));

            // Set the number of items to the smaller of the number of items in the Contacts folder or 1000
            int numItems = contactsfolder.TotalCount < 1000 ? contactsfolder.TotalCount : 1000;

            // Instantiate the item view with the number of items to retrieve from the Contacts folder.
            ItemView view = new ItemView(numItems);

            // To keep the request smaller, send only the display name.
            view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ContactSchema.DisplayName);

            //Create a searchfilter.
            SearchFilter.IsEqualTo filter = new SearchFilter.IsEqualTo(ContactSchema.DisplayName, DisplayName);

            // Retrieve the items in the Contacts folder with the properties you've selected.
            FindItemsResults <Item> contactItems = service.FindItems(WellKnownFolderName.Contacts, filter, view);

            if (contactItems.Count() == 1) //Only one contact was found
            {
                return((Contact)contactItems.Items[0]);
            }
            else //No contacts, or more than one contact with the same DisplayName, were found.
            {
                return(null);
            }
        }
        private void CreateContactsFolder(ExchangeService svc, string folderName, FolderId folderId)
        {
            ContactsFolder folder = new ContactsFolder(svc);

            folder.DisplayName = folderName;

            try
            {
                folder.Save(folderId);
            }
            catch (Exception erro)
            {
                ValidationCreationFolderException(erro);
            }
        }
Beispiel #10
0
        /// <summary>
        /// Sucht im Kontakte Ordner des Postfaches einen Ordner mit dem Namen aus der Config Datei (zb. "Arges Intern"). Wird der Name nicht gefunden wird ein Ordner mit dem Namen erstellt.
        /// </summary>
        /// <param name="init">true wenn es der Initiale SyncRun ist.</param>
        /// <returns>Das Ordnerobjekt des Ordners mit dem richtigen Namen. Wird benutzt um den Ordner per Id zu binden.</returns>
        public Folder getMailboxFolder(bool init = false)
        {
            var MailboxContactRoot = Folder.Bind(service, WellKnownFolderName.Contacts);

            SearchFilter.IsEqualTo filter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, ContactFolderName);
            FindFoldersResults     FindMailboxContactFolder = service.FindFolders(MailboxContactRoot.Id, filter, new FolderView(1));

            Folder MailboxContactFolder;

            if (FindMailboxContactFolder.TotalCount != 0)
            {
                //löscht den Kontakt Ordner falls er beim Initialen SyncRun vorhanden ist
                if (init)
                {
                    try
                    {
                        FindMailboxContactFolder.Folders[0].Delete(DeleteMode.HardDelete);
                    }
                    catch (Exception)
                    {
                        throw new Exception(ContactFolderName + " wurde nicht gelöscht");
                    }


                    ContactsFolder folder = new ContactsFolder(service);
                    folder.DisplayName = ContactFolderName;
                    folder.Save(MailboxContactRoot.Id);
                    MailboxContactFolder = folder;
                }
                else
                {
                    MailboxContactFolder = FindMailboxContactFolder.Folders[0];
                }
            }
            else
            {
                ContactsFolder folder = new ContactsFolder(service);
                folder.DisplayName = ContactFolderName;
                folder.Save(MailboxContactRoot.Id);
                MailboxContactFolder = folder;
            }

            return(MailboxContactFolder);
        }
Beispiel #11
0
        private static void GetNamesByAnrFromContacts(UserContext userContext, AnrManager.NameParsingResult parsingResult, AnrManager.Options options, List <RecipientAddress> addresses)
        {
            if (string.IsNullOrEmpty(parsingResult.Name))
            {
                return;
            }
            if (userContext.TryGetMyDefaultFolderId(DefaultFolderType.Contacts) == null)
            {
                return;
            }
            string ambiguousName = parsingResult.ParsedSuccessfully ? parsingResult.RoutingAddress : parsingResult.Name;

            using (ContactsFolder contactsFolder = ContactsFolder.Bind(userContext.MailboxSession, DefaultFolderType.Contacts))
            {
                if (contactsFolder.IsValidAmbiguousName(ambiguousName))
                {
                    PropertyDefinition[] array;
                    object[][]           results;
                    if (AnrManager.IsMobileNumberInput(parsingResult, options))
                    {
                        array   = AnrManager.AnrProperties.Get(AnrManager.AnrProperties.PropertiesType.ContactFindSomeone, options);
                        results = contactsFolder.FindNamesView(new Dictionary <PropertyDefinition, object>
                        {
                            {
                                ContactSchema.MobilePhone,
                                parsingResult.Name
                            }
                        }, AnrManager.nameLimit, null, array);
                    }
                    else if (options.ResolveAgainstAllContacts || options.IsDefaultRoutingType("MOBILE"))
                    {
                        array   = AnrManager.AnrProperties.Get(AnrManager.AnrProperties.PropertiesType.ContactFindSomeone, options);
                        results = contactsFolder.FindSomeoneView(ambiguousName, AnrManager.nameLimit, null, array);
                    }
                    else
                    {
                        array   = AnrManager.AnrProperties.Get(AnrManager.AnrProperties.PropertiesType.ContactAnr, options);
                        results = contactsFolder.ResolveAmbiguousNameView(ambiguousName, AnrManager.nameLimit, null, array);
                    }
                    AnrManager.AddContacts(userContext, options, array, results, addresses);
                }
            }
        }
Beispiel #12
0
        protected override ContactFolderResponse InternalExecute()
        {
            ExchangeVersion.Current = ExchangeVersion.Latest;
            MailboxSession mailboxIdentityMailboxSession = base.MailboxIdentityMailboxSession;
            IdAndSession   idAndSession = base.IdConverter.ConvertFolderIdToIdAndSession(this.parentFolderId, IdConverter.ConvertOption.IgnoreChangeKey);
            StoreId        id;

            try
            {
                using (Folder folder = ContactsFolder.Create(mailboxIdentityMailboxSession, idAndSession.Id, StoreObjectType.ContactsFolder, this.displayName, CreateMode.CreateNew))
                {
                    PeopleFilterGroupPriorityManager.SetSortGroupPriorityOnFolder(folder, this.priority);
                    folder.Save();
                    folder.Load(new PropertyDefinition[]
                    {
                        FolderSchema.Id
                    });
                    id = folder.Id;
                }
            }
            catch (ObjectExistedException)
            {
                return(new ContactFolderResponse
                {
                    ResponseCode = ResponseCodeType.ErrorFolderExists.ToString()
                });
            }
            PeopleFilterGroupPriorityManager peopleFilterGroupPriorityManager = new PeopleFilterGroupPriorityManager(mailboxIdentityMailboxSession, new XSOFactory());

            mailboxIdentityMailboxSession.ContactFolders.MyContactFolders.Set(peopleFilterGroupPriorityManager.GetMyContactFolderIds());
            ConcatenatedIdAndChangeKey concatenatedId = IdConverter.GetConcatenatedId(id, new MailboxId(mailboxIdentityMailboxSession), null);

            return(new ContactFolderResponse
            {
                ResponseCode = ResponseCodeType.NoError.ToString(),
                FolderId = new FolderId
                {
                    Id = concatenatedId.Id,
                    ChangeKey = concatenatedId.ChangeKey
                }
            });
        }
Beispiel #13
0
        /* Get all contacts in the users contacts folder - Needs to be called once. */
        public void GetAllContacts(ExchangeService service)
        {
            Contacts       contacts       = new Contacts();
            ContactsFolder contactsFolder = ContactsFolder.Bind(service, WellKnownFolderName.Contacts, new PropertySet(BasePropertySet.IdOnly, FolderSchema.TotalCount));
            ItemView       view           = new ItemView(contactsFolder.TotalCount);

            view.PropertySet = new PropertySet(BasePropertySet.FirstClassProperties, ContactSchema.Id);
            view.PropertySet = new PropertySet(BasePropertySet.FirstClassProperties, ContactSchema.DisplayName);
            FindItemsResults <Item> contactItems = service.FindItems(WellKnownFolderName.Contacts, view);

            // Display the list of contacts.
            foreach (Item item in contactItems)
            {
                if (item is Contact)
                {
                    Contact contact = item as Contact;
                    contacts.id          = contact.Id.ToString();
                    contacts.DisplayName = contact.DisplayName.ToString();
                    // AddContact(service, contact);
                }
            }
        }
Beispiel #14
0
 // Token: 0x06002C60 RID: 11360 RVA: 0x000F7198 File Offset: 0x000F5398
 private Stream GetContactPictureStream(OwaStoreObjectId storeId, string attId, string email, out string contentType)
 {
     contentType = string.Empty;
     if (storeId != null)
     {
         using (Item item = Utilities.GetItem <Item>(base.UserContext, storeId, new PropertyDefinition[0]))
         {
             return(this.GetContactPictureStream(item, attId, out contentType));
         }
     }
     using (ContactsFolder contactsFolder = ContactsFolder.Bind(base.UserContext.MailboxSession, DefaultFolderType.Contacts))
     {
         using (FindInfo <Contact> findInfo = contactsFolder.FindByEmailAddress(email, new PropertyDefinition[0]))
         {
             if (findInfo.FindStatus == FindStatus.Found)
             {
                 return(this.GetContactPictureStream(findInfo.Result, attId, out contentType));
             }
         }
     }
     return(new MemoryStream());
 }
Beispiel #15
0
        //gavdcodeend 01

        //gavdcodebegin 02
        static void FindAllContacts(ExchangeService ExService)
        {
            ContactsFolder myContactsfolder = ContactsFolder.Bind(
                ExService, WellKnownFolderName.Contacts);

            int ammountContacts = myContactsfolder.TotalCount < 50 ?
                                  myContactsfolder.TotalCount : 50;

            ItemView myView = new ItemView(ammountContacts);

            myView.PropertySet = new PropertySet(BasePropertySet.IdOnly,
                                                 ContactSchema.DisplayName);
            FindItemsResults <Item> allContacts = ExService.FindItems(
                WellKnownFolderName.Contacts, myView);

            foreach (Item oneContact in allContacts)
            {
                if (oneContact is Contact myContact)
                {
                    Console.WriteLine(myContact.DisplayName);
                }
            }
        }
 // Token: 0x06002F25 RID: 12069 RVA: 0x0010FFF0 File Offset: 0x0010E1F0
 public RecipientWellEventHandler.ContactRecipientProperties GetContactRecipientProperties(string email, UserContext userContext)
 {
     if (email == null)
     {
         throw new ArgumentNullException("email");
     }
     if (userContext == null)
     {
         throw new ArgumentNullException("userContext");
     }
     RecipientWellEventHandler.ContactRecipientProperties result = default(RecipientWellEventHandler.ContactRecipientProperties);
     using (ContactsFolder contactsFolder = ContactsFolder.Bind(userContext.MailboxSession, DefaultFolderType.Contacts))
     {
         using (FindInfo <Contact> findInfo = contactsFolder.FindByEmailAddress(email, new PropertyDefinition[0]))
         {
             if (findInfo.FindStatus == FindStatus.Found)
             {
                 Contact result2 = findInfo.Result;
                 result2.Load(new PropertyDefinition[]
                 {
                     ContactSchema.BusinessPhoneNumber,
                     ContactSchema.MobilePhone,
                     ContactSchema.HomePhone
                 });
                 result.WorkPhone   = (result2.TryGetProperty(ContactSchema.BusinessPhoneNumber) as string);
                 result.HomePhone   = (result2.TryGetProperty(ContactSchema.HomePhone) as string);
                 result.MobilePhone = (result2.TryGetProperty(ContactSchema.MobilePhone) as string);
             }
             else
             {
                 ExTraceGlobals.ContactsDataTracer.TraceDebug(0L, "Contact item could not be found.");
                 base.RenderPartialFailure(string.Empty, null, ButtonDialogIcon.NotSet, OwaEventHandlerErrorCode.NotSet);
             }
         }
     }
     return(result);
 }
Beispiel #17
0
        private void SincronizarContactosActionExecute(object sender, SimpleActionExecuteEventArgs e)
        {
            var config = Identificadores.GetInstance(ObjectSpace);

            if (config.CuentaSincContactos == null)
            {
                throw new UserFriendlyException("No se configuró la cuenta de Exchange a utilizar para sincronizar contactos.");
            }
            if (config.IdentificacionTipoEmail == null)
            {
                throw new UserFriendlyException("No se configuró el tipo de identif. para emails, para sincronizar contactos.");
            }
            if (config.IdentificacionTipoTelOtro == null)
            {
                throw new UserFriendlyException("No se configuró el tipo de identif. para 'otros teléfonos', para sincronizar contactos.");
            }

            var service = config.CuentaSincContactos.ExchangeService;

            var objectSpace = Application.CreateObjectSpace( );

            var paresDirecciones = new List <ParPersonaDireccionDireccion>( );

            // Get the number of items in the Contacts folder. To keep the response smaller, request only the TotalCount property.
            var contactsfolder = ContactsFolder.Bind(service, WellKnownFolderName.Contacts);

            // Instantiate the item view with the number of items to retrieve from the Contacts folder.
            FindItemsResults <Item> findResults;

            var view = new ItemView(EWSModule.NumContactosPorLote, 0, OffsetBasePoint.Beginning);

            var propSet = new PropertySet(BasePropertySet.FirstClassProperties,
                                          ContactSchema.HasPicture,
                                          ContactSchema.Birthday,
                                          ContactSchema.Notes,
                                          ContactSchema.WeddingAnniversary,
                                          ContactSchema.PhysicalAddresses,
                                          ContactSchema.ImAddresses,
                                          ContactSchema.PhoneNumbers,
                                          ContactSchema.EmailAddresses,
                                          ContactSchema.CompleteName,
                                          ContactSchema.Attachments);

            do
            {
                // Retrieve the items in the Contacts folder that have the properties you've selected.
                findResults = contactsfolder.FindItems(view);
                service.LoadPropertiesForItems(findResults, propSet);

                processItems(findResults, objectSpace, config, paresDirecciones);

                if (findResults.NextPageOffset.HasValue)
                {
                    view.Offset = findResults.NextPageOffset.Value;
                }
            } while(findResults.MoreAvailable);


            objectSpace.CommitChanges( );
            objectSpace.Dispose(  );

            if (!paresDirecciones.IsEmpty( ))
            {
                var auxObjectSpace = Application.CreateObjectSpace( );
                foreach (var par in paresDirecciones)
                {
                    var persDir = auxObjectSpace.GetObjectByKey <PersonaDireccion>(par.PersonaDireccion.Oid);
                    persDir.Direccion =
                        auxObjectSpace.GetObjectByKey <Direccion>(par.Direccion.Oid);

                    persDir.Save( );
                }
                auxObjectSpace.CommitChanges( );
            }

            ObjectSpace.Refresh( );
        }
Beispiel #18
0
        private void MainFormLoad(object sender, EventArgs e)
        {
            Form.CheckForIllegalCrossThreadCalls = false;
            Action <string> action = str => this.lbLog.Items.Add(str);

            Logger.AddAlgorithm(new ComponentLogWriteAlgorithm(action));

            this.panel1.Enabled = false;
            this.generateToolStripMenuItem.Enabled     = false;
            this.saveSettingsToolStripMenuItem.Enabled = false;

            this.splitContainer4.SplitterWidth = 10;
            this.splitContainer1.SplitterWidth = 10;
            this.RearrangeCountControls();

            ToolStripButton tsbtnMove =
                new ToolStripButton(LocalizibleStrings.BtnAddSelectedToMailList)
            {
                DisplayStyle = ToolStripItemDisplayStyle.Image,
                Image        = LocalizibleStrings.ArrowRight
            };

            tsbtnMove.Click += (o, args) =>
            {
                IEnumerable <StoredContact> storedContacts =
                    this.clTargetContacts.dgObjects.Objects.Cast <StoredContact>().ToList();

                foreach (Contact obj in
                         from Contact obj in this.clEwsContacts.dgObjects.SelectedObjects
                         let existed = storedContacts.FirstOrDefault(s => s.UniqId == obj.Id.UniqueId)
                                       where existed == null
                                       select obj)
                {
                    this.clTargetContacts.dgObjects.AddObject(new StoredContact(obj));
                }
            };

            this.clEwsContacts._barTools.Items.Insert(2, tsbtnMove);

            string mailTemplateFolder;
            string eventTemplateFolder;

            switch (Thread.CurrentThread.CurrentUICulture.LCID)
            {
            case LocalizationHelper.EnInt:
                this.englishToolStripMenuItem.Checked = true;
                this.russianToolStripMenuItem.Checked = false;
                mailTemplateFolder  = Config.EmailTemplateFolderEn;
                eventTemplateFolder = Config.EventTemplateFolderEn;
                break;

            case LocalizationHelper.RuInt:
                this.russianToolStripMenuItem.Checked = true;
                this.englishToolStripMenuItem.Checked = false;
                mailTemplateFolder  = Config.EmailTemplateFolderRu;
                eventTemplateFolder = Config.EventTemplateFolderRu;
                break;

            default:
                this.englishToolStripMenuItem.Checked = true;
                this.russianToolStripMenuItem.Checked = false;
                mailTemplateFolder  = Config.EmailTemplateFolderEn;
                eventTemplateFolder = Config.EventTemplateFolderEn;
                break;
            }

            this.SetEwsContactsColumns();
            this.SetMailTemplatesColumns();
            this.SetEventTemplatesColumns();
            this.SetTargetContactsColumns();

            this.clEwsContacts.tsbtnFilteredProperties.Visible = false;
            this.clEwsContacts.tsbtnCreate.Visible             = false;
            this.clEwsContacts.tsbtnEdit.Visible               = false;
            this.clEwsContacts.tsbtnDelete.Visible             = false;
            this.clEwsContacts.tsbtnFilterSettings.Visible     = false;
            this.clEwsContacts.tsbtnFilteredProperties.Visible = false;

            this.clEwsContacts.tsbtnRefresh.Text     = LocalizibleStrings.BtnRefresh;
            this.clEwsContacts.tsbtnClearFilter.Text = LocalizibleStrings.BtnClear;
            this.clEwsContacts.tsbtnSearch.Text      = LocalizibleStrings.BtnSearch;
            this.clEwsContacts.tslbSearch.Text       = LocalizibleStrings.LbSearch;
            this.clEwsContacts.tslbCount.Text        = LocalizibleStrings.LbCount;

            this.clEwsContacts.tsbtnRefresh.Click += (s, args) =>
            {
                try
                {
                    Folder contactsFolder;
                    if (!TryGetFolder(Config.ContactFolder, out contactsFolder))
                    {
                        Logger.Message(LocalizibleStrings.TryLoadFromDefault);
                        contactsFolder = ContactsFolder.Bind(_service, WellKnownFolderName.Contacts);
                    }

                    SearchFilter sf = new SearchFilter.IsEqualTo(ItemSchema.ItemClass, @"IPM.Contact");

                    FindItemsResults <Item> items =
                        contactsFolder.FindItems(sf, new ItemView(int.MaxValue));
                    this.clEwsContacts.dgObjects.SetObjects(items.ToList());
                }
                catch (Exception exc)
                {
                    Logger.Error(LocalizibleStrings.CannotGetContactList, exc);
                }
            };

            this.clMailTemplates.tsbtnFilteredProperties.Visible = false;
            this.clMailTemplates.tsbtnCreate.Visible             = false;
            this.clMailTemplates.tsbtnEdit.Visible               = false;
            this.clMailTemplates.tsbtnDelete.Visible             = false;
            this.clMailTemplates.tsbtnFilterSettings.Visible     = false;
            this.clMailTemplates.tsbtnFilteredProperties.Visible = false;

            this.clMailTemplates.tsbtnRefresh.Text     = LocalizibleStrings.BtnRefresh;
            this.clMailTemplates.tsbtnClearFilter.Text = LocalizibleStrings.BtnClear;
            this.clMailTemplates.tsbtnSearch.Text      = LocalizibleStrings.BtnSearch;
            this.clMailTemplates.tslbSearch.Text       = LocalizibleStrings.LbSearch;
            this.clMailTemplates.tslbCount.Text        = LocalizibleStrings.LbCount;

            this.clMailTemplates.tsbtnRefresh.Click += (s, args) =>
            {
                try
                {
                    /*Folder templatesFolder;
                     * if (!TryGetFolder(mailTemplateFolder, out templatesFolder))
                     *  return;
                     *
                     * FindItemsResults<Item> items =
                     *  templatesFolder.FindItems(new ItemView(int.MaxValue));*/

                    IList <Storage.Message> items = new List <Storage.Message>();

                    // ReSharper disable once LoopCanBeConvertedToQuery
                    // под отладчиком всякая фигня происходит если linq
                    foreach (string path in
                             Directory.GetFiles(Config.GetParam(mailTemplateFolder)))
                    {
                        items.Add(new Storage.Message(path));
                    }

                    this.clMailTemplates.dgObjects.SetObjects(items.ToList());
                }
                catch (Exception exc)
                {
                    Logger.Error(LocalizibleStrings.CannotGetMailTemplateList, exc);
                }
            };

            this.clEventTemplates.tsbtnCreate.Visible             = false;
            this.clEventTemplates.tsbtnEdit.Visible               = false;
            this.clEventTemplates.tsbtnDelete.Visible             = false;
            this.clEventTemplates.tsbtnFilterSettings.Visible     = false;
            this.clEventTemplates.tsbtnFilteredProperties.Visible = false;

            this.clEventTemplates.tsbtnRefresh.Text     = LocalizibleStrings.BtnRefresh;
            this.clEventTemplates.tsbtnClearFilter.Text = LocalizibleStrings.BtnClear;
            this.clEventTemplates.tsbtnSearch.Text      = LocalizibleStrings.BtnSearch;
            this.clEventTemplates.tslbSearch.Text       = LocalizibleStrings.LbSearch;
            this.clEventTemplates.tslbCount.Text        = LocalizibleStrings.LbCount;

            this.clEventTemplates.tsbtnRefresh.Click += (s, args) =>
            {
                try
                {
                    /*Folder templatesFolder;
                     * if (!TryGetFolder(eventTemplateFolder, out templatesFolder))
                     *  return;
                     *
                     * FindItemsResults<Item> items =
                     *  templatesFolder.FindItems(new ItemView(int.MaxValue));*/

                    List <Storage.Message> tasks =
                        Directory.GetFiles(Config.GetParam(eventTemplateFolder))
                        .Select(t => new Storage.Message(t))
                        .ToList();

                    this.clEventTemplates.dgObjects.SetObjects(tasks);
                }
                catch (Exception exc)
                {
                    Logger.Error(LocalizibleStrings.CannotGetEventTemplateList, exc);
                }
            };

            this.clTargetContacts.tsbtnCreate.Text      = LocalizibleStrings.BtnCreate;
            this.clTargetContacts.tsbtnDelete.Text      = LocalizibleStrings.BtnDelete;
            this.clTargetContacts.tsbtnRefresh.Text     = LocalizibleStrings.BtnRefresh;
            this.clTargetContacts.tsbtnClearFilter.Text = LocalizibleStrings.BtnClear;
            this.clTargetContacts.tsbtnSearch.Text      = LocalizibleStrings.BtnSearch;
            this.clTargetContacts.tslbSearch.Text       = LocalizibleStrings.LbSearch;
            this.clTargetContacts.tslbCount.Text        = LocalizibleStrings.LbCount;

            this.clTargetContacts.tsbtnCreate.Visible             = true;
            this.clTargetContacts.tsbtnEdit.Visible               = false;
            this.clTargetContacts.tsbtnDelete.Visible             = true;
            this.clTargetContacts.tsbtnFilterSettings.Visible     = false;
            this.clTargetContacts.tsbtnFilteredProperties.Visible = false;

            this.clTargetContacts.dgObjects.TriStateCheckBoxes = false;
            this.clTargetContacts.dgObjects.RenderNonEditableCheckboxesAsDisabled = false;
            this.clTargetContacts.dgObjects.UseSubItemCheckBoxes = true;

            ToolStripButton tsbtnSave =
                new ToolStripButton(LocalizibleStrings.BtnSaveAll)
            {
                DisplayStyle = ToolStripItemDisplayStyle.Image,
                Image        = LocalizibleStrings.Save
            };

            tsbtnSave.Click +=
                (o, args) =>
            {
                IEnumerable <StoredContact> contacts =
                    this.clTargetContacts.dgObjects.Objects.Cast <StoredContact>();
                foreach (StoredContact contact in contacts)
                {
                    contact.Save();
                }
            };

            this.clTargetContacts._barTools.Items.Insert(1, tsbtnSave);

            this.clTargetContacts.tsbtnRefresh.Click += (s, args) =>
            {
                try
                {
                    this.clTargetContacts.dgObjects.SetObjects(StoredContact.GetAll());
                }
                catch (Exception exc)
                {
                    Logger.Error(LocalizibleStrings.CannotGetStoredContacts, exc);
                }
            };

            this.clTargetContacts.tsbtnCreate.Click +=
                (o, args) => this.clTargetContacts.dgObjects.AddObject(new StoredContact());

            this.clTargetContacts.tsbtnDelete.Click += (o, args) =>
            {
                DialogResult res = MessageBox.Show(
                    LocalizibleStrings.DeleteConfirmation,
                    LocalizibleStrings.Warning,
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Warning,
                    MessageBoxDefaultButton.Button2);

                if (res == DialogResult.No)
                {
                    return;
                }

                foreach (StoredContact cont in this.clTargetContacts.dgObjects.SelectedObjects)
                {
                    try
                    {
                        this.clTargetContacts.dgObjects.RemoveObject(cont);
                        cont.Delete();
                    }
                    catch (Exception exc)
                    {
                        Logger.Error(LocalizibleStrings.CannotDeleteContact + cont.FileName, exc);
                    }
                }
            };
        }
Beispiel #19
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // access master page from nested master page
            Protected.ClaimRuler masterPage = Master.Master as Protected.ClaimRuler;

            // check user permission
            //masterPage.checkPermission();

            clientID = SessionHelper.getClientId();

            // get current lead
            leadID = SessionHelper.getLeadId();

            // get current lead id
            claimID = SessionHelper.getClaimID();

            // get current user
            userID = SessionHelper.getUserId();

            // set directory where client can upload pictures for signature
            txtSignature.UploadedFilesDirectory = appPath + "/clientLogo/" + clientID;

            if (!Page.IsPostBack)
            {
                bindData();
                userID = SessionHelper.getUserId();

                CRM.Data.Entities.SecUser secUser = SecUserManager.GetByUserId(userID);
                string email    = secUser.Email;
                string password = SecurityManager.Decrypt(secUser.emailPassword);
                string url      = "https://" + secUser.emailHost + "/EWS/Exchange.asmx";

                try
                {
                    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                    service.Credentials = new WebCredentials(email, password);
                    service.Url         = new Uri(url);

                    ContactsFolder contactsfolder = ContactsFolder.Bind(service, WellKnownFolderName.Contacts);

                    int numItems = contactsfolder.TotalCount < 50 ? contactsfolder.TotalCount : 50;

                    ItemView view = new ItemView(int.MaxValue);

                    view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ContactSchema.DisplayName);

                    FindItemsResults <Item> contactItems = service.FindItems(WellKnownFolderName.Contacts, view);

                    DataTable table = new DataTable();
                    table.Columns.Add("FirstName", typeof(string));
                    table.Columns.Add("LastName", typeof(string));
                    table.Columns.Add("CompanyName", typeof(string));
                    table.Columns.Add("Email", typeof(string));
                    table.Columns.Add("ContactType", typeof(string));

                    foreach (GridRecord crow in contractGrid.Rows)
                    {
                        DataRow row = table.NewRow();
                        row[0] = crow.Items[0].Text;
                        row[1] = crow.Items[1].Text;
                        //row[2] = crow.Cells[2].Text;
                        row[3] = crow.Items[3].Text;
                        row[4] = crow.Items[4].Text;
                        table.Rows.Add(row);
                    }
                    foreach (Item item in contactItems)
                    {
                        if (item is Microsoft.Exchange.WebServices.Data.Contact)
                        {
                            item.Load();
                            Microsoft.Exchange.WebServices.Data.Contact contact = item as Microsoft.Exchange.WebServices.Data.Contact;



                            DataRow row = table.NewRow();
                            row[0] = contact.GivenName;
                            row[1] = contact.Surname;
                            row[3] = contact.EmailAddresses[0].Address;
                            row[4] = "Outlook";
                            table.Rows.Add(row);
                        }
                    }
                    contractGrid.DataSourceID = null;
                    contractGrid.Columns.Clear();
                    contractGrid.DataBind();
                    contractGrid.DataSource = table;
                    contractGrid.DataBind();
                }
                catch (Exception ex)
                {
                }
            }
        }
Beispiel #20
0
 // Token: 0x06000371 RID: 881 RVA: 0x00014240 File Offset: 0x00012440
 private AnrManager.LookupState GetNamesByAnrFromContacts(string name, List <ResolvedRecipient> recipients)
 {
     if (this.mailboxSession.GetDefaultFolderId(DefaultFolderType.Contacts) == null)
     {
         return(AnrManager.LookupState.FoundNone);
     }
     AnrManager.LookupState result;
     using (ContactsFolder contactsFolder = ContactsFolder.Bind(this.mailboxSession, DefaultFolderType.Contacts))
     {
         if (!contactsFolder.IsValidAmbiguousName(name))
         {
             result = AnrManager.LookupState.FoundNone;
         }
         else
         {
             object[][] array             = contactsFolder.ResolveAmbiguousNameView(name, int.MaxValue, null, AnrManager.anrContactProperties);
             List <RecipientAddress> list = new List <RecipientAddress>();
             int num = 0;
             while (array != null && num < array.GetLength(0))
             {
                 object[]    array2      = array[num];
                 Participant participant = array2[1] as Participant;
                 if (participant != null)
                 {
                     string           displayName      = array2[0] as string;
                     VersionedId      versionedId      = (VersionedId)array2[2];
                     StoreObjectId    storeId          = (versionedId == null) ? null : versionedId.ObjectId;
                     RecipientAddress recipientAddress = this.ConstructStoreRecipientAddress(participant, displayName, storeId);
                     if (recipientAddress != null)
                     {
                         if (recipientAddress.RoutingType != null && string.Equals(recipientAddress.RoutingType, "MAPIPDL", StringComparison.OrdinalIgnoreCase))
                         {
                             list.Add(recipientAddress);
                         }
                         else
                         {
                             recipients.Add(new ResolvedRecipient(recipientAddress));
                         }
                     }
                 }
                 num++;
             }
             bool flag = recipients.Count + list.Count == 1;
             foreach (RecipientAddress address in list)
             {
                 this.ExpandPDL(address, recipients);
             }
             if (recipients.Count == 0)
             {
                 result = AnrManager.LookupState.FoundNone;
             }
             else if (flag)
             {
                 result = AnrManager.LookupState.FoundExact;
             }
             else
             {
                 result = AnrManager.LookupState.FoundMany;
             }
         }
     }
     return(result);
 }
Beispiel #21
0
        protected void loadData(string keyword)
        {
            int clientID = Core.SessionHelper.getClientId();

            IQueryable <CRM.Data.Entities.Contact> contacts = null;

            if (keyword == null)
            {
                contacts = ContactManager.GetAll(clientID);
            }
            else
            {
                contacts = ContactManager.Search(keyword, clientID);
            }

            List <CRM.Data.Entities.Contact> contactList = contacts.ToList();

            int userID = SessionHelper.getUserId();

            CRM.Data.Entities.SecUser secUser = SecUserManager.GetByUserId(userID);
            string email    = secUser.Email;
            string password = SecurityManager.Decrypt(secUser.emailPassword);
            string url      = "https://" + secUser.emailHost + "/EWS/Exchange.asmx";

            try
            {
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                service.Credentials = new WebCredentials(email, password);
                service.Url         = new Uri(url);

                ContactsFolder contactsfolder = ContactsFolder.Bind(service, WellKnownFolderName.Contacts);

                int numItems = contactsfolder.TotalCount < 50 ? contactsfolder.TotalCount : 50;

                ItemView view = new ItemView(int.MaxValue);

                view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ContactSchema.DisplayName);

                FindItemsResults <Item> contactItems = service.FindItems(WellKnownFolderName.Contacts, view);


                foreach (Item item in contactItems)
                {
                    if (item is Microsoft.Exchange.WebServices.Data.Contact)
                    {
                        item.Load();
                        Microsoft.Exchange.WebServices.Data.Contact contact = item as Microsoft.Exchange.WebServices.Data.Contact;
                        CRM.Data.Entities.Contact newContact = new Data.Entities.Contact();
                        newContact.FirstName      = contact.GivenName;
                        newContact.LastName       = contact.Surname;
                        newContact.Email          = contact.EmailAddresses[0].Address;
                        newContact.DepartmentName = "Outlook";
                        bool exist = false;
                        if (keyword == null || keyword[0] == newContact.Email[0])
                        {
                            foreach (var con in contactList)
                            {
                                if (con.Email == newContact.Email)
                                {
                                    exist = true;
                                }
                            }
                        }
                        if (!exist)
                        {
                            contactList.Add(newContact);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }

            gvContact.DataSource = contactList;
            gvContact.DataBind();
        }
        private async Task <bool> FindExchangeContactsFoldersAsync()
        {
            try // Autodiscover
            {
                exService.TraceListener = new EwsTraceListener();
                exService.TraceFlags    = TraceFlags.AutodiscoverConfiguration |
                                          TraceFlags.AutodiscoverRequest |
                                          TraceFlags.AutodiscoverResponse;

                exService.TraceEnabled = DebugMode;
                exService.Credentials  = new NetworkCredential(Username, SecurePassword);

                await System.Threading.Tasks.Task.Run(() =>
                {
                    exService.AutodiscoverUrl(Username, redirectionUrlValidationCallback);
                });
            }
            catch (ServiceRequestException ex)
            {
                Console.WriteLine("Exchange Fehler: " + ex.Message);
                if (DebugMode)
                {
                    Console.WriteLine(ex.ToString());
                }

                LoggedIn = false;
                return(false);
            }
            catch (ServiceResponseException ex)
            {
                Console.WriteLine("Exchange Fehler: " + ex.Message);
                if (DebugMode)
                {
                    Console.WriteLine(ex.ToString());
                }

                LoggedIn = false;
                return(false);
            }
            catch (AutodiscoverLocalException ex)
            {
                Console.WriteLine("Exchange Fehler: " + ex.Message);
                if (DebugMode)
                {
                    Console.WriteLine(ex.ToString());
                }

                LoggedIn = false;
                return(false);
            }

            Console.WriteLine("EWS Endpoint: {0}", exService.Url);

            try // Find local contacts folders in user's mailbox
            {
                ContactsFolder contactsFolder = await System.Threading.Tasks.Task.Run(() =>
                {
                    return(ContactsFolder.Bind(exService, WellKnownFolderName.Contacts));
                });

                ContactsFolderEntries.Add(new ContactsFolderEntry
                {
                    Display        = contactsFolder.DisplayName,
                    ContactsFolder = contactsFolder
                });

                CurrentContactsFolder = contactsFolder;


                FindFoldersResults allMailboxContactsFolders = await System.Threading.Tasks.Task.Run(() =>
                {
                    var contactsFolderFilter = new SearchFilter.IsEqualTo(
                        FolderSchema.FolderClass,
                        CurrentContactsFolder.FolderClass
                        );

                    return(exService.FindFolders(
                               WellKnownFolderName.MsgFolderRoot,
                               contactsFolderFilter,
                               new FolderView(int.MaxValue)
                    {
                        Traversal = FolderTraversal.Deep
                    }
                               ));
                });

                foreach (var folder in allMailboxContactsFolders)
                {
                    if (folder.Id.UniqueId == CurrentContactsFolder.Id.UniqueId)
                    {
                        continue;
                    }
                    if (folder.DisplayName == "ExternalContacts")
                    {
                        continue;
                    }
                    if (folder.DisplayName == "PersonMetadata")
                    {
                        continue;
                    }

                    ContactsFolderEntries.Add(new ContactsFolderEntry
                    {
                        Display        = folder.DisplayName,
                        ContactsFolder = folder as ContactsFolder
                    });
                }
            }
            catch (ServiceRequestException ex)
            {
                Console.WriteLine("Exchange Fehler: " + ex.Message);
                if (DebugMode)
                {
                    Console.WriteLine(ex.ToString());
                }

                LoggedIn = false;
                return(false);
            }
            catch (ServiceResponseException ex)
            {
                Console.WriteLine("Exchange Fehler: " + ex.Message);
                if (DebugMode)
                {
                    Console.WriteLine(ex.ToString());
                }

                LoggedIn = false;
                return(false);
            }

            try // Find contacts folders in public folder tree
            {
                FindFoldersResults allPublicContactsFolders = await System.Threading.Tasks.Task.Run(() =>
                {
                    var contactsFolderFilter = new SearchFilter.IsEqualTo(
                        FolderSchema.FolderClass,
                        CurrentContactsFolder.FolderClass
                        );

                    return(exService.FindFolders(
                               WellKnownFolderName.PublicFoldersRoot,
                               contactsFolderFilter,
                               new FolderView(int.MaxValue)
                               ));
                });

                foreach (var folder in allPublicContactsFolders)
                {
                    ContactsFolderEntries.Add(new ContactsFolderEntry
                    {
                        Display        = folder.DisplayName,
                        ContactsFolder = folder as ContactsFolder
                    });
                }
            }
            catch (ServiceRequestException ex)
            {
                Console.WriteLine("Exchange Fehler: " + ex.Message);
                if (DebugMode)
                {
                    Console.WriteLine(ex.ToString());
                }

                LoggedIn = false;
                return(false);
            }
            catch (ServiceResponseException ex)
            {
                Console.WriteLine("Exchange Fehler: " + ex.Message);
                if (DebugMode)
                {
                    Console.WriteLine(ex.ToString());
                }

                // Do nothing, if public folder search doesn't return successfully.
            }


            Console.WriteLine("Es wurden {0} Kontakte-Ordner identifiziert.", ContactsFolderEntries.Count);

            return(true);
        }