public Task MonitorForDisconnect(ServerEndpoint serverEndpoint, CancellationToken stoppingToken)
            {
                var tcs = new TaskCompletionSource <bool>();

                stoppingToken.Register(() => tcs.SetResult(true));
                return(tcs.Task);
            }
        /// <summary>
        /// This method allows a client to determine whether a server's endpoint is reachable and operational.
        /// </summary>
        /// <param name="endpoint">The endpoint used by PING request.</param>
        /// <param name="metatags">The meta tags in the response body of the Ping request type.</param>
        /// <param name="headers">The request and response header of the PING request type.</param>
        /// <returns>The status code of the PING request type.</returns>
        public uint PING(ServerEndpoint endpoint, out List <string> metatags, out WebHeaderCollection headers)
        {
            metatags = null;
            byte[] rawBuffer;
            WebHeaderCollection webHeaderCollection = AdapterHelper.InitializeHTTPHeader(RequestType.PING, AdapterHelper.ClientInstance, AdapterHelper.Counter);

            // Send the PING HTTP request and get the response.
            HttpWebResponse response = this.SendMAPIHttpRequest(this.userName, this.password, null, endpoint, AdapterHelper.SessionContextCookies, webHeaderCollection, out rawBuffer);

            headers = response.Headers;

            // Read the HTTP response buffer and parse the response to correct format.
            uint responseCode = AdapterHelper.GetFinalResponseCode(response.Headers["X-ResponseCode"]);

            CommonResponse commonResponse = CommonResponse.ParseCommonResponse(rawBuffer);

            if (responseCode == 0)
            {
                // PING succeeded when the response code equals zero and PING request has no response body.
                metatags = commonResponse.MetaTags;
                this.VerifyHTTPS(response);
                this.VerifyAuthentication(response);
                this.VerifyAutoDiscover(response.StatusCode, endpoint);
                this.VerifyHTTPHeaders(response.Headers);
                this.VerifyAdditionalHeaders(commonResponse.AdditionalHeaders);
                this.VerifyPINGRequestType(commonResponse, endpoint, responseCode);
                this.VerifyResponseMetaTags(commonResponse.MetaTags);
            }

            this.VerifyContentTypeHeader(response.Headers);
            this.VerifyRespondingToAllRequestTypeRequests(response, commonResponse, responseCode);
            response.GetResponseStream().Close();
            return(responseCode);
        }
        /// <summary>
        /// Executes the cmdlet.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            ExecuteClientAction(() =>
            {
                var resourceName           = default(string);
                var resourceGroupName      = default(string);
                var storageSyncServiceName = default(string);
                var parentResourceName     = default(string);

                if (this.IsParameterBound(c => c.ResourceId))
                {
                    var resourceIdentifier = new ResourceIdentifier(ResourceId);
                    resourceName           = resourceIdentifier.ResourceName;
                    resourceGroupName      = resourceIdentifier.ResourceGroupName;
                    parentResourceName     = resourceIdentifier.GetParentResourceName(StorageSyncConstants.SyncGroupTypeName, 0);
                    storageSyncServiceName = resourceIdentifier.GetParentResourceName(StorageSyncConstants.StorageSyncServiceTypeName, 1);
                }
                else if (this.IsParameterBound(c => c.InputObject))
                {
                    resourceName           = InputObject.ServerEndpointName;
                    resourceGroupName      = InputObject.ResourceGroupName;
                    parentResourceName     = InputObject.SyncGroupName;
                    storageSyncServiceName = InputObject.StorageSyncServiceName;
                }
                else
                {
                    resourceName           = Name;
                    resourceGroupName      = ResourceGroupName;
                    parentResourceName     = SyncGroupName;
                    storageSyncServiceName = StorageSyncServiceName;
                }

                var updateParameters = new ServerEndpointUpdateParameters()
                {
                    CloudTiering           = CloudTiering.IsPresent ? StorageSyncConstants.CloudTieringOn : StorageSyncConstants.CloudTieringOff,
                    VolumeFreeSpacePercent = VolumeFreeSpacePercent,
                    TierFilesOlderThanDays = TierFilesOlderThanDays,
                    OfflineDataTransfer    = OfflineDataTransfer.IsPresent ? "on" : "off"
                };

                Target = string.Join("/", resourceGroupName, storageSyncServiceName, parentResourceName, resourceName);
                if (ShouldProcess(Target, ActionMessage))
                {
                    ServerEndpoint resource = StorageSyncClientWrapper.StorageSyncManagementClient.ServerEndpoints.Update(
                        resourceGroupName,
                        storageSyncServiceName,
                        parentResourceName,
                        resourceName,
                        updateParameters);

                    WriteObject(resource);
                }
            });
        }
        public static void VerifyServerEndpointUpdateProperties(ServerEndpoint resource, bool useDefaults)
        {
            VerifyServerEndpointProperties(resource, useDefaults: false);

            if (useDefaults)
            {
                var defaults = GetDefaultServerEndpointUpdateParameters();
                Assert.Equal(resource.CloudTiering, defaults.CloudTiering);
                Assert.Equal(resource.VolumeFreeSpacePercent, defaults.VolumeFreeSpacePercent);
            }
        }
            public Task <bool> VerifyServer(ServerEndpoint serverEndpoint, HttpClient httpClient, CancellationToken stoppingToken)
            {
                _count++;
                if (_count == 2)
                {
                    LastAttemptDelta = DateTime.Now - _lastAttemptTime.Value;
                    _lastAttemptTime = DateTime.Now;
                    return(Task.FromResult(true));
                }

                _lastAttemptTime = DateTime.Now;
                return(Task.FromResult(false));
            }
Пример #6
0
        public Connection(ServerEndpoint endpoint, string joinKey, MultiplayerProxy proxy = null)
        {
            _endpoint = endpoint;
            _joinKey  = joinKey;

            _socket = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            if (proxy != null)
            {
                _socket.ProxyEndPoint = new IPEndPoint(IPAddress.Parse(proxy.Address), proxy.Port);
                _socket.ProxyType     = proxy.Type;

                if (proxy.Username != null)
                {
                    _socket.ProxyUser = proxy.Username;
                }

                if (proxy.Password != null)
                {
                    _socket.ProxyPass = proxy.Password;
                }
            }

            // TODO: check for functional non-transparent proxy connection per MultiplayerProxy.StrictProxyMode
            _socket.Connect(endpoint.Address, endpoint.Port);

            _stream = new NetworkStream(_socket);

            _serializer   = new BinarySerializer();
            _deserializer = new BinaryDeserializer();

            _socket.Send(new[] { (byte)Enums.ProtocolType.Binary });
            _socket.Send(_serializer.Serialize(new Message("join", joinKey)));

            OnMessage += (sender, message) => {
                if (message.Type == "playerio.joinresult")
                {
                    if (!message.GetBoolean(0))
                    {
                        throw new PlayerIOError((ErrorCode)message.GetInteger(1), message.GetString(2));
                    }

                    this.Connected = true;
                }
            };

            _deserializer.OnDeserializedMessage += (message) => OnMessage.Invoke(this, message);
            _stream.BeginRead(_buffer, 0, _buffer.Length, new AsyncCallback(this.ReceiveCallback), null);
        }
        public static void VerifyServerEndpointProperties(ServerEndpoint resource, bool useDefaults)
        {
            Assert.NotNull(resource);
            Assert.NotNull(resource.Id);
            Assert.NotNull(resource.Name);

            if (useDefaults)
            {
                var defaults = GetDefaultServerEndpointParameters(resource.ServerResourceId);
                Assert.Equal(resource.ServerResourceId, defaults.ServerResourceId);
                Assert.Equal(resource.ServerLocalPath, defaults.ServerLocalPath);
                Assert.Equal(resource.CloudTiering, defaults.CloudTiering);
                Assert.Equal(resource.VolumeFreeSpacePercent, defaults.VolumeFreeSpacePercent);
            }
        }
        /// <summary>
        /// Executes the cmdlet.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();
            ExecuteClientAction(() =>
            {
                var parentResourceIdentifier = default(ResourceIdentifier);

                if (this.IsParameterBound(c => c.ParentResourceId))
                {
                    parentResourceIdentifier = new ResourceIdentifier(ParentResourceId);

                    if (!string.Equals(StorageSyncConstants.SyncGroupType, parentResourceIdentifier.ResourceType, System.StringComparison.OrdinalIgnoreCase))
                    {
                        throw new PSArgumentException(StorageSyncResources.MissingParentResourceIdErrorMessage);
                    }
                }

                var createParameters = new ServerEndpointCreateParameters()
                {
                    CloudTiering                 = CloudTiering.ToBool() ? StorageSyncConstants.CloudTieringOn : StorageSyncConstants.CloudTieringOff,
                    VolumeFreeSpacePercent       = VolumeFreeSpacePercent,
                    ServerLocalPath              = ServerLocalPath,
                    ServerResourceId             = ServerResourceId,
                    TierFilesOlderThanDays       = TierFilesOlderThanDays,
                    OfflineDataTransfer          = OfflineDataTransfer.ToBool() ? StorageSyncConstants.OfflineDataTransferOn : StorageSyncConstants.OfflineDataTransferOff,
                    OfflineDataTransferShareName = OfflineDataTransferShareName
                };

                string resourceGroupName      = ResourceGroupName ?? ParentObject?.ResourceGroupName ?? parentResourceIdentifier.ResourceGroupName;
                string storageSyncServiceName = StorageSyncServiceName ?? ParentObject?.StorageSyncServiceName ?? parentResourceIdentifier.GetParentResourceName(StorageSyncConstants.StorageSyncServiceTypeName, 0);
                string syncGroupName          = SyncGroupName ?? ParentObject?.SyncGroupName ?? parentResourceIdentifier.ResourceName;

                Target = string.Join("/", resourceGroupName, storageSyncServiceName, syncGroupName, Name);
                if (ShouldProcess(Target, ActionMessage))
                {
                    ServerEndpoint resource = StorageSyncClientWrapper.StorageSyncManagementClient.ServerEndpoints.Create(
                        resourceGroupName,
                        storageSyncServiceName,
                        syncGroupName,
                        Name,
                        createParameters);

                    WriteObject(resource);
                }
            });
        }
Пример #9
0
        public bool ConnectGateway()
        {
            try
            {
                internetAccessAdapter = GetAdapterWithInternetAccess();

                log.LogInformation("Adapter with Internet Access: " + internetAccessAdapter);

                TCPClientGateway = new TcpClient();
                TCPClientGateway.Client.Connect(ServerEndpoint);

                UDPListen = true;
                TCPListen = true;

                SendMessageUDP(LocalHubInfo.Simplified(), ServerEndpoint);
                LocalHubInfo.InternalEndpoint = (IPEndPoint)UDPClientGateway.Client.LocalEndPoint;

                Thread.Sleep(550);
                SendMessageTCP(LocalHubInfo);

                Thread keepAlive = new Thread(new ThreadStart(delegate
                {
                    while (TCPClientGateway.Connected)
                    {
                        Thread.Sleep(5000);
                        SendMessageTCP(new KeepAlive(LocalHubInfo.Id));
                    }
                }))
                {
                    IsBackground = true
                };

                keepAlive.Start();

                hub.Publish(new GatewayConnectedEvent());

                return(true);
            }
            catch (Exception ex)
            {
                log.LogError($"Error when connecting to gateway {ServerEndpoint.ToString()}. Will retry again soon...", ex);
                hub.Publish(new GatewayErrorEvent($"Error when connecting to gateway {ServerEndpoint.ToString()}. Will retry again soon..."));
            }

            return(false);
        }
Пример #10
0
        /// <summary>
        /// Initialise.
        /// </summary>
        private void Initialise()
        {
            // Create the server.
            _server = new ServerEndpoint(_serverContextType, _multiEndpointModels, _maxNumClients);

            // For each server.
            for (int i = 0; i < _multiEndpointModels.Length; i++)
            {
                // Assign the on connect action handler.
                _server[i].Timeout                = 60;
                _server[i].ReadBufferSize         = 32768;
                _server[i].WriteBufferSize        = 32768;
                _server[i].ResponseBufferCapacity = 10000000;
                _server[i].RequestBufferCapacity  = 10000000;
                _server[i].Name        = "Custom Net Server";
                _server[i].ServiceName = "CustomNetServer";
            }
        }
Пример #11
0
        /// <summary>
        /// Dispose(bool disposing) executes in two distinct scenarios.  If disposing
        /// equals true, the method has been called directly or indirectly by a user's
        /// code. Managed and unmanaged resources can be disposed.  If disposing equals
        /// false, the method has been called by the runtime from inside the finalizer
        /// and you should not reference other objects. Only unmanaged resources can
        /// be disposed.
        /// </summary>
        protected virtual void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!this._disposed)
            {
                // Note disposing has been done.
                _disposed = true;

                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                if (disposing)
                {
                    // Dispose managed resources.
                    if (_server != null)
                    {
                        _server.Dispose();
                    }
                }

                // Call the appropriate methods to clean up
                // unmanaged resources here.
                _server = null;
            }
        }
 public Task MonitorForDisconnect(ServerEndpoint serverEndpoint, CancellationToken stoppingToken)
 {
     return(Task.CompletedTask);
 }
Пример #13
0
 public Disconnected(EndpointConnectionManager endpointConnectionManager,
                     ServerEndpoint serverEndpoint)
 {
     EndpointConnectionManager = endpointConnectionManager;
     ServerEndpoint            = serverEndpoint;
 }
        /// <summary>
        /// This method allows a client to determine whether a server's endpoint is reachable and operational.
        /// </summary>
        /// <param name="endpoint">The endpoint used by PING request.</param>
        /// <param name="metatags">The meta tags in the response body of the Ping request type.</param>
        /// <param name="headers">The request and response header of the PING request type.</param>
        /// <returns>The status code of the PING request type.</returns>
        public uint PING(ServerEndpoint endpoint, out List<string> metatags, out WebHeaderCollection headers)
        {
            metatags = null;
            byte[] rawBuffer;
            WebHeaderCollection webHeaderCollection = AdapterHelper.InitializeHTTPHeader(RequestType.PING, AdapterHelper.ClientInstance, AdapterHelper.Counter);

            // Send the PING HTTP request and get the response.
            HttpWebResponse response = this.SendMAPIHttpRequest(this.userName, this.password, null, endpoint, AdapterHelper.SessionContextCookies, webHeaderCollection, out rawBuffer);
            headers = response.Headers;

            // Read the HTTP response buffer and parse the response to correct format.
            uint responseCode = AdapterHelper.GetFinalResponseCode(response.Headers["X-ResponseCode"]);

            CommonResponse commonResponse = CommonResponse.ParseCommonResponse(rawBuffer);
            if (responseCode == 0)
            {
                // PING succeeded when the response code equals zero and PING request has no response body.
                metatags = commonResponse.MetaTags;
                this.VerifyHTTPS(response);
                this.VerifyAuthentication(response);
                this.VerifyAutoDiscover(response.StatusCode, endpoint);
                this.VerifyHTTPHeaders(response.Headers);
                this.VerifyAdditionalHeaders(commonResponse.AdditionalHeaders);
                this.VerifyPINGRequestType(commonResponse, endpoint, responseCode);
                this.VerifyResponseMetaTags(commonResponse.MetaTags);
            }

            this.VerifyContentTypeHeader(response.Headers);
            this.VerifyRespondingToAllRequestTypeRequests(response, commonResponse, responseCode);
            response.GetResponseStream().Close();
            return responseCode;
        }
Пример #15
0
 public Connection(ServerEndpoint endpoint, string joinKey)
 {
 }
        /// <summary>
        /// This method is used to send the http request.
        /// </summary>
        /// <param name="userName">The user name used to connect with server.</param>
        /// <param name="password">The password used to connect with server.</param>
        /// <param name="requestBody">The request body.</param>
        /// <param name="endpoint">The endpoint which the request would be send to.</param>
        /// <param name="cookies">Cookies used to identify the Session Context.</param>
        /// <param name="resquestHeaders">The specified request header used by the request.</param>
        /// <param name="rawBuffer">The raw buffer of the response.</param>
        /// <returns>The response of the request.</returns>
        private HttpWebResponse SendMAPIHttpRequest(string userName, string password, IRequestBody requestBody, ServerEndpoint endpoint, CookieCollection cookies, WebHeaderCollection resquestHeaders, out byte[] rawBuffer)
        {
            rawBuffer = null;
            HttpWebResponse response = null;
            AdapterHelper.Counter++;
            string url = string.Empty;
            if (endpoint == ServerEndpoint.MailboxServerEndpoint)
            {
                if (string.IsNullOrEmpty(this.mailStoreUrl))
                {
                    this.GetEndpointUrl();
                }

                url = this.mailStoreUrl;
            }
            else
            {
                if (string.IsNullOrEmpty(this.addressBookUrl))
                {
                    this.GetEndpointUrl();
                }

                url = this.addressBookUrl;
            }

            System.Net.ServicePointManager.ServerCertificateValidationCallback =
            new System.Net.Security.RemoteCertificateValidationCallback(Common.ValidateServerCertificate);
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.CookieContainer = new CookieContainer();
            request.Method = "POST";
            request.ProtocolVersion = HttpVersion.Version11;
            request.ContentType = "application/mapi-http";
            request.Credentials = new NetworkCredential(userName, password, this.domainName);
            request.Headers.Add(resquestHeaders);
            request.CookieContainer.Add(cookies);
            request.Timeout = System.Threading.Timeout.Infinite;

            byte[] buffer = null;
            if (requestBody != null)
            {
                buffer = requestBody.Serialize();
                request.ContentLength = buffer.Length;
            }
            else
            {
                request.ContentLength = 0;
            }   

            if (requestBody != null)
            {
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(buffer, 0, buffer.Length);
                }
            }

            try
            {
                response = request.GetResponse() as HttpWebResponse;

                // Read the HTTP response buffer and parse the response to correct format.
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    rawBuffer = this.ReadHttpResponse(response);
                }
            }
            catch (WebException ex)
            {
                this.Site.Log.Add(
                    LogEntryKind.Comment, 
                    "A WebException happened when connecting the server, The exception is {0}.",
                    ex.Message);
                return (HttpWebResponse)ex.Response;
            }

            return response;
        }
        /// <summary>
        /// Executes the cmdlet.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            ExecuteClientAction(() =>
            {
                var resourceName           = default(string);
                var resourceGroupName      = default(string);
                var storageSyncServiceName = default(string);
                var parentResourceName     = default(string);

                var updateParameters = new ServerEndpointUpdateParameters();

                if (this.IsParameterBound(c => c.InputObject))
                {
                    resourceName           = InputObject.ServerEndpointName;
                    resourceGroupName      = InputObject.ResourceGroupName;
                    parentResourceName     = InputObject.SyncGroupName;
                    storageSyncServiceName = InputObject.StorageSyncServiceName;

                    updateParameters.CloudTiering           = InputObject.CloudTiering;
                    updateParameters.VolumeFreeSpacePercent = InputObject.VolumeFreeSpacePercent;
                    updateParameters.TierFilesOlderThanDays = InputObject.TierFilesOlderThanDays;
                    updateParameters.OfflineDataTransfer    = InputObject.OfflineDataTransfer;
                }
                else
                {
                    if (this.IsParameterBound(c => c.ResourceId))
                    {
                        var resourceIdentifier = new ResourceIdentifier(ResourceId);
                        resourceName           = resourceIdentifier.ResourceName;
                        resourceGroupName      = resourceIdentifier.ResourceGroupName;
                        parentResourceName     = resourceIdentifier.GetParentResourceName(StorageSyncConstants.SyncGroupTypeName, 0);
                        storageSyncServiceName = resourceIdentifier.GetParentResourceName(StorageSyncConstants.StorageSyncServiceTypeName, 1);
                    }
                    else
                    {
                        resourceName           = Name;
                        resourceGroupName      = ResourceGroupName;
                        parentResourceName     = SyncGroupName;
                        storageSyncServiceName = StorageSyncServiceName;
                    }
                }

                if (this.IsParameterBound(c => c.CloudTiering))
                {
                    updateParameters.CloudTiering = CloudTiering.ToBool() ? StorageSyncConstants.CloudTieringOn : StorageSyncConstants.CloudTieringOff;
                }
                if (this.IsParameterBound(c => c.VolumeFreeSpacePercent))
                {
                    updateParameters.VolumeFreeSpacePercent = VolumeFreeSpacePercent;
                }
                if (this.IsParameterBound(c => c.TierFilesOlderThanDays))
                {
                    updateParameters.TierFilesOlderThanDays = TierFilesOlderThanDays;
                }
                if (this.IsParameterBound(c => c.OfflineDataTransfer))
                {
                    updateParameters.OfflineDataTransfer = OfflineDataTransfer.ToBool() ? StorageSyncConstants.OfflineDataTransferOn : StorageSyncConstants.OfflineDataTransferOff;
                }

                if (this.IsParameterBound(c => c.LocalCacheMode))
                {
                    updateParameters.LocalCacheMode = LocalCacheMode;
                }

                Target = string.Join("/", resourceGroupName, storageSyncServiceName, parentResourceName, resourceName);
                if (ShouldProcess(Target, ActionMessage))
                {
                    ServerEndpoint resource = StorageSyncClientWrapper.StorageSyncManagementClient.ServerEndpoints.Update(
                        resourceGroupName,
                        storageSyncServiceName,
                        parentResourceName,
                        resourceName,
                        updateParameters);

                    WriteObject(resource);
                }
            });
        }
        /// <summary>
        /// This method is used to send the http request.
        /// </summary>
        /// <param name="userName">The user name used to connect with server.</param>
        /// <param name="password">The password used to connect with server.</param>
        /// <param name="requestBody">The request body.</param>
        /// <param name="endpoint">The endpoint which the request would be send to.</param>
        /// <param name="cookies">Cookies used to identify the Session Context.</param>
        /// <param name="resquestHeaders">The specified request header used by the request.</param>
        /// <param name="rawBuffer">The raw buffer of the response.</param>
        /// <returns>The response of the request.</returns>
        private HttpWebResponse SendMAPIHttpRequest(string userName, string password, IRequestBody requestBody, ServerEndpoint endpoint, CookieCollection cookies, WebHeaderCollection resquestHeaders, out byte[] rawBuffer)
        {
            rawBuffer = null;
            HttpWebResponse response = null;

            AdapterHelper.Counter++;
            string url = string.Empty;

            if (endpoint == ServerEndpoint.MailboxServerEndpoint)
            {
                if (string.IsNullOrEmpty(this.mailStoreUrl))
                {
                    this.GetEndpointUrl();
                }

                url = this.mailStoreUrl;
            }
            else
            {
                if (string.IsNullOrEmpty(this.addressBookUrl))
                {
                    this.GetEndpointUrl();
                }

                url = this.addressBookUrl;
            }

            System.Net.ServicePointManager.ServerCertificateValidationCallback =
                new System.Net.Security.RemoteCertificateValidationCallback(Common.ValidateServerCertificate);
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            request.CookieContainer = new CookieContainer();
            request.Method          = "POST";
            request.ProtocolVersion = HttpVersion.Version11;
            request.ContentType     = "application/mapi-http";
            request.Credentials     = new NetworkCredential(userName, password, this.domainName);
            request.Headers.Add(resquestHeaders);
            request.CookieContainer.Add(cookies);
            request.Timeout = System.Threading.Timeout.Infinite;

            byte[] buffer = null;
            if (requestBody != null)
            {
                buffer = requestBody.Serialize();
                request.ContentLength = buffer.Length;
            }
            else
            {
                request.ContentLength = 0;
            }

            if (requestBody != null)
            {
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(buffer, 0, buffer.Length);
                }
            }

            try
            {
                response = request.GetResponse() as HttpWebResponse;

                // Read the HTTP response buffer and parse the response to correct format.
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    rawBuffer = this.ReadHttpResponse(response);
                }
            }
            catch (WebException ex)
            {
                this.Site.Log.Add(
                    LogEntryKind.Comment,
                    "A WebException happened when connecting the server, The exception is {0}.",
                    ex.Message);
                return((HttpWebResponse)ex.Response);
            }

            return(response);
        }
Пример #19
0
 protected virtual void ConstructManualEndpoints()
 {
     this.Auth     = new AuthEndpoint(this);
     this.Accounts = new AccountsEndpoint(this);
     this.Server   = new ServerEndpoint(this);
 }
Пример #20
0
        /// <summary>
        /// Verify the requirements related to AutoDiscover.
        /// </summary>
        /// <param name="httpStatusCode">The HttpStatusCode to be verified.</param>
        /// <param name="serverEndpoint">The value of server endpoint.</param>
        private void VerifyAutoDiscover(HttpStatusCode httpStatusCode, ServerEndpoint serverEndpoint)
        {
            // The status code in response is 200 OK which means client accesses server successfully.
            if (httpStatusCode == HttpStatusCode.OK)
            {
                if (serverEndpoint == ServerEndpoint.MailboxServerEndpoint)
                {
                    // Add the debug information
                    this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCMAPIHTTP_R1436: the URL {0} is returned in Autodiscover for mailbox server point.", this.mailStoreUrl.Replace("\0", string.Empty));

                    // Verify MS-OXCMAPIHTTP requirement: MS-OXCMAPIHTTP_R1436
                    // The value of mailStoreUri is returned from MailStore element in response of Autodiscover.
                    // So if the value of mailStoreUri follows the URI format, R1436 will be verified.
                    bool isVerifiedR1436 = Uri.IsWellFormedUriString(this.mailStoreUrl, UriKind.RelativeOrAbsolute);

                    this.Site.CaptureRequirementIfIsTrue(
                        isVerifiedR1436,
                        1436,
                        @"[In POST Method] A separate URI is returned in Autodiscover for mailbox server point.");

                    // Because the URI includes the information about destination server, request path and optional parameters.
                    // So if R1436 has been verified, the AutoDiscover has returned the URIs for accessing a given mailbox and R28 will be verified.
                    this.Site.CaptureRequirement(
                        28,
                        @"[In POST Method] The destination server, request path, and optional parameters for accessing a given mailbox are returned in URIs from Autodiscover.");

                    // Because client uses this URI to access mailbox server.
                    // So if the status code in response is 200 OK, then client uses the URI to access mailbox server.
                    // So MS-OXCMAPIHTTP_R30 will be verified.
                    this.Site.CaptureRequirement(
                        30,
                        @"[In POST Method] The URI is used by the server to route a request to the appropriate mailbox server.");
                }

                if (serverEndpoint == ServerEndpoint.AddressBookServerEndpoint)
                {
                    // Add the debug information
                    this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCMAPIHTTP_R1437: the URI {0} is returned in Autodiscover for address book server point.", this.addressBookUrl.Replace("\0", string.Empty));

                    // Verify MS-OXCMAPIHTTP requirement: MS-OXCMAPIHTTP_R1437
                    // The value of addressBookUri is returned from MailStore element in response of Autodiscover.
                    // So if the value of addressBookUri follows the URI format, then R1437 will be verified.
                    bool isVerifiedR1437 = Uri.IsWellFormedUriString(this.addressBookUrl, UriKind.RelativeOrAbsolute);

                    this.Site.CaptureRequirementIfIsTrue(
                        isVerifiedR1437,
                        1437,
                        @"[In POST Method] A separate URI is returned in Autodiscover for address book server point.");
                }

                // In the upper two if statements, one verified Mailbox server endpoint and another one verified AddressBook server endpoint.
                // The validity of URI is verified in all the two endpoints, so if code run to here, R459 is verified.
                this.Site.CaptureRequirement(
                    459,
                    @"[In Transport] The Autodiscover response, as specified in [MS-OXDSCLI], contains a URI that the client will use to access the two endpoints (4) used by this protocol: the mailbox sever endpoint (same as that used for the EMSMDB interface) and the address book server endpoint (same as that used for the NSPI interface).");
            }
        }
Пример #21
0
        /// <summary>
        /// Verify the PING request type related requirements.
        /// </summary>
        /// <param name="commonResponse">The CommonResponse to be verified.</param>
        /// <param name="endpoint">The value of server endpoint.</param>
        /// <param name="responseCode">The value of X-ResponseCode header.</param>
        private void VerifyPINGRequestType(CommonResponse commonResponse, ServerEndpoint endpoint, uint responseCode)
        {
            // Add the debug information
            this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCMAPIHTTP_R1460");

            // Verify MS-OXCMAPIHTTP requirement: MS-OXCMAPIHTTP_R1460
            this.Site.CaptureRequirementIfAreEqual<int>(
                0,
                commonResponse.ResponseBodyRawData.Length,
                1460,
                @"[In PING Request Type] The PING request type has no response body.");

            if (responseCode == 0 && endpoint == ServerEndpoint.MailboxServerEndpoint)
            {
                // If the code can reach here, that means the Mailbox server endpoint executes successfully, R1127 is verified successfully.
                this.Site.CaptureRequirement(
                    1127,
                    @"[In PING Request Type] The PING request type is supported by the mailbox server endpoint (4).");
            }
            else if (responseCode == 0 && endpoint == ServerEndpoint.AddressBookServerEndpoint)
            {
                // If the code can reach here, that means the AddressBook server endpoint executes successfully, R1128 is verified successfully.
                this.Site.CaptureRequirement(
                    1128,
                    @"[In PING Request Type] The PING request type is supported by the address book server endpoint (4).");
            }

            // Add the debug information
            this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCMAPIHTTP_R1247");
        
            // Verify MS-OXCMAPIHTTP requirement: MS-OXCMAPIHTTP_R1247
            // If the response is not null, that means the server responds to a PING request type.
            this.Site.CaptureRequirementIfIsNotNull(
                commonResponse,
                1247,
                @"[In Responding to a PING Request Type] The server responds to a PING request type by returning a PING request type response, as specified in section 2.2.6.");

            // Add the debug information
            this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCMAPIHTTP_R1249");
        
            // Verify MS-OXCMAPIHTTP requirement: MS-OXCMAPIHTTP_R1249
            this.Site.CaptureRequirementIfIsTrue(
                commonResponse.MetaTags.Count != 0 && commonResponse.ResponseBodyRawData.Length == 0,
                1249,
                @"[In Responding to a PING Request Type] Meta-tags can be returned, but no response body is returned.");
        }
 public Task <bool> VerifyServer(ServerEndpoint serverEndpoint, HttpClient httpClient, CancellationToken stoppingToken)
 {
     return(Task.FromResult(true));
 }
 public HttpClient CreateHttpClient(ServerEndpoint serverEndpoint)
 {
     return(_httpClientFactory(serverEndpoint));
 }
        public void ServerEndpointAllOperationsTest()
        {
            var handler = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                IResourceManagementClient    resourcesClient             = StorageSyncManagementTestUtilities.GetResourceManagementClient(context, handler);
                IStorageSyncManagementClient storageSyncManagementClient = StorageSyncManagementTestUtilities.GetStorageSyncManagementClient(context, handler);

                // Create ResourceGroup
                string resourceGroupName = StorageSyncManagementTestUtilities.CreateResourceGroup(resourcesClient);

                // Create ServerEndpoint
                string storageSyncServiceName = TestUtilities.GenerateName("sss-sepall");
                string syncGroupName          = TestUtilities.GenerateName("sg-sepall");
                string resourceName           = TestUtilities.GenerateName("sepall");

                var storageSyncServiceParameters = StorageSyncManagementTestUtilities.GetDefaultStorageSyncServiceParameters();
                var syncGroupParameters          = StorageSyncManagementTestUtilities.GetDefaultSyncGroupParameters();
                var cloudEndpointParameters      = StorageSyncManagementTestUtilities.GetDefaultCloudEndpointParameters();

                StorageSyncService storageSyncServiceResource = storageSyncManagementClient.StorageSyncServices.Create(resourceGroupName, storageSyncServiceName, storageSyncServiceParameters);
                Assert.NotNull(storageSyncServiceResource);
                StorageSyncManagementTestUtilities.VerifyStorageSyncServiceProperties(storageSyncServiceResource, true);

                SyncGroup syncGroupResource = storageSyncManagementClient.SyncGroups.Create(resourceGroupName, storageSyncServiceResource.Name, syncGroupName, syncGroupParameters);
                Assert.NotNull(syncGroupResource);
                StorageSyncManagementTestUtilities.VerifySyncGroupProperties(syncGroupResource, true);

                CloudEndpoint cloudEndpointResource = storageSyncManagementClient.CloudEndpoints.Create(resourceGroupName, storageSyncServiceResource.Name, syncGroupResource.Name, resourceName, cloudEndpointParameters);
                Assert.NotNull(cloudEndpointResource);
                StorageSyncManagementTestUtilities.VerifyCloudEndpointProperties(cloudEndpointResource, true);

                RegisteredServer registeredServerResource = EnsureRegisteredServerResource(storageSyncManagementClient, resourceGroupName, storageSyncServiceName, syncGroupName, storageSyncServiceResource);
                Assert.NotNull(registeredServerResource);

                StorageSyncManagementTestUtilities.VerifyRegisteredServerProperties(registeredServerResource, true);

                var serverEndpointParameters       = StorageSyncManagementTestUtilities.GetDefaultServerEndpointParameters(registeredServerResource.Id);
                var serverEndpointUpdateParameters = StorageSyncManagementTestUtilities.GetDefaultServerEndpointUpdateParameters();

                // Delete Test before it exists.
                storageSyncManagementClient.ServerEndpoints.Delete(resourceGroupName, storageSyncServiceResource.Name, syncGroupResource.Name, resourceName);

                ServerEndpoint serverEndpointResource = storageSyncManagementClient.ServerEndpoints.Create(resourceGroupName, storageSyncServiceResource.Name, syncGroupResource.Name, resourceName, serverEndpointParameters);
                Assert.NotNull(serverEndpointResource);
                StorageSyncManagementTestUtilities.VerifyServerEndpointProperties(serverEndpointResource, true);

                // GET Test
                serverEndpointResource = storageSyncManagementClient.ServerEndpoints.Get(resourceGroupName, storageSyncServiceResource.Name, syncGroupResource.Name, resourceName);
                Assert.NotNull(serverEndpointResource);
                StorageSyncManagementTestUtilities.VerifyServerEndpointProperties(serverEndpointResource, true);

                // List Test
                IEnumerable <ServerEndpoint> serverEndpoints = storageSyncManagementClient.ServerEndpoints.ListBySyncGroup(resourceGroupName, storageSyncServiceResource.Name, syncGroupResource.Name);
                Assert.Single(serverEndpoints);
                Assert.NotNull(serverEndpoints.Single());
                StorageSyncManagementTestUtilities.VerifyServerEndpointProperties(serverEndpoints.Single(), true);

                // Recall Test
                RecallActionParameters             recallActionParameters             = StorageSyncManagementTestUtilities.GetDefaultRecallActionParameters();
                ServerEndpointsRecallActionHeaders serverEndpointsRecallActionHeaders = storageSyncManagementClient.ServerEndpoints.RecallAction(resourceGroupName, storageSyncServiceResource.Name, syncGroupResource.Name, resourceName, recallActionParameters);
                Assert.NotNull(serverEndpointsRecallActionHeaders);
                Assert.NotEmpty(serverEndpointsRecallActionHeaders.XMsCorrelationRequestId);
                Assert.NotEmpty(serverEndpointsRecallActionHeaders.XMsRequestId);

                // Update Test
                serverEndpointResource = storageSyncManagementClient.ServerEndpoints.Update(resourceGroupName, storageSyncServiceResource.Name, syncGroupResource.Name, resourceName, serverEndpointUpdateParameters);
                Assert.NotNull(serverEndpointResource);
                StorageSyncManagementTestUtilities.VerifyServerEndpointUpdateProperties(serverEndpointResource, true);

                // Delete Test
                storageSyncManagementClient.ServerEndpoints.Delete(resourceGroupName, storageSyncServiceResource.Name, syncGroupResource.Name, resourceName);

                storageSyncManagementClient.CloudEndpoints.Delete(resourceGroupName, storageSyncServiceResource.Name, syncGroupName, resourceName);
                storageSyncManagementClient.SyncGroups.Delete(resourceGroupName, storageSyncServiceResource.Name, syncGroupName);
                storageSyncManagementClient.RegisteredServers.Delete(resourceGroupName, storageSyncServiceResource.Name, registeredServerResource.ServerId.Trim('"'));
                storageSyncManagementClient.StorageSyncServices.Delete(resourceGroupName, storageSyncServiceResource.Name);
                StorageSyncManagementTestUtilities.RemoveResourceGroup(resourcesClient, resourceGroupName);
            }
        }
Пример #25
0
 public Connection(ServerEndpoint endpoint, string joinKey)
 {
     //...
     Connected = true;
 }