public Dictionary <string, string> GetDropDownValues(WebProperties webProps, IntegrationLog log, string property,
                                                             string parentPropertyValue)
        {
            var dictionary = new Dictionary <string, string>();

            try
            {
                O365Service o365Service = GetO365Service(webProps);

                if (property.Equals("List"))
                {
                    dictionary = o365Service.GetIntegratableLists();
                }
                else if (property.Equals("UserMapType"))
                {
                    return new Dictionary <string, string> {
                               { "Email", "Email" }
                    }
                }
                ;

                throw new Exception("Invalid property: " + property);
            }
            catch (Exception e)
            {
                log.LogMessage(e.Message, IntegrationLogType.Error);
            }

            return(dictionary);
        }
        public List <ColumnProperty> GetColumns(WebProperties webProps, IntegrationLog log, string listName)
        {
            var columnProperties = new List <ColumnProperty>();

            try
            {
                O365Service o365Service = GetO365Service(webProps);

                var ignoredFields = new[]
                {
                    "AppAuthor", "AppEditor", "Attachments", "DocIcon",
                    "ItemChildCount", "FolderChildCount", "_UIVersionString"
                };

                columnProperties.AddRange(
                    from field in o365Service.GetListFields(webProps.Properties["List"].ToString())
                    let internalName = field.InternalName
                                       where !ignoredFields.Contains(internalName) &&
                                       !internalName.StartsWith("LinkTitle") && !internalName.EndsWith("NoMenu")
                                       orderby field.Title
                                       select new ColumnProperty
                {
                    ColumnName        = internalName,
                    DiplayName        = field.Title,
                    type              = TranslateFieldType(field.FieldTypeKind),
                    DefaultListColumn = GetMatchingListColumn(internalName)
                });
            }
            catch (Exception e)
            {
                log.LogMessage(e.Message, IntegrationLogType.Error);
            }

            return(columnProperties);
        }
        public bool TestConnection(WebProperties webProps, IntegrationLog log, out string message)
        {
            message = string.Empty;

            try
            {
                O365Service o365Service = GetO365Service(webProps);
                if (!o365Service.EnsureEPMLiveAppInstalled())
                {
                    log.LogMessage(
                        "Please make sure that you have installed the EPM Live app in your Office 365 environment.",
                        IntegrationLogType.Error);

                    return(false);
                }

                return(true);
            }
            catch (Exception e)
            {
                message = e.Message;
                log.LogMessage(message, IntegrationLogType.Error);

                return(false);
            }
        }
        public bool InstallIntegration(WebProperties webProps, IntegrationLog log, out string message,
                                       string integrationKey,
                                       string apiUrl)
        {
            message = string.Empty;

            try
            {
                O365Service o365Service = GetO365Service(webProps);

                o365Service.InstallIntegration(webProps.IntegrationId, integrationKey, apiUrl, webProps.Title,
                                               webProps.FullURL, webProps.EnabledFeatures,
                                               (string)webProps.Properties["List"],
                                               bool.Parse((string)webProps.Properties["AllowAddInt"]),
                                               bool.Parse((string)webProps.Properties["AllowAddList"]),
                                               bool.Parse((string)webProps.Properties["AllowDeleteInt"]));

                return(true);
            }
            catch (Exception e)
            {
                message = e.Message;
            }

            return(false);
        }
        public void Initialize()
        {
            _shimContext   = ShimsContext.Create();
            _o365Service   = new O365Service(DummyUserName, DummySecurePassword, DummySiteUrl);
            _privateObject = new PrivateObject(_o365Service);

            ShimClientContext.AllInstances.WebGet = sender => new ShimWeb()
            {
                ListsGet = () => new ShimListCollection()
                {
                    GetByTitleString = title => new ShimList()
                    {
                        GetItemByIdInt32 = id => new ShimListItem()
                        {
                            DeleteObject = () => { }
                        }
                    }
                }
            };
            ShimClientContext.AllInstances.ExecuteQuery = sender => { };
            ShimSharePointOnlineCredentials.ConstructorStringSecureString = (sender, userName, password) => new ShimSharePointOnlineCredentials();

            ShimClientRuntimeContext.AllInstances.LoadOf1M0ExpressionOfFuncOfM0ObjectArray <ClientObject>((sender, client, retrievals) => { });
            ShimClientRuntimeContext.AllInstances.LoadOf1M0ExpressionOfFuncOfM0ObjectArray <List>((sender, client, retrievals) => { });
            ShimClientRuntimeContext.AllInstances.LoadOf1M0ExpressionOfFuncOfM0ObjectArray <ListItem>((sender, client, retrievals) => { });
            ShimClientRuntimeContext.AllInstances.LoadOf1M0ExpressionOfFuncOfM0ObjectArray <ListCollection>((sender, client, retrievals) => { });
            ShimClientRuntimeContext.AllInstances.LoadOf1M0ExpressionOfFuncOfM0ObjectArray <FieldCollection>((sender, client, retrievals) => { });
            ShimClientRuntimeContext.AllInstances.LoadOf1M0ExpressionOfFuncOfM0ObjectArray <ListItemCollection>((sender, client, retrievals) => { });
        }
        public Dictionary <string, ImportExportRecord> Export(O365Service service)
        {
            EnsurePhotosDirectory();

            // Export all the images from SPO
            _o365.PageThroughAllUsers(null, 10, (page) => ProcessO365PageOfUsers(page, service));

            return(_allPeople);
        }
        // Public Methods (9) 

        public TransactionTable DeleteItems(WebProperties webProps, DataTable items, IntegrationLog log)
        {
            var transactionTable = new TransactionTable();

            try
            {
                if (!bool.Parse((string)webProps.Properties["AllowDeleteInt"]))
                {
                    throw new Exception("Office 365 delete is not allowed.");
                }

                O365Service o365Service = GetO365Service(webProps);

                List <string> ids;
                Dictionary <string, string> idMap = BuildIdMap(items, out ids);

                int index = 0;

                foreach (
                    O365Result result in
                    o365Service.DeleteListItemsById(ids.ToArray(), (string)webProps.Properties["List"]))
                {
                    string o365Id = result.ItemId.ToString();
                    string spid;

                    try
                    {
                        spid = idMap[o365Id];
                    }
                    catch
                    {
                        spid = items.Rows[index]["SPID"].ToString();
                    }

                    if (result.Success)
                    {
                        transactionTable.AddRow(spid, o365Id, TransactionType.DELETE);
                    }
                    else
                    {
                        transactionTable.AddRow(spid, o365Id, TransactionType.FAILED);
                        log.LogMessage(string.Format(
                                           "Could not delete record with Office 365 ID: {0}, SharePoint ID: {1}. Message: {2}",
                                           o365Id, spid, result.Error), IntegrationLogType.Warning);
                    }

                    index++;
                }
            }
            catch (Exception e)
            {
                log.LogMessage(e.Message, IntegrationLogType.Error);
            }

            return(transactionTable);
        }
        public TransactionTable UpdateItems(WebProperties webProps, DataTable items, IntegrationLog log)
        {
            var transactionTable = new TransactionTable();

            try
            {
                O365Service o365Service = GetO365Service(webProps);

                List <string> ids;
                Dictionary <string, string> idMap = BuildIdMap(items, out ids);

                int index = 0;

                foreach (
                    O365Result result in
                    o365Service.UpsertItems((string)webProps.Properties["List"], webProps.IntegrationId, items))
                {
                    string o365Id = result.ItemId.ToString();

                    string spId;

                    try
                    {
                        spId = idMap[o365Id];
                    }
                    catch
                    {
                        spId = items.Rows[index]["SPID"].ToString();
                    }

                    if (result.Success)
                    {
                        transactionTable.AddRow(spId, o365Id, result.TransactionType);
                    }
                    else
                    {
                        transactionTable.AddRow(spId, o365Id, TransactionType.FAILED);

                        log.LogMessage(string.Format(
                                           "Could not insert / update record with Office 365 ID: {0}, SharePoint ID: {1}. Message: {2}",
                                           o365Id, spId, result.Error), IntegrationLogType.Warning);
                    }

                    index++;
                }
            }
            catch (Exception e)
            {
                log.LogMessage(e.Message, IntegrationLogType.Error);
            }

            return(transactionTable);
        }
        public DataTable PullData(WebProperties webProps, IntegrationLog log, DataTable items, DateTime lastSynchDate)
        {
            try
            {
                O365Service o365Service = GetO365Service(webProps);
                o365Service.GetListItems((string)webProps.Properties["List"], items, lastSynchDate);
            }
            catch (Exception e)
            {
                log.LogMessage("Scheduled Pull. " + e.Message, e.Message.StartsWith("No records found")
                    ? IntegrationLogType.Warning
                    : IntegrationLogType.Error);
            }

            return(items);
        }
        public DataTable GetItem(WebProperties webProps, IntegrationLog log, string itemId, DataTable items)
        {
            try
            {
                O365Service o365Service = GetO365Service(webProps);
                o365Service.GetListItemsById((string)webProps.Properties["List"], itemId, items);
            }
            catch (Exception e)
            {
                log.LogMessage(e.Message, e.Message.StartsWith("No records found")
                    ? IntegrationLogType.Warning
                    : IntegrationLogType.Error);
            }

            return(items);
        }
Exemple #11
0
        static void ExportFromO365(O365Service service)
        {
            try
            {
                Logger.Debug($"Starting Export from {service}");

                WriteToConsole($"O365 Tenant name [e.g. \"Contoso\", from {{contoso}}.onmicrosoft.com]: ");
                var tenantName = ReadFromConsole();

                WriteToConsole($"O365 Administrator username [e.g. [email protected]]: ");
                var username = ReadFromConsole();

                WriteToConsole($"O365 Administrator password: "******"Tenant: {tenantName}");
                Logger.Debug($"Username: {username}");

                var settings = new O365Settings()
                {
                    Username   = username,
                    Password   = password,
                    TenantName = tenantName
                };

                Logger.Debug($"Initializing O365 worker");

                var worker = new O365Worker(settings);

                var newPeopleList = worker.Export(service);

                // merge
                MergeAndSavePeopleLists(newPeopleList);

                Logger.Debug($"Completed export from {service}");

                WriteToConsole();
                WriteToConsole($"Completed export of photos. Press any key to return to main menu.");
                ReadFromConsole();
            }
            catch (Exception e)
            {
                WriteToConsole($"Problem exporting: {e.Message}");
                WriteToConsole("Press any key to continue");
                var input = ReadFromConsole();
            }
        }
        public void Import(Dictionary <string, ImportExportRecord> people, O365Service service)
        {
            foreach (var person in people)
            {
                if (string.IsNullOrEmpty(person.Value.PhotoLocation))
                {
                    // no photo .. skipping
                    Logger.Debug($"No photo found for {person.Value.Upn} ... skipping");
                    continue;
                }

                using (var fs = File.Open(person.Value.PhotoLocation, FileMode.Open))
                {
                    var profile = new O365Profile(new UpnIdentifier(person.Value.Upn));
                    _o365.UpdateUserProfilePhoto(profile, service, fs);

                    Logger.Info($"Uploaded photo for {person.Value.Upn}");
                }
            }
        }
        public void UpdateUserProfilePhoto(O365Profile person, O365Service service, Stream photoStream)
        {
            switch (service)
            {
            case O365Service.Spo:

                var clientContext = GetSpoClientContextForSite(SpoSite.Admin);

                UpdateSpoPhoto(clientContext, person.Upn, photoStream);

                return;

            case O365Service.Exo:

                UpdateExoPhoto(person.Upn, photoStream);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(service), service, null);
            }
        }
        public MemoryStream DownloadProfilePhoto(O365Profile person, O365Service service)
        {
            switch (service)
            {
            case O365Service.Spo:

                var clientContext = GetSpoClientContextForSite(SpoSite.MySite);

                var uri = person.SpoProfilePictureUrlLarge;
                var serverrelativePath = uri.AbsolutePath;

                var memoryStream = new MemoryStream();

                using (FileInformation f = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, serverrelativePath))
                {
                    f.Stream.CopyTo(memoryStream);
                }

                return(memoryStream);

            case O365Service.Exo:

                var exo     = GetExoClientContext();
                var results = exo.GetUserPhoto(person.Upn.Upn, "HR648x648", string.Empty);

                if (results.Status == GetUserPhotoStatus.PhotoReturned)
                {
                    var picStream = new MemoryStream(results.Photo);
                    return(picStream);
                }
                else
                {
                    throw new FileNotFoundException($"Failed to get photo from Exo for {person.Upn.Upn}");
                }

            default:
                throw new ArgumentOutOfRangeException(nameof(service), service, null);
            }
        }
        public bool RemoveIntegration(WebProperties webProps, IntegrationLog log, out string message,
                                      string integrationKey)
        {
            message = string.Empty;

            try
            {
                O365Service o365Service = GetO365Service(webProps);
                o365Service.UninstallIntegration(integrationKey, webProps.IntegrationId);

                return(true);
            }
            catch (Exception e)
            {
                if (e.Message.Contains("List 'EPMLiveIntegrations' does not exist"))
                {
                    return(true);
                }
                message = e.Message;
            }

            return(false);
        }
        private bool ProcessO365PageOfUsers(IList <O365Profile> page, O365Service service)
        {
            foreach (var person in page)
            {
                if (person.Upn == null)
                {
                    Logger.Info($"Upn for user not found. Moving on");
                    continue;
                }

                Logger.Info($"Found user {person.Upn} attempting to download photo");

                if (service == O365Service.Spo && !person.HasSpoProfilePicture)
                {
                    Logger.Info($"Found user {person.Upn}, but skipping as they dont have a photo set");
                    continue;
                }

                try
                {
                    var filename = SanitizeFileName(person.Upn.Upn) + ".jpg";
                    var fullPath = Path.Combine(PhotoDirectory, filename);
                    var record   = new ImportExportRecord()
                    {
                        PhotoLocation = String.Empty, Upn = person.Upn.Upn
                    };

                    var pictureStream = _o365.DownloadProfilePhoto(person, service);

                    if (pictureStream == null)
                    {
                        Logger.Info($"Image failed to download for {person.Upn}, moving on");
                        continue;
                    }

                    if (IsPhotoLargeSilouette(pictureStream))
                    {
                        // this is a silouette photo ... move on
                        Logger.Info($"Image for {person.Upn} is a silouette, moving on");
                        continue;
                    }
                    else
                    {
                        Logger.Info($"Got photo for {person.Upn}, saving to {fullPath}");

                        // save the picture
                        using (FileStream fs = new FileStream(fullPath, FileMode.Create))
                        {
                            if (pictureStream.CanSeek)
                            {
                                pictureStream.Seek(0, SeekOrigin.Begin);
                            }
                            pictureStream.CopyTo(fs);
                        }

                        record.PhotoLocation = fullPath;
                    }

                    // keep their record
                    _allPeople[person.Upn.Upn] = record;
                }
                catch (Exception e)
                {
                    Logger.Error($"Error downloading photo for user {person.Upn}, Message: {e.Message}");
                    // move on
                }
            }

            return(true);
        }