/// <summary> /// Проверяет успешность подключения к серверу Exchange с указанными параметрами /// </summary> /// <param name="ex">Параметры подключения</param> /// <param name="message">Возвращает текст ошибки подключения при ее наличии</param> /// <returns></returns> public static bool CheckConnection(Configuration.Exchange ex, out string message) { try { message = string.Empty; ExchangeServiceBinding bind = new ExchangeServiceBinding(); bind.Credentials = new NetworkCredential(ex.Username, ex.Password, ex.Domain); bind.Url = "https://" + ex.ServerName + "/EWS/Exchange.asmx"; FindItemType findType = new FindItemType(); findType.Traversal = ItemQueryTraversalType.Shallow; findType.ItemShape = new ItemResponseShapeType(); findType.ItemShape.BaseShape = DefaultShapeNamesType.IdOnly; DistinguishedFolderIdType folder = new DistinguishedFolderIdType(); folder.Id = DistinguishedFolderIdNameType.inbox; findType.ParentFolderIds = new BaseFolderIdType[] { folder }; FindItemResponseType findResp = bind.FindItem(findType); } catch (Exception error) { message = error.Message; return(false); } return(true); }
public IWebServiceBinding GetEwsBinding(DirectoryContext directoryContext) { IClientProxy clientProxy; switch (base.TrackingAuthorityKind) { case TrackingAuthorityKind.RemoteSiteInCurrentOrg: { ExchangeServiceBinding exchangeServiceBinding = new ExchangeServiceBinding("MessageTracking", WebServiceTrackingAuthority.noValidationCallback); this.SetAuthenticationMechanism(exchangeServiceBinding); exchangeServiceBinding.Proxy = new WebProxy(); RemoteSiteInCurrentOrgTrackingAuthority remoteSiteInCurrentOrgTrackingAuthority = (RemoteSiteInCurrentOrgTrackingAuthority)this; exchangeServiceBinding.Url = this.Uri.ToString(); exchangeServiceBinding.UserAgent = WebServiceTrackingAuthority.EwsUserAgentString; exchangeServiceBinding.RequestServerVersionValue = new RequestServerVersion(); exchangeServiceBinding.RequestServerVersionValue.Version = VersionConverter.GetExchangeVersionType(remoteSiteInCurrentOrgTrackingAuthority.ServerVersion); exchangeServiceBinding.CookieContainer = new CookieContainer(); clientProxy = new ClientProxyEWS(exchangeServiceBinding, this.Uri, remoteSiteInCurrentOrgTrackingAuthority.ServerVersion); break; } case TrackingAuthorityKind.RemoteForest: clientProxy = new ClientProxyRD(directoryContext, this.ProxyRecipient, this.Domain, ExchangeVersion.Exchange2010); break; case TrackingAuthorityKind.RemoteTrustedOrg: clientProxy = new ClientProxyRD(directoryContext, this.ProxyRecipient, this.Domain, ExchangeVersion.Exchange2010_SP1); break; default: throw new NotImplementedException(); } return(new WebServiceBinding(clientProxy, directoryContext, this)); }
public FolderIdType FindFolderID(ExchangeServiceBinding service, DistinguishedFolderIdNameType folder) { FindFolderType requestFindFolder = new FindFolderType(); requestFindFolder.Traversal = FolderQueryTraversalType.Deep; DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1]; folderIDArray[0] = new DistinguishedFolderIdType(); folderIDArray[0].Id = folder; FolderResponseShapeType itemProperties = new FolderResponseShapeType(); itemProperties.BaseShape = DefaultShapeNamesType.AllProperties; requestFindFolder.ParentFolderIds = folderIDArray; requestFindFolder.FolderShape = itemProperties; //requestFindFolder.FolderShape.BaseShape = DefaultShapeNamesType.AllProperties; FindFolderResponseType objFindFolderResponse = service.FindFolder(requestFindFolder); foreach (ResponseMessageType responseMsg in objFindFolderResponse.ResponseMessages.Items) { if (responseMsg.ResponseClass == ResponseClassType.Success) { FindFolderResponseMessageType objFindResponse = responseMsg as FindFolderResponseMessageType; foreach (BaseFolderType objFolderType in objFindResponse.RootFolder.Folders) { return(objFolderType.FolderId); } } } return(null); }
protected override void SetAuthenticationMechanism(ExchangeServiceBinding ewsBinding) { if (ADAuthenticationTrackingAuthority.CanImpersonateNetworkService) { ewsBinding.Authenticator = SoapHttpClientAuthenticator.CreateNetworkService(); return; } ewsBinding.Credentials = CredentialCache.DefaultNetworkCredentials; }
public ClientProxyEWS(ExchangeServiceBinding ewsBinding, Uri uri, int serverVersion) { if (uri == null) { throw new ArgumentNullException("uri"); } this.ewsBinding = ewsBinding; this.TargetInfoForLogging = uri.ToString(); this.serverVersion = serverVersion; }
protected ExchangeServiceBinding GetExchangeBinding() { ExchangeServiceBinding binding = new ExchangeServiceBinding(); ServicePointManager.ServerCertificateValidationCallback = ValidateCertificate; binding.Credentials = new NetworkCredential(Username, Password, Domain); binding.Url = ServerUrl; return(binding); }
/// <summary> /// Initialize some variables overridden. /// </summary> /// <param name="testSite">The instance of ITestSite Class.</param> public override void Initialize(ITestSite testSite) { base.Initialize(testSite); string userName = Common.GetConfigurationPropertyValue("Sender", this.Site); string password = Common.GetConfigurationPropertyValue("SenderPassword", this.Site); string domain = Common.GetConfigurationPropertyValue("Domain", this.Site); string url = Common.GetConfigurationPropertyValue("ServiceUrl", this.Site); this.exchangeServiceBinding = new ExchangeServiceBinding(url, userName, password, domain, this.Site); Common.InitializeServiceBinding(this.exchangeServiceBinding, this.Site); }
/// <summary> /// Overrides IAdapter's Initialize() and sets default protocol short name of the testSite. /// </summary> /// <param name="testSite">Pass ITestSite to adapter, make adapter can use ITestSite's function.</param> public override void Initialize(ITestSite testSite) { base.Initialize(testSite); Common.MergeConfiguration(testSite); this.username = Common.GetConfigurationPropertyValue("OrganizerName", this.Site); this.password = Common.GetConfigurationPropertyValue("OrganizerPassword", this.Site); this.domain = Common.GetConfigurationPropertyValue("Domain", this.Site); this.url = Common.GetConfigurationPropertyValue("ServiceUrl", this.Site); this.exchangeServiceBinding = new ExchangeServiceBinding(this.url, this.username, this.password, this.domain, this.Site); Common.InitializeServiceBinding(this.exchangeServiceBinding, this.Site); }
/// <summary> /// Overrides IAdapter's Initialize() and sets default protocol short name of the testSite. /// </summary> /// <param name="testSite">Pass ITestSite to adapter, make adapter can use ITestSite's function</param> public override void Initialize(TestTools.ITestSite testSite) { base.Initialize(testSite); testSite.DefaultProtocolDocShortName = "MS-OXWSATT"; Common.MergeConfiguration(testSite); string userName = Common.GetConfigurationPropertyValue("UserName", testSite); string password = Common.GetConfigurationPropertyValue("UserPassword", testSite); string domain = Common.GetConfigurationPropertyValue("Domain", testSite); string url = Common.GetConfigurationPropertyValue("ServiceUrl", testSite); this.exchangeServiceBinding = new ExchangeServiceBinding(url, userName, password, domain, testSite); Common.InitializeServiceBinding(this.exchangeServiceBinding, testSite); }
/// <summary> /// Overrides IAdapter's Initialize() and sets default protocol short name of the testSite. /// </summary> /// <param name="testSite">Pass ITestSite to adapter, make adapter can use ITestSite's function.</param> public override void Initialize(ITestSite testSite) { base.Initialize(testSite); Site.DefaultProtocolDocShortName = "MS-OXWSMSG"; Common.MergeConfiguration(testSite); this.userName = Common.GetConfigurationPropertyValue("Sender", this.Site); this.password = Common.GetConfigurationPropertyValue("SenderPassword", this.Site); this.domain = Common.GetConfigurationPropertyValue("Domain", this.Site); this.url = Common.GetConfigurationPropertyValue("ServiceUrl", this.Site); this.exchangeServiceBinding = new ExchangeServiceBinding(this.url, this.userName, this.password, this.domain, this.Site); Common.InitializeServiceBinding(this.exchangeServiceBinding, this.Site); }
private static void SetSecurityHeader(ExchangeServiceBinding binding, string email) { binding.Authenticator = SoapHttpClientAuthenticator.CreateNetworkService(); binding.Authenticator.AdditionalSoapHeaders.Add(new OpenAsAdminOrSystemServiceType { ConnectingSID = new ConnectingSIDType { Item = new PrimarySmtpAddressType { Value = email } }, LogonType = SpecialLogonType.SystemService }); }
/// <summary> /// Implements Microsoft.Protocols.TestTools.IAdapter.Initialize(Microsoft.Protocols.TestTools.ITestSite). /// </summary> /// <param name="testSite">The test site instance associated with the current adapter.</param> public override void Initialize(TestTools.ITestSite testSite) { base.Initialize(testSite); string commonConfigFileName = Common.GetConfigurationPropertyValue("CommonConfigurationFileName", testSite); Common.MergeGlobalConfig(commonConfigFileName, testSite); string userName = Common.GetConfigurationPropertyValue("UserName", testSite); string password = Common.GetConfigurationPropertyValue("UserPassword", testSite); string domain = Common.GetConfigurationPropertyValue("Domain", testSite); string url = Common.GetConfigurationPropertyValue("ServiceUrl", testSite); this.exchangeServiceBinding = new ExchangeServiceBinding(url, userName, password, domain, testSite); Common.InitializeServiceBinding(this.exchangeServiceBinding, testSite); }
/// <summary> /// Overrides IAdapter's Initialize() and sets default protocol short name of the testSite. /// </summary> /// <param name="testSite">Pass ITestSite to adapter, make adapter can use ITestSite's function.</param> public override void Initialize(TestTools.ITestSite testSite) { // Initialize. base.Initialize(testSite); Common.MergeConfiguration(testSite); // Get the parameters from configuration files. string userName = Common.GetConfigurationPropertyValue("OrganizerName", testSite); string password = Common.GetConfigurationPropertyValue("OrganizerPassword", testSite); string domain = Common.GetConfigurationPropertyValue("Domain", testSite); string urlFormat = Common.GetConfigurationPropertyValue("ServiceUrl", testSite); // Initialize service. this.exchangeServiceBinding = new ExchangeServiceBinding(urlFormat, userName, password, domain, testSite); Common.InitializeServiceBinding(this.exchangeServiceBinding, testSite); }
/// <summary> /// Overrides IAdapter's Initialize() and sets default protocol short name of the testSite. /// </summary> /// <param name="testSite">Pass ITestSite to adapter, make adapter can use ITestSite's function</param> public override void Initialize(ITestSite testSite) { base.Initialize(testSite); testSite.DefaultProtocolDocShortName = "MS-OXWSCORE"; Common.MergeConfiguration(testSite); string userName = Common.GetConfigurationPropertyValue("User1Name", testSite); string password = Common.GetConfigurationPropertyValue("User1Password", testSite); string domain = Common.GetConfigurationPropertyValue("Domain", testSite); string url = Common.GetConfigurationPropertyValue("ServiceUrl", testSite); this.exchangeServiceBinding = new ExchangeServiceBinding(url, userName, password, domain, testSite); Common.InitializeServiceBinding(this.exchangeServiceBinding, testSite); this.itemAdapter = Site.GetAdapter <IMS_OXWSITEMIDAdapter>(); }
/// <summary> /// Overrides IAdapter's Initialize() and sets default protocol short name of the testSite. /// </summary> /// <param name="testSite">Pass ITestSite to adapter, make adapter can use ITestSite's function</param> public override void Initialize(TestTools.ITestSite testSite) { base.Initialize(testSite); testSite.DefaultProtocolDocShortName = "MS-OXWSSYNC"; // Merge configuration files. Common.MergeConfiguration(testSite); // Get the parameters from configuration files. this.userName = Common.GetConfigurationPropertyValue("User1Name", testSite); this.password = Common.GetConfigurationPropertyValue("User1Password", testSite); this.domain = Common.GetConfigurationPropertyValue("Domain", testSite); this.url = Common.GetConfigurationPropertyValue("ServiceUrl", testSite); this.exchangeServiceBinding = new ExchangeServiceBinding(this.url, this.userName, this.password, this.domain, testSite); Common.InitializeServiceBinding(this.exchangeServiceBinding, testSite); }
private static ExchangeServiceBinding CreateBinding(string email) { NetworkServiceImpersonator.Initialize(); if (NetworkServiceImpersonator.Exception != null) { ExTraceGlobals.ELCTracer.TraceError<LocalizedException>(0L, "Unable to impersonate network service to call EWS due to exception {0}", NetworkServiceImpersonator.Exception); throw new ElcUserConfigurationException(Strings.ElcUserConfigurationServiceBindingNotAvailable, NetworkServiceImpersonator.Exception); } ExchangeServiceBinding exchangeServiceBinding = new ExchangeServiceBinding(new RemoteCertificateValidationCallback(StoreRetentionPolicyTagHelper.CertificateErrorHandler)); exchangeServiceBinding.UserAgent = WellKnownUserAgent.GetEwsNegoAuthUserAgent("MRMTask"); exchangeServiceBinding.RequestServerVersionValue = new RequestServerVersion { Version = ExchangeVersionType.Exchange2010_SP1 }; StoreRetentionPolicyTagHelper.SetSecurityHeader(exchangeServiceBinding, email); return exchangeServiceBinding; }
/// <summary> /// Overrides IAdapter's Initialize() and sets default protocol short name of the testSite. /// </summary> /// <param name="testSite">Pass ITestSite to adapter, make adapter can use ITestSite's function</param> public override void Initialize(ITestSite testSite) { base.Initialize(testSite); testSite.DefaultProtocolDocShortName = "MS-OXWSTASK"; // Execute the merge the configuration Common.MergeConfiguration(testSite); // Get the parameters from configuration files. string userName = Common.GetConfigurationPropertyValue("UserName", testSite); string password = Common.GetConfigurationPropertyValue("UserPassword", testSite); string domain = Common.GetConfigurationPropertyValue("Domain", testSite); string url = Common.GetConfigurationPropertyValue("ServiceUrl", testSite); this.exchangeServiceBinding = new ExchangeServiceBinding(url, userName, password, domain, testSite); Common.InitializeServiceBinding(this.exchangeServiceBinding, testSite); this.exchangeServiceBinding.SoapVersion = SoapProtocolVersion.Soap11; }
public virtual IExchangeService CreateBinding(RemoteCertificateValidationCallback certificateErrorHandler) { bool flag = true; NetworkServiceImpersonator.Initialize(); if (NetworkServiceImpersonator.Exception != null) { if (this.IsTraceEnabled(TraceType.ErrorTrace)) { this.Tracer.TraceError <LocalizedException>(0L, "Unable to impersonate network service to call EWS due to exception {0}", NetworkServiceImpersonator.Exception); } flag = false; } ExchangeServiceBinding exchangeServiceBinding = new ExchangeServiceBinding(certificateErrorHandler); exchangeServiceBinding.UserAgent = WellKnownUserAgent.GetEwsNegoAuthUserAgent("AuditLog"); exchangeServiceBinding.RequestServerVersionValue = new RequestServerVersion { Version = ExchangeVersionType.Exchange2013 }; if (flag) { exchangeServiceBinding.Authenticator = SoapHttpClientAuthenticator.CreateNetworkService(); } else { exchangeServiceBinding.Authenticator = SoapHttpClientAuthenticator.Create(CredentialCache.DefaultCredentials); } exchangeServiceBinding.Authenticator.AdditionalSoapHeaders.Add(new OpenAsAdminOrSystemServiceType { ConnectingSID = new ConnectingSIDType { Item = new PrimarySmtpAddressType { Value = this.GetSmtpAddress() } }, LogonType = SpecialLogonType.SystemService, BudgetType = (int)this.budgetType, BudgetTypeSpecified = true }); return(exchangeServiceBinding); }
/// <summary> /// Overrides IAdapter's Initialize() and sets default protocol short name of the testSite. /// </summary> /// <param name="testSite">Pass ITestSite to adapter, make adapter can use ITestSite's function.</param> public override void Initialize(TestTools.ITestSite testSite) { base.Initialize(testSite); // Merge the common configuration into local configuration string commonConfigFileName = Common.GetConfigurationPropertyValue("CommonConfigurationFileName", testSite); Common.MergeGlobalConfig(commonConfigFileName, testSite); // Get the parameters from configuration files. string userName = Common.GetConfigurationPropertyValue("User1Name", testSite); string password = Common.GetConfigurationPropertyValue("User1Password", testSite); string domain = Common.GetConfigurationPropertyValue("Domain", testSite); string urlFormat = Common.GetConfigurationPropertyValue("ServiceUrl", testSite); // initialize service. this.exchangeServiceBinding = new ExchangeServiceBinding(urlFormat, userName, password, domain, testSite); Common.InitializeServiceBinding(this.exchangeServiceBinding, testSite); }
/// <summary> /// Overrides IAdapter's Initialize() and sets default protocol short name of the testSite. /// </summary> /// <param name="testSite">Pass ITestSite to adapter, make adapter can use ITestSite's function.</param> public override void Initialize(TestTools.ITestSite testSite) { // Initialize. base.Initialize(testSite); testSite.DefaultProtocolDocShortName = "MS-OXWSFOLD"; // Merge the common configuration into local configuration. Common.MergeConfiguration(testSite); // Get the parameters from configuration files. string userName = Common.GetConfigurationPropertyValue("User1Name", testSite); string password = Common.GetConfigurationPropertyValue("User1Password", testSite); string domain = Common.GetConfigurationPropertyValue("Domain", testSite); string urlFormat = Common.GetConfigurationPropertyValue("ServiceUrl", testSite); // Initialize service. this.exchangeServiceBinding = new ExchangeServiceBinding(urlFormat, userName, password, domain, testSite); Common.InitializeServiceBinding(this.exchangeServiceBinding, testSite); }
private ResponseMessageType[] GetFolderItems(ExchangeServiceBinding svc, DistinguishedFolderIdNameType folder) { // Form the FindItem request. FindItemType findItemRequest = new FindItemType(); findItemRequest.Traversal = ItemQueryTraversalType.Shallow; // Define which item properties are returned in the response. ItemResponseShapeType itemProperties = new ItemResponseShapeType(); itemProperties.BaseShape = DefaultShapeNamesType.AllProperties; //Define propriedade que armazena antigo ID PathToExtendedFieldType netShowUrlPath = new PathToExtendedFieldType(); netShowUrlPath.PropertyTag = "0x3A4D"; netShowUrlPath.PropertyType = MapiPropertyTypeType.String; //Adiciona propriedade na busca itemProperties.AdditionalProperties = new BasePathToElementType[1]; itemProperties.AdditionalProperties[0] = netShowUrlPath; // Add properties shape to the request. findItemRequest.ItemShape = itemProperties; // Identify which folders to search to find items. DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[2]; folderIDArray[0] = new DistinguishedFolderIdType(); folderIDArray[0].Id = folder; // Add folders to the request. findItemRequest.ParentFolderIds = folderIDArray; // Send the request and get the response. FindItemResponseType findItemResponse = svc.FindItem(findItemRequest); // Get the response messages. ResponseMessageType[] rmta = findItemResponse.ResponseMessages.Items; return(rmta); }
internal static ExchangeServiceBinding BuildChannel(string hostname, string username, string password) { // First, set up the binding to Exchange Web Services. ExchangeServiceBinding binding = new ExchangeServiceBinding(); Uri epUri = new Uri(hostname); // Add prefix unless user specifies one himself if (!hostname.EndsWith(".asmx", StringComparison.InvariantCultureIgnoreCase)) { epUri = new Uri(epUri, "/EWS/Exchange.asmx"); } binding.Credentials = new NetworkCredential(username, password); binding.Url = epUri.ToString(); binding.RequestServerVersionValue = new RequestServerVersion { Version = ExchangeVersionType.Exchange2007_SP1 }; return(binding); }
/// <summary> /// Отправляет электронное письмо /// </summary> /// <param name="subject">Тема письма</param> /// <param name="body">Текст письма</param> public static void SendMail(string subject, string body) { using (ExchangeServiceBinding bind = new ExchangeServiceBinding()) { bind.Credentials = new NetworkCredential(Username, Password, Domain); bind.Url = "https://" + Host + "/EWS/Exchange.asmx"; bind.RequestServerVersionValue = new RequestServerVersion(); bind.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2007_SP1; CreateItemType createItemRequest = new CreateItemType { Items = new NonEmptyArrayOfAllItemsType(), MessageDispositionSpecified = true, MessageDisposition = MessageDispositionType.SendOnly }; MessageType message = new MessageType(); message.ToRecipients = new EmailAddressType[1]; message.ToRecipients[0] = new EmailAddressType(); message.ToRecipients[0].EmailAddress = ToRecipient; message.Subject = subject; message.Body = new BodyType(); message.Body.BodyType1 = BodyTypeType.Text; message.Body.Value = body; createItemRequest.Items.Items = new ItemType[1]; createItemRequest.Items.Items[0] = message; CreateItemResponseType createItemResponse = bind.CreateItem(createItemRequest); ArrayOfResponseMessagesType responseMessages = createItemResponse.ResponseMessages; ResponseMessageType[] responseMessage = responseMessages.Items; foreach (ResponseMessageType rmt in responseMessage.Where(rmt => rmt.ResponseClass == ResponseClassType.Error)) { throw new Exception(rmt.MessageText); } } }
public void CallEWS(ref DataGridViewRow row, string srcUserMail, string tgtUserMail) { try { ConfigData data = new ConfigData(); string ewsSrcUrl = string.Format("https://{0}/ews/exchange.asmx", data.SourceServer); ExchangeServiceBinding exSrcServer = this.GetService(data.SourceAdminUser, data.SourceAdminPassword, srcUserMail, ewsSrcUrl, ExchangeVersionType.Exchange2010_SP1); string ewsTgtUrl = string.Format("https://{0}/ews/exchange.asmx", data.TargetServer); ExchangeServiceBinding exTgtServer = this.GetService(data.TargetAdminUser, data.TargetAdminPassword, tgtUserMail, ewsTgtUrl, ExchangeVersionType.Exchange2010_SP1); //Migrando Tarefas Tools.SetRowValue(ref row, EColumns.steps, "2- Tasks"); Tools.SetRowValue(ref row, EColumns.results, string.Empty); MigrateItens(ref row, exSrcServer, exTgtServer, DistinguishedFolderIdNameType.contacts, srcUserMail, tgtUserMail); //this.MigrateTasks(ref row, exSrcServer, exTgtServer); ////Migrando Contatos //Tools.SetRowValue(ref row, EColumns.steps, "3- Contacts"); //Tools.SetRowValue(ref row, EColumns.results, string.Empty); //this.MigrateContacts(ref row, exSrcServer, exTgtServer); ////Migrando Calendario //Tools.SetRowValue(ref row, EColumns.steps, "4- Calendars"); //Tools.SetRowValue(ref row, EColumns.results, string.Empty); //this.MigrateCalendar(ref row, exSrcServer, exTgtServer); } catch (Exception erro) { throw new Exception("Erro:" + erro.Message); } }
private ExchangeServiceBinding GetService(string adminUserName, string adminPassword, string userMail, string ewsUrl, ExchangeVersionType exVersion) { //Ignorar validação de certificado ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(OnValidationCallback); // Identify the service binding and the user. ExchangeServiceBinding service = new ExchangeServiceBinding(); service.RequestServerVersionValue = new RequestServerVersion(); service.RequestServerVersionValue.Version = exVersion; service.Credentials = new NetworkCredential(adminUserName, adminPassword); service.Url = ewsUrl; //Impersonating user context ExchangeImpersonationType exExchangeImpersonation = new ExchangeImpersonationType(); ConnectingSIDType csConnectingSid = new ConnectingSIDType(); csConnectingSid.Item = userMail; exExchangeImpersonation.ConnectingSID = csConnectingSid; service.ExchangeImpersonation = exExchangeImpersonation; return(service); }
private static void TraceResponse(IAsyncResult asyncResult) { ExchangeServiceBinding exchangeServiceBinding = (ExchangeServiceBinding)asyncResult.AsyncState; RefreshSharingFolderClient.Tracer.TraceDebug <string>(0L, "Received RefreshSharingFolder response from {0}", exchangeServiceBinding.Url); Exception ex = null; try { exchangeServiceBinding.EndRefreshSharingFolder(asyncResult); } catch (SoapException ex2) { ex = ex2; } catch (WebException ex3) { ex = ex3; } catch (IOException ex4) { ex = ex4; } catch (InvalidOperationException ex5) { ex = ex5; } catch (LocalizedException ex6) { ex = ex6; } if (ex != null) { RefreshSharingFolderClient.Tracer.TraceError <Exception>(0L, "Exception when receiving response from RefreshSharingFolder: {0}", ex); } }
public static List <CalendarObject> GetCalendarData(DateTime lookupDate) { List <CalendarObject> calendarObjects = new List <CalendarObject>(); //umdemo.dnsalias.com explicit credentials ExchangeServiceBinding exchangeServer = new ExchangeServiceBinding(); ICredentials creds = new NetworkCredential(user, password, "um.test.com"); exchangeServer.Credentials = creds; exchangeServer.Url = @"http://um.test.com/ews/exchange.asmx"; GetUserAvailabilityRequestType request = new GetUserAvailabilityRequestType(); MailboxData[] mailboxes = new MailboxData[1]; mailboxes[0] = new MailboxData(); // Identify the user mailbox to review their Free/Busy data EmailAddress emailAddress = new EmailAddress(); emailAddress.Address = "*****@*****.**"; emailAddress.Name = String.Empty; mailboxes[0].Email = emailAddress; request.MailboxDataArray = mailboxes; //Set TimeZone request.TimeZone = new SerializableTimeZone(); request.TimeZone.Bias = 480; request.TimeZone.StandardTime = new SerializableTimeZoneTime(); request.TimeZone.StandardTime.Bias = 0; request.TimeZone.StandardTime.DayOfWeek = DayOfWeekType.Sunday.ToString(); request.TimeZone.StandardTime.DayOrder = 1; request.TimeZone.StandardTime.Month = 11; request.TimeZone.StandardTime.Time = "02:00:00"; request.TimeZone.DaylightTime = new SerializableTimeZoneTime(); request.TimeZone.DaylightTime.Bias = -60; request.TimeZone.DaylightTime.DayOfWeek = DayOfWeekType.Sunday.ToString(); request.TimeZone.DaylightTime.DayOrder = 2; request.TimeZone.DaylightTime.Month = 3; request.TimeZone.DaylightTime.Time = "02:00:00"; // Identify the time to compare if the user is Free/Busy Duration duration = new Duration(); duration.StartTime = lookupDate; duration.EndTime = lookupDate.AddDays(1); // Identify the options for comparing F/B FreeBusyViewOptionsType viewOptions = new FreeBusyViewOptionsType(); viewOptions.TimeWindow = duration; viewOptions.RequestedView = FreeBusyViewType.Detailed; viewOptions.RequestedViewSpecified = true; request.FreeBusyViewOptions = viewOptions; GetUserAvailabilityResponseType response = exchangeServer.GetUserAvailability(request); foreach (FreeBusyResponseType responseType in response.FreeBusyResponseArray) { if (responseType.FreeBusyView.CalendarEventArray.Length > 0) { foreach (CalendarEvent calendar in responseType.FreeBusyView.CalendarEventArray) { CalendarObject calendarObject = new CalendarObject(); calendarObject.Location = calendar.CalendarEventDetails.Location; calendarObject.Subject = calendar.CalendarEventDetails.Subject; calendarObject.StartDate = calendar.StartTime; calendarObject.EndDate = calendar.EndTime; calendarObject.IsMeeting = calendar.CalendarEventDetails.IsMeeting; calendarObjects.Add(calendarObject); } } } return(calendarObjects); }
private void MigrateItens(ref DataGridViewRow row, ExchangeServiceBinding srcService, ExchangeServiceBinding tgtService, DistinguishedFolderIdNameType folder, string srcUserMail, string tgtUserMail) { ResponseMessageType[] itemsResponse = this.GetFolderItems(srcService, folder); ExportItemsType exExportItems = new ExportItemsType(); foreach (ResponseMessageType responseMessage in itemsResponse) { FindItemResponseMessageType firmt = responseMessage as FindItemResponseMessageType; FindItemParentType fipt = firmt.RootFolder; object obj = fipt.Item; int count = 0; // FindItem contains an array of items. if (obj is ArrayOfRealItemsType) { ArrayOfRealItemsType items = (obj as ArrayOfRealItemsType); exExportItems.ItemIds = new ItemIdType[(items.Items.Count() + 1)]; foreach (ItemType it in items.Items) { exExportItems.ItemIds[count] = new ItemIdType(); exExportItems.ItemIds[count].Id = it.ItemId.Id; count++; } } } ExportItemsResponseType exResponse = srcService.ExportItems(exExportItems); ResponseMessageType[] rmResponses = exResponse.ResponseMessages.Items; UploadItemsType upUploadItems = new UploadItemsType(); upUploadItems.Items = new UploadItemType[(rmResponses.Length + 1)]; Int32 icItemCount = 0; foreach (ResponseMessageType rmReponse in rmResponses) { if (rmReponse.ResponseClass == ResponseClassType.Success) { ExportItemsResponseMessageType exExportedItem = (ExportItemsResponseMessageType)rmReponse; Byte[] messageBytes = exExportedItem.Data; UploadItemType upUploadItem = new UploadItemType(); upUploadItem.CreateAction = CreateActionType.UpdateOrCreate; upUploadItem.Data = messageBytes; upUploadItem.IsAssociatedSpecified = true; upUploadItem.IsAssociated = false; upUploadItems.Items[icItemCount] = upUploadItem; FolderIdManager folderIdMgr = new FolderIdManager(); FolderIdType folderId = new FolderIdType(); folderId.Id = folderIdMgr.GetFolderId(tgtUserMail, Microsoft.Exchange.WebServices.Data.WellKnownFolderName.Contacts, Microsoft.Exchange.WebServices.Data.ExchangeVersion.Exchange2010_SP2); upUploadItem.ParentFolderId = folderId; icItemCount += 1; } } //Erro de Internal Server Error nessa etapa UploadItemsResponseType upLoadResponse = tgtService.UploadItems(upUploadItems); Int32 Success = 0; Int32 Failure = 0; foreach (ResponseMessageType upResponse in upLoadResponse.ResponseMessages.Items) { if (upResponse.ResponseClass == ResponseClassType.Success) { Success++; } if (upResponse.ResponseClass == ResponseClassType.Error) { Failure++; } } string resTask = string.Format("Items Copied Sucessfull : {0} - Failure: {1}", Success, Failure); Tools.SetRowValue(ref row, EColumns.results, resTask); //iv.Offset += fiItems.Items.Count; }
static void CreateFolder(ExchangeServiceBinding esb, FolderIdType fiFolderID, String fnFldName) { // Create the request FolderType folder = new FolderType(); folder.DisplayName = fnFldName; TargetFolderIdType targetID = new TargetFolderIdType(); targetID.Item = fiFolderID; CreateFolderType createFolder = new CreateFolderType(); createFolder.Folders = new FolderType[] { folder }; createFolder.ParentFolderId = targetID; try { // Send the request and get the response CreateFolderResponseType response = esb.CreateFolder(createFolder); // Get the response messages ResponseMessageType[] rmta = response.ResponseMessages.Items; } catch (Exception e) { string problem = e.Message; } }
static void MoveFolder(ExchangeServiceBinding esb, FolderIdType sourceFolderID, FolderIdType destinationFolderID) { MoveFolderType moveFolder = new MoveFolderType(); moveFolder.FolderIds = new FolderIdType[] { sourceFolderID }; TargetFolderIdType targetID = new TargetFolderIdType(); targetID.Item = destinationFolderID; moveFolder.ToFolderId = targetID; try { // Send the request and get the response MoveFolderResponseType response = esb.MoveFolder(moveFolder); // Get the response messages ResponseMessageType[] rmta = response.ResponseMessages.Items; } catch (Exception e) { string problem = e.Message; } }
static ExchangeServiceBinding CreateESB() { // Define the service binding and the user account to use. ExchangeServiceBinding esb = new ExchangeServiceBinding(); esb.RequestServerVersionValue = new RequestServerVersion(); esb.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2007_SP1; // use credentials of currently logged in user esb.UseDefaultCredentials = true; //esb.Credentials = new NetworkCredential("michael.devenney", "Sigmaphi2", "Veritas"); esb.Url = @"https://sites/EWS/Exchange.asmx"; return esb; }
/// <summary> /// Set user mailbox Out of Office state. /// </summary> /// <param name="mailAddress">User's email address.</param> /// <param name="password">Password of user mailbox.</param> /// <param name="isOOF">If true, set OOF state, else make sure OOF state is not set (clear OOF state).</param> /// <returns>If the operation succeed then return true, otherwise return false.</returns> public bool SetUserOOFSettings(string mailAddress, string password, bool isOOF) { using (ExchangeServiceBinding service = new ExchangeServiceBinding()) { service.Url = Common.GetConfigurationPropertyValue(Constants.SetOOFWebServiceURL, this.Site); if (service.Url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { this.AcceptServerCertificate(); } service.Credentials = new System.Net.NetworkCredential(mailAddress, password); EmailAddress emailAddress = new EmailAddress { Address = mailAddress, Name = string.Empty }; UserOofSettings userSettings = new UserOofSettings { // Identify the external audience. ExternalAudience = ExternalAudience.Known }; // Create the OOF reply messages. ReplyBody replyBody = new ReplyBody { Message = Constants.MessageOfOOFReply }; userSettings.ExternalReply = replyBody; userSettings.InternalReply = replyBody; // Set OOF state. if (isOOF) { userSettings.OofState = OofState.Enabled; } else { userSettings.OofState = OofState.Disabled; } // Create the request. SetUserOofSettingsRequest request = new SetUserOofSettingsRequest { Mailbox = emailAddress, UserOofSettings = userSettings }; bool success = false; try { SetUserOofSettingsResponse response = service.SetUserOofSettings(request); if (response.ResponseMessage.ResponseCode == ResponseCodeType.NoError) { success = true; } } catch (System.Xml.Schema.XmlSchemaValidationException e) { // Catch the following critical exceptions, other unexpected exceptions will be emitted to protocol test framework. Site.Log.Add(LogEntryKind.Debug, "An XML schema exception happened. The exception type is {0}.\n The exception message is {1}.", e.GetType().ToString(), e.Message); } catch (System.Xml.XmlException e) { Site.Log.Add(LogEntryKind.Debug, "An XML schema exception happened. The exception type is {0}.\n The exception message is {1}.", e.GetType().ToString(), e.Message); } catch (System.Reflection.TargetException e) { Site.Log.Add(LogEntryKind.Debug, "An operation exception happened when invoke Soap operation. The exception type is {0}.\n The exception message is {1}.", e.GetType().ToString(), e.Message); throw; } catch (System.IO.IOException e) { Site.Log.Add(LogEntryKind.Debug, "An IO exception happened when invoke Soap operation. The exception type is {0}.\n The exception message is {1}.", e.GetType().ToString(), e.Message); throw; } return(success); } }
/// <summary> /// Log on mailbox with specified user account. /// </summary> /// <param name="name">Name of the user.</param> /// <param name="userPassword">Password of the user.</param> /// <param name="userDomain">Domain of the user.</param> /// <param name="exchangeServiceBinding">An instance of Service Binding</param> /// <param name="site">An instance of ITestSite</param> /// <returns>If the user logs on mailbox successfully, return true; otherwise, return false.</returns> public static bool SwitchUser(string name, string userPassword, string userDomain, ExchangeServiceBinding exchangeServiceBinding, ITestSite site) { exchangeServiceBinding.Credentials = new NetworkCredential(name, userPassword, userDomain); // Verify the credential of the exchange service binding. bool isVerified = false; Uri uri = new Uri(Common.GetConfigurationPropertyValue("ServiceUrl", site)); NetworkCredential credential = exchangeServiceBinding.Credentials.GetCredential(uri, "basic"); if (credential.Domain == userDomain && credential.UserName == name) { isVerified = true; } return(isVerified); }
/// <summary> /// Set user mailbox Out of Office state. /// </summary> /// <param name="mailAddress">User's email address.</param> /// <param name="password">Password of user mailbox.</param> /// <param name="isOOF">If true, set OOF state, else make sure OOF state is not set (clear OOF state).</param> /// <returns>If the operation succeed then return true, otherwise return false.</returns> public bool SetUserOOFSettings(string mailAddress, string password, bool isOOF) { using (ExchangeServiceBinding service = new ExchangeServiceBinding()) { service.Url = Common.GetConfigurationPropertyValue(Constants.SetOOFWebServiceURL, this.Site); if (service.Url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { this.AcceptServerCertificate(); } service.Credentials = new System.Net.NetworkCredential(mailAddress, password); EmailAddress emailAddress = new EmailAddress { Address = mailAddress, Name = string.Empty }; UserOofSettings userSettings = new UserOofSettings { // Identify the external audience. ExternalAudience = ExternalAudience.Known }; // Create the OOF reply messages. ReplyBody replyBody = new ReplyBody { Message = Constants.MessageOfOOFReply }; userSettings.ExternalReply = replyBody; userSettings.InternalReply = replyBody; // Set OOF state. if (isOOF) { userSettings.OofState = OofState.Enabled; } else { userSettings.OofState = OofState.Disabled; } // Create the request. SetUserOofSettingsRequest request = new SetUserOofSettingsRequest { Mailbox = emailAddress, UserOofSettings = userSettings }; bool success = false; try { SetUserOofSettingsResponse response = service.SetUserOofSettings(request); if (response.ResponseMessage.ResponseCode == ResponseCodeType.NoError) { success = true; } } catch (System.Xml.Schema.XmlSchemaValidationException e) { // Catch the following critical exceptions, other unexpected exceptions will be emitted to protocol test framework. Site.Log.Add(LogEntryKind.Debug, "An XML schema exception happened. The exception type is {0}.\n The exception message is {1}.", e.GetType().ToString(), e.Message); } catch (System.Xml.XmlException e) { Site.Log.Add(LogEntryKind.Debug, "An XML schema exception happened. The exception type is {0}.\n The exception message is {1}.", e.GetType().ToString(), e.Message); } catch (System.Reflection.TargetException e) { Site.Log.Add(LogEntryKind.Debug, "An operation exception happened when invoke Soap operation. The exception type is {0}.\n The exception message is {1}.", e.GetType().ToString(), e.Message); throw; } catch (System.IO.IOException e) { Site.Log.Add(LogEntryKind.Debug, "An IO exception happened when invoke Soap operation. The exception type is {0}.\n The exception message is {1}.", e.GetType().ToString(), e.Message); throw; } return success; } }
static FolderIdType FindFolder(ExchangeServiceBinding esb, DistinguishedFolderIdType fiFolderID, String fnFldName) { FolderIdType rvFolderID = new FolderIdType(); // Create the request and specify the travesal type FindFolderType findFolderRequest = new FindFolderType(); findFolderRequest.Traversal = FolderQueryTraversalType.Deep; // Define the properties returned in the response FolderResponseShapeType responseShape = new FolderResponseShapeType(); responseShape.BaseShape = DefaultShapeNamesType.Default; findFolderRequest.FolderShape = responseShape; // Identify which folders to search DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1]; folderIDArray[0] = new DistinguishedFolderIdType(); folderIDArray[0].Id = fiFolderID.Id; //Add Restriction for DisplayName RestrictionType ffRestriction = new RestrictionType(); IsEqualToType ieToType = new IsEqualToType(); PathToUnindexedFieldType diDisplayName = new PathToUnindexedFieldType(); diDisplayName.FieldURI = UnindexedFieldURIType.folderDisplayName; FieldURIOrConstantType ciConstantType = new FieldURIOrConstantType(); ConstantValueType cvConstantValueType = new ConstantValueType(); cvConstantValueType.Value = fnFldName; ciConstantType.Item = cvConstantValueType; ieToType.Item = diDisplayName; ieToType.FieldURIOrConstant = ciConstantType; ffRestriction.Item = ieToType; findFolderRequest.Restriction = ffRestriction; // Add the folders to search to the request findFolderRequest.ParentFolderIds = folderIDArray; try { // Send the request and get the response FindFolderResponseType findFolderResponse = esb.FindFolder(findFolderRequest); // Get the response messages ResponseMessageType[] rmta = findFolderResponse.ResponseMessages.Items; foreach (ResponseMessageType rmt in rmta) { // Cast to the correct response message type FindFolderResponseMessageType ffResponse = (FindFolderResponseMessageType)rmt; foreach (FolderType fFoundFolder in ffResponse.RootFolder.Folders) { rvFolderID = fFoundFolder.FolderId; } } } catch (Exception e) { string problem = e.Message; } return rvFolderID; }