Exemplo n.º 1
0
        public JsonResult SaveSetting(SettingViewModel model)
        {
            if (ModelState.IsValid)
            {
                using (ApplicationDbContext context = new ApplicationDbContext())
                {
                    EwsServiceArgument argument = new EwsServiceArgument();
                    if (model.IsExist)
                    {
                        SettingModel saveModel = context.Settings.Where(s => s.UserMail == model.UserMail).FirstOrDefault();
                        saveModel.UserMail = model.UserMail;
                        saveModel.AdminPassword = model.EncryptPassword;
                        saveModel.AdminUserName = model.AdminUserName;
                        saveModel.EwsConnectUrl = model.EwsConnectUrl;
                    }
                    else
                    {
                        SettingModel saveModel = new SettingModel()
                        {
                            UserMail = model.UserMail,
                            AdminPassword = model.EncryptPassword,
                            AdminUserName = model.AdminUserName,
                            EwsConnectUrl = model.EwsConnectUrl
                        };
                        context.Settings.Add(saveModel);
                    }

                    context.SaveChanges();
                }
            }
            return Json(model);
        }
Exemplo n.º 2
0
        private ServiceContext(string adminUserName, string adminPassword, string domainName, string organization, TaskType taskType)
        {
            AdminInfo = new OrganizationAdminInfo();

            AdminInfo.UserName = adminUserName;
            AdminInfo.UserPassword = adminPassword;
            AdminInfo.UserDomain = domainName;
            AdminInfo.OrganizationName = organization;

            _argument = new EwsServiceArgument();
            _argument.ServiceCredential = new System.Net.NetworkCredential(adminUserName, adminPassword);
            _argument.UseDefaultCredentials = false;

            CurrentMailbox = adminUserName;

            TaskType = taskType;
        }
Exemplo n.º 3
0
        private static string GetImportSOAPXml(EwsServiceArgument argument, bool isCreateNew, ref HttpWebRequest webRequest)
        {
            string result;
            if (isCreateNew)
            {
                if (argument.UserToImpersonate == null)
                {
                    result = TemplateEwsRequests.UploadItems_CreateNew;
                }
                else
                {
                    switch (argument.UserToImpersonate.IdType)
                    {
                        case ConnectingIdType.PrincipalName:
                            result = TemplateEwsRequests.UploadItems_CreateNewWithImpersonatePrincipleName;
                            break;
                        case ConnectingIdType.SID:
                            result = TemplateEwsRequests.UploadItems_CreateNewWithImpersonateId;
                            break;
                        case ConnectingIdType.SmtpAddress:
                            result = TemplateEwsRequests.UploadItems_CreateNewWithImpersonateSMTPAddress;
                            break;
                        default:
                            throw new NotSupportedException();
                    }

                    result = result.Replace(TemplateEwsRequests.ImpersonateString, argument.UserToImpersonate.Id);
                    if (argument.SetXAnchorMailbox)
                        webRequest.Headers.Add("X-AnchorMailbox", argument.XAnchorMailbox);
                }
            }
            else
            {
                if (argument.UserToImpersonate == null)
                {
                    result = TemplateEwsRequests.UploadItems_Update;
                }
                else
                {
                    switch (argument.UserToImpersonate.IdType)
                    {
                        case ConnectingIdType.PrincipalName:
                            result = TemplateEwsRequests.UploadItems_UpdateWithImpersonatePrincipleName;
                            break;
                        case ConnectingIdType.SID:
                            result = TemplateEwsRequests.UploadItems_UpdateWithImpersonateId;
                            break;
                        case ConnectingIdType.SmtpAddress:
                            result = TemplateEwsRequests.UploadItems_UpdateWithImpersonateSMTPAddress;
                            break;
                        default:
                            throw new NotSupportedException();
                    }

                    result = result.Replace(TemplateEwsRequests.ImpersonateString, argument.UserToImpersonate.Id);
                    if (argument.SetXAnchorMailbox)
                        webRequest.Headers.Add("X-AnchorMailbox", argument.XAnchorMailbox);
                }
            }

            return result;
        }
Exemplo n.º 4
0
 //public IMailbox NewMailboxOperatorImpl()
 //{
 //    return (IMailbox)CreateType<IMailbox>(EwsServiceImplAssembly);
 //}
 //public IFolder NewFolderOperatorImpl(ExchangeService service)
 //{
 //    return (IFolder)CreateType<IFolder>(EwsServiceImplAssembly, service);
 //}
 //public IItem NewItemOperatorImpl(ExchangeService service, IDataAccess dataAccess)
 //{
 //    return (IItem)CreateType<IItem>(EwsServiceImplAssembly, service, dataAccess);
 //}
 public ICatalogDataAccess NewCatalogDataAccessInternal(EwsServiceArgument argument, string organization)
 {
     return (ICatalogDataAccess)CreateType<ICatalogDataAccess>(EwsDataImplAssembly, argument, organization);
 }
Exemplo n.º 5
0
        public JsonResult TestConnect(SettingViewModel model)
        {
            if (ModelState.IsValid)
            {
                IEwsAdapter mailboxOper = CatalogFactory.Instance.NewEwsAdapter();
                EwsServiceArgument argument = new EwsServiceArgument();
                var password = RSAUtil.AsymmetricDecrypt(model.EncryptPassword);
                argument.ServiceCredential = new System.Net.NetworkCredential(model.AdminUserName, password);
                argument.UseDefaultCredentials = false;
                argument.SetConnectMailbox(model.AdminUserName);
                try {
                    var url = mailboxOper.ConnectMailbox(argument, model.AdminUserName);

                    if (url == model.EwsConnectUrl)
                        return Json(new { Success = true, IsChangeUrl = false });
                    else
                        return Json(new { Success = true, IsChangeUrl = true, Url = url });
                }
                catch(Exception e)
                {
                    System.Diagnostics.Trace.TraceError(e.GetExceptionDetail());
                    return Json(new { Success = false});
                }
            }
            return Json(model);
        }
Exemplo n.º 6
0
        internal static bool ExportItemPost(string ServerVersion, string sItemId, string sFile, EwsServiceArgument argument)
        {
            // Write base 64 encoded text Data XML string into a binary base 64 text/XML file
            using (FileStream stream = File.Open(sFile, FileMode.Create))
            {
                var result = ExportItemPost(ServerVersion, sItemId, argument);

                stream.Write(result, 0, result.Length);
                stream.Flush();
                return true;
            }
        }
Exemplo n.º 7
0
 public void ConnectMailbox(EwsServiceArgument argument, string connectMailAddress)
 {
     argument.SetConnectMailbox(connectMailAddress);
     MailboxPrincipalAddress = connectMailAddress;
     CurrentExchangeService = EwsProxyFactory.CreateExchangeService(argument, MailboxPrincipalAddress);
 }
Exemplo n.º 8
0
        public static ExchangeService CreateExchangeService(EwsServiceArgument ewsServiceArgument, string mailboxAddress, bool isDoAutodiscovery = false)
        {
            if (String.IsNullOrEmpty(ewsServiceArgument.ServiceCredential.Password))
            {
                throw new ArgumentException("Please input password first.");
            }

            ewsServiceArgument.EwsUrl = null;
            ExchangeService service = null;
            TimeZoneInfo oTimeZone = null;
            if (ewsServiceArgument.SelectedTimeZoneId != null)
            {
                if (ewsServiceArgument.OverrideTimezone == true)
                {
                    oTimeZone = TimeZoneInfo.FindSystemTimeZoneById(ewsServiceArgument.SelectedTimeZoneId);
                }
            }

            if (ewsServiceArgument.RequestedExchangeVersion.HasValue)
            {
                if (oTimeZone != null)
                    service = new ExchangeService(ewsServiceArgument.RequestedExchangeVersion.Value, oTimeZone);
                else
                    service = new ExchangeService(ewsServiceArgument.RequestedExchangeVersion.Value);

                //System.Diagnostics.Debug.WriteLine(service.PreferredCulture);

            }
            else
            {
                if (oTimeZone != null)
                    service = new ExchangeService(oTimeZone);
                else
                    service = new ExchangeService();
            }

            if (ewsServiceArgument.UserAgent.Length != 0)
                service.UserAgent = ewsServiceArgument.UserAgent;

            // EWS Tracing: http://msdn.microsoft.com/en-us/library/office/dn495632(v=exchg.150).aspx
            service.TraceEnabled = true;
            service.TraceListener = new EwsTraceListener();

            // Instrumentation settings: http://msdn.microsoft.com/en-us/library/office/dn720380(v=exchg.150).aspx
            service.ReturnClientRequestId = true;  // This will give us more data back about the servers used in the response headers
            service.SendClientLatencies = true;  // sends latency info which is used by Microsoft to improve EWS and Exchagne 365.

            if (ewsServiceArgument.EnableScpLookup.HasValue)
            {
                service.EnableScpLookup = ewsServiceArgument.EnableScpLookup.Value;
            }

            if (ewsServiceArgument.PreAuthenticate.HasValue)
            {
                service.PreAuthenticate = ewsServiceArgument.PreAuthenticate.Value;
            }

            if (ewsServiceArgument.OverrideTimeout.HasValue)
            {
                if (ewsServiceArgument.OverrideTimeout == true)
                {
                    if (ewsServiceArgument.Timeout.HasValue)
                        service.Timeout = (int)ewsServiceArgument.Timeout;
                }
            }

            if (ewsServiceArgument.SpecifyProxySettings == true)
            {
                WebProxy oWebProxy = null;
                oWebProxy = new WebProxy(ewsServiceArgument.ProxyServerName, ewsServiceArgument.ProxyServerPort);

                oWebProxy.BypassProxyOnLocal = ewsServiceArgument.BypassProxyForLocalAddress;

                if (ewsServiceArgument.OverrideProxyCredentials == true)
                {

                    if (ewsServiceArgument.ProxyServerUser.Trim().Length == 0)
                    {
                        oWebProxy.UseDefaultCredentials = true;
                    }
                    else
                    {
                        if (ewsServiceArgument.ProxyServerDomain.Trim().Length == 0)
                            oWebProxy.Credentials = new NetworkCredential(ewsServiceArgument.ProxyServerUser, ewsServiceArgument.ProxyServerPassword);
                        else
                            oWebProxy.Credentials = new NetworkCredential(ewsServiceArgument.ProxyServerUser, ewsServiceArgument.ProxyServerPassword, ewsServiceArgument.ProxyServerDomain);
                    }
                }
                else
                {

                    oWebProxy.UseDefaultCredentials = true;
                }
                service.WebProxy = oWebProxy;

            }

            if (ewsServiceArgument.ServiceCredential != null)
            {
                service.Credentials = ewsServiceArgument.ServiceCredential;
            }

            if (ewsServiceArgument.EwsUrl != null)
            {
                service.Url = ewsServiceArgument.EwsUrl;
            }

            if (ewsServiceArgument.UseDefaultCredentials.HasValue)
            {
                service.UseDefaultCredentials = ewsServiceArgument.UseDefaultCredentials.Value;
            }

            if (ewsServiceArgument.UserToImpersonate != null)
            {
                service.ImpersonatedUserId = ewsServiceArgument.UserToImpersonate;

                if(ewsServiceArgument.SetXAnchorMailbox)
                    service.HttpHeaders.Add("X-AnchorMailbox", mailboxAddress);

                // Set headers which help with affinity when Impersonation is being used against Exchange 2013 and Exchagne Online 15.
                // http://blogs.msdn.com/b/mstehle/archive/2013/07/17/more-affinity-considerations-for-exchange-online-and-exchange-2013.aspx
                if (service.RequestedServerVersion.ToString().StartsWith("Exchange2007") == false &&
                    service.RequestedServerVersion.ToString().StartsWith("Exchange2010") == false)
                {
                    //// Should set for 365...:

                    //if (service.HttpHeaders.ContainsKey("X-AnchorMailbox") == false)
                    //    service.HttpHeaders.Add("X-AnchorMailbox", service.ImpersonatedUserId.Id);
                    //else
                    //    service.HttpHeaders["X-AnchorMailbox"] = service.ImpersonatedUserId.Id;

                    //if (service.HttpHeaders.ContainsKey("X-PreferServerAffinity") == false)
                    //    service.HttpHeaders.Add("X-PreferServerAffinity", "true");
                    //else
                    //    service.HttpHeaders["X-PreferServerAffinity"] = "true";
                }
            }

            //var domainName = AutodiscoveryUrlCache.GetDomainName(mailboxAddress);
            //ICache urlCache = null;
            //using(OrganizationCacheManager.CacheManager.LockWhile(()=> {

            //    urlCache = OrganizationCacheManager.CacheManager.GetCache(domainName, AutodiscoveryUrlCache.CacheName);
            //    if (urlCache == null)
            //    {
            //        urlCache = OrganizationCacheManager.CacheManager.NewCache(domainName, AutodiscoveryUrlCache.CacheName, typeof(AutodiscoveryUrlCache));
            //    }

            //})) { }

            //StringCacheKey mailboxKey = new StringCacheKey(domainName);
            object urlObj = null;

            if (isDoAutodiscovery)
            {
                DoAutodiscover(service, mailboxAddress);
                urlObj = service.Url;
            }
            else
            {
                urlObj = "https://outlook.office365.com/EWS/Exchange.asmx";
                service.Url = new Uri(urlObj.ToString());
                try
                {
                    TestExchangeService(service);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.TraceError(ex.GetExceptionDetail());
                    DoAutodiscover(service, mailboxAddress);
                }
            }

            //if(!urlCache.TryGetValue(mailboxKey, out urlObj) || isDoAutodiscovery)
            //{
            //    DoAutodiscover(service, mailboxAddress);
            //    if (!isDoAutodiscovery && urlObj == null)
            //        urlCache.AddKeyValue(mailboxKey, urlObj);
            //    urlObj = service.Url;
            //}
            //else
            //{
            //    try
            //    {
            //        service.Url = new Uri(urlObj.ToString());
            //        TestExchangeService(service);
            //    }
            //    catch(Exception ex)
            //    {
            //        System.Diagnostics.Trace.TraceError(ex.GetExceptionDetail());
            //        DoAutodiscover(service, mailboxAddress);
            //        urlCache.SetKeyValue(mailboxKey, service.Url);
            //    }
            //}

            ewsServiceArgument.EwsUrl = service.Url;
            return service;
        }
Exemplo n.º 9
0
 public void ImportItem(string parentFolderId, byte[] itemData, EwsServiceArgument argument)
 {
     _ewsOperator.ImportItem(parentFolderId, itemData, argument);
 }
Exemplo n.º 10
0
 public void ImportItem(FolderId parentFolderId, byte[] itemData, EwsServiceArgument argument)
 {
     ExportUploadHelper.UploadItemPost(Enum.GetName(typeof(ExchangeVersion), CurrentExchangeService.RequestedServerVersion), parentFolderId, CreateActionType.CreateNew, string.Empty, itemData, argument);
 }
Exemplo n.º 11
0
 public byte[] ExportItem(string itemId, EwsServiceArgument argument)
 {
     return _ewsOperator.ExportItem(itemId, argument);
 }
Exemplo n.º 12
0
 public void ImportItem(string parentFolderId, Stream stream, EwsServiceArgument argument)
 {
     _ewsOperator.ImportItem(parentFolderId, stream, argument);
 }
Exemplo n.º 13
0
 public byte[] ExportItem(IItemData item, EwsServiceArgument argument)
 {
     return _ewsOperator.ExportItem(item.Id, argument);
 }
Exemplo n.º 14
0
 public byte[] ExportEmlItem(IItemData item, EwsServiceArgument argument)
 {
     var itemInEws = item.Data as Item;
     PropertySet props = new PropertySet(EmailMessageSchema.MimeContent);
     _ewsOperator.Load(itemInEws, props);
     byte[] result = itemInEws.MimeContent.Content;
     itemInEws.MimeContent.Content = null;
     return result;
 }
Exemplo n.º 15
0
 public string ConnectMailbox(EwsServiceArgument argument, string connectMailAddress)
 {
     argument.SetConnectMailbox(connectMailAddress);
     MailboxPrincipalAddress = connectMailAddress;
     var url = _ewsOperator.NewExchangeService(connectMailAddress, argument);
     CreatedFolders = new Dictionary<string, FolderId>();
     return url;
 }
Exemplo n.º 16
0
 public void ExportEmlItem(Item itemInEws, MemoryStream emlStream, EwsServiceArgument argument)
 {
     int retryCount = 0;
     Exception lastException = null;
     while (retryCount < 3)
     {
         if (retryCount > 0)
         {
             const int sleepCount = 10 * 1000;
             LogFactory.LogInstance.WriteLog(LogLevel.WARN, "retry export eml", "after sleeping  {0} seconde ,will try the [{1}]th export.", sleepCount, retryCount);
             Thread.Sleep(sleepCount);
         }
         try
         {
             DoExportEmlItem(itemInEws, emlStream, argument);
             break;
         }
         catch (Exception e)
         {
             System.Diagnostics.Trace.TraceError(e.GetExceptionDetail());
             LogFactory.LogInstance.WriteException(LogLevel.ERR, "Export eml error", e, e.Message);
             lastException = e;
             retryCount++;
         }
     }
     if (lastException != null)
         throw new ApplicationException("Export eml failure", lastException);
 }
Exemplo n.º 17
0
        public static string UploadItemPost(string ServerVersion, string parentFolderId, CreateActionType oCreateActionType, string sItemId, Stream stream, EwsServiceArgument argument)
        {
            try
            {
                string sResponseText = string.Empty;
                System.Net.HttpWebRequest oHttpWebRequest = null;
                EwsProxyFactory.CreateHttpWebRequest(ref oHttpWebRequest, argument);

                string EwsRequest = string.Empty;

                if (oCreateActionType != CreateActionType.CreateNew)
                {
                    EwsRequest = GetImportSOAPXml(argument, false, ref oHttpWebRequest);

                    if (oCreateActionType == CreateActionType.Update)
                        EwsRequest = EwsRequest.Replace("##CreateAction##", "Update");
                    else
                        EwsRequest = EwsRequest.Replace("##CreateAction##", "UpdateOrCreate");
                    EwsRequest = EwsRequest.Replace("##ItemId##", sItemId);
                }
                else
                {
                    EwsRequest = GetImportSOAPXml(argument, true, ref oHttpWebRequest);
                    EwsRequest = EwsRequest.Replace("##CreateAction##", "CreateNew");
                }
                EwsRequest = EwsRequest.Replace("##RequestServerVersion##", ServerVersion);
                EwsRequest = EwsRequest.Replace("##ParentFolderId_Id##", parentFolderId);

                string sBase64Data = string.Empty;
                sBase64Data = FileHelper.GetBinaryFileAsBase64(stream);
                System.Diagnostics.Debug.WriteLine("sBase64: " + sBase64Data);

                // Convert byte array to base64
                EwsRequest = EwsRequest.Replace("##Data##", sBase64Data);

                //ShowTextDocument oForm = new ShowTextDocument();
                //oForm.txtEntry.WordWrap = false;
                //oForm.Text = "Info";
                //oForm.txtEntry.Text = EwsRequest;
                //oForm.ShowDialog();

                // Now inject the base64 body into the stream:

                byte[] bytes = Encoding.UTF8.GetBytes(EwsRequest);
                oHttpWebRequest.ContentLength = bytes.Length;

                using (Stream requestStream = oHttpWebRequest.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                    requestStream.Flush();
                    requestStream.Close();
                }

                // Get response
                using (HttpWebResponse oHttpWebResponse = (HttpWebResponse)oHttpWebRequest.GetResponse())
                {

                    using (StreamReader oStreadReader = new StreamReader(oHttpWebResponse.GetResponseStream()))
                    {
                        sResponseText = oStreadReader.ReadToEnd();

                        if (oHttpWebResponse.StatusCode == HttpStatusCode.OK)
                        {
                            string responseCode = GetFirstResponseCode(sResponseText);

                            if (responseCode != "NoError")
                            {
                                string messageText = GetFirstMessageText(sResponseText);
                                LogFactory.LogInstance.WriteLog(LogLevel.ERR, "Import Failed", "Import ftstream failed with error stream, the detail of response is:{0}.", sResponseText);
                                return messageText;
                            }
                            else
                            {
                                return string.Empty;
                            }
                        }
                        else
                        {
                            LogFactory.LogInstance.WriteLog(LogLevel.ERR, "Import Failed", "Import ftstream failed with error response status code, the detail of response is:{0}.", sResponseText);

                            return oHttpWebResponse.StatusCode.ToString();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Trace.TraceError(e.GetExceptionDetail());
                LogFactory.LogInstance.WriteException(LogLevel.ERR, "Import Failed", e, string.Empty);
                return e.Message;
            }
        }
Exemplo n.º 18
0
 public void ExportItem(Item item, Stream stream, EwsServiceArgument argument)
 {
     ExportUploadHelper.ExportItemPost(Enum.GetName(typeof(ExchangeVersion), item.Service.RequestedServerVersion), item.Id.UniqueId, stream, argument);
 }
Exemplo n.º 19
0
        private void TestSync(string lastSyncState)
        {
            EwsServiceArgument argument = new EwsServiceArgument();
            argument.SetXAnchorMailbox = true;
            argument.ServiceCredential = new System.Net.NetworkCredential("*****@*****.**", "arcserve1!");
            argument.XAnchorMailbox = "*****@*****.**";
            argument.ServiceEmailAddress = "*****@*****.**";
            argument.UserToImpersonate = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "*****@*****.**");

            var service = EwsProxyFactory.CreateExchangeService(argument, "*****@*****.**");

            var fcc = service.SyncFolderHierarchy(new FolderId(WellKnownFolderName.MsgFolderRoot), PropertySet.IdOnly, lastSyncState);

            if (fcc.Count == 0)
            {
                Debug.WriteLine("There are no folders to synchronize.");
            }

            // Otherwise, write all the changes included in the response
            // to the console.
            // For the initial synchronization, all the changes will be of type
            // ChangeType.Create.
            else
            {
                PropertySet set = new PropertySet(FolderSchema.Id, FolderSchema.DisplayName, FolderSchema.ParentFolderId, FolderSchema.FolderClass);
                var moreInfoSet = new PropertySet(FolderSchema.ChildFolderCount, FolderSchema.TotalCount, FolderSchema.UnreadCount, FolderSchema.WellKnownFolderName);
                foreach (FolderChange fc in fcc)
                {
                    Debug.Write("ChangeType: " + fc.ChangeType.ToString());
                    Debug.Write("\tFolderId: " + fc.FolderId);

                    Folder folder = Folder.Bind(service, fc.FolderId, set);

                    foreach (var setItem in set)
                    {
                        Debug.Write("\t");
                        Debug.Write(setItem.ToString());
                        Debug.Write(":");
                        object value = null;
                        if (folder.TryGetProperty(setItem, out value) && value != null)
                            Debug.Write(value.ToString());
                        else
                            Debug.Write("NULL");
                    }

                    Debug.WriteLine("===========");
                }

            }

            // Save the sync state for use in future SyncFolderItems requests.
            // The sync state is used by the server to determine what changes to report
            // to the client.
            string fSyncState = fcc.SyncState;
            Debug.WriteLine("State:" + fSyncState);
        }
Exemplo n.º 20
0
        private void DoExportEmlItem(Item itemInEws, MemoryStream emlStream, EwsServiceArgument argument)
        {
            PropertySet props = new PropertySet(EmailMessageSchema.MimeContent);
            //itemInEws.Load(props);
            //This results in a GetItem call to EWS.
            AutoResetEvent ev = new AutoResetEvent(false);
            Exception ex = null;
            Timer t = null;
            try
            {
                bool hasLoad = false;
                t = new Timer((arg) =>
                {
                    try
                    {
                        if (hasLoad)
                        {
                            ex = new TimeoutException("Export eml message time out.");
                            ev.Set();
                        }
                        else
                        {
                            hasLoad = true;
                            itemInEws.Load(props);
                            ev.Set();
                        }
                    }
                    catch (Exception e)
                    {
                        ex = e;
                        LogFactory.LogInstance.WriteException(LogLevel.ERR, "Export eml failed", e, e.Message);
                        ev.Set();
                    }
                }, null, 0, ExportUploadHelper.TimeOut);
                while (!ev.WaitOne(1000))
                {

                }
            }
            finally
            {
                if (t != null)
                    t.Dispose();
                if (ev != null)
                    ev.Dispose();
                t = null;
                ev = null;
            }

            if (ex != null)
            {
                throw new ApplicationException("Export eml error", ex);
            }

            //var email = EmailMessage.Bind(CurrentExchangeService, itemInEws.Id, props);
            emlStream.Write(itemInEws.MimeContent.Content, 0, itemInEws.MimeContent.Content.Length);
            itemInEws.MimeContent.Content = null;
        }
Exemplo n.º 21
0
 public RestoreDestinationExImpl(EwsServiceArgument argument, IDataAccess dataAccess)
 {
     _argument = argument;
     _dataAccess = dataAccess;
 }
Exemplo n.º 22
0
 public static string UploadItemPost(string ServerVersion, FolderId ParentFolderId, CreateActionType oCreateActionType, string sItemId, byte[] data, EwsServiceArgument argument)
 {
     using (var memoryStream = new MemoryStream(data))
     {
         return UploadItemPost(ServerVersion, ParentFolderId.UniqueId, oCreateActionType, sItemId, memoryStream, argument);
     }
 }
Exemplo n.º 23
0
        /// <summary>
        ///  This is used for preparing an HttpWebRequest for a raw post.
        /// </summary>
        /// <param name="oRequest"></param>
        public static void CreateHttpWebRequest(ref HttpWebRequest oRequest, EwsServiceArgument argument)
        {
            if (String.IsNullOrEmpty(argument.ServiceCredential.Password))
            {
                throw new ArgumentException("Please input password first.");
            }

            HttpWebRequest oHttpWebRequest = (HttpWebRequest)WebRequest.Create(argument.EwsUrl);

            if (argument.UserAgent.Length != 0)
                oHttpWebRequest.Headers.Add("UserAgent", argument.UserAgent);

            oHttpWebRequest.Method = "POST";
            oHttpWebRequest.ContentType = "text/xml";

            if (argument.OverrideTimeout.HasValue)
            {
                if (argument.OverrideTimeout == true)
                {
                    if (argument.Timeout.HasValue)
                        oHttpWebRequest.Timeout = (int)argument.Timeout;
                }
            }

            oHttpWebRequest.Headers.Add("Translate", "f");
            oHttpWebRequest.Headers.Add("Pragma", "no-cache");
            oHttpWebRequest.Headers.Add("return-client-request-id", "true");  // This will give us more data back about the servers used in the response headers
            if (argument.PreAuthenticate.HasValue)
            {
                oHttpWebRequest.Headers.Add("PreAuthenticate", argument.PreAuthenticate.Value.ToString());
            }

            // TODO:  Add timezone injection
            //TimeZoneInfo oTimeZone = null;
            //if (SelectedTimeZoneId != null)
            //{
            //    if (OverrideTimezone == true)
            //    {
            //        oTimeZone = TimeZoneInfo.FindSystemTimeZoneById(SelectedTimeZoneId);
            //    }
            //}

            //if (RequestedExchangeVersion.HasValue)
            //{
            //    if (oTimeZone != null)
            //        service = new ExchangeService(RequestedExchangeVersion.Value, oTimeZone);
            //    else
            //        service = new ExchangeService(RequestedExchangeVersion.Value);

            //    //System.Diagnostics.Debug.WriteLine(service.PreferredCulture);

            //}
            //else
            //{
            //    if (oTimeZone != null)
            //        service = new ExchangeService(oTimeZone);
            //    else
            //        service = new ExchangeService();
            //}

            if (argument.SpecifyProxySettings == true)
            {
                WebProxy oWebProxy = null;
                oWebProxy = new WebProxy(argument.ProxyServerName, argument.ProxyServerPort);

                oWebProxy.BypassProxyOnLocal = argument.BypassProxyForLocalAddress;

                if (argument.OverrideProxyCredentials == true)
                {

                    if (argument.ProxyServerUser.Trim().Length == 0)
                    {
                        oWebProxy.UseDefaultCredentials = true;
                    }
                    else
                    {
                        if (argument.ProxyServerDomain.Trim().Length == 0)
                            oWebProxy.Credentials = new NetworkCredential(argument.ProxyServerUser, argument.ProxyServerPassword);
                        else
                            oWebProxy.Credentials = new NetworkCredential(argument.ProxyServerUser, argument.ProxyServerPassword, argument.ProxyServerDomain);
                    }
                }
                else
                {

                    oWebProxy.UseDefaultCredentials = true;
                }
                oHttpWebRequest.Proxy = oWebProxy;
            }

            if (argument.UseDefaultCredentials.HasValue)
            {
                oHttpWebRequest.UseDefaultCredentials = argument.UseDefaultCredentials.Value;
            }

            if (argument.ServiceCredential != null)
            {
                oHttpWebRequest.Credentials = argument.ServiceCredential;
            }
            //else
            //{
            //    oHttpWebRequest.Credentials =   GetNetworkCredential();

            //}

            //if (ServiceCredential != null)
            //{
            //    service.Credentials = ServiceCredential;
            //}

            //    if (sAuthentication == "DefaultCredentials")
            //    {
            //        oHttpWebRequest.UseDefaultCredentials = true;
            //        oHttpWebRequest.Credentials = CredentialCache.DefaultCredentials;
            //    }
            //    else
            //    {
            //        if (sAuthentication == "DefaultNetworkCredentials")
            //            oHttpWebRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
            //        else
            //        {
            //            oHttpWebRequest.Credentials = oCrentialCache;
            //        }
            //    }

            if (argument.UserToImpersonate != null)
            {
                //service.ImpersonatedUserId = UserToImpersonate;
                // TODO: Add injection of impersonation.

            }

            oRequest = oHttpWebRequest;
        }
Exemplo n.º 24
0
 public RestoreDestinationOrgExImpl(EwsServiceArgument argument, IDataAccess dataAccess)
     : base(argument, dataAccess)
 {
 }
Exemplo n.º 25
0
 public static string UploadItemPost(string ServerVersion, FolderId ParentFolderId, CreateActionType oCreateActionType, string sItemId, string sFile, EwsServiceArgument argument)
 {
     using (FileStream oFileStream = new FileStream(sFile, FileMode.Open, FileAccess.Read))
     {
         return UploadItemPost(ServerVersion, ParentFolderId.UniqueId, oCreateActionType, sItemId, oFileStream, argument);
     }
 }
Exemplo n.º 26
0
        public ActionResult Index(BackupModel model)
        {
            if (ModelState.IsValid)
            {

                model.Index++;
                if (model.Index == 3)
                    return Run(model);

                if (model.Index == 1)
                {
                    IEwsAdapter mailboxOper = CatalogFactory.Instance.NewEwsAdapter();
                    EwsServiceArgument argument = new EwsServiceArgument();
                    var password = RSAUtil.AsymmetricDecrypt(model.EncryptPassword);
                    argument.ServiceCredential = new System.Net.NetworkCredential(model.BackupUserMailAddress, password);
                    argument.UseDefaultCredentials = false;
                    argument.SetConnectMailbox(model.BackupUserMailAddress);
                    mailboxOper.ConnectMailbox(argument, model.BackupUserMailAddress);
                    return Json(model);
                }
            }

            return Json(model);
        }
Exemplo n.º 27
0
        internal static byte[] ExportItemPost(string ServerVersion, string sItemId, EwsServiceArgument argument)
        {
            string sResponseText = string.Empty;
            System.Net.HttpWebRequest oHttpWebRequest = null;
            StreamReader oStreadReader = null;
            HttpWebResponse oHttpWebResponse = null;
            byte[] buffer = null;
            // Build request body...
            try
            {
                EwsProxyFactory.CreateHttpWebRequest(ref oHttpWebRequest, argument);
                string EwsRequest = GetExportSOAPXml(argument, ref oHttpWebRequest);
                EwsRequest = EwsRequest.Replace("##RequestServerVersion##", ServerVersion);
                EwsRequest = EwsRequest.Replace("##ItemId##", sItemId);
                // Use request to do POST to EWS so we get back the data for the item to export.
                byte[] bytes = Encoding.UTF8.GetBytes(EwsRequest);
                oHttpWebRequest.ContentLength = bytes.Length;
                oHttpWebRequest.Timeout = TimeOut;
                using (Stream requestStream = oHttpWebRequest.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                    requestStream.Flush();
                    requestStream.Close();
                }

                // Get response
                oHttpWebResponse = (HttpWebResponse)oHttpWebRequest.GetResponse();

                //oStreadReader = new StreamReader(oHttpWebResponse.GetResponseStream());
                //sResponseText = oStreadReader.ReadToEnd();
                //if (sResponseText.Length > MaxSupportItemSize)
                //{
                //    LogFactory.LogInstance.WriteLog(LogLevel.WARN, string.Format("{0} is too much. not support now.", sItemId));
                //    return false;
                //}

                // OK?
                if (oHttpWebResponse.StatusCode == HttpStatusCode.OK)
                {
                    //int BUFFER_SIZE = 1024;
                    //int iReadBytes = 0;
                    //XmlDocument oDoc = new XmlDocument();
                    //XmlNamespaceManager namespaces = new XmlNamespaceManager(oDoc.NameTable);
                    //namespaces.AddNamespace("m", "http://schemas.microsoft.com/exchange/services/2006/messages");
                    //oDoc.LoadXml(sResponseText);
                    //XmlNode oData = oDoc.SelectSingleNode("//m:Data", namespaces);

                    XDocument doc = XDocument.Load(oHttpWebResponse.GetResponseStream());
                    XNamespace mnameSpace = "http://schemas.microsoft.com/exchange/services/2006/messages";

                    //var sb = new StringBuilder(102400);
                    //sb.Append("<Data>");
                    //sb.Append(doc.Descendants(mnameSpace + "Data").FirstOrDefault().Value);
                    //sb.Append("</Data>");
                    var dataNode = doc.Descendants(mnameSpace + "Data").FirstOrDefault();
                    if (dataNode == null)
                        throw new XmlException("can't find the data.");
                    var val = dataNode.Value;
                    buffer = Convert.FromBase64String(val);

                    // Write base 64 encoded text Data XML string into a binary base 64 text/XML file
                    //BinaryWriter oBinaryWriter = new BinaryWriter(File.Open(sFile, FileMode.Create));
                    //using (StringReader oStringReader = new StringReader(sb.ToString()))
                    //{
                    //    using (XmlTextReader oXmlTextReader = new XmlTextReader(oStringReader))
                    //    {

                    //        oXmlTextReader.MoveToContent();
                    //        byte[] buffer = new byte[BUFFER_SIZE];
                    //        do
                    //        {

                    //            iReadBytes = oXmlTextReader.ReadBase64(buffer, 0, BUFFER_SIZE);
                    //            //oBinaryWriter.Write(buffer, 0, iReadBytes);
                    //            writer.Write(buffer, 0, iReadBytes);
                    //        }
                    //        while (iReadBytes >= BUFFER_SIZE);

                    //        oXmlTextReader.Close();
                    //    }
                    //}

                }

            }
            finally
            {
                if (oStreadReader != null)
                {
                    oStreadReader.Dispose();
                    oStreadReader = null;
                }
                if (oHttpWebResponse != null)
                {
                    oHttpWebResponse.Dispose();
                    oHttpWebResponse = null;
                }
            }
            return buffer;
        }