Esempio n. 1
0
        public async Task <ExchangeSyncResult> ExecuteFirstSyncAsync(ExchangeConnectionInfo connectionInfo, ExchangeChangeSet changeSet)
        {
            ExchangeSyncResult loginResult = await this.EnsureLoginAsync(this.taskFolderId, connectionInfo);

            if (loginResult != null)
            {
                return(loginResult);
            }

            ActiveSyncServer server = CreateExchangeServer(connectionInfo);

            // Start sync with sync state = 0
            // In this case we only obtain a non ero syncKey to use with future queries
            SyncCommandResult syncCommandResult = await server.Sync(InitialSyncKey, this.taskFolderId, new ExchangeChangeSet());

            connectionInfo.PolicyKey = server.PolicyKey;

            if (syncCommandResult.Status != StatusOk)
            {
                var result = new ExchangeSyncResult
                {
                    AuthorizationResult = this.GetFailedAuthResult("ExecuteFirstSync", syncCommandResult)
                };

                return(result);
            }

            // As it is first sync, we have just picked a new SyncId
            // We have to re-sync with this new SyncId
            return(await this.ExecuteSyncAsync(connectionInfo, changeSet, syncCommandResult.SyncKey, this.taskFolderId, true));
        }
Esempio n. 2
0
        protected override ExchangeInfoBuild BuildExchangeConnectionInfo()
        {
            var settings = this.Workbook.Settings;

            string plainPassword = this.CryptoService.Decrypt(settings.GetValue <byte[]>(ExchangeSettings.ExchangePassword));

            if (string.IsNullOrEmpty(plainPassword))
            {
                this.OnSynchronizationFailed(ExchangeResources.Exchange_EmptyPassword);
                return(new ExchangeInfoBuild {
                    IsValid = false
                });
            }

            var connectionInfo = new ExchangeConnectionInfo
            {
                Username             = settings.GetValue <string>(ExchangeSettings.ExchangeUsername),
                Password             = plainPassword,
                Email                = settings.GetValue <string>(ExchangeSettings.ExchangeEmail),
                Domain               = settings.GetValue <string>(ExchangeSettings.ExchangeDomain),
                TimeZoneStandardName = TimeZoneInfo.Local.StandardName,
                UtcOffset            = TimeZoneInfo.Local.GetUtcOffset(DateTime.Now).TotalHours,
                SyncFlaggedItems     = settings.GetValue <bool>(ExchangeSettings.ExchangeSyncFlaggedItems)
            };

            if (string.IsNullOrEmpty(connectionInfo.Username))
            {
                this.OnSynchronizationFailed(ExchangeResources.Exchange_EmptyUsername);
                return(new ExchangeInfoBuild {
                    IsValid = false
                });
            }
            else if (string.IsNullOrEmpty(plainPassword))
            {
                this.OnSynchronizationFailed(ExchangeResources.Exchange_EmptyPassword);
                return(new ExchangeInfoBuild {
                    IsValid = false
                });
            }
            else if (string.IsNullOrEmpty(connectionInfo.Email))
            {
                this.OnSynchronizationFailed(ExchangeResources.Exchange_EmptyEmail);
                return(new ExchangeInfoBuild {
                    IsValid = false
                });
            }

            var uriString = settings.GetValue <string>(ExchangeSettings.ExchangeServerUri);

            if (!string.IsNullOrEmpty(uriString))
            {
                connectionInfo.ServerUri = SafeUri.Get(uriString, UriKind.RelativeOrAbsolute);
            }

            connectionInfo.Version = settings.GetValue <ExchangeServerVersion>(ExchangeSettings.ExchangeVersion);

            return(new ExchangeInfoBuild {
                IsValid = true, ConnectionInfo = connectionInfo
            });
        }
Esempio n. 3
0
 private static ActiveSyncServer CreateExchangeServer(ExchangeConnectionInfo connectionInfo)
 {
     return(new ActiveSyncServer(
                connectionInfo.ServerUri == null ? string.Empty : connectionInfo.ServerUri.OriginalString,
                connectionInfo.Email,
                connectionInfo.Password,
                connectionInfo.DeviceId,
                connectionInfo.PolicyKey));
 }
Esempio n. 4
0
        public async Task <ExchangeSyncResult> ExecuteSyncAsync(ExchangeConnectionInfo connectionInfo, ExchangeChangeSet changeSet, string syncState, string folderId)
        {
            var syncRequest = new ExchangeSyncRequest
            {
                ConnectionInfo = connectionInfo,
                ChangeSet      = changeSet,
                SyncState      = syncState
            };
            var content = await this.requestBuilder.PostJsonAsync <ExchangeSyncRequest, ExchangeSyncResult>(this.serverUri + "/Api/Sync/Sync", syncRequest);

            this.taskFolderName = content.FolderName;

            return(content);
        }
Esempio n. 5
0
        private async Task <ExchangeSyncResult> Sync(ExchangeConnectionInfo connectionInfo, ExchangeChangeSet changeSet = null)
        {
            if (changeSet == null)
            {
                changeSet = new ExchangeChangeSet();
            }

            var data = await this.service.ExecuteFirstSyncAsync(connectionInfo, changeSet);

            string message = string.Format("Operation success: {0} status: {1}", data.AuthorizationResult.IsOperationSuccess, data.AuthorizationResult.AuthorizationStatus);

            Assert.IsTrue(data.AuthorizationResult.IsOperationSuccess, message);
            Assert.AreEqual(ExchangeAuthorizationStatus.OK, data.AuthorizationResult.AuthorizationStatus, message);

            return(data);
        }
Esempio n. 6
0
        private async Task <ExchangeSyncResult> EnsureLoginAsync(string folderId, ExchangeConnectionInfo connectionInfo)
        {
            if (string.IsNullOrEmpty(folderId) || connectionInfo.ServerUri == null)
            {
                var authorizationResult = await this.LoginAsync(connectionInfo);

                if (authorizationResult.AuthorizationStatus != ExchangeAuthorizationStatus.OK || !authorizationResult.IsOperationSuccess || this.taskFolderId == null)
                {
                    return new ExchangeSyncResult {
                               AuthorizationResult = authorizationResult
                    }
                }
                ;
            }

            return(null);
        }
Esempio n. 7
0
        public async Task <ExchangeAuthorizationResult> LoginAsync(ExchangeConnectionInfo connectionInfo)
        {
            GetFolderIdentifiersResult result;

            var autoDiscoverResult = await this.EnsureAutoDiscover(connectionInfo);

            if (!IsExchangeSyncResultValid(autoDiscoverResult))
            {
                return(autoDiscoverResult.AuthorizationResult);
            }

            try
            {
                var server = new EwsSyncServer(connectionInfo.CreateEwsSettings());
                result = await server.GetRootFolderIdentifiersAsync(useCache : false);
            }
            catch (Exception e)
            {
                return(HandleLoginException(e));
            }

            if (result != null && result.TaskFolderIdentifier != null)
            {
                return(new ExchangeAuthorizationResult
                {
                    AuthorizationStatus = ExchangeAuthorizationStatus.OK,
                    IsOperationSuccess = true,
                    ServerUri = connectionInfo.ServerUri
                });
            }
            else
            {
                return(new ExchangeAuthorizationResult
                {
                    AuthorizationStatus = ExchangeAuthorizationStatus.Unkown,
                    ErrorMessage = "Unable to find mailbox identifiers",
                    IsOperationSuccess = false
                });
            }
        }
        protected override ExchangeInfoBuild BuildExchangeConnectionInfo()
        {
            var settings = this.Workbook.Settings;

            byte[] encryptedPasswordData = settings.GetValue <byte[]>(ExchangeSettings.ActiveSyncPassword);

            string serverUri = settings.GetValue <string>(ExchangeSettings.ActiveSyncServerUri);

            var connectionInfo = new ExchangeConnectionInfo
            {
                Username          = settings.GetValue <string>(ExchangeSettings.ActiveSyncEmail),
                EncryptedPassword = encryptedPasswordData,
                Password          = this.CryptoService.Decrypt(encryptedPasswordData),
                Email             = settings.GetValue <string>(ExchangeSettings.ActiveSyncEmail),
                Domain            = string.Empty,
                ServerUri         = StringExtension.TryCreateUri(serverUri),
                DeviceId          = this.deviceId,
                PolicyKey         = settings.GetValue <uint>(ExchangeSettings.ActiveSyncPolicyKey)
            };

            if (connectionInfo.EncryptedPassword == null || string.IsNullOrEmpty(connectionInfo.Password))
            {
                this.OnSynchronizationFailed(ExchangeResources.Exchange_EmptyPassword);
                return(new ExchangeInfoBuild {
                    IsValid = false
                });
            }

            if (string.IsNullOrEmpty(connectionInfo.Email))
            {
                this.OnSynchronizationFailed(ExchangeResources.Exchange_EmptyEmail);
                return(new ExchangeInfoBuild {
                    IsValid = false
                });
            }

            return(new ExchangeInfoBuild {
                IsValid = true, ConnectionInfo = connectionInfo
            });
        }
Esempio n. 9
0
        public async Task <ExchangeAuthorizationResult> LoginAsync(ExchangeConnectionInfo connectionInfo)
        {
            var content = await this.requestBuilder.PostJsonAsync <ExchangeConnectionInfo, ExchangeAuthorizationResult>(this.serverUri + "/Api/Sync/Login", connectionInfo);

            return(content);
        }
        protected override ExchangeInfoBuild BuildExchangeConnectionInfo()
        {
            ISettings settings = this.Workbook.Settings;

            // encrypt the password using the public RSA key of the server
            Stream publicKeyStream = Assembly.Load(new AssemblyName("2Day.Exchange.Shared")).GetManifestResourceStream(PublicKeyTxtName);
            string publicKey       = new StreamReader(publicKeyStream).ReadToEnd();

            byte[] encryptedPassword = settings.GetValue <byte[]>(ExchangeSettings.ExchangePassword);
            if (encryptedPassword == null || encryptedPassword.Length == 0)
            {
                this.OnSynchronizationFailed(ExchangeResources.Exchange_EmptyPassword);
                return(new ExchangeInfoBuild {
                    IsValid = false
                });
            }
            string plainPassword = this.CryptoService.Decrypt(encryptedPassword);

            var encryptedPasswordData = this.CryptoService.RsaEncrypt(publicKey, plainPassword);

            var connectionInfo = new ExchangeConnectionInfo
            {
                Username             = settings.GetValue <string>(ExchangeSettings.ExchangeUsername),
                EncryptedPassword    = encryptedPasswordData,
                Email                = settings.GetValue <string>(ExchangeSettings.ExchangeEmail),
                Domain               = settings.GetValue <string>(ExchangeSettings.ExchangeDomain),
                TimeZoneStandardName = TimeZoneInfo.Local.StandardName,
                UtcOffset            = TimeZoneInfo.Local.GetUtcOffset(DateTime.Now).TotalHours,
            };

            if (string.IsNullOrEmpty(connectionInfo.Username))
            {
                this.OnSynchronizationFailed(ExchangeResources.Exchange_EmptyUsername);
                return(new ExchangeInfoBuild {
                    IsValid = false
                });
            }
            else if (string.IsNullOrEmpty(plainPassword))
            {
                this.OnSynchronizationFailed(ExchangeResources.Exchange_EmptyPassword);
                return(new ExchangeInfoBuild {
                    IsValid = false
                });
            }
            else if (string.IsNullOrEmpty(connectionInfo.Email))
            {
                this.OnSynchronizationFailed(ExchangeResources.Exchange_EmptyEmail);
                return(new ExchangeInfoBuild {
                    IsValid = false
                });
            }

            var uriString = settings.GetValue <string>(ExchangeSettings.ExchangeServerUri);

            if (!string.IsNullOrEmpty(uriString))
            {
                try
                {
                    connectionInfo.ServerUri = SafeUri.Get(uriString, UriKind.RelativeOrAbsolute);
                }
                catch (Exception)
                {
                    this.OnSynchronizationFailed(ExchangeResources.Exchange_InvalidServerUri);
                    return(new ExchangeInfoBuild {
                        IsValid = false
                    });
                }
            }

            connectionInfo.Version          = settings.GetValue <ExchangeServerVersion>(ExchangeSettings.ExchangeVersion);
            connectionInfo.IsBackgroundSync = this.Manager.IsBackground;
            connectionInfo.Source           = this.Manager.Platform;

            return(new ExchangeInfoBuild {
                IsValid = true, ConnectionInfo = connectionInfo
            });
        }
 protected override void UpdateSettingsAfterSync(ExchangeConnectionInfo connectionInfo, string serverUri)
 {
     this.Workbook.Settings.SetValue <string>(ExchangeSettings.ExchangeServerUri, serverUri);
 }
 protected override void UpdateSettingsAfterSync(ExchangeConnectionInfo connectionInfo, string serverUri)
 {
     this.Workbook.Settings.SetValue <uint>(ExchangeSettings.ActiveSyncPolicyKey, connectionInfo.PolicyKey);
     this.Workbook.Settings.SetValue <string>(ExchangeSettings.ActiveSyncServerUri, serverUri);
 }
Esempio n. 13
0
        private async Task <ExchangeSyncResult> ExecuteSyncAsync(ExchangeConnectionInfo connectionInfo, ExchangeChangeSet changeSet, string syncState, string folderId, bool isFirstSync)
        {
            if (connectionInfo == null)
            {
                throw new ArgumentNullException("connectionInfo");
            }
            if (changeSet == null)
            {
                throw new ArgumentNullException("changeSet");
            }
            if (string.IsNullOrEmpty(syncState))
            {
                throw new ArgumentNullException("syncState");
            }

            if (string.IsNullOrEmpty(folderId) || connectionInfo.ServerUri == null || string.IsNullOrWhiteSpace(connectionInfo.ServerUri.ToString()))
            {
                ExchangeSyncResult loginResult = await this.EnsureLoginAsync(folderId, connectionInfo);

                if (loginResult != null)
                {
                    return(loginResult);
                }
            }
            else
            {
                this.taskFolderId = folderId;
            }

            ActiveSyncServer server = CreateExchangeServer(connectionInfo);

            ExchangeSyncResult returnValue = new ExchangeSyncResult
            {
                SyncState = syncState,
                ChangeSet = new ExchangeChangeSet()
            };

            bool mustSync = true;

            while (mustSync)
            {
                SyncCommandResult result = await server.Sync(returnValue.SyncState, this.taskFolderId, changeSet);

                if (result.Status != StatusOk)
                {
                    returnValue.AuthorizationResult = this.GetFailedAuthResult("Sync", result);
                    mustSync = false;
                }
                else
                {
                    returnValue.AuthorizationResult = new ExchangeAuthorizationResult
                    {
                        AuthorizationStatus = ExchangeAuthorizationStatus.OK,
                        IsOperationSuccess  = true,
                        ServerUri           = connectionInfo.ServerUri
                    };

                    if (result.SyncKey != null)
                    {
                        returnValue.SyncState = result.SyncKey;
                    }

                    connectionInfo.PolicyKey = server.PolicyKey;

                    // If we don't have any syncstate (nothing has changed) we return the old one
                    returnValue.OperationResult.IsOperationSuccess = true;

                    returnValue.ChangeSet.AddedTasks.AddRange(result.AddedTasks);
                    returnValue.ChangeSet.ModifiedTasks.AddRange(result.ModifiedTasks);
                    returnValue.ChangeSet.DeletedTasks.AddRange(result.DeletedTasks);
                    returnValue.TaskAddedCount  += result.ServerAddedTasks;
                    returnValue.TaskEditedCount += result.ServerModifiedTasks;

                    foreach (var map in result.ClientServerMapIds)
                    {
                        returnValue.AddMap(map.Key, map.Value);
                    }

                    returnValue.TaskDeletedCount += changeSet.DeletedTasks.Count;
                    mustSync = result.MoreAvailable;

                    changeSet = new ExchangeChangeSet(); // changeSet has been pushed to server, reset it !
                }
            }
            return(returnValue);
        }
Esempio n. 14
0
 public async Task <ExchangeSyncResult> ExecuteFirstSyncAsync(ExchangeConnectionInfo connectionInfo, ExchangeChangeSet changeSet)
 {
     return(await this.ExecuteSyncAsync(connectionInfo, changeSet, null, null));
 }
Esempio n. 15
0
        private async Task <ExchangeSyncResult> EnsureAutoDiscover(ExchangeConnectionInfo connectionInfo)
        {
            var success = new ExchangeSyncResult
            {
                AuthorizationResult = new ExchangeAuthorizationResult
                {
                    AuthorizationStatus = ExchangeAuthorizationStatus.OK,
                    IsOperationSuccess  = true
                },
                OperationResult = new ServiceOperationResult
                {
                    IsOperationSuccess = true
                },
            };

            // check Office 365 server uri is correct (ie. https://outlook.office365.com/EWS/Exchange.asmx)
            if (connectionInfo.ServerUri != null)
            {
                string uri = connectionInfo.ServerUri.ToString().ToLowerInvariant();
                if (uri.Contains("outlook.office365.com") && !uri.EndsWith("/ews/exchange.asmx"))
                {
                    connectionInfo.ServerUri = SafeUri.Get("https://outlook.office365.com/EWS/Exchange.asmx");
                }

                if (uri.Contains("/ews/exchange.asmx/ews/exchange.asmx"))
                {
                    connectionInfo.ServerUri = SafeUri.Get(uri.Replace("/ews/exchange.asmx/ews/exchange.asmx", "/EWS/Exchange.asmx"));
                }

                // check if the server uri looks correct, if it doesn't, run autodiscover
                var server = new EwsSyncServer(connectionInfo.CreateEwsSettings());
                try
                {
                    var identifiers = await server.GetRootFolderIdentifiersAsync(useCache : false);

                    if (identifiers != null)
                    {
                        return(success);
                    }
                }
                catch (Exception ex)
                {
                    if (connectionInfo.ServerUri != null && !connectionInfo.ServerUri.ToString().EndsWith("/ews/exchange.asmx", StringComparison.OrdinalIgnoreCase))
                    {
                        // one more try with the /ews/exchange.asmx path
                        connectionInfo.ServerUri = SafeUri.Get(uri.TrimEnd('/') + "/ews/exchange.asmx");
                        var secondResult = await this.EnsureAutoDiscover(connectionInfo);

                        if (IsExchangeSyncResultValid(secondResult))
                        {
                            return(success);
                        }
                    }
                    LogService.Log("EwsSyncService", $"Server uri is {connectionInfo.ServerUri} but GetRootFolderIds failed ({ex.Message}), fallbacking to classic autodiscover");
                }
            }

            LogService.Log("EwsSyncService", "Server uri is empty, performing auto discover");

            var engine             = new AutoDiscoverEngine();
            var autoDiscoverResult = await engine.AutoDiscoverAsync(connectionInfo.Email, connectionInfo.Username, connectionInfo.Password, connectionInfo.Version);

            if (autoDiscoverResult != null)
            {
                if (autoDiscoverResult.ServerUri != null)
                {
                    LogService.Log("EwsSyncService", "Now using server uri: " + autoDiscoverResult.ServerUri);
                    connectionInfo.ServerUri = autoDiscoverResult.ServerUri;
                }

                if (!string.IsNullOrWhiteSpace(autoDiscoverResult.RedirectEmail))
                {
                    LogService.Log("EwsSyncService", "Now using email redirect: " + autoDiscoverResult.RedirectEmail);
                    connectionInfo.Email = autoDiscoverResult.RedirectEmail;
                }
                return(success);
            }

            LogService.Log("EwsSyncService", "Auto discovery failed");

            return(new ExchangeSyncResult
            {
                AuthorizationResult = new ExchangeAuthorizationResult
                {
                    AuthorizationStatus = ExchangeAuthorizationStatus.AutodiscoveryServiceNotFound,
                    ErrorMessage = "Check credentials are valid and/or try to specify manually a valid server address"
                }
            });
        }
Esempio n. 16
0
        public async Task <ExchangeSyncResult> ExecuteSyncAsync(ExchangeConnectionInfo connectionInfo, ExchangeChangeSet changeSet, string syncState, string folderId)
        {
            if (connectionInfo == null)
            {
                throw new ArgumentNullException(nameof(connectionInfo));
            }
            if (changeSet == null)
            {
                throw new ArgumentNullException(nameof(changeSet));
            }

            var outChangeSet = new ExchangeChangeSet();

            var autoDiscoverResult = await this.EnsureAutoDiscover(connectionInfo);

            if (!IsExchangeSyncResultValid(autoDiscoverResult))
            {
                return(autoDiscoverResult);
            }

            var server = new EwsSyncServer(connectionInfo.CreateEwsSettings());

            var identifiers = await server.GetRootFolderIdentifiersAsync();

            //var subFolders = await server.GetSubFoldersAsync(identifiers.TaskFolderIdentifier);

            //var flaggedItemFolders = await this.EnsureSearchFolder(server);

            /*
             * var a = await server.EnumerateFolderContentAsync(flaggedItemFolders);
             * var d = await server.DownloadFolderContentAsync(a);
             */

            var mapId = new List <ExchangeMapId>();

            await this.PushLocalChanges(changeSet, server, mapId, identifiers.TaskFolderIdentifier);

            var remoteIdentifiers = await this.ApplyRemoteChanges(outChangeSet, server, mapId, identifiers.TaskFolderIdentifier, EwsItemType.Task);

            /*foreach (var subFolder in subFolders.Folders)
             * {
             *  await this.ApplyRemoteChanges(outChangeSet, server, mapId, subFolder);
             * }*/

            if (connectionInfo.SyncFlaggedItems)
            {
                try
                {
                    var identifier = await this.EnsureSearchFolderAsync(server);

                    var otherRemoteIdentifiers = await this.ApplyRemoteChanges(outChangeSet, server, mapId, identifier, EwsItemType.Item);

                    remoteIdentifiers.AddRange(otherRemoteIdentifiers);
                }
                catch (Exception ex)
                {
                    LogService.Log("EwsSyncService", $"Exception while syncing flagged items: {ex}");
                    TrackingManagerHelper.Exception(ex, "Exception while syncing flagged items");
                }
            }

            // check for deleted items
            foreach (var task in this.workbook.Tasks.Where(t => t.SyncId != null))
            {
                var remoteId = remoteIdentifiers.FirstOrDefault(i => i.Id == task.SyncId.GetId());
                if (remoteId == null)
                {
                    // local item not found on server because it was deleted => delete
                    outChangeSet.DeletedTasks.Add(new ServerDeletedAsset(task.SyncId));
                }
            }

            var result = new ExchangeSyncResult
            {
                AuthorizationResult = new ExchangeAuthorizationResult
                {
                    Status = "OK",
                    AuthorizationStatus = ExchangeAuthorizationStatus.OK,
                    IsOperationSuccess  = true,
                    ServerUri           = connectionInfo.ServerUri
                },
                ChangeSet       = outChangeSet,
                MapId           = mapId,
                SyncState       = identifiers.TaskFolderIdentifier.ChangeKey,
                OperationResult = new ServiceOperationResult
                {
                    IsOperationSuccess = true
                }
            };

            return(result);
        }
Esempio n. 17
0
        public async Task <ExchangeAuthorizationResult> LoginAsync(ExchangeConnectionInfo connectionInfo)
        {
            if (connectionInfo == null)
            {
                throw new ArgumentNullException("connectionInfo");
            }

            ActiveSyncServer server;

            // reset cached task folder id
            this.taskFolderId = null;

            if (connectionInfo.ServerUri == null)
            {
                LogService.Log("ActiveSyncService", "Server is empty, trying to auto discover...");
                server = CreateExchangeServer(connectionInfo);

                string discoveredUri = await server.GetAutoDiscoveredServer();

                if (string.IsNullOrEmpty(discoveredUri))
                {
                    LogService.Log("ActiveSyncService", "Didn't found a server for the email address");
                    // Wrong credentials passed to the server
                    return(new ExchangeAuthorizationResult
                    {
                        AuthorizationStatus = ExchangeAuthorizationStatus.UserCredentialsInvalid,
                        IsOperationSuccess = false,
                        ErrorMessage = ExchangeResources.ExchangeActiveSync_InvalidCredentialsMessage
                    });
                }
                connectionInfo.ServerUri = SafeUri.Get(discoveredUri);
                LogService.LogFormat("ActiveSyncService", "Server autodiscovered at '{0}'", discoveredUri);
            }

            // Try to get folders information to know if user is correct
            server = CreateExchangeServer(connectionInfo);
            FolderSyncCommandResult result;

            try
            {
                result = await server.FolderSync("0");

                connectionInfo.PolicyKey = server.PolicyKey;
            }
            catch (Exception ex)
            {
                string message = string.Empty + ex.Message;
                if (ex.InnerException != null && ex.Message != null)
                {
                    message += ", " + ex.InnerException.Message;
                }

                return(new ExchangeAuthorizationResult
                {
                    AuthorizationStatus = ExchangeAuthorizationStatus.UserCredentialsInvalid,
                    IsOperationSuccess = false,
                    ErrorMessage = message
                });
            }

            if (result.Status != StatusOk)
            {
                return(new ExchangeAuthorizationResult
                {
                    AuthorizationStatus = ExchangeAuthorizationStatus.OK,
                    IsOperationSuccess = false,
                    ErrorMessage = ActiveSyncErrorHelper.GetFolderSyncErrorMessage(result.Status)
                });
            }

            ExchangeFolder taskFolder = null;

            if (string.IsNullOrWhiteSpace(this.taskFolderId))
            {
                taskFolder = result.AddedFolders.FirstOrDefault(f => f.FolderType == DefaultTaskFolderType);
                if (taskFolder == null)
                {
                    LogService.Log("ActiveSyncService", "No default task folder found");

                    return(new ExchangeAuthorizationResult
                    {
                        AuthorizationStatus = ExchangeAuthorizationStatus.OK,
                        IsOperationSuccess = false,
                        ErrorMessage = ExchangeResources.ExchangeActiveSync_NoTasksFolder
                    });
                }
            }
            else
            {
                taskFolder = result.AddedFolders.FirstOrDefault(f => f.ServerId == this.taskFolderId);
                if (taskFolder == null)
                {
                    taskFolder = result.AddedFolders.FirstOrDefault(f => f.FolderType == DefaultTaskFolderType);
                    string taskFolderName = taskFolder != null ? taskFolder.DisplayName : "unkown";
                    string message        = $"Could not retrieve task folder with id {this.taskFolderId} (default: {taskFolderName}, all: {result.AddedFolders.Select(f => f.DisplayName).AggregateString()})";

                    LogService.LogFormat("ActiveSyncService", message);

                    return(new ExchangeAuthorizationResult
                    {
                        AuthorizationStatus = ExchangeAuthorizationStatus.OK,
                        IsOperationSuccess = false,
                        ErrorMessage = message
                    });
                }
                else
                {
                    LogService.LogFormat("ActiveSyncService", "Using task folder: {0}", taskFolder.ServerId);
                }
            }

            this.taskFolderId   = taskFolder.ServerId;
            this.taskFolderName = taskFolder.DisplayName;

            // all is Ok, update server Uri with the found Uri
            return(new ExchangeAuthorizationResult
            {
                AuthorizationStatus = ExchangeAuthorizationStatus.OK,
                IsOperationSuccess = true,
                ServerUri = connectionInfo.ServerUri
            });
        }
Esempio n. 18
0
 public static EwsRequestSettings CreateEwsSettings(this ExchangeConnectionInfo connectionInfo)
 {
     return(new EwsRequestSettings(connectionInfo.Email, connectionInfo.Username, connectionInfo.Password, connectionInfo.ServerUri.ToString()));
 }
Esempio n. 19
0
 protected abstract void UpdateSettingsAfterSync(ExchangeConnectionInfo connectionInfo, string serverUri);
Esempio n. 20
0
        public ExchangeConnectionInfo GetConnectionInfo()
        {
            if (this.service is ExchangeSyncService)
            {
                var    stream    = Assembly.GetExecutingAssembly().GetManifestResourceStream("Chartreuse.Today.Sync.Test.ServerPublicKey.xml");
                string publicKey = new StreamReader(stream).ReadToEnd();
                byte[] password  = this.workbook.Settings.GetValue <byte[]>(ExchangeSettings.ExchangePassword);

                var connectionInfo = new ExchangeConnectionInfo
                {
                    Email             = this.workbook.Settings.GetValue <string>(ExchangeSettings.ExchangeEmail),
                    Username          = this.workbook.Settings.GetValue <string>(ExchangeSettings.ExchangeUsername),
                    Domain            = this.workbook.Settings.GetValue <string>(ExchangeSettings.ExchangeDomain),
                    EncryptedPassword = this.cryptoService.RsaEncrypt(publicKey, this.cryptoService.Decrypt(password)),
                    Password          = this.cryptoService.Decrypt(password),
                    Version           = this.workbook.Settings.GetValue <ExchangeServerVersion>(ExchangeSettings.ExchangeVersion),
                    DeviceId          = this.deviceId
                };

                string serverUri = this.workbook.Settings.GetValue <string>(ExchangeSettings.ExchangeServerUri);
                if (!string.IsNullOrEmpty(serverUri))
                {
                    connectionInfo.ServerUri = SafeUri.Get(serverUri);
                }

                return(connectionInfo);
            }
            else if (this.service is EwsSyncService)
            {
                byte[] password = this.workbook.Settings.GetValue <byte[]>(ExchangeSettings.ExchangePassword);

                var connectionInfo = new ExchangeConnectionInfo
                {
                    Email             = this.workbook.Settings.GetValue <string>(ExchangeSettings.ExchangeEmail),
                    Username          = this.workbook.Settings.GetValue <string>(ExchangeSettings.ExchangeUsername),
                    Domain            = this.workbook.Settings.GetValue <string>(ExchangeSettings.ExchangeDomain),
                    EncryptedPassword = password,
                    Password          = this.cryptoService.Decrypt(password),
                    Version           = this.workbook.Settings.GetValue <ExchangeServerVersion>(ExchangeSettings.ExchangeVersion),
                    DeviceId          = this.deviceId,
                    SyncFlaggedItems  = true
                };

                string serverUri = this.workbook.Settings.GetValue <string>(ExchangeSettings.ExchangeServerUri);
                if (!string.IsNullOrEmpty(serverUri))
                {
                    connectionInfo.ServerUri = SafeUri.Get(serverUri);
                }

                return(connectionInfo);
            }
            else if (this.service is ActiveSyncService)
            {
                var connectionInfo = new ExchangeConnectionInfo
                {
                    Email             = this.workbook.Settings.GetValue <string>(ExchangeSettings.ActiveSyncEmail),
                    EncryptedPassword = this.workbook.Settings.GetValue <byte[]>(ExchangeSettings.ActiveSyncPassword),
                    Password          = this.cryptoService.Decrypt(this.workbook.Settings.GetValue <byte[]>(ExchangeSettings.ActiveSyncPassword)),
                    DeviceId          = this.deviceId,
                };

                string serverUri = this.workbook.Settings.GetValue <string>(ExchangeSettings.ActiveSyncServerUri);
                if (!string.IsNullOrEmpty(serverUri))
                {
                    connectionInfo.ServerUri = SafeUri.Get(serverUri);
                }

                return(connectionInfo);
            }
            else
            {
                throw new NotSupportedException();
            }
        }
Esempio n. 21
0
 public async Task <ExchangeSyncResult> ExecuteSyncAsync(ExchangeConnectionInfo connectionInfo, ExchangeChangeSet changeSet, string syncState, string folderId)
 {
     return(await this.ExecuteSyncAsync(connectionInfo, changeSet, syncState, folderId, false));
 }