コード例 #1
0
ファイル: EntitySearchHandler.cs プロジェクト: zzcandor/ailab
        /// <summary>
        /// Run the API call and get the response message and records telemetry event with time to complete api call and status code
        /// </summary>
        /// <param name="entityNameStream">Name of entity to be used for the call</param>
        /// <returns>The HttpResponseMessage containing the Json result</returns>
        protected async Task <HttpResponseMessage> Run(string entityName)
        {
            // Construct the uri to perform Bing Entity Search
            RequestParams = "mkt=en-us&q=" + System.Net.WebUtility.UrlEncode(entityName);
            BuildURI();

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            HttpResponseMessage response = null;

            try
            {
                // Execute the REST API GET call asynchronously
                response = await RequestAndRetry(() => CloudServiceClient.GetAsync(URI));

                response.EnsureSuccessStatusCode();
            }
            finally
            {
                stopwatch.Stop();
                string responseStatusCode = Telemetry.PropertyValue.NoResponse;
                if (response != null)
                {
                    responseStatusCode = response.StatusCode.ToString();
                }
                Telemetry.ApplicationLogger.Instance.SubmitApiCallEvent(Telemetry.EventName.CompleteApiCall, Telemetry.EventName.EntitySearchApi, stopwatch.ElapsedMilliseconds, responseStatusCode);
            }

            return(response);
        }
コード例 #2
0
        private void Initialize()
        {
            _bindingSource = new BindingSource();

            // Initializing service proxy
            var cloudProxy = new CloudServiceClient();

            try
            {
                // Getting file names from cloud server
                _fileList = new List <string>(cloudProxy.GetFileList().Select(Path.GetFileName));

                // Logging
                Log("Connected to cloud, " + _fileList.Count + " files available");

                // Setting data source for the listbox control
                _bindingSource.DataSource = _fileList;
                fileListBox.DataSource    = _bindingSource;
            }
            catch (Exception e)
            {
                Log(e.Message);
            }
            finally
            {
                // Close service proxy
                cloudProxy.Close();
            }
        }
コード例 #3
0
 /// <summary>
 /// Creates new WebsitesClient
 /// </summary>
 /// <param name="subscription">Subscription containing websites to manipulate</param>
 /// <param name="logger">The logger action</param>
 public WebsitesClient(WindowsAzureSubscription subscription, Action<string> logger)
 {
     Logger = logger;
     cloudServiceClient = new CloudServiceClient(subscription, debugStream: logger);
     WebsiteManagementClient = subscription.CreateClient<WebSiteManagementClient>();
     this.subscription = subscription;
 }
コード例 #4
0
        public override void ExecuteCmdlet()
        {
            ConfirmAction(
                Force.IsPresent,
                string.Format(Resources.RemoveServiceWarning),
                Resources.RemoveServiceWhatIfMessage,
                string.Empty,
                () =>
            {
                CloudServiceClient = CloudServiceClient ?? new CloudServiceClient(
                    Profile,
                    Profile.Context.Subscription,
                    SessionState.Path.CurrentLocation.Path,
                    WriteDebug,
                    WriteVerbose,
                    WriteWarning);

                CloudServiceClient.RemoveCloudService(ServiceName, DeleteAll.IsPresent);

                if (PassThru)
                {
                    WriteObject(true);
                }
            });
        }
コード例 #5
0
        private void Delete(string cloudFileName)
        {
            // Initializing service proxy
            var cloudProxy = new CloudServiceClient();

            try
            {
                if (cloudProxy.DeleteFile(cloudFileName))
                {
                    Log("File " + cloudFileName + " deleted");
                    _fileList.RemoveAt(fileListBox.SelectedIndex);
                    _bindingSource.ResetBindings(false);
                }
                else
                {
                    Log("Error deleting the file");
                }
            }
            catch (Exception exception)
            {
                Log(exception.Message);
            }
            finally
            {
                // Close service proxy
                cloudProxy.Close();
            }
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: muttenthaler/CoOp
        static void Main()
        {
            using (CloudServiceClient cloudService = new CloudServiceClient())
            using (ArtifactServiceClient artifactService = new ArtifactServiceClient())
            {
                Artifact artifact = cloudService.CreateArtifact();
                Console.WriteLine("Id: {0}, Type: {1}", artifact.Id, artifact.GetType());

                CollectionArtifact collection = cloudService.CreateCollectionArtifact();
                Console.WriteLine("Id: {0}, Type: {1}", collection.Id, collection.GetType());

                Artifact[] artifacts = cloudService.GetArtifacts();
                foreach (var item in artifacts)
                {
                    Console.WriteLine("Id: {0}, Type: {1}", item.Id, item.GetType());
                }

                artifactService.AddProperty(artifact, "a string", "asdf");
                artifactService.AddProperty(artifact, "a int", 1234);

                Property[] properties = artifactService.GetProperties(artifact);
                foreach (var item in properties)
                {
                    Console.WriteLine("Parent: {0}, Name: {1}, Value: {2}", item.Parent.Id, item.Name, item.Value);
                }
            }
        }
コード例 #7
0
ファイル: Program.cs プロジェクト: xeb/ServiceCloud
        static void Main()
        {
            // Start up the Cloud Gateway!
            using (var cloud = new CloudServiceClient())
            {
                // Formulate our Request
                var request = new Request
                {
                    Argument = 15,
                    Services = new[]
                    {
                        new ServiceCall
                        {
                            Name = "Decrementer",
                            Services = new[]
                            {
                                new ServiceCall { Name = "Incrementer" },
                                new ServiceCall { Name = "Incrementer" },
                                new ServiceCall { Name = "Incrementer" },
                                new ServiceCall { Name = "Incrementer" },
                                new ServiceCall { Name = "Incrementer" },
                                new ServiceCall { Name = "Incrementer" },
                                new ServiceCall { Name = "Incrementer" },
                            },
                        },
                        new ServiceCall { Name = "Decrementer" },
                        new ServiceCall { Name = "Decrementer" },
                        new ServiceCall { Name = "Decrementer" },
                    },
                };

                // Assign the Endpoint Addresses (avoids redundancy -- this could easily be its own Service)
                request.Services.ToList().ForEach(AssignAddress);

                // Get a Response from the Gateway
                var response = cloud.Execute(request);

                if (response == null)
                {
                    Console.WriteLine("Response is NULL!!!");
                    Console.ReadLine();
                    return;
                }

                Console.WriteLine("ReturnObject is {0}", response.ReturnObject);

                // Find out which services ran
                if (response.ServicesRan != null && response.ServicesRan.Length > 0)
                {
                    response.ServicesRan.ToList().ForEach(s => Console.WriteLine("Ran on Service: {0}", s));
                }

                cloud.Close();
            }

            Console.ReadLine();
        }
コード例 #8
0
        /// <summary>
        /// Run the API call and get the response message and records telemetry event with time to complete api call and status code
        /// </summary>
        /// <param name="entityName">Name of entity to be used for the call</param>
        /// <returns>The HttpResponseMessage containing the Json result</returns>
        protected async Task <HttpResponseMessage> Run(string entityName)
        {
            //<add-endpoint-params-here>

            HttpResponseMessage response = null;

            // Execute the REST API GET call asynchronously and
            // await for non-blocking API call to Bing Entity Search
            response = await RequestAndRetry(() => CloudServiceClient.GetAsync(URI));

            response.EnsureSuccessStatusCode();

            return(response);
        }
コード例 #9
0
        /// <summary>
        /// Run the API call and get the response message and records telemetry event with time to complete api call and status code
        /// </summary>
        /// <param name="entityName">Name of entity to be used for the call</param>
        /// <returns>The HttpResponseMessage containing the Json result</returns>
        protected async Task <HttpResponseMessage> Run(string entityName)
        {
            RequestParams = "q=" + System.Net.WebUtility.UrlEncode(entityName);
            BuildURI();

            HttpResponseMessage response = null;

            // Execute the REST API GET call asynchronously and
            // await for non-blocking API call to Bing Entity Search
            response = await RequestAndRetry(() => CloudServiceClient.GetAsync(URI));

            response.EnsureSuccessStatusCode();

            return(response);
        }
コード例 #10
0
        public override void ExecuteCmdlet()
        {
            CloudServiceClient = CloudServiceClient ?? new CloudServiceClient(
                CurrentSubscription,
                SessionState.Path.CurrentLocation.Path,
                WriteDebug,
                WriteVerbose,
                WriteWarning);

            CloudServiceClient.StopCloudService(ServiceName, Slot);

            if (PassThru)
            {
                WriteObject(true);
            }
        }
コード例 #11
0
        private void Upload(System.ComponentModel.DoWorkEventArgs e)
        {
            // Initializing service proxy
            var cloudProxy = new CloudServiceClient();

            try
            {
                // Creating fileInfo and fileName
                var fileInfo = new FileInfo(_localFilePath);
                var fileName = fileInfo.Name;

                // Uploading file
                using (var stream = new FileStream(_localFilePath, FileMode.Open, FileAccess.Read))
                {
                    using (var uploadStream = new ProgressStream(stream))
                    {
                        // Adding event handler to uploadStream
                        uploadStream.ProgressChanged += uploadStream_ProgressChanged;

                        // Invoking service method
                        cloudProxy.UploadFile(ref fileName, fileInfo.Length, uploadStream);

                        // Check for cancellation
                        if (backgroundWorker.CancellationPending)
                        {
                            e.Cancel       = true;
                            _cloudFileName = fileName;
                            return;
                        }

                        // Adding file name to list instead of invoking GetFileList
                        _fileList.Add(fileName);
                        _bindingSource.ResetBindings(false);
                    }
                }
            }
            catch (Exception exception)
            {
                throw new ArgumentException(exception.Message);
            }
            finally
            {
                // Closing service proxy
                cloudProxy.Close();
            }
        }
コード例 #12
0
        /// <summary>
        /// Run the HTTP call to get a list of similar products
        /// </summary>
        /// <param name="stream">Captured Image</param>
        /// <returns>The HTTP response for the call</returns>
        protected override async Task <HttpResponseMessage> Run(MemoryStream stream)
        {
            var strContent = new StreamContent(stream);

            strContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                FileName = "AnyNameWorks"
            };

            var content = new MultipartFormDataContent();

            content.Add(strContent);

            // Execute the REST API call.
            var result = await RequestAndRetry(() => CloudServiceClient.PostAsync(URI, content));

            result.EnsureSuccessStatusCode();
            return(result);
        }
コード例 #13
0
        /// <summary>
        /// Run the API call and get the response message and records telemetry event with time to complete api call and status code
        /// </summary>
        /// <param name="ocrResult">OCR results to be used for the call</param>
        /// <returns>The HttpResponseMessage containing the Json result</returns>
        protected async Task <HttpResponseMessage> Run(string ocrResult)
        {
            var queryString = HttpUtility.ParseQueryString(string.Empty);

            queryString["q"] = ocrResult;
            // These optional request parameters are set to their default values
            queryString["timezoneOffset"] = "0";
            queryString["verbose"]        = "false";
            queryString["spellCheck"]     = "false";
            queryString["staging"]        = "false";

            RequestParams = queryString.ToString();
            BuildURI();

            HttpResponseMessage response = await RequestAndRetry(() => CloudServiceClient.GetAsync(URI));

            response.EnsureSuccessStatusCode();

            return(response);
        }
コード例 #14
0
        public override void ExecuteCmdlet()
        {
            CloudServiceClient = CloudServiceClient ?? new CloudServiceClient(
                CurrentSubscription,
                SessionState.Path.CurrentLocation.Path,
                WriteDebug,
                WriteVerbose,
                WriteWarning);

            Deployment deployment = CloudServiceClient.PublishCloudService(
                ServiceName,
                Slot,
                Location,
                AffinityGroup,
                StorageAccountName,
                DeploymentName,
                Launch);

            WriteObject(deployment);
        }
コード例 #15
0
        private void backgroundWorker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            // Operation was cancelled
            if (e.Cancelled)
            {
                // If uploading delete file server-side
                if (_upload)
                {
                    // Initializing service proxy
                    var cloudProxy = new CloudServiceClient();

                    // Deleting file server-side
                    cloudProxy.DeleteFile(_cloudFileName);

                    // Closing service proxy
                    cloudProxy.Close();
                }
                // If downloading delete file locally
                else
                {
                    if (File.Exists(_localFilePath))
                    {
                        File.Delete(_localFilePath);
                    }
                }
            }
            // Error
            else if (e.Error != null)
            {
                Close();
                MessageBox.Show("There has been an error in the process: " + e.Error.Message,
                                "Error", MessageBoxButtons.OK);
            }
            // Operation completed
            else
            {
                // Close form when work completes
                Close();
            }
        }
コード例 #16
0
        public override void ExecuteCmdlet()
        {
            CloudServiceClient = CloudServiceClient ?? new CloudServiceClient(
                Profile,
                Profile.Context.Subscription,
                SessionState.Path.CurrentLocation.Path,
                WriteDebug,
                WriteVerbose,
                WriteWarning);

            Deployment deployment;

            if (!string.IsNullOrEmpty(Package))
            {
                deployment = CloudServiceClient.PublishCloudService(
                    Package,
                    Configuration,
                    Slot,
                    Location,
                    AffinityGroup,
                    StorageAccountName,
                    DeploymentName,
                    Launch,
                    ForceUpgrade);
            }
            else
            {
                deployment = CloudServiceClient.PublishCloudService(
                    ServiceName,
                    Slot,
                    Location,
                    AffinityGroup,
                    StorageAccountName,
                    DeploymentName,
                    Launch,
                    ForceUpgrade);
            }

            WriteObject(deployment);
        }
コード例 #17
0
ファイル: ImageSearchHandler.cs プロジェクト: zzcandor/ailab
        /// <summary>
        /// Make the API call with supplied request contents and records telemetry event with time to complete api call and status code
        /// </summary>
        /// <param name="stream">MemoryStream to read the image byte array</param>
        /// <returns>String response from the API call</returns>
        protected override async Task <HttpResponseMessage> Run(MemoryStream stream)
        {
            var strContent = new StreamContent(stream);

            strContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                FileName = "AnyNameWorks"
            };

            var content = new MultipartFormDataContent();

            content.Add(strContent);

            HttpResponseMessage result    = null;
            Stopwatch           stopwatch = new Stopwatch();

            stopwatch.Start();

            try
            {
                // Execute the REST API call.
                result = await RequestAndRetry(() => CloudServiceClient.PostAsync(URI, content));

                result.EnsureSuccessStatusCode();
            }
            finally
            {
                stopwatch.Stop();
                string responseStatusCode = Telemetry.PropertyValue.NoResponse;
                if (result != null)
                {
                    responseStatusCode = result.StatusCode.ToString();
                }
                Telemetry.ApplicationLogger.Instance.SubmitApiCallEvent(Telemetry.EventName.CompleteApiCall, Telemetry.EventName.CelebrityRecognitionApi, stopwatch.ElapsedMilliseconds, responseStatusCode);
            }

            return(result);
        }
コード例 #18
0
        /// Run the stream asynchronously, return the HttpResonseMessage and records telemetry event with time to complete api call and status code
        /// </summary>
        /// <param name="stream">Captured Image</param>
        /// <returns>ResponseMessage of the API request/call</returns>
        protected override async Task <HttpResponseMessage> Run(MemoryStream stream)
        {
            var result = await base.Run(stream);

            if (!result.IsSuccessStatusCode)
            {
                return(null);
            }

            string operationLocation     = result.Headers.GetValues("Operation-Location").FirstOrDefault();
            HttpResponseMessage response = await RequestAndRetry(() => CloudServiceClient.GetAsync(operationLocation));

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            try
            {
                response.EnsureSuccessStatusCode();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                // Pass the exception to the next level
                throw e;
            }
            finally{
                stopwatch.Stop();
                string responseStatusCode = Telemetry.PropertyValue.NoResponse;
                if (result != null)
                {
                    responseStatusCode = result.StatusCode.ToString();
                }
                Telemetry.ApplicationLogger.Instance.SubmitApiCallEvent(Telemetry.EventName.CompleteApiCall, Telemetry.EventName.HandWrittenTextApi, stopwatch.ElapsedMilliseconds, responseStatusCode);
            }

            return(response);
        }
コード例 #19
0
        /// <summary>
        /// Creates new WebsitesClient.
        /// </summary>
        /// <param name="subscription">The Windows Azure subscription data object</param>
        /// <param name="logger">The logger action</param>
        public WebsitesClient(SubscriptionData subscription, Action <string> logger)
        {
            subscriptionId   = subscription.SubscriptionId;
            Subscription     = subscription;
            Logger           = logger;
            HeadersInspector = new HeadersInspector();
            HeadersInspector.RequestHeaders.Add(ServiceManagement.Constants.VersionHeaderName, WebsitesServiceVersion);
            HeadersInspector.RequestHeaders.Add(ApiConstants.UserAgentHeaderName, ApiConstants.UserAgentHeaderValue);
            HeadersInspector.RemoveHeaders.Add(ApiConstants.VSDebuggerCausalityDataHeaderName);
            WebsiteChannel = ChannelHelper.CreateChannel <IWebsitesServiceManagement>(
                ConfigurationConstants.WebHttpBinding(),
                new Uri(subscription.ServiceEndpoint),
                subscription.Certificate,
                HeadersInspector,
                new HttpRestMessageInspector(logger));

            ServiceManagementChannel = ChannelHelper.CreateServiceManagementChannel <IServiceManagement>(
                ConfigurationConstants.WebHttpBinding(),
                new Uri(subscription.ServiceEndpoint),
                subscription.Certificate,
                new HttpRestMessageInspector(logger));

            cloudServiceClient = new CloudServiceClient(subscription, debugStream: logger);
        }
コード例 #20
0
 private static System.ServiceModel.Channels.Binding GetDefaultBinding()
 {
     return(CloudServiceClient.GetBindingForEndpoint(EndpointConfiguration.BasicHttpBinding_ICloudService));
 }
コード例 #21
0
 public CloudServiceClient() :
     base(CloudServiceClient.GetDefaultBinding(), CloudServiceClient.GetDefaultEndpointAddress())
 {
     this.Endpoint.Name = EndpointConfiguration.BasicHttpBinding_ICloudService.ToString();
     ConfigureEndpoint(this.Endpoint, this.ClientCredentials);
 }
コード例 #22
0
        private void Download(System.ComponentModel.DoWorkEventArgs e)
        {
            // Initializing service proxy
            var cloudProxy = new CloudServiceClient();

            try
            {
                // Initializing client-side decryption
                var clientCypher = new XTEA();

                // Getting decryption key
                clientCypher.SetKey(Encoding.ASCII.GetBytes(cloudProxy.GetKey()));

                // Initializing stream from service
                var length = cloudProxy.DownloadFile(ref _cloudFileName, out var inputStream);

                // Write stream to disk
                using (var writeStream = new FileStream(_localFilePath, FileMode.CreateNew, FileAccess.Write))
                {
                    // Initializing buffer
                    var buffer = new byte[ChunkSize];

                    // Initializing boolean determining whether it's the last chunk
                    var lastChunk = false;

                    do
                    {
                        // Read bytes from input stream
                        var bytesRead = inputStream.Read(buffer, 0, ChunkSize);
                        if (bytesRead == 0)
                        {
                            break;
                        }

                        // Check if it is the last chunk
                        if (bytesRead < ChunkSize)
                        {
                            var temp = new byte[bytesRead];
                            Array.Copy(buffer, temp, bytesRead);
                            buffer    = temp;
                            lastChunk = true;
                        }

                        // Decrypt data from the buffer
                        var decryptedBuffer = clientCypher.Decrypt(buffer);

                        // Write bytes to output stream
                        writeStream.Write(decryptedBuffer, 0, decryptedBuffer.Length);

                        // Update progress bar
                        if (lastChunk)
                        {
                            backgroundWorker.ReportProgress(100);
                        }
                        else
                        {
                            backgroundWorker.ReportProgress((int)(writeStream.Position * 100 / length));
                        }

                        // Check for cancellation
                        if (!backgroundWorker.CancellationPending)
                        {
                            continue;
                        }

                        e.Cancel = true;
                        inputStream.Dispose();
                        return;
                    } while (!lastChunk);

                    writeStream.Close();
                }

                // Deallocate stream
                inputStream.Dispose();
            }
            catch (Exception exception)
            {
                throw new ArgumentException(exception.Message);
            }
            finally
            {
                // Close service proxy
                cloudProxy.Close();
            }
        }
コード例 #23
0
 public CloudServiceClient(EndpointConfiguration endpointConfiguration) :
     base(CloudServiceClient.GetBindingForEndpoint(endpointConfiguration), CloudServiceClient.GetEndpointAddress(endpointConfiguration))
 {
     this.Endpoint.Name = endpointConfiguration.ToString();
     ConfigureEndpoint(this.Endpoint, this.ClientCredentials);
 }
コード例 #24
0
 public CloudServiceClient(EndpointConfiguration endpointConfiguration, System.ServiceModel.EndpointAddress remoteAddress) :
     base(CloudServiceClient.GetBindingForEndpoint(endpointConfiguration), remoteAddress)
 {
     this.Endpoint.Name = endpointConfiguration.ToString();
     ConfigureEndpoint(this.Endpoint, this.ClientCredentials);
 }
コード例 #25
0
 private static System.ServiceModel.EndpointAddress GetDefaultEndpointAddress()
 {
     return(CloudServiceClient.GetEndpointAddress(EndpointConfiguration.BasicHttpBinding_ICloudService));
 }
コード例 #26
0
 /// <summary>
 /// Creates new WebsitesClient
 /// </summary>
 /// <param name="subscription">Subscription containing websites to manipulate</param>
 /// <param name="logger">The logger action</param>
 public WebsitesClient(WindowsAzureSubscription subscription, Action <string> logger)
 {
     Logger                  = logger;
     cloudServiceClient      = new CloudServiceClient(subscription, debugStream: logger);
     WebsiteManagementClient = subscription.CreateClient <WebSiteManagementClient>();
 }