Example #1
0
        // This works with a native application not with a web application
        // Perhaps using a native app is required for now
        static void CreateSqlServer(TokenCloudCredentials creds)
        {
            var client         = new SqlManagementClient(creds);
            var someProperties = new ServerCreateOrUpdateProperties
            {
                AdministratorLogin         = adminAccountName,
                AdministratorLoginPassword = adminAccountPwd,
                Version = "12"
            };

            var parameters = new ServerCreateOrUpdateParameters(someProperties, location);
            ServerGetResponse aCreateResponse
                = client.Servers.CreateOrUpdate(resourceGroupName, serverName, parameters);
        }
Example #2
0
        static ServerGetResponse CreateOrUpdateServer(SqlManagementClient sqlMgmtClient, string resourceGroupName, string serverLocation, string serverName, string serverAdmin, string serverAdminPassword)
        {
            ServerCreateOrUpdateParameters serverParameters = new ServerCreateOrUpdateParameters()
            {
                Location   = serverLocation,
                Properties = new ServerCreateOrUpdateProperties()
                {
                    AdministratorLogin         = serverAdmin,
                    AdministratorLoginPassword = serverAdminPassword,
                    Version = "12.0"
                }
            };
            ServerGetResponse serverResult = sqlMgmtClient.Servers.CreateOrUpdate(resourceGroupName, serverName, serverParameters);

            return(serverResult);
        }
        static void CreateSqlServer(TokenCloudCredentials creds)
        {
            var client         = new SqlManagementClient(creds);
            var someProperties = new ServerCreateOrUpdateProperties
            {
                AdministratorLogin         = adminAccountName,
                AdministratorLoginPassword = adminAccountPwd,
                Version = "12"
            };

            var parameters = new ServerCreateOrUpdateParameters(someProperties, location);

            // { "AuthorizationFailed: The client 'xxxxx-xxxxx-xxxxx-xxxxx'
            // with object id 'xxxxx-xxxxx-xxxxx-xxxxx' does not have authorization
            // to perform action 'Microsoft.Sql/servers/write' over scope
            // '/subscriptions/xxxxx-xxxxx-xxxxx-xxxxx/resourceGroups/MY_RESOURCE_GROUP_NAME/providers/Microsoft.Sql/servers/MY_SERVER_NAME'."}
            ServerGetResponse aCreateResponse
                = client.Servers.CreateOrUpdate(resourceGroupName, serverName, parameters);
        }
Example #4
0
        static string _databasePerfLevel = ""; // "S0", "S1", and so on here for other tiers


        static void Main(string[] args)
        {
            // Authenticate:
            _token = GetToken(_tenantId, _applicationId, _applicationSecret);
            Console.WriteLine("Token acquired. Expires on:" + _token.ExpiresOn);

            // Instantiate management clients:
            _resourceMgmtClient = new ResourceManagementClient(new Microsoft.Rest.TokenCredentials(_token.AccessToken));
            _sqlMgmtClient      = new SqlManagementClient(new TokenCloudCredentials(_subscriptionId, _token.AccessToken));


            Console.WriteLine("Resource group...");
            ResourceGroup rg = CreateOrUpdateResourceGroup(_resourceMgmtClient, _subscriptionId, _resourceGroupName, _resourceGrouplocation);

            Console.WriteLine("Resource group: " + rg.Id);


            Console.WriteLine("Server...");
            ServerGetResponse sgr = CreateOrUpdateServer(_sqlMgmtClient, _resourceGroupName, _serverlocation, _serverName, _serverAdmin, _serverAdminPassword);

            Console.WriteLine("Server: " + sgr.Server.Id);

            Console.WriteLine("Server firewall...");
            FirewallRuleGetResponse fwr = CreateOrUpdateFirewallRule(_sqlMgmtClient, _resourceGroupName, _serverName, _firewallRuleName, _startIpAddress, _endIpAddress);

            Console.WriteLine("Server firewall: " + fwr.FirewallRule.Id);

            Console.WriteLine("Database...");
            DatabaseCreateOrUpdateResponse dbr = CreateOrUpdateDatabase(_sqlMgmtClient, _resourceGroupName, _serverName, _databaseName, _databaseEdition, _databasePerfLevel);

            Console.WriteLine("Database: " + dbr.Database.Id);


            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
        /// <summary>
        /// Creates a new Azure SQL Database server.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the Resource Group to which the server
        /// belongs.
        /// </param>
        /// <param name='serverName'>
        /// Required. The name of the Azure SQL Database Server on which the
        /// database is hosted.
        /// </param>
        /// <param name='parameters'>
        /// Required. The required parameters for createing or updating a
        /// database.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Represents the response to a Get Database request.
        /// </returns>
        public async Task <ServerGetResponse> CreateOrUpdateAsync(string resourceGroupName, string serverName, ServerCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (serverName == null)
            {
                throw new ArgumentNullException("serverName");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (parameters.Location == null)
            {
                throw new ArgumentNullException("parameters.Location");
            }
            if (parameters.Properties == null)
            {
                throw new ArgumentNullException("parameters.Properties");
            }
            if (parameters.Tags == null)
            {
                throw new ArgumentNullException("parameters.Tags");
            }

            // 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);
                tracingParameters.Add("serverName", serverName);
                tracingParameters.Add("parameters", parameters);
                TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", 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/" + Uri.EscapeDataString(serverName) + "?";

            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.Put;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers

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

                // Serialize Request
                string requestContent = null;
                JToken requestDoc     = null;

                JObject serverCreateOrUpdateParametersValue = new JObject();
                requestDoc = serverCreateOrUpdateParametersValue;

                JObject propertiesValue = new JObject();
                serverCreateOrUpdateParametersValue["properties"] = propertiesValue;

                if (parameters.Properties.Version != null)
                {
                    propertiesValue["version"] = parameters.Properties.Version;
                }

                if (parameters.Properties.AdministratorLogin != null)
                {
                    propertiesValue["administratorLogin"] = parameters.Properties.AdministratorLogin;
                }

                if (parameters.Properties.AdministratorLoginPassword != null)
                {
                    propertiesValue["administratorLoginPassword"] = parameters.Properties.AdministratorLoginPassword;
                }

                serverCreateOrUpdateParametersValue["location"] = parameters.Location;

                if (parameters.Tags != null)
                {
                    JObject tagsDictionary = new JObject();
                    foreach (KeyValuePair <string, string> pair in parameters.Tags)
                    {
                        string tagsKey   = pair.Key;
                        string tagsValue = pair.Value;
                        tagsDictionary[tagsKey] = tagsValue;
                    }
                    serverCreateOrUpdateParametersValue["tags"] = tagsDictionary;
                }

                requestContent      = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
                httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
                httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");

                // 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 && statusCode != HttpStatusCode.Created)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

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

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

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            Server serverInstance = new Server();
                            result.Server = serverInstance;

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

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

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

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

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

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

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

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

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

                            JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
                            if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
                            {
                                foreach (JProperty property in tagsSequenceElement)
                                {
                                    string tagsKey2   = ((string)property.Name);
                                    string tagsValue2 = ((string)property.Value);
                                    serverInstance.Tags.Add(tagsKey2, tagsValue2);
                                }
                            }
                        }
                    }
                    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();
                }
            }
        }