Beispiel #1
0
        protected override void Response()
        {
            GOAEncryption enc =
                new GOAEncryption(_secretKey, _request.Challenge, SBServer.ServerChallenge);

            _sendingBuffer = new ServerListResponse().
                             CombineHeaderAndContext
                             (
                enc.Encrypt(_dataList.ToArray()),
                SBServer.ServerChallenge
                             );
            //refresh encryption state
            SBSession session = (SBSession)_session.GetInstance();

            session.EncState = enc.State;

            if (_sendingBuffer == null || _sendingBuffer.Length < 4)
            {
                return;
            }

            LogWriter.ToLog(LogEventLevel.Debug,
                            $"[Send] { StringExtensions.ReplaceUnreadableCharToHex(_dataList.ToArray(), 0, _dataList.Count)}");
            session.BaseSendAsync(_sendingBuffer);
        }
        /// <summary>
        /// Queries all / by default.
        /// </summary>
        private void GetAll()
        {
            ServerListResponse serverListResponse =
                RecoveryServicesClient.GetAzureSiteRecoveryServer();

            this.WriteServers(serverListResponse.Servers);
        }
        private static void ServerListCommand(object command)
        {
            ServerListRequest  request  = (ServerListRequest)command;
            ServerListResponse response = new ServerListResponse();
            string             address  = request.GetAddress();

            // Decode JSON stream
            try
            {
                string jsonStream;
                using (WebClient client = new WebClient())
                    jsonStream = Encoding.ASCII.GetString(client.DownloadData(address));

                response = Json.LoadStream <ServerListResponse>(jsonStream);
            }
            catch (Exception e)
            {
                Console.WriteLine("ServerList error: {0}", e.Message);
            }

            if (!String.IsNullOrEmpty(response.Token))
            {
                Console.WriteLine("Private token: {0}", response.Token);
                token = response.Token;
            }

            Console.WriteLine("Status: {0}; Reason: {1}", response.Status, response.Reason);
        }
        private static void ServerListCommand(object command)
        {
            ServerListRequest request = (ServerListRequest)command;
            ServerListResponse response = new ServerListResponse();
            string address = request.GetAddress();

            // Decode JSON stream
            try
            {
                string jsonStream;
                using (WebClient client = new WebClient())
                    jsonStream = Encoding.ASCII.GetString(client.DownloadData(address));

                response = Json.LoadStream<ServerListResponse>(jsonStream);
            }
            catch (Exception e)
            {
                Console.WriteLine("ServerList error: {0}", e.Message);
            }

            if (!String.IsNullOrEmpty(response.Token))
            {
                Console.WriteLine("Private token: {0}", response.Token);
                token = response.Token;
            }

            Console.WriteLine("Status: {0}; Reason: {1}", response.Status, response.Reason);
        }
        /// <summary>
        /// Queries by name.
        /// </summary>
        private void GetByName()
        {
            ServerListResponse serverListResponse =
                RecoveryServicesClient.GetAzureSiteRecoveryServer();

            bool found = false;

            foreach (Server server in serverListResponse.Servers)
            {
                if (0 == string.Compare(this.Name, server.Name, true))
                {
                    this.WriteServer(server);
                    found = true;
                }
            }

            if (!found)
            {
                throw new InvalidOperationException(
                          string.Format(
                              Properties.Resources.ServerNotFound,
                              this.Name,
                              PSRecoveryServicesClient.asrVaultCreds.ResourceName));
            }
        }
Beispiel #6
0
        private void OnServerListReceived(ServerListResponse e)
        {
            var handler = ServerListReceived;

            if (handler != null)
            {
                handler(this, e);
            }
        }
Beispiel #7
0
        /// <summary>
        /// Serializes this instance to a server list packet, which can be sent to the client.
        /// </summary>
        /// <returns>The serialized server list.</returns>
        public byte[] Serialize()
        {
            var result = this.Cache;

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

            byte[] packet;
            if (this.clientVersion.Season == 0)
            {
                packet = new byte[ServerListResponseOld.GetRequiredSize(this.Servers.Count)];
                var response = new ServerListResponseOld(packet)
                {
                    ServerCount = (byte)this.Servers.Count,
                };
                var i = 0;
                foreach (var server in this.Servers)
                {
                    var serverBlock = response[i];
                    serverBlock.ServerId       = (byte)server.ServerId;
                    serverBlock.LoadPercentage = server.ServerLoad;
                    i++;
                }
            }
            else
            {
                packet = new byte[ServerListResponse.GetRequiredSize(this.Servers.Count)];
                var response = new ServerListResponse(packet)
                {
                    ServerCount = (ushort)this.Servers.Count,
                };
                var i = 0;
                foreach (var server in this.Servers)
                {
                    var serverBlock = response[i];
                    serverBlock.ServerId       = server.ServerId;
                    serverBlock.LoadPercentage = server.ServerLoad;
                    i++;
                }
            }

            this.Cache = packet;
            return(packet);
        }
Beispiel #8
0
        private async void GetServerList()
        {
            currentFilter.offset = serverList.Count;
            string json = await DoHttpRequestAsync(URL.BF3SearchServers + SerializeFilter(currentFilter));

            ServerListResponse resp = await DeserializeResponse2Async <ServerListResponse>(json);

            foreach (var i in resp.data)
            {
                serverList.Add(i);
                string playerCountString = String.Format("{0}/{1}", i.slots.normal.current, i.slots.normal.max);
                if (i.slots.queued.current != 0)
                {
                    playerCountString = String.Format("{0} [{1}]", playerCountString, i.slots.queued.current);
                }
                serverBrowserView.Rows.Add(serverList.Count - 1, GetMapName(i.map), i.name, GetGameModeName(i.mapMode), playerCountString, '-');
                UpdatePing(serverList.Count - 1);
            }
        }
Beispiel #9
0
        /// <summary>
        /// Retrieves one or more servers in the current subscription.
        /// </summary>
        /// <param name="serverName">
        /// The specific name of the server to retrieve, or <c>null</c> to
        /// retrieve all servers in the current subscription.
        /// </param>
        /// <returns>A list of servers in the subscription.</returns>
        internal IEnumerable <SqlDatabaseServerContext> GetAzureSqlDatabaseServersProcess(string serverName)
        {
            // Get the SQL management client for the current subscription
            SqlManagementClient sqlManagementClient = GetCurrentSqlClient();

            // Retrieve the list of servers
            ServerListResponse response = sqlManagementClient.Servers.List();
            IEnumerable <Management.Sql.Models.Server> servers = response.Servers;

            if (!string.IsNullOrEmpty(serverName))
            {
                // Server name is specified, find the one with the
                // specified rule name and return that.
                servers = response.Servers.Where(s => s.Name == serverName);
                if (!servers.Any())
                {
                    throw new ItemNotFoundException(string.Format(
                                                        CultureInfo.InvariantCulture,
                                                        Resources.GetAzureSqlDatabaseServerNotFound,
                                                        serverName));
                }
            }
            else
            {
                // Server name is not specified, return all servers
                // in the subscription.
            }

            // Construct the result
            IEnumerable <SqlDatabaseServerContext> processResult = servers.Select(server => new SqlDatabaseServerContext
            {
                OperationStatus      = Services.Constants.OperationSuccess,
                OperationDescription = CommandRuntime.ToString(),
                OperationId          = response.RequestId,
                ServerName           = server.Name,
                Location             = server.Location,
                Version            = server.Version,
                AdministratorLogin = server.AdministratorUserName,
                State = server.State,
            });

            return(processResult);
        }
        private void ProcessServerListRequest(UdpMessage message)
        {
            Logger.Info(string.Format("{0} ServerList", message.RemoteEndPoint));

            //query server list and send results back

            var session = SessionHandler.GetSession(message.RemoteEndPoint);

            if (serverList.Any())
            {
                var    total       = (ushort)serverList.Count;
                ushort packetIndex = 0;

                serverList.Values.ToList().ForEach(serverInfo =>
                {
                    var serverListResponse = new ServerListResponse(message.RemoteEndPoint);
                    serverListResponse.AddSession(session);

                    serverListResponse.PacketIndex  = ++packetIndex;
                    serverListResponse.TotalPackets = total;

                    serverListResponse.Message = serverListResponse.WriteUdpMessage().Concat(serverInfo.WriteUdpMessage()).ToArray();

                    Send(serverListResponse);
                });
            }
            else
            {
                var serverListResponse = new ServerListResponse(message.RemoteEndPoint);
                serverListResponse.AddSession(session);

                serverListResponse.PacketIndex  = 1;
                serverListResponse.TotalPackets = 1;

                serverListResponse.Message = serverListResponse.WriteUdpMessage();

                Send(serverListResponse);
            }
        }
        void WebApiServerListReceived(object sender, ServerListResponse e)
        {
            var gui = _iocContainer.Get <GuiManager>();

            gui.RunInGuiThread(() => {
                var selection = _iocContainer.Get <ServerSelectionComponent>();

                if (e.Exception == null)
                {
                    selection.List.Items.Clear();

#if DEBUG
                    if (e.Servers == null)
                    {
                        e.Servers = new List <ServerInfo>();
                    }
                    e.Servers.Add(new ServerInfo {
                        ServerAddress = "127.0.0.1", Port = 4815, ServerName = "localhost"
                    });
#endif

                    if (e.Servers != null)
                    {
                        foreach (var serverInfo in e.Servers)
                        {
                            selection.List.Items.Add(string.Format("{0} ({1})", serverInfo.ServerName, serverInfo.UsersCount));
                        }
                        ServerList = e.Servers;
                    }
                }
                else
                {
                    selection.List.Items.Clear();
                    selection.List.Items.Add("Error!");
                }
            });
        }
Beispiel #12
0
        public static async Task OnHttpRequest(Microsoft.AspNetCore.Http.HttpContext e, DbUser u)
        {
            //Get servers
            var servers = await Program.connection.GetServersByOwnerAsync(u.id);

            //Convert
            ServerListResponse response = new ServerListResponse
            {
                servers = new List <ServerListResponseServer>(),
                token   = await u.GetServerCreationToken(Program.connection)
            };

            foreach (var s in servers)
            {
                //Get map
                string mapName = null;
                var    mapData = await s.GetMapEntryAsync(Program.connection);

                if (mapData != null)
                {
                    mapName = mapData.displayName;
                }

                //Write
                response.servers.Add(new ServerListResponseServer
                {
                    icon = s.image_url,
                    id   = s.id,
                    map  = mapName,
                    name = s.display_name
                });
            }

            //Write
            await Program.QuickWriteJsonToDoc(e, response);
        }
 private async void ViewDatabasesForServer(ServerListResponse.Server server)
 {
     SelectedServer = server;
     await GetSqlDatabaseList();
 }
        /// <summary>
        /// Returns information about an Azure SQL Database Server.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the Resource Group to which the server
        /// belongs.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Represents the response to a Get Database request.
        /// </returns>
        public async Task <ServerListResponse> ListAsync(string resourceGroupName, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
            }

            // Construct URL
            string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId == null ? "" : Uri.EscapeDataString(this.Client.Credentials.SubscriptionId)) + "/resourceGroups/" + Uri.EscapeDataString(resourceGroupName) + "/providers/Microsoft.Sql/servers?";

            url = url + "api-version=2014-04-01";
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    ServerListResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new ServerListResponse();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken valueArray = responseDoc["value"];
                            if (valueArray != null && valueArray.Type != JTokenType.Null)
                            {
                                foreach (JToken valueValue in ((JArray)valueArray))
                                {
                                    Server serverInstance = new Server();
                                    result.Servers.Add(serverInstance);

                                    JToken nameValue = valueValue["name"];
                                    if (nameValue != null && nameValue.Type != JTokenType.Null)
                                    {
                                        string nameInstance = ((string)nameValue);
                                        serverInstance.Name = nameInstance;
                                    }

                                    JToken propertiesValue = valueValue["properties"];
                                    if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
                                    {
                                        ServerProperties propertiesInstance = new ServerProperties();
                                        serverInstance.Properties = propertiesInstance;

                                        JToken fullyQualifiedDomainNameValue = propertiesValue["fullyQualifiedDomainName"];
                                        if (fullyQualifiedDomainNameValue != null && fullyQualifiedDomainNameValue.Type != JTokenType.Null)
                                        {
                                            string fullyQualifiedDomainNameInstance = ((string)fullyQualifiedDomainNameValue);
                                            propertiesInstance.FullyQualifiedDomainName = fullyQualifiedDomainNameInstance;
                                        }

                                        JToken versionValue = propertiesValue["version"];
                                        if (versionValue != null && versionValue.Type != JTokenType.Null)
                                        {
                                            string versionInstance = ((string)versionValue);
                                            propertiesInstance.Version = versionInstance;
                                        }

                                        JToken administratorLoginValue = propertiesValue["administratorLogin"];
                                        if (administratorLoginValue != null && administratorLoginValue.Type != JTokenType.Null)
                                        {
                                            string administratorLoginInstance = ((string)administratorLoginValue);
                                            propertiesInstance.AdministratorLogin = administratorLoginInstance;
                                        }

                                        JToken administratorLoginPasswordValue = propertiesValue["administratorLoginPassword"];
                                        if (administratorLoginPasswordValue != null && administratorLoginPasswordValue.Type != JTokenType.Null)
                                        {
                                            string administratorLoginPasswordInstance = ((string)administratorLoginPasswordValue);
                                            propertiesInstance.AdministratorLoginPassword = administratorLoginPasswordInstance;
                                        }
                                    }

                                    JToken idValue = valueValue["id"];
                                    if (idValue != null && idValue.Type != JTokenType.Null)
                                    {
                                        string idInstance = ((string)idValue);
                                        serverInstance.Id = idInstance;
                                    }

                                    JToken typeValue = valueValue["type"];
                                    if (typeValue != null && typeValue.Type != JTokenType.Null)
                                    {
                                        string typeInstance = ((string)typeValue);
                                        serverInstance.Type = typeInstance;
                                    }

                                    JToken locationValue = valueValue["location"];
                                    if (locationValue != null && locationValue.Type != JTokenType.Null)
                                    {
                                        string locationInstance = ((string)locationValue);
                                        serverInstance.Location = locationInstance;
                                    }

                                    JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
                                    if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
                                    {
                                        foreach (JProperty property in tagsSequenceElement)
                                        {
                                            string tagsKey   = ((string)property.Name);
                                            string tagsValue = ((string)property.Value);
                                            serverInstance.Tags.Add(tagsKey, tagsValue);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
        /// <summary>
        /// Returns all SQL Database Servers that are provisioned for a
        /// subscription.
        /// </summary>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response structure for the Server List operation.  Contains a
        /// list of all the servers in a subscription.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Sql.Models.ServerListResponse> ListAsync(CancellationToken cancellationToken)
        {
            // Validate

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = Tracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
            }

            // Construct URL
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            string url     = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers";

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("x-ms-version", "2012-03-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    ServerListResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    result = new ServerListResponse();
                    XDocument responseDoc = XDocument.Parse(responseContent);

                    XElement serversSequenceElement = responseDoc.Element(XName.Get("Servers", "http://schemas.microsoft.com/sqlazure/2010/12/"));
                    if (serversSequenceElement != null)
                    {
                        foreach (XElement serversElement in serversSequenceElement.Elements(XName.Get("Server", "http://schemas.microsoft.com/sqlazure/2010/12/")))
                        {
                            Server serverInstance = new Server();
                            result.Servers.Add(serverInstance);

                            XElement nameElement = serversElement.Element(XName.Get("Name", "http://schemas.microsoft.com/sqlazure/2010/12/"));
                            if (nameElement != null)
                            {
                                string nameInstance = nameElement.Value;
                                serverInstance.Name = nameInstance;
                            }

                            XElement administratorLoginElement = serversElement.Element(XName.Get("AdministratorLogin", "http://schemas.microsoft.com/sqlazure/2010/12/"));
                            if (administratorLoginElement != null)
                            {
                                string administratorLoginInstance = administratorLoginElement.Value;
                                serverInstance.AdministratorUserName = administratorLoginInstance;
                            }

                            XElement locationElement = serversElement.Element(XName.Get("Location", "http://schemas.microsoft.com/sqlazure/2010/12/"));
                            if (locationElement != null)
                            {
                                string locationInstance = locationElement.Value;
                                serverInstance.Location = locationInstance;
                            }

                            XElement fullyQualifiedDomainNameElement = serversElement.Element(XName.Get("FullyQualifiedDomainName", "http://schemas.microsoft.com/sqlazure/2010/12/"));
                            if (fullyQualifiedDomainNameElement != null)
                            {
                                string fullyQualifiedDomainNameInstance = fullyQualifiedDomainNameElement.Value;
                                serverInstance.FullyQualifiedDomainName = fullyQualifiedDomainNameInstance;
                            }

                            XElement stateElement = serversElement.Element(XName.Get("State", "http://schemas.microsoft.com/sqlazure/2010/12/"));
                            if (stateElement != null)
                            {
                                string stateInstance = stateElement.Value;
                                serverInstance.State = stateInstance;
                            }

                            XElement versionElement = serversElement.Element(XName.Get("Version", "http://schemas.microsoft.com/sqlazure/2010/12/"));
                            if (versionElement != null)
                            {
                                string versionInstance = versionElement.Value;
                                serverInstance.Version = versionInstance;
                            }
                        }
                    }

                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
        /// <summary>
        /// Returns all SQL Database servers that are provisioned for a
        /// subscription.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/gg715269.aspx
        /// for more information)
        /// </summary>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response structure for the Server List operation.
        /// </returns>
        public async Task <ServerListResponse> ListAsync(CancellationToken cancellationToken)
        {
            // Validate

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = Tracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
            }

            // Construct URL
            string url = new Uri(this.Client.BaseUri, "/").ToString() + this.Client.Credentials.SubscriptionId + "/services/sqlservers/servers";

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("x-ms-version", "2012-03-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    ServerListResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    result = new ServerListResponse();
                    XDocument responseDoc = XDocument.Parse(responseContent);

                    XElement serversSequenceElement = responseDoc.Element(XName.Get("Servers", "http://schemas.microsoft.com/sqlazure/2010/12/"));
                    if (serversSequenceElement != null)
                    {
                        foreach (XElement serversElement in serversSequenceElement.Elements(XName.Get("Server", "http://schemas.microsoft.com/sqlazure/2010/12/")))
                        {
                            ServerListResponse.Server serverInstance = new ServerListResponse.Server();
                            result.Servers.Add(serverInstance);

                            XElement nameElement = serversElement.Element(XName.Get("Name", "http://schemas.microsoft.com/sqlazure/2010/12/"));
                            if (nameElement != null)
                            {
                                string nameInstance = nameElement.Value;
                                serverInstance.Name = nameInstance;
                            }

                            XElement administratorLoginElement = serversElement.Element(XName.Get("AdministratorLogin", "http://schemas.microsoft.com/sqlazure/2010/12/"));
                            if (administratorLoginElement != null)
                            {
                                string administratorLoginInstance = administratorLoginElement.Value;
                                serverInstance.AdministratorUserName = administratorLoginInstance;
                            }

                            XElement locationElement = serversElement.Element(XName.Get("Location", "http://schemas.microsoft.com/sqlazure/2010/12/"));
                            if (locationElement != null)
                            {
                                string locationInstance = locationElement.Value;
                                serverInstance.Location = locationInstance;
                            }

                            XElement featuresSequenceElement = serversElement.Element(XName.Get("Features", "http://schemas.microsoft.com/sqlazure/2010/12/"));
                            if (featuresSequenceElement != null)
                            {
                                foreach (XElement featuresElement in featuresSequenceElement.Elements(XName.Get("Feature", "http://schemas.microsoft.com/sqlazure/2010/12/")))
                                {
                                    string featuresKey   = featuresElement.Element(XName.Get("Name", "http://schemas.microsoft.com/sqlazure/2010/12/")).Value;
                                    string featuresValue = featuresElement.Element(XName.Get("Value", "http://schemas.microsoft.com/sqlazure/2010/12/")).Value;
                                    serverInstance.Features.Add(featuresKey, featuresValue);
                                }
                            }
                        }
                    }

                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Beispiel #17
0
        /// <summary>
        /// Get the list of all servers under the vault.
        /// </summary>
        /// <param name='customRequestHeaders'>
        /// Optional. Request header parameters.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response model for the list servers operation.
        /// </returns>
        public async Task <ServerListResponse> ListAsync(CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
        {
            // Validate

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("customRequestHeaders", customRequestHeaders);
                TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/cloudservices/";
            url = url + Uri.EscapeDataString(this.Client.CloudServiceName);
            url = url + "/resources/";
            url = url + "WAHyperVRecoveryManager";
            url = url + "/~/";
            url = url + "HyperVRecoveryManagerVault";
            url = url + "/";
            url = url + Uri.EscapeDataString(this.Client.ResourceName);
            url = url + "/Servers";
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=2015-02-10");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/xml");
                httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
                httpRequest.Headers.Add("x-ms-version", "2013-03-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    ServerListResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new ServerListResponse();
                        XDocument responseDoc = XDocument.Parse(responseContent);

                        XElement arrayOfServerSequenceElement = responseDoc.Element(XName.Get("ArrayOfServer", "http://schemas.microsoft.com/windowsazure"));
                        if (arrayOfServerSequenceElement != null)
                        {
                            foreach (XElement arrayOfServerElement in arrayOfServerSequenceElement.Elements(XName.Get("Server", "http://schemas.microsoft.com/windowsazure")))
                            {
                                Server serverInstance = new Server();
                                result.Servers.Add(serverInstance);

                                XElement providerVersionElement = arrayOfServerElement.Element(XName.Get("ProviderVersion", "http://schemas.microsoft.com/windowsazure"));
                                if (providerVersionElement != null)
                                {
                                    string providerVersionInstance = providerVersionElement.Value;
                                    serverInstance.ProviderVersion = providerVersionInstance;
                                }

                                XElement serverVersionElement = arrayOfServerElement.Element(XName.Get("ServerVersion", "http://schemas.microsoft.com/windowsazure"));
                                if (serverVersionElement != null)
                                {
                                    string serverVersionInstance = serverVersionElement.Value;
                                    serverInstance.ServerVersion = serverVersionInstance;
                                }

                                XElement lastHeartbeatElement = arrayOfServerElement.Element(XName.Get("LastHeartbeat", "http://schemas.microsoft.com/windowsazure"));
                                if (lastHeartbeatElement != null)
                                {
                                    DateTime lastHeartbeatInstance = DateTime.Parse(lastHeartbeatElement.Value, CultureInfo.InvariantCulture);
                                    serverInstance.LastHeartbeat = lastHeartbeatInstance;
                                }

                                XElement connectedElement = arrayOfServerElement.Element(XName.Get("Connected", "http://schemas.microsoft.com/windowsazure"));
                                if (connectedElement != null)
                                {
                                    bool connectedInstance = bool.Parse(connectedElement.Value);
                                    serverInstance.Connected = connectedInstance;
                                }

                                XElement typeElement = arrayOfServerElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
                                if (typeElement != null)
                                {
                                    string typeInstance = typeElement.Value;
                                    serverInstance.Type = typeInstance;
                                }

                                XElement fabricTypeElement = arrayOfServerElement.Element(XName.Get("FabricType", "http://schemas.microsoft.com/windowsazure"));
                                if (fabricTypeElement != null)
                                {
                                    string fabricTypeInstance = fabricTypeElement.Value;
                                    serverInstance.FabricType = fabricTypeInstance;
                                }

                                XElement fabricObjectIDElement = arrayOfServerElement.Element(XName.Get("FabricObjectID", "http://schemas.microsoft.com/windowsazure"));
                                if (fabricObjectIDElement != null)
                                {
                                    string fabricObjectIDInstance = fabricObjectIDElement.Value;
                                    serverInstance.FabricObjectID = fabricObjectIDInstance;
                                }

                                XElement nameElement = arrayOfServerElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
                                if (nameElement != null)
                                {
                                    string nameInstance = nameElement.Value;
                                    serverInstance.Name = nameInstance;
                                }

                                XElement idElement = arrayOfServerElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
                                if (idElement != null)
                                {
                                    string idInstance = idElement.Value;
                                    serverInstance.ID = idInstance;
                                }
                            }
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
 private async void ViewFirewallRulesForServer(ServerListResponse.Server server)
 {
     SelectedServer = server;
     await GetSqlFirewallRuleList();
 }
        /// <summary>
        /// Get the list of all servers under the vault.
        /// </summary>
        /// <param name='customRequestHeaders'>
        /// Optional. Request header parameters.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response model for the list servers operation.
        /// </returns>
        public async Task <ServerListResponse> ListAsync(CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
        {
            // Validate

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("customRequestHeaders", customRequestHeaders);
                TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "/Subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(this.Client.ResourceGroupName);
            url = url + "/providers/";
            url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
            url = url + "/";
            url = url + "SiteRecoveryVault";
            url = url + "/";
            url = url + Uri.EscapeDataString(this.Client.ResourceName);
            url = url + "/Servers";
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=2015-08-10");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
                httpRequest.Headers.Add("x-ms-version", "2015-01-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    ServerListResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new ServerListResponse();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken valueArray = responseDoc["value"];
                            if (valueArray != null && valueArray.Type != JTokenType.Null)
                            {
                                foreach (JToken valueValue in ((JArray)valueArray))
                                {
                                    Server serverInstance = new Server();
                                    result.Servers.Add(serverInstance);

                                    JToken propertiesValue = valueValue["properties"];
                                    if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
                                    {
                                        ServerProperties propertiesInstance = new ServerProperties();
                                        serverInstance.Properties = propertiesInstance;

                                        JToken providerVersionValue = propertiesValue["providerVersion"];
                                        if (providerVersionValue != null && providerVersionValue.Type != JTokenType.Null)
                                        {
                                            string providerVersionInstance = ((string)providerVersionValue);
                                            propertiesInstance.ProviderVersion = providerVersionInstance;
                                        }

                                        JToken serverVersionValue = propertiesValue["serverVersion"];
                                        if (serverVersionValue != null && serverVersionValue.Type != JTokenType.Null)
                                        {
                                            string serverVersionInstance = ((string)serverVersionValue);
                                            propertiesInstance.ServerVersion = serverVersionInstance;
                                        }

                                        JToken lastHeartbeatValue = propertiesValue["lastHeartbeat"];
                                        if (lastHeartbeatValue != null && lastHeartbeatValue.Type != JTokenType.Null)
                                        {
                                            DateTime lastHeartbeatInstance = ((DateTime)lastHeartbeatValue);
                                            propertiesInstance.LastHeartbeat = lastHeartbeatInstance;
                                        }

                                        JToken connectionStatusValue = propertiesValue["connectionStatus"];
                                        if (connectionStatusValue != null && connectionStatusValue.Type != JTokenType.Null)
                                        {
                                            string connectionStatusInstance = ((string)connectionStatusValue);
                                            propertiesInstance.ConnectionStatus = connectionStatusInstance;
                                        }

                                        JToken friendlyNameValue = propertiesValue["friendlyName"];
                                        if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null)
                                        {
                                            string friendlyNameInstance = ((string)friendlyNameValue);
                                            propertiesInstance.FriendlyName = friendlyNameInstance;
                                        }

                                        JToken fabricTypeValue = propertiesValue["fabricType"];
                                        if (fabricTypeValue != null && fabricTypeValue.Type != JTokenType.Null)
                                        {
                                            string fabricTypeInstance = ((string)fabricTypeValue);
                                            propertiesInstance.FabricType = fabricTypeInstance;
                                        }

                                        JToken fabricObjectIDValue = propertiesValue["fabricObjectID"];
                                        if (fabricObjectIDValue != null && fabricObjectIDValue.Type != JTokenType.Null)
                                        {
                                            string fabricObjectIDInstance = ((string)fabricObjectIDValue);
                                            propertiesInstance.FabricObjectID = fabricObjectIDInstance;
                                        }
                                    }

                                    JToken idValue = valueValue["id"];
                                    if (idValue != null && idValue.Type != JTokenType.Null)
                                    {
                                        string idInstance = ((string)idValue);
                                        serverInstance.Id = idInstance;
                                    }

                                    JToken nameValue = valueValue["name"];
                                    if (nameValue != null && nameValue.Type != JTokenType.Null)
                                    {
                                        string nameInstance = ((string)nameValue);
                                        serverInstance.Name = nameInstance;
                                    }

                                    JToken typeValue = valueValue["type"];
                                    if (typeValue != null && typeValue.Type != JTokenType.Null)
                                    {
                                        string typeInstance = ((string)typeValue);
                                        serverInstance.Type = typeInstance;
                                    }

                                    JToken locationValue = valueValue["location"];
                                    if (locationValue != null && locationValue.Type != JTokenType.Null)
                                    {
                                        string locationInstance = ((string)locationValue);
                                        serverInstance.Location = locationInstance;
                                    }

                                    JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
                                    if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
                                    {
                                        foreach (JProperty property in tagsSequenceElement)
                                        {
                                            string tagsKey   = ((string)property.Name);
                                            string tagsValue = ((string)property.Value);
                                            serverInstance.Tags.Add(tagsKey, tagsValue);
                                        }
                                    }
                                }
                            }

                            JToken nextLinkValue = responseDoc["nextLink"];
                            if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
                            {
                                string nextLinkInstance = ((string)nextLinkValue);
                                result.NextLink = nextLinkInstance;
                            }
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }