/// <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); }
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(); } }
/// <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; }
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); } }); }
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(); } }
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); } } }
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(); }
/// <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); }
/// <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); }
public override void ExecuteCmdlet() { CloudServiceClient = CloudServiceClient ?? new CloudServiceClient( CurrentSubscription, SessionState.Path.CurrentLocation.Path, WriteDebug, WriteVerbose, WriteWarning); CloudServiceClient.StopCloudService(ServiceName, Slot); if (PassThru) { WriteObject(true); } }
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(); } }
/// <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); }
/// <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); }
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); }
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(); } }
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); }
/// <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); }
/// 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); }
/// <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); }
private static System.ServiceModel.Channels.Binding GetDefaultBinding() { return(CloudServiceClient.GetBindingForEndpoint(EndpointConfiguration.BasicHttpBinding_ICloudService)); }
public CloudServiceClient() : base(CloudServiceClient.GetDefaultBinding(), CloudServiceClient.GetDefaultEndpointAddress()) { this.Endpoint.Name = EndpointConfiguration.BasicHttpBinding_ICloudService.ToString(); ConfigureEndpoint(this.Endpoint, this.ClientCredentials); }
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(); } }
public CloudServiceClient(EndpointConfiguration endpointConfiguration) : base(CloudServiceClient.GetBindingForEndpoint(endpointConfiguration), CloudServiceClient.GetEndpointAddress(endpointConfiguration)) { this.Endpoint.Name = endpointConfiguration.ToString(); ConfigureEndpoint(this.Endpoint, this.ClientCredentials); }
public CloudServiceClient(EndpointConfiguration endpointConfiguration, System.ServiceModel.EndpointAddress remoteAddress) : base(CloudServiceClient.GetBindingForEndpoint(endpointConfiguration), remoteAddress) { this.Endpoint.Name = endpointConfiguration.ToString(); ConfigureEndpoint(this.Endpoint, this.ClientCredentials); }
private static System.ServiceModel.EndpointAddress GetDefaultEndpointAddress() { return(CloudServiceClient.GetEndpointAddress(EndpointConfiguration.BasicHttpBinding_ICloudService)); }
/// <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>(); }