/// <summary> /// </summary> /// <param name="syncMetric"></param> /// <param name="accountName"></param> /// <returns> /// </returns> public async Task<bool> UploadSyncData(SyncMetric syncMetric, string accountName) { try { var analyticsService = new AnalyticsService(new BaseClientService.Initializer { ApplicationName = ApplicationInfo.ProductName, ApiKey = "AIzaSyBrpqcL6Nh1vVecfhIbxGVnyGHMZ8-aH6k" }); var batchRequest = new BatchRequest(analyticsService); var metric = new CustomMetric { Name = "SyncMetric", Kind = "string" }; var insertRequest = analyticsService.Management.CustomMetrics.Insert(metric, "", ""); batchRequest.Queue<CustomMetric>(insertRequest, InsertMetricCallback); await batchRequest.ExecuteAsync(); } catch (Exception ex) { Logger.Error(ex); return false; } return true; }
public static void Main(string[] args) { // This first part is to simply setup the connection to the Cimom string progName = System.AppDomain.CurrentDomain.FriendlyName; if (args.Length != 4) { Console.WriteLine("Usage: " + progName + " <server name> <username> <password> <namespace>"); return; } string host = args[0]; string user = args[1]; string pwd = args[2]; string defaultNamespace = args[3]; // This is the line that defines our wbem client. No connection is made // to the Cimom until a call is made. WbemClient client = new WbemClient(host, user, pwd, defaultNamespace); GetClassOpSettings gcos = new GetClassOpSettings("CIM_NFS"); EnumerateClassNamesOpSettings ecnos = new EnumerateClassNamesOpSettings(); GetClassOpSettings gcos2 = new GetClassOpSettings("CIM_Component"); BatchRequest batch = new BatchRequest("root/cimv2"); batch.Add(gcos); batch.Add(ecnos); batch.Add(gcos2); BatchResponse response = client.ExecuteBatchRequest(batch); }
public BatchResponse(BatchRequest request, AstoriaResponse response) : base(request) { if (request.ExpectedStatusCode == HttpStatusCode.Accepted) { try { ResponseVerification.VerifyStatusCode(response); } catch (Exception e) { ResponseVerification.LogFailure(response, e); } } Responses = new List<AstoriaResponse>(); this.Headers = response.Headers; this.Payload = response.Payload; this.ETagHeaderFound = response.ETagHeaderFound; this.ActualStatusCode = response.ActualStatusCode; this.Exception = response.Exception; if (request.ExpectedStatusCode == HttpStatusCode.Accepted) BatchReader.ParseBatchResponse(this); }
public void Finish() { if(currentBatch != null) currentBatch.GetResponse().Verify(); currentBatch = null; currentChangeset = null; }
/// <summary> /// Konstruktor z nadaniem identyfikatora kalendarzowi. /// </summary> /// <param name="userEmail">Email użytkownika. Jest to również nazwa głównego kalendarza.</param> /// <param name="userId"></param> public Calendar(string userEmail, int userId) { IsCalendarAuthorized = false; CalendarId = userEmail; Request = new BatchRequest(Service); EventsQueue = new Queue<Event>(); Logs.WriteErrorLog("Konstruktor calendar userid: " + userId.ToString()); UserIdInDatabase = userId; }
private void batchGetClassToolStripMenuItem_Click(object sender, EventArgs e) { BatchRequest breq = new BatchRequest(mainWbemClient.DefaultNamespace); breq.Add(new GetClassOpSettings("CIM_NFS")); breq.Add(new GetClassOpSettings("NonExistantClass")); breq.Add(new GetClassOpSettings("OMC_Processor")); BatchResponse br = mainWbemClient.ExecuteBatchRequest(breq); }
public void CreateRequestContentString_Test() { var expectedMessage = NormalizeLineEndings(@"GET http://test.com:2020/ Accept-Encoding: gzip Content-Type: application/json Content-Length: 11 hello world "); var request = new HttpRequestMessage(HttpMethod.Get, "http://test.com:2020"); request.Content = new StringContent("hello world"); request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var requestStr = BatchRequest.CreateRequestContentString(request).Result; Assert.Equal(expectedMessage, NormalizeLineEndings(requestStr)); }
public void Add(AstoriaRequest request) { if (currentBatch == null) currentBatch = new BatchRequest(request.Workspace); if (request.Verb == RequestVerb.Get) { currentBatch.Add(request); } else { if (currentChangeset == null) currentChangeset = currentBatch.GetChangeset(); currentChangeset.Add(request); } if (currentBatch.TotalRequests >= Size && AutoSubmit) Finish(); }
private BatchRequest CreateBatchRequest( IEnumerable <Message> messages, bool dryRun, BatchRequest.OnResponse <SingleMessageResponse> callback) { var batch = new BatchRequest(this.fcmClientService, FcmBatchUrl); foreach (var message in messages) { var body = new SendRequest() { Message = message, ValidateOnly = dryRun, }; batch.Queue(new FCMClientServiceRequest(this.fcmClientService, this.restPath, body), callback); } return(batch); }
public async Task DeleteContainerAsync(string containerName) { try { var batch = new BatchRequest(_client.Service); foreach (var blob in await ListBlobsAsync(containerName)) { batch.Queue <string>(_client.Service.Objects.Delete(_bucket, ObjectName(blob.Container, blob.Name)), (content, error, i, message) => { }); } await batch.ExecuteAsync(); } catch (GoogleApiException gae) { throw Error(gae); } }
public directoryRequestRequest createDirReq(BatchRequestTypes batchRequestType) { directoryRequestRequest request = new directoryRequestRequest(); BatchRequest batchRequest = new BatchRequest(); request.batchRequest = batchRequest; switch (batchRequestType) { case BatchRequestTypes.searchRequest: { SearchRequest searchRequest = new SearchRequest(); batchRequest.Items = new SearchRequest[] { searchRequest }; break; } case BatchRequestTypes.addRequest: { AddRequest addRequest = new AddRequest(); batchRequest.Items = new AddRequest[] { addRequest }; break; } case BatchRequestTypes.modifyRequest: { ModifyRequest modifyRequest = new ModifyRequest(); batchRequest.Items = new ModifyRequest[] { modifyRequest }; break; } case BatchRequestTypes.delRequest: { DelRequest delRequest = new DelRequest(); batchRequest.Items = new DelRequest[] { delRequest }; break; } default: break; } return(request); }
public static void WriteBatchRequest(BatchRequest batchRequest, StringWriter writer) { //--batchresponse_aa2a62c3-d5f4-447e-9302-d31f062b02f7 //Content-Type: multipart/mixed; boundary=changesetresponse_1837899f-f0ce-447e-a980-d2596a561051 string batchBoundary = "batch_" + batchRequest.Identifier; foreach (BatchChangeset changeset in batchRequest.Changesets) { string setBoundary = "changeset_" + changeset.Identifier; writer.Write("--"); writer.WriteLine(batchBoundary); writer.WriteLine("Content-Type: " + RequestUtil.RandomizeContentTypeCapitalization("multipart/mixed; boundary=" + setBoundary)); writer.WriteLine(); foreach (AstoriaRequest request in changeset) { writer.Write("--"); writer.WriteLine(setBoundary); WriteBatchRequestFragment(request, writer); } writer.Write("--"); writer.Write(setBoundary); writer.WriteLine("--"); } foreach (AstoriaRequest request in batchRequest.Requests) { // TODO: newline? writer.Write("--"); writer.WriteLine(batchBoundary); // TODO: newline? WriteBatchRequestFragment(request, writer); } writer.Write("--"); writer.Write(batchBoundary); writer.WriteLine("--"); }
public void AddMembersToEmailList(int campaignId, string listId, IEnumerable <string> recipients) { var members = new List <Member>(); // add subscribers to list foreach (var recipient in recipients) { members.Add(new Member { EmailAddress = recipient, StatusIfNew = Status.Subscribed, }); } var batchRequest = new BatchRequest { Operations = members.Select(x => new Operation { Method = "PUT", Path = $"/lists/{listId}/members/{manager.Members.Hash(x.EmailAddress.ToLower())}", Body = JsonConvert.SerializeObject( x, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }), }), }; var batch = manager.Batches.AddAsync(batchRequest).Result; var batchId = batch.Id; while (batch.Status != "finished") { batch = manager.Batches.GetBatchStatus(batchId).Result; Task.Delay(new TimeSpan(0, 0, 30)).Wait(); } if (batch.ErroredOperations > 0) { Console.WriteLine($"({campaignId})-Error adding members to list via batch for listId {listId}. Amount of errors: {batch.ErroredOperations}"); } }
/// <summary> /// Delete Google API Events from Google Calendar /// </summary> /// <param name="owner">calendar owner</param> /// <param name="calendarId">calendar id</param> /// <param name="events">Google API Events object</param> /// <returns>async task for the background Api tasks</returns> private static async Task DeleteGoogleEventsAsync(string owner, string calendarId, Events events) { try { int batchCount = 1; // Create a batch request. var request = new BatchRequest(GetCalendarService(owner)); foreach (Event e in events.Items) { if (batchCount < 900) { request.Queue <Event>( GetCalendarService(owner).Events.Delete(calendarId, e.Id), (content, error, i, message) => { // Put your callback code here. if (error != null) { log.Error("Error deleting event from Google Calendar: " + error.Message); } }); batchCount++; } else { // Execute the batch request and create a new batch as cannot send more than 1000 await request.ExecuteAsync(); batchCount = 1; request = new BatchRequest(GetCalendarService(owner)); } } // Execute the batch request await request.ExecuteAsync(); } catch (Exception e) { log.Error("Error deleting Google Events : " + e.Message); } }
//Apenas edit pois não há suporte para criar folder ao mesmo tempo inserir permissoes public static void EditPermission(DriveService service, Permission permission, string Id) { var batch = new BatchRequest(service); BatchRequest.OnResponse <Permission> callback = delegate( Permission permissionCb, RequestError error, int index, HttpResponseMessage message) { if (error != null) { throw new Exception(); } }; var request = service.Permissions.Create(permission, Id); request.Fields = "id"; batch.Queue(request, callback); request.Execute(); }
public void Can_Generate_Api_Xml() { //Arrange string expected = new XElement("LinkRequest", new XAttribute("name", "foo"), new XAttribute("targetLocation", "bar")).ToString(); var request = new LinkRequest("foo", "bar"); //Act var actual = request.ToAdsml(); var batchRequest = new BatchRequest(request); Console.WriteLine(actual.ToString()); //Assert Assert.That(actual.ToString(), Is.EqualTo(expected)); Assert.DoesNotThrow(() => batchRequest.ToAdsml().ValidateAdsmlDocument("adsml.xsd")); }
public async Task BatchRequestRetryStackTracePreserved() { var request = new BatchRequest < JobScheduleListOptions, AzureOperationResponse <IPage <ProxyModels.CloudJobSchedule> > >(null, CancellationToken.None); request.ServiceRequestFunc = (token) => { throw new TimeoutException(); }; IRetryPolicy policy = new ExponentialRetry(TimeSpan.FromSeconds(0), 3); request.RetryPolicy = policy; TimeoutException e = await Assert.ThrowsAsync <TimeoutException>(async() => { await request.ExecuteRequestAsync(); }); //The StackTrace should contain this method Assert.Contains("BatchRequestRetryStackTracePreserved", e.StackTrace); }
public void CanGenerateApiXmlWithFilter() { //Arrange string expected = new XElement("LookupRequest", new XAttribute("name", "/foo/bar"), new XAttribute("returnNoAttributes", "true") ).ToString(); //Act var req = new LookupRequest("/foo/bar", null, Filter.ReturnNoAttributes(true)); var actual = req.ToAdsml(); var batchRequest = new BatchRequest(req); Console.WriteLine(actual); //Assert Assert.That(actual.ToString(), Is.EqualTo(expected)); Assert.DoesNotThrow(() => batchRequest.ToAdsml().ValidateAdsmlDocument("adsml.xsd")); }
public void Can_Send_ApiRequests_Via_ApiClient() { //Arrange var builder = new AqlQueryBuilder(); builder .BasePath("/Structures/Classification/JULA Produkter/") .SearchRequestFilters(Filter.ReturnNoAttributes()) .QueryType(AqlQueryTypes.Below) .ObjectTypeToFind(12) .QueryString("#215 = \"169010\""); //Act var request = new BatchRequest(builder.Build()); var result = _client.SendApiRequest(request); //Assert Assert.That(result, Is.Not.Null); Assert.That(result, Is.InstanceOf <XElement>()); }
/// <summary> /// To Start New Batch /// </summary> /// <param name="batchDetail"></param> /// <returns cref={Task<string>}></returns> public async Task <string> StartProcess(BatchRequest batchDetail) { UpdateCurrentStatus(BatchStatus.Started); BatchDetails = new ConcurrentDictionary <int, GeneratorBatch>(); _numbersPerBatch = batchDetail.NumbersPerBatch; for (var i = 0; i < batchDetail.NumberOfBatches; i++) { var batch = new GeneratorBatch { BatchNumber = i + 1, NumbersPerBatch = _numbersPerBatch }; BatchDetails.TryAdd(i + 1, batch); await _channel.WriteAsync(batch); } return(batchDetail.BatchId); }
public void Can_Generate_Api_Xml_With_RequestFilters() { //Arrange string expected = new XElement("ModifyRequest", new XAttribute("name", "/foo/bar"), new XAttribute("returnNoAttributes", "true"), new XAttribute("failOnError", "true"), new XElement("ModificationItem", new XAttribute("operation", "addValue"), new XElement("AttributeDetails", new XElement("StructureAttribute", new XAttribute("id", "31"), new XElement("StructureValue", new XAttribute("langId", "10"), new XAttribute("scope", "global"), new XCData("foo")))))).ToString(); //Act var modReq = new ModifyRequest("/foo/bar", new List <ModificationItem> { ModificationItem.New( Modifications.AddValue, StructureAttribute.New(31, new StructureValue(10, "foo")) ) }) { RequestFilters = new List <IModifyRequestFilter> { Filter.ReturnNoAttributes(), Filter.FailOnError() } }; var actual = modReq.ToAdsml(); var request = new BatchRequest(modReq); Console.WriteLine(actual.ToString()); //Assert Assert.That(actual.ToString(), Is.EqualTo(expected)); Assert.DoesNotThrow(() => request.ToAdsml().ValidateAdsmlDocument("adsml.xsd")); }
/// <summary> /// Serializes an HttpWebRespone and response body into a BatchResponse /// </summary> private static object GenerateBatchResponse(BatchRequest batchRequest, HttpWebResponse webResponse, Stream responseBody) { object batchResponse = null; Type requestBaseType = batchRequest.GetType().BaseType; if (requestBaseType != null) { Type batchResponseType = requestBaseType.GetGenericArguments()[0]; MethodInfo processMethod = batchResponseType.GetMethod("ProcessResponse", BindingFlags.NonPublic | BindingFlags.Instance); ConstructorInfo constructor = batchResponseType.GetConstructor(new Type[] { }); if (constructor != null) { batchResponse = constructor.Invoke(null); if (processMethod != null) { processMethod.Invoke(batchResponse, new object[] { webResponse, responseBody, null }); } } } return(batchResponse); }
public void Can_Build_ModifyRequest_With_Request_Filters() { //Arrange var builder = new ModifyRequestBuilder(); //Act builder.Context("/foo/bar") .ReturnNoAttributes() .FailOnError() .AddModification(Modifications.RemoveAttribute, SimpleAttribute.New(AttributeTypes.Integer, "objectId")); var request = builder.Build(); var batchRequest = new BatchRequest(request); //Assert Assert.That(request.RequestFilters.Count(), Is.EqualTo(2)); Assert.That(request.RequestFilters.ElementAt(0), Is.InstanceOf <ReturnNoAttributesFilter>()); Assert.That(request.RequestFilters.ElementAt(1), Is.InstanceOf <FailOnErrorFilter>()); Assert.DoesNotThrow(() => batchRequest.ToAdsml().ValidateAdsmlDocument("adsml.xsd")); }
private List <BatchData> CheckBatchData(BatchRequest request, List <BatchData> batchDatas) { List <BatchData> checkedbatchList = new List <BatchData>(); int i = 0; if (batchDatas.Count() == 0) { return(checkedbatchList); } foreach (var v in batchDatas) { i++; checkedbatchList.Add(v); if (v.End == true && v.StationId == request.StationId) { break; } } GetBatchList.RemoveRange(0, i); return(checkedbatchList); }
public static string ToSQL([NotNull] this BatchRequest @this) { var sqlBuilder = new StringBuilder(); if ([email protected] && [email protected]()) { sqlBuilder.Append(Invariant($"INSERT INTO {@this.Table} ")).AppendColumnsSQL(@this.Insert !); if (@this.Output.Any()) { sqlBuilder.AppendOutputSQL(@this.Output); } sqlBuilder.AppendLine().AppendValuesSQL(@this.Input.Rows); } else { sqlBuilder.Append(Invariant(@$ "MERGE {@this.Table} AS t WITH(UPDLOCK) USING ( " )).AppendValuesSQL(@this.Input.Rows).Append(@" ) AS s ").AppendColumnsSQL(@this.Input.Columns).Append(@" ON ").AppendJoin(Invariant($" {LogicalOperator.And.ToSQL()} "), @this.On.To(column => Invariant($"s.{column.EscapeIdentifier()} = t.{column.EscapeIdentifier()}")));
public void GetBatchTaskTest() { // Setup cmdlet to get a task by id BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.JobId = "job-1"; cmdlet.Id = "task1"; cmdlet.Filter = null; // Build a CloudTask instead of querying the service on a Get CloudTask call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest <CloudTaskGetParameters, CloudTaskGetResponse> request = (BatchRequest <CloudTaskGetParameters, CloudTaskGetResponse>)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { CloudTaskGetResponse response = BatchTestHelpers.CreateCloudTaskGetResponse(cmdlet.Id); Task <CloudTaskGetResponse> task = Task.FromResult(response); return(task); }; }); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List <PSCloudTask> pipeline = new List <PSCloudTask>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSCloudTask>())).Callback <object>(t => pipeline.Add((PSCloudTask)t)); cmdlet.ExecuteCmdlet(); // Verify that the cmdlet wrote the task returned from the OM to the pipeline Assert.Equal(1, pipeline.Count); Assert.Equal(cmdlet.Id, pipeline[0].Id); }
public void CreateIndividualRequest_Test() { var expectedMessage = @"POST http://sample.com/5?q=20 If-Match: ""123"" Content-Type: application/json; charset=utf-8 Content-Length: 40 {""etag_key"":""\""123\"""",""name_key"":""Name""} "; using (var service = new MockClientService("http://sample.com")) { var request = new TestClientServiceRequest(service, new MockRequest { ETag = "\"123\"", Name = "Name" }); var content = BatchRequest.CreateIndividualRequest(request).Result; var requestStr = content.ReadAsStringAsync().Result; Assert.AreEqual(expectedMessage, requestStr); } }
/// <summary> /// Deletes several products from the specified account, as a batch. /// </summary> private async Task DeleteProductsBatch(ulong merchantId, List <Product> newProductsBatch) { Console.WriteLine("================================================================="); Console.WriteLine("Deleting several products"); Console.WriteLine("================================================================="); // Create a batch request. BatchRequest request = new BatchRequest(service); foreach (Product product in newProductsBatch) { ProductsResource.DeleteRequest deleteRequest = service.Products.Delete(merchantId, product.Id); request.Queue <Product>( deleteRequest, (content, error, i, message) => { Console.WriteLine("Product deleted."); }); } await request.ExecuteAsync(CancellationToken.None); }
public void Queue <TResponse>(IClientServiceRequest request, BatchRequest.OnResponse <TResponse> callback) where TResponse : class { if (request == null) { throw new ArgumentNullException(nameof(request)); } if (callback == null) { throw new ArgumentNullException(nameof(callback)); } var currentBatch = _batches.Last(); if (currentBatch.Count == BatchSizeLimit) { currentBatch = new BatchRequest(_service); _batches.Add(currentBatch); } currentBatch.Queue(request, callback); }
public void CanGenerateApiXml() { //Arrange var expected = new XElement("CreateRequest", new XAttribute("name", "fooName"), new XAttribute("type", "fooObjectTypeName"), new XAttribute("parentIdPath", "fooPath"), new XElement("AttributesToSet", new XElement("StructureAttribute", new XAttribute("id", "215"), new XAttribute("name", "fooAttributeName"), new XElement("StructureValue", new XAttribute("langId", "10"), new XAttribute("scope", "global"), new XCData("fooValue"))))); var value = new StructureValue { LanguageId = 10, Value = "fooValue" }; var attribute = new StructureAttribute { DefinitionId = 215, Name = "fooAttributeName", Values = new List <StructureValue> { value } }; var create = new CreateRequest("fooObjectTypeName", "fooName", "fooPath", attribute); //Act var actual = create.ToAdsml(); var request = new BatchRequest(create); //Assert Assert.That(actual, Is.Not.Null); Assert.That(actual.ToString(), Is.EqualTo(expected.ToString())); Assert.DoesNotThrow(() => request.ToAdsml().ValidateAdsmlDocument("adsml.xsd")); }
internal static string GetRequestString(BatchRequest batchRequest, WebApi webApi) { var requestString = batchRequest.GetBatchBodyHeader(); foreach (var request in batchRequest.Requests) { requestString += request.GetBatchString(batchRequest, webApi, null); var nextRequest = request.NextRequest; var ContentId = batchRequest.ContentId; while (nextRequest != null) { batchRequest.ContentId++; requestString += nextRequest.GetBatchString(batchRequest, webApi, ContentId); nextRequest = nextRequest.NextRequest; } batchRequest.ContentId++; } requestString += System.Environment.NewLine + batchRequest.GetBatchBodyFooter(); return(requestString); }
public void DisableJobRequestTest() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; DisableJobOption disableOption = DisableJobOption.Terminate; DisableJobOption requestDisableOption = DisableJobOption.Requeue; cmdlet.Id = "testJob"; cmdlet.DisableJobOption = disableOption; // Don't go to the service on an Enable AutoScale call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest <CloudJobDisableParameters, CloudJobDisableResponse> request = (BatchRequest <CloudJobDisableParameters, CloudJobDisableResponse>)baseRequest; // Grab the disable option off the outgoing request. requestDisableOption = request.TypedParameters.DisableJobOption; request.ServiceRequestFunc = (cancellationToken) => { CloudJobDisableResponse response = new CloudJobDisableResponse(); Task <CloudJobDisableResponse> task = Task.FromResult(response); return(task); }; }); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; cmdlet.ExecuteCmdlet(); // Verify that the job disable option was properly set on the outgoing request Assert.Equal(disableOption, requestDisableOption); }
public async Task <BatchRequestResponse> ExecuteBatchRequestAsync(BatchRequest batchRequest) { string requestBody = BatchRequestParser.GetRequestString(batchRequest, this); var request = new HttpRequestMessage(new HttpMethod("POST"), ApiUrl + "$batch"); SetRequestContent(request, requestBody, batchRequest.BatchId); HttpResponseMessage response = await Authorization.GetHttpClient().SendAsync(request); ResponseValidator.EnsureSuccessStatusCode(response); string data = await response.Content.ReadAsStringAsync(); var batchRequestResponse = new BatchRequestResponse(data); foreach (Entity entity in batchRequestResponse.Entities) { entity.LogicalName = WebApiMetadata.GetLogicalName(entity.LogicalName); } return(batchRequestResponse); }
public void ToSQL_BatchRequest() { var date = DateTime.UtcNow; var request = new BatchRequest { Delete = false, Input = new RowSet(new[] { "ID", "Col 2", "Column3]" }, new[] { new object[] { 1, "aaa", date }, new object[] { 2, "bbb", date }, new object[] { 3, "ccc", date }, }), Insert = new[] { "Col 2", "Column3]" }, On = new[] { "ID" }, Table = "Customers", }; request.Update = null; var expected = Invariant(@$ "INSERT INTO Customers ([Col 2], [Column3]]]) VALUES (1, N'aaa', {date.ToSQL()})
private static void ShareFileById(string fileId, string filename, string recipientEmail, string senderName, RoleType roleType) { var batch = new BatchRequest(DriveService); BatchRequest.OnResponse <Permission> callback = delegate( Permission permission, RequestError error, int index, System.Net.Http.HttpResponseMessage message) { if (error != null) { MessageBox.Show("Could not share the file with " + recipientEmail + "!\nReason: " + error.Message, "Drive Crypt", MessageBoxButtons.OK, MessageBoxIcon.Error); } }; Permission userPermission = new Permission(); userPermission.Type = "user"; userPermission.Role = roleType.ToString(); userPermission.EmailAddress = recipientEmail; var request = DriveService.Permissions.Create(userPermission, fileId); request.Fields = "id"; if (Path.GetExtension(filename) == FileCryptor.DRIVE_CRYPT_EXTENSTION) { request.SendNotificationEmail = true; request.EmailMessage = string.Format("{0} has shared the following encoded file with you:\n{1}\nwhich you can view under http://drive.google.com/file/d/{2} \nbut it can only be readable after decoding, using DriveCrypt application.", senderName, filename, fileId); } else { request.SendNotificationEmail = false; } batch.Queue(request, callback); batch.ExecuteAsync(); }
public void GetBatchNodeFileByComputeNodeParametersTest() { // Setup cmdlet without required parameters BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.PoolId = null; cmdlet.ComputeNodeId = null; cmdlet.Name = null; cmdlet.ComputeNode = null; cmdlet.Filter = null; // Build a NodeFile instead of querying the service on a List NodeFile call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest <NodeFileListParameters, NodeFileListResponse> request = (BatchRequest <NodeFileListParameters, NodeFileListResponse>)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { NodeFileListResponse response = BatchTestHelpers.CreateNodeFileListResponse(new string[] { cmdlet.Name }); Task <NodeFileListResponse> task = Task.FromResult(response); return(task); }; }); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; Assert.Throws <ArgumentException>(() => cmdlet.ExecuteCmdlet()); cmdlet.PoolId = "pool"; cmdlet.ComputeNodeId = "computeNode1"; // Verify no exceptions occur cmdlet.ExecuteCmdlet(); }
private async Task <List <Appointment> > AddCalendarEventsInternal(List <Appointment> calendarAppointments, bool addDescription, bool addReminder, bool addAttendees, bool attendeesToDescription, CalendarService calendarService, Dictionary <int, Appointment> errorList) { var addedEvents = new List <Appointment>(); //Create a Batch Request var batchRequest = new BatchRequest(calendarService); for (var i = 0; i < calendarAppointments.Count; i++) { if (i != 0 && i % 999 == 0) { await batchRequest.ExecuteAsync(); batchRequest = new BatchRequest(calendarService); } var appointment = calendarAppointments[i]; var calendarEvent = CreateGoogleCalendarEvent(appointment, addDescription, addReminder, addAttendees, attendeesToDescription); var insertRequest = calendarService.Events.Insert(calendarEvent, CalendarId); insertRequest.SendNotifications = false; insertRequest.MaxAttendees = 10000; batchRequest.Queue <Event>(insertRequest, (content, error, index, message) => CallbackEventErrorMessage(content, error, index, message, calendarAppointments, "Error in adding events", errorList, addedEvents)); } await batchRequest.ExecuteAsync(); return(addedEvents); }
public async Task BatchRequestNoRetryPolicyNoRetriesExecutedWithAggregateException() { int serviceRequestFuncCallCount = 0; var request = new BatchRequest < JobScheduleListOptions, AzureOperationResponse <IPage <ProxyModels.CloudJobSchedule> > >(null, CancellationToken.None); request.ServiceRequestFunc = async(token) => { ++serviceRequestFuncCallCount; void throwsAction() { throw new ArgumentException(); } Task throwsTask1 = Task.Factory.StartNew(throwsAction); Task throwsTask2 = Task.Factory.StartNew(throwsAction); await Task.WhenAll(throwsTask1, throwsTask2); //This will throw return(null); }; Task executeRequestTask = request.ExecuteRequestAsync(); //We will observe only 1 exception (not an Aggregate) from the throw ArgumentException e = await Assert.ThrowsAsync <ArgumentException>(async() => { await executeRequestTask; }); //But the task itself should have the full set of exceptions which were hit AggregateException aggregateException = executeRequestTask.Exception; //TODO: Why can't this be 2? //Assert.Equal(2, aggregateException.InnerExceptions.Count); Assert.Single(aggregateException.InnerExceptions); Assert.Equal(1, serviceRequestFuncCallCount); }
/// <summary> /// Adds several products to the specified account, as a batch. /// </summary> /// <returns>The task containing the list of products</returns> private async Task<List<Product>> InsertProductBatch(ulong merchantId) { Console.WriteLine("================================================================="); Console.WriteLine("Inserting several products"); Console.WriteLine("================================================================="); // Create a batch request. BatchRequest request = new BatchRequest(service); List<Product> products = new List<Product>(); // Add three product insertions to the queue. for (int i = 0; i < 3; i++) { ProductsResource.InsertRequest insertRequest = service.Products.Insert(shoppingUtil.GenerateProduct(), merchantId); request.Queue<Product>( insertRequest, (content, error, index, message) => { products.Add(content); Console.WriteLine(String.Format("Product inserted with id {0}", ((Product)content).Id)); }); } await request.ExecuteAsync(CancellationToken.None); return products; }
/// <summary> /// Deletes several products from the specified account, as a batch. /// </summary> private async Task DeleteProductsBatch(ulong merchantId, List<Product> newProductsBatch) { Console.WriteLine("================================================================="); Console.WriteLine("Deleting several products"); Console.WriteLine("================================================================="); // Create a batch request. BatchRequest request = new BatchRequest(service); foreach (Product product in newProductsBatch) { ProductsResource.DeleteRequest deleteRequest = service.Products.Delete(merchantId, product.Id); request.Queue<Product>( deleteRequest, (content, error, i, message) => { Console.WriteLine("Product deleted."); }); } await request.ExecuteAsync(CancellationToken.None); }
public virtual AstoriaResponse GetResponse() { LogRequest(); OnSend(this); // NOTHING should come in between this and actually sending the request #if !ClientSKUFramework SetupAPICallLog(); #endif AstoriaResponse response; if (AstoriaTestProperties.BatchAllRequests) { BatchRequest batchRequest = new BatchRequest(Workspace); if (Verb_Internal == RequestVerb.Get) batchRequest.Add(this); else { BatchChangeset changeset = batchRequest.GetChangeset(); changeset.Add(this); } BatchResponse batchResponse = batchRequest.GetResponse() as BatchResponse; response = batchResponse.Responses.FirstOrDefault(); } else response = RequestSender.SendRequest(this); #if !ClientSKUFramework // NOTHING should come in between this and actually recieving the response RetrieveAPICallLog(); #endif OnReceive(this, response); return response; }
public static BatchResponse ParseBatchResponse(BatchRequest batchRequest, StringReader reader, string boundary) { // even if content-id is specified, we may not get it back in error cases. This doesn't feel entirely correct, it seems like there should // always be a 1-1 mapping that explicitly honors content-id's // TODO: responses / requests without content IDs should be matched up in order within changeset only // changesets should have the right number of responses too BatchResponse response = null;// new BatchResponse(batchRequest); List<ResponseFragment> unmatchedFragments = new List<ResponseFragment>(); List<AstoriaRequest> unmatchedRequests = batchRequest.Requests .Union(batchRequest.Changesets.SelectMany(changeset => changeset.AsEnumerable())) .ToList(); foreach (ResponseFragment fragment in ParseBatchResponse(reader, boundary)) { AstoriaRequest request = null; if (fragment.ContentID != null) request = unmatchedRequests .FirstOrDefault(r => r.Headers.ContainsKey("Content-ID") && r.Headers["Content-ID"].Equals(fragment.ContentID)); if (request == null) unmatchedFragments.Add(fragment); else { unmatchedRequests.Remove(request); response.Responses.Add(FragmentToResponse(request, fragment)); } } if (unmatchedFragments.Any()) { if (unmatchedFragments.Count < unmatchedRequests.Count) AstoriaTestLog.WriteLine("Warning: recieved fewer batch response fragments than expected"); else if (unmatchedFragments.Count > unmatchedRequests.Count) AstoriaTestLog.FailAndThrow("Recieved more batch fragments than expected"); for (int i = 0; i < unmatchedFragments.Count; i++) { response.Responses.Add(FragmentToResponse(unmatchedRequests[i], unmatchedFragments[i])); } } return response; }
public async System.Threading.Tasks.Task UploadResults() { var request = new BatchRequest(Service); foreach (WorkDay day in Schedule) { // Setup request for current events. EventsResource.ListRequest listrequest = Service.Events.List(Calendarid); listrequest.TimeMin = DateTime.Today.AddDays(-6); listrequest.TimeMax = DateTime.Today.AddDays(15); listrequest.ShowDeleted = false; listrequest.SingleEvents = true; listrequest.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime; // Check to see if work events are already in place on the schedule, if they are, // setup a batch request to delete them. // Not the best implementation, but takes care of duplicates without tracking // eventIds to update existing events. String workevent = "Wegmans: "; Events eventslist = listrequest.Execute(); if (eventslist.Items != null && eventslist.Items.Count > 0) { foreach (Event eventItem in eventslist.Items) { if(eventItem.Start.DateTime != null) { DateTime eventcontainer = (DateTime)eventItem.Start.DateTime; // Typecast to use ToShortDateString() method for comparison. if (((eventcontainer.ToShortDateString()) == (day.Date.ToShortDateString())) && (eventItem.Summary.Contains(workevent))) { request.Queue<Event>(Service.Events.Delete(Calendarid, eventItem.Id), (content, error, i, message) => { if (error != null) { throw new Exception(error.ToString()); } }); } } } } // Setup a batch request to upload the work events. request.Queue<Event>(Service.Events.Insert( new Event { Summary = workevent + day.Activity, Description = day.Comments, Location = day.Location, Start = new EventDateTime() { DateTime = day.StartDateTime, TimeZone = "America/New_York", }, End = new EventDateTime() { DateTime = day.EndDateTime, TimeZone = "America/New_York", }, Reminders = new Event.RemindersData() { UseDefault = true, }, }, Calendarid), (content, error, i, message) => { if (error != null) { throw new Exception(error.ToString()); } }); } // Execute batch request. await request.ExecuteAsync(); }
public BatchResponse ExecuteBatchRequest(BatchRequest request) { ParseResponse pr = new ParseResponse(); string opXml = Wbem.CimXml.CreateRequest.ToXml(request); string respXml = ExecuteRequest("BatchRequest", opXml); return pr.ParseXml(respXml); }
public async Task<CalendarAppointments> DeleteCalendarEvents(List<Appointment> calendarAppointments, IDictionary<string, object> calendarSpecificData) { var deletedAppointments = new CalendarAppointments(); if (!calendarAppointments.Any()) { deletedAppointments.IsSuccess = true; return deletedAppointments; } CheckCalendarSpecificData(calendarSpecificData); var errorList = new Dictionary<int, Appointment>(); //Get Calendar Service var calendarService = GetCalendarService(AccountName); if (calendarAppointments == null || string.IsNullOrEmpty(CalendarId)) { deletedAppointments.IsSuccess = false; return deletedAppointments; } try { if (calendarAppointments.Any()) { //Create a Batch Request var batchRequest = new BatchRequest(calendarService); //Split the list of calendarAppointments by 1000 per list //Iterate over each appointment to create a event and batch it for (var i = 0; i < calendarAppointments.Count; i++) { if (i != 0 && i % 999 == 0) { await batchRequest.ExecuteAsync(); batchRequest = new BatchRequest(calendarService); } var appointment = calendarAppointments[i]; var deleteRequest = calendarService.Events.Delete(CalendarId, appointment.AppointmentId); batchRequest.Queue<Event>(deleteRequest, (content, error, index, message) => CallbackEventErrorMessage(content, error, index, message, calendarAppointments, "Error in deleting events",errorList,deletedAppointments)); } await batchRequest.ExecuteAsync(); } } catch (Exception exception) { Logger.Error(exception); deletedAppointments.IsSuccess = false; return deletedAppointments; } deletedAppointments.IsSuccess = true; return deletedAppointments; }
/// <summary> /// Metoda wysyła wszystkie zdarzenia do kalendarza jako jeden request. /// Wykonywana po zaktualizowaniu wszystkich zdarzeń z bazy danych. /// </summary> public async Task SendEventsRequest() { Logs.WriteErrorLog("SendEventsRequest " +Request.Count.ToString()); await Request.ExecuteAsync(); Request = new BatchRequest(Service); }
/// <summary> /// Metoda tworząca listę wydarzeń do kalendarza. /// </summary> /// <param name="booking">Pojedyncza rezerwacja z listą gości.</param> public void MakeEventRequest(SimpleBookingUser booking) { Logs.WriteErrorLog("Robie request eventa (wrzucam zdarzenia na kolejke)."); Logs.WriteErrorLog(booking.BookingEndTime.ToString("g")); Logs.WriteErrorLog(booking.BookingBeginTime.ToString("g")); var eventStartDateTime = new EventDateTime { DateTime = booking.BookingBeginTime }; Logs.WriteErrorLog("Moja data rozp: " + eventStartDateTime.DateTime.ToString()); var eventEndDateTime = new EventDateTime { DateTime = booking.BookingEndTime }; Logs.WriteErrorLog("Moja data zakonczenia: " + eventEndDateTime.DateTime.ToString()); Request = new BatchRequest(Service); Logs.WriteErrorLog("tytul: " + booking.BookingTitle); Logs.WriteErrorLog("Opis" + booking.BookingDescription); Request.Queue<Event>(Service.Events.Insert( new Event { Summary = booking.BookingTitle, Description = booking.BookingDescription, Start = eventStartDateTime, End = eventEndDateTime }, CalendarId), (content, error, i, message) => { //Do wypełnienia "Callback" }); Logs.WriteErrorLog("Wrzucilem."); }
/// <summary> /// Generates an HttpRequestMessage from the BatchRequest. /// </summary> private static HttpRequestMessage GenerateHttpRequest(BatchRequest batchRequest) { HttpRequestMessage requestMessage = null; Uri uri = null; // Since we aren't directly using the Protocol Layer to send the request, we have to extract the pieces to create the signed web request // that we can convert into a format compatible with the HTTP Recorder. MethodInfo getResourceMethod = batchRequest.GetType().GetMethod("GetResourceUri", BindingFlags.NonPublic | BindingFlags.Instance); if (getResourceMethod != null) { uri = getResourceMethod.Invoke(batchRequest, null) as Uri; } // Get the generated HttpWebRequest from the BatchRequest MethodInfo createCommandMethod = batchRequest.GetType().GetMethod("CreateRestCommand", BindingFlags.NonPublic | BindingFlags.Instance); if (createCommandMethod != null) { object command = createCommandMethod.Invoke(batchRequest, null); FieldInfo buildRequestField = command.GetType().GetField("BuildRequestDelegate", BindingFlags.Public | BindingFlags.Instance); if (buildRequestField != null) { PropertyInfo currentResultProperty = command.GetType().GetProperty("CurrentResult", BindingFlags.NonPublic | BindingFlags.Instance); if (currentResultProperty != null) { currentResultProperty.SetValue(command, new RequestResult()); } Delegate buildRequest = buildRequestField.GetValue(command) as Delegate; if (buildRequest != null) { HttpWebRequest webRequest = buildRequest.DynamicInvoke(uri, null, false, null, null) as HttpWebRequest; if (webRequest != null) { // Delete requests set a Content-Length of 0 with the HttpRequestMessage class for some reason. // Add in this header before signing the request. if (webRequest.Method == "DELETE") { webRequest.ContentLength = 0; } // Sign the request to add the Authorization header batchRequest.AuthenticationHandler.SignRequest(webRequest, null); // Convert the signed HttpWebRequest into an HttpRequestMessage for use with the HTTP Recorder requestMessage = new HttpRequestMessage(new HttpMethod(webRequest.Method), webRequest.RequestUri); foreach (var header in webRequest.Headers) { string key = header.ToString(); string value = webRequest.Headers[key]; if (string.Equals(key, "Content-Type")) { // Copy the Content to the HttpRequestMessage FieldInfo streamField = command.GetType().GetField("SendStream", BindingFlags.Public | BindingFlags.Instance); if (streamField != null) { Stream contentStream = streamField.GetValue(command) as Stream; if (contentStream != null) { MemoryStream memStream = new MemoryStream(); contentStream.CopyTo(memStream); memStream.Seek(0, SeekOrigin.Begin); requestMessage.Content = new StreamContent(memStream); // Add Content-Type header to the HttpRequestMessage // Use a custom class to force the proper formatting of the Content-Type header. requestMessage.Content.Headers.ContentType = new JsonOdataMinimalHeader(); requestMessage.Content.Headers.ContentLength = webRequest.ContentLength; } } } else { requestMessage.Headers.Add(key, value); } } } } } } return requestMessage; }
/// <summary> /// Serializes an HttpWebRespone and response body into a BatchResponse /// </summary> private static object GenerateBatchResponse(BatchRequest batchRequest, HttpWebResponse webResponse, Stream responseBody) { object batchResponse = null; MethodInfo createCommandMethod = batchRequest.GetType().GetMethod("CreateRestCommand", BindingFlags.NonPublic | BindingFlags.Instance); if (createCommandMethod != null) { object command = createCommandMethod.Invoke(batchRequest, null); FieldInfo preProcessField = command.GetType().GetField("PreProcessResponse", BindingFlags.Public | BindingFlags.Instance); if (preProcessField != null) { Delegate preProcessDelegate = preProcessField.GetValue(command) as Delegate; if (preProcessDelegate != null) { preProcessDelegate.DynamicInvoke(command, webResponse, null, null); } } FieldInfo postProcessField = command.GetType().GetField("PostProcessResponse", BindingFlags.Public | BindingFlags.Instance); if (postProcessField != null) { Delegate postProcessDelegate = postProcessField.GetValue(command) as Delegate; if (postProcessDelegate != null) { FieldInfo responseStreamField = command.GetType().GetField("ResponseStream", BindingFlags.Public | BindingFlags.Instance); if (responseStreamField != null) { responseStreamField.SetValue(command, responseBody); } FieldInfo destinationStreamField = command.GetType().GetField("DestinationStream", BindingFlags.Public | BindingFlags.Instance); if (destinationStreamField != null) { Stream destinationStream = destinationStreamField.GetValue(command) as Stream; if (destinationStream != null) { responseBody.CopyTo(destinationStream); } } batchResponse = postProcessDelegate.DynamicInvoke(command, webResponse, null, null); } } } return batchResponse; }
public async Task<TasksWrapper> UpdateReminderTasks(List<ReminderTask> reminderTasks, IDictionary<string, object> taskListSpecificData) { var updatedAppointments = new TasksWrapper(); if (!reminderTasks.Any()) { updatedAppointments.IsSuccess = true; return updatedAppointments; } CheckTaskListSpecificData(taskListSpecificData); var errorList = new Dictionary<int, ReminderTask>(); //Get Calendar Service var calendarService = GetTasksService(AccountName); if (reminderTasks == null || string.IsNullOrEmpty(TaskListId)) { updatedAppointments.IsSuccess = false; return updatedAppointments; } try { if (reminderTasks.Any()) { //Create a Batch Request var batchRequest = new BatchRequest(calendarService); //Split the list of calendarAppointments by 1000 per list //Iterate over each appointment to create a event and batch it for (var i = 0; i < reminderTasks.Count; i++) { if (i != 0 && i % 999 == 0) { await batchRequest.ExecuteAsync(); batchRequest = new BatchRequest(calendarService); } var appointment = reminderTasks[i]; var task = CreateUpdatedGoogleTask(appointment); var updateRequest = calendarService.Tasks.Update(task, TaskListId, task.Id); batchRequest.Queue<Task>(updateRequest, (content, error, index, message) => CallbackEventErrorMessage(content, error, index, message, reminderTasks, "Error in updating event", errorList, updatedAppointments)); } await batchRequest.ExecuteAsync(); } } catch (Exception exception) { Logger.Error(exception); updatedAppointments.IsSuccess = false; return updatedAppointments; } updatedAppointments.IsSuccess = reminderTasks.Count == updatedAppointments.Count; return updatedAppointments; }
private async Task<List<ReminderTask>> AddTasksInternal(List<ReminderTask> reminderTasks, TasksService taskService, Dictionary<int, ReminderTask> errorList) { var addedEvents = new List<ReminderTask>(); //Create a Batch Request var batchRequest = new BatchRequest(taskService); for (var i = 0; i < reminderTasks.Count; i++) { if (i != 0 && i % 999 == 0) { await batchRequest.ExecuteAsync(); batchRequest = new BatchRequest(taskService); } var reminderTask = reminderTasks[i]; var googleTask = CreaterGoogleTask(reminderTask); var insertRequest = taskService.Tasks.Insert(googleTask, TaskListId); batchRequest.Queue<Task>(insertRequest, (content, error, index, message) => CallbackEventErrorMessage(content, error, index, message, reminderTasks, "Error in adding events", errorList, addedEvents)); } await batchRequest.ExecuteAsync(); return addedEvents; }
public async Task<ActionResult> Index(CancellationToken cancellationToken, string q = null) { var result = await new AuthorizationCodeMvcApp(this, new MyMailFlowMetadata()).AuthorizeAsync(cancellationToken); if (result.Credential != null) { List<Message> messages = new List<Message>(); List<Label> labels = new List<Label>(); var service = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = result.Credential, ApplicationName = ApplicationName }); UsersResource.LabelsResource.ListRequest labelsRequest = service.Users.Labels.List("me"); UsersResource.MessagesResource.ListRequest messagesRequest = service.Users.Messages.List("me"); messagesRequest.Q = q ?? "label:inbox "; ListLabelsResponse labelsResponse = null; ListMessagesResponse messagesResponse = null; var batchRequests = new BatchRequest(service); batchRequests.Queue<ListLabelsResponse>(labelsRequest, (content, error, i, message) => { labelsResponse = content; }); batchRequests.Queue<ListMessagesResponse>(messagesRequest, (content, error, i, message) => { messagesResponse = content; }); await batchRequests.ExecuteAsync(); batchRequests = new BatchRequest(service); foreach (var label in labelsResponse.Labels) { batchRequests.Queue<Label>(service.Users.Labels.Get("me", label.Id), (content, error, i, label2) => { labels.Add(content); }); } foreach (var message in messagesResponse.Messages) { batchRequests.Queue<Message>(service.Users.Messages.Get("me", message.Id), (content, error, i, message2) => { messages.Add(content); }); } await batchRequests.ExecuteAsync(); ViewBag.Labels = labels; ViewBag.Messages = messages; return View(); } else { return new RedirectResult(result.RedirectUri); } }
public void BatchRequestTests() { var ytService1 = NewTestYouTubeService("OAUTH-ACCESSTOKEN-1", "RefreshToken"); var batchRequest = new BatchRequest(ytService1); var x = batchRequest.GetService(); }
private async Task<List<Appointment>> AddCalendarEventsInternal(List<Appointment> calendarAppointments, bool addDescription, bool addReminder, bool addAttendees, bool attendeesToDescription, CalendarService calendarService, Dictionary<int, Appointment> errorList) { var addedEvents = new List<Appointment>(); //Create a Batch Request var batchRequest = new BatchRequest(calendarService); for (var i = 0; i < calendarAppointments.Count; i++) { if (i != 0 && i % 999 == 0) { await batchRequest.ExecuteAsync(); batchRequest = new BatchRequest(calendarService); } var appointment = calendarAppointments[i]; var calendarEvent = CreateGoogleCalendarEvent(appointment, addDescription, addReminder, addAttendees, attendeesToDescription); var insertRequest = calendarService.Events.Insert(calendarEvent, CalendarId); insertRequest.MaxAttendees = 10000; batchRequest.Queue<Event>(insertRequest, (content, error, index, message) => CallbackEventErrorMessage(content, error, index, message, calendarAppointments, "Error in adding events",errorList, addedEvents)); } await batchRequest.ExecuteAsync(); return addedEvents; }
public async Task<AppointmentsWrapper> UpdateCalendarEvents(List<Appointment> calendarAppointments, bool addDescription, bool addReminder, bool addAttendees, bool attendeesToDescription, IDictionary<string, object> calendarSpecificData) { var updatedAppointments = new AppointmentsWrapper(); if (!calendarAppointments.Any()) { updatedAppointments.IsSuccess = true; return updatedAppointments; } CheckCalendarSpecificData(calendarSpecificData); var errorList = new Dictionary<int, Appointment>(); //Get Calendar Service var calendarService = GetCalendarService(AccountName); if (calendarAppointments == null || string.IsNullOrEmpty(CalendarId)) { updatedAppointments.IsSuccess = false; return updatedAppointments; } try { if (calendarAppointments.Any()) { //Create a Batch Request var batchRequest = new BatchRequest(calendarService); //Split the list of calendarAppointments by 1000 per list //Iterate over each appointment to create a event and batch it for (var i = 0; i < calendarAppointments.Count; i++) { if (i != 0 && i % 999 == 0) { await batchRequest.ExecuteAsync(); batchRequest = new BatchRequest(calendarService); } var appointment = calendarAppointments[i]; var calendarEvent = CreateUpdatedGoogleCalendarEvent(appointment, addDescription, addReminder, addAttendees, attendeesToDescription); var updateRequest = calendarService.Events.Update(calendarEvent, CalendarId, calendarEvent.Id); batchRequest.Queue<Event>(updateRequest, (content, error, index, message) => CallbackEventErrorMessage(content, error, index, message, calendarAppointments, "Error in updating event",errorList,updatedAppointments)); } await batchRequest.ExecuteAsync(); } } catch (Exception exception) { Logger.Error(exception); updatedAppointments.IsSuccess = false; return updatedAppointments; } updatedAppointments.IsSuccess = true; return updatedAppointments; }
public static string ToXml(BatchRequest batch) { CimXmlWriter cxw = new CimXmlWriter(); if (batch.Count > 1) cxw.WriteMultiReqElement(); foreach (SingleRequest curOp in batch) { CimName tmpNameSpace = string.Empty; // Namespace if (curOp.Namespace == null) tmpNameSpace = batch.DefaultNamespace; else tmpNameSpace = curOp.Namespace; cxw.WriteSimpleReqElement(); switch (curOp.ReqType) { case SingleRequest.RequestType.GetClass: GetClass(cxw, (GetClassOpSettings)curOp, tmpNameSpace); break; case SingleRequest.RequestType.GetInstance: GetInstance(cxw, (GetInstanceOpSettings)curOp, tmpNameSpace); break; case SingleRequest.RequestType.DeleteClass: DeleteClass(cxw, (DeleteClassOpSettings)curOp, tmpNameSpace); break; case SingleRequest.RequestType.DeleteInstance: DeleteInstance(cxw, (DeleteInstanceOpSettings)curOp, tmpNameSpace); break; case SingleRequest.RequestType.CreateClass: CreateClass(cxw, (CreateClassOpSettings)curOp, tmpNameSpace); break; case SingleRequest.RequestType.ModifyClass: ModifyClass(cxw, (ModifyClassOpSettings)curOp, tmpNameSpace); break; case SingleRequest.RequestType.ModifyInstance: ModifyInstance(cxw, (ModifyInstanceOpSettings)curOp, tmpNameSpace); break; case SingleRequest.RequestType.EnumerateClasses: EnumerateClasses(cxw, (EnumerateClassesOpSettings)curOp, tmpNameSpace); break; case SingleRequest.RequestType.EnumerateClassNames: EnumerateClassNames(cxw, (EnumerateClassNamesOpSettings)curOp, tmpNameSpace); break; case SingleRequest.RequestType.EnumerateInstances: EnumerateInstances(cxw, (EnumerateInstancesOpSettings)curOp, tmpNameSpace); break; case SingleRequest.RequestType.EnumerateInstanceNames: EnumerateInstanceNames(cxw, (EnumerateInstanceNamesOpSettings)curOp, tmpNameSpace); break; case SingleRequest.RequestType.CreateInstance: CreateInstance(cxw, (CreateInstanceOpSettings)curOp, tmpNameSpace); break; case SingleRequest.RequestType.GetProperty: GetProperty(cxw, (GetPropertyOpSettings)curOp, tmpNameSpace); break; case SingleRequest.RequestType.InvokeMethod: InvokeMethod(cxw, (InvokeMethodOpSettings)curOp, tmpNameSpace); break; case SingleRequest.RequestType.SetProperty: SetProperty(cxw, (SetPropertyOpSettings)curOp, tmpNameSpace); break; case SingleRequest.RequestType.GetQualifier: GetQualifier(cxw, (GetQualifierOpSettings)curOp, tmpNameSpace); break; case SingleRequest.RequestType.SetQualifier: SetQualifier(cxw, (SetQualifierOpSettings)curOp, tmpNameSpace); break; case SingleRequest.RequestType.DeleteQualifier: DeleteQualifier(cxw, (DeleteQualifierOpSettings)curOp, tmpNameSpace); break; case SingleRequest.RequestType.EnumerateQualifiers: EnumerateQualifiers(cxw, (EnumerateQualifierOpSettings)curOp, tmpNameSpace); break; case SingleRequest.RequestType.ExecuteQuery: ExecuteQuery(cxw, (ExecuteQueryOpSettings)curOp, tmpNameSpace); break; case SingleRequest.RequestType.ExecQuery: ExecQuery(cxw, (ExecQueryOpSettings)curOp, tmpNameSpace); break; case SingleRequest.RequestType.Associators: Associators(cxw, (AssociatorsOpSettings)curOp, tmpNameSpace); break; case SingleRequest.RequestType.AssociatorNames: AssociatorNames(cxw, (AssociatorNamesOpSettings)curOp, tmpNameSpace); break; case SingleRequest.RequestType.References: References(cxw, (ReferencesOpSettings)curOp, tmpNameSpace); break; case SingleRequest.RequestType.ReferenceNames: ReferenceNames(cxw, (ReferenceNamesOpSettings)curOp, tmpNameSpace); break; default: throw (new Exception("Not Implemented Yet")); } //</SIMPLEREQ> cxw.WriteEndElement(); } if (batch.Count > 1) cxw.WriteEndElement(); // </MULTIREQ> return cxw.ToString(); }