Example #1
0
        public void WhenRemoveLastMessageShouldRemoveIt()
        {
            var batchMessage = new Message(new Uri("http://post.com"), "payload");
            batchMessage.Id = 1;
            var batch = new Batch();
            batch.Add(batchMessage);
            batchMessage = new Message(new Uri("http://post2.com"), "payload2");
            batchMessage.Id = 2;
            batch.Add(batchMessage);
            batchMessage = new Message(new Uri("http://post3.com"), "payload3");
            batchMessage.Id = 3;
            batch.Add(batchMessage);

            batch.RemoveLastMessage();

            Assert.Equal(2, batch.Events.Count);
            var message = batch.Events[0];
            Assert.Equal("http://post.com/", message.Url.AbsoluteUri);
            Assert.Equal(1, message.ReynaId);
            Assert.Equal("payload", message.Payload);

            message = batch.Events[1];
            Assert.Equal("http://post2.com/", message.Url.ToString());
            Assert.Equal(2, message.ReynaId);
            Assert.Equal("payload2", message.Payload);
        }
Example #2
0
        public void AddTransactionMethod_AmountLessThanTenDollars_ThrowsException()
        {
            var transaction = new Transaction { Id = 91325125, Amount = 9.99M };

            var sut = new Batch();
            sut.AddTransaction(transaction);
        }
Example #3
0
        /// <summary>
        /// Create a new test batch
        /// </summary>
        /// <param name="name">Name of the test batch</param>
        /// <param name="description">Description of the test batch</param>
        /// <param name="tests">Array containing all of the tests to add to the batch</param>
        /// <returns></returns>
        public Boolean CreateBatch(String name, String description, ScriptInfo[] tests)
        {
            //set the batch's properties
            Batch temp = new Batch();
            temp.name = name;
            temp.description = description;
            temp.scripts = tests;
            bool result;

            //create the batch
            try
            {
                result= Connection.Servicer.makeBatch(temp);
            }
            catch (System.Net.WebException e)
            {
                error = e.Message;
                error_type = MessageBoxIcon.Error;
                return false;
            }

            //batch creation failed
            if (!result)
            {
                error = "An error occured while creating the batch.  Please try again.";
                error_type = MessageBoxIcon.Error;
                return false;
            }

            return true;
        }
Example #4
0
        public ImperativeRenderer(
            IBatchContainer container,
            DefaultMaterialSet materials,
            int layer = 0, 
            RasterizerState rasterizerState = null,
            DepthStencilState depthStencilState = null,
            BlendState blendState = null,
            SamplerState samplerState = null,
            bool worldSpace = true,
            bool useZBuffer = false,
            bool autoIncrementSortKey = false,
            bool autoIncrementLayer = false
        )
        {
            if (container == null)
                throw new ArgumentNullException("container");
            if (materials == null)
                throw new ArgumentNullException("materials");

            Container = container;
            Materials = materials;
            Layer = layer;
            RasterizerState = rasterizerState;
            DepthStencilState = depthStencilState;
            BlendState = blendState;
            SamplerState = samplerState;
            UseZBuffer = useZBuffer;
            WorldSpace = worldSpace;
            AutoIncrementSortKey = autoIncrementSortKey;
            AutoIncrementLayer = autoIncrementLayer;
            NextSortKey = 0;
            PreviousBatch = null;
        }
 protected void ExecuteBatch(Batch batch)
 {
     WriteStart(batch);
     Batch[] batches = batch(null);
     ExecuteBatches(batches);
     WriteEnd(batch);
 }
 protected virtual int GetBatchIdForNextMessageTo(string destination)
 {
     lock (_batches)
     {
         Batch b;
         if (!_batches.TryGetValue(destination, out b))
         {
             b = new Batch
             {
                 Id = _batchCnt++,
                 Count = 1
             };
             _batches[destination] = b;
         }
         else
         {
             b.Count++;
             if (b.Count > BatchSize)
             {
                 b.Count = 0;
                 b.Id = _batchCnt++;
             }
         }
         return b.Id;
     }
 }
Example #7
0
 public static Batch CreateOrders2()
 {
     var b = new Batch();
     var o = new PurchaseOrder();
     o.CustId = "0815";
     var i = new Item();
     i.ProdId = "1234";
     i.Price = 37;
     i.Quantity = 2;
     o.Item.Add(i);
     i = new Item();
     i.ProdId = "5678";
     i.Price = 1.5;
     i.Quantity = 3;
     o.Item.Add(i);
     b.PurchaseOrder.Add(o);
     o = new PurchaseOrder();
     o.CustId = "1324";
     i = new Item();
     i.ProdId = "7788";
     i.Price = 42;
     i.Quantity = 1;
     b.PurchaseOrder.Add(o);
     return b;
 }
Example #8
0
 public void AddTransactionMethod_TransactionInput_IncrementsCount()
 {
     var sut = new Batch();
     Assert.AreEqual(0, sut.Transactions.Count());
     sut.AddTransaction(new Transaction {Id = 91352, Amount = 10.01M});
     Assert.AreEqual(1, sut.Transactions.Count());
 }
Example #9
0
        public void AddTransactionMethod_DuplicateInput_ThrowsException()
        {
            var transaction = new Transaction { Id = 91325125, Amount = 10.01M };

            var sut = new Batch();
            sut.AddTransaction(transaction);
            sut.AddTransaction(transaction);
        }
Example #10
0
        public void WhenCallingToJsonWithEmptyEventsShouldReturnExpected()
        {
            var batch = new Batch();

            var expected = "{\"events\":[]}";
            var actual = batch.ToJson();
            Assert.Equal(expected, actual);
        }
 protected void ExecuteBatches(Batch[] batches)
 {
     if (batches != null)
         foreach (Batch batch in batches)
         {
             ExecuteBatch(batch);
         }
 }
Example #12
0
 public Batch BillForMonthlyCharge(DateTime today)
 {
     DisallowManualChargesForOntarioCustomers(this);
     var transaction = new Transaction { Id = 3945, Amount = this.PackagePrice };
     var batch = new Batch();
     batch.AddTransaction(transaction);
     return batch;
 }
Example #13
0
 static double CalculateTotal(Batch os)
 {
     double Total = 0.0;
     foreach (PurchaseOrder o in os.PurchaseOrder)
         foreach (Item i in o.Item)
             Total += i.Price * i.Quantity;
     return Total;
 }
Example #14
0
 static double CalculateTotal(Batch batch)
 {
     return
         (from purchaseOrder in batch.PurchaseOrder
          from item in purchaseOrder.Item
          select item.Price * item.Quantity
         ).Sum();
 }
 protected void WriteStart(Batch batch)
 {
     if (batch.IsIgnored())
     {
         return;
     }
     string name = batch.Method.GetParameters()[0].Name;
     if (!string.IsNullOrEmpty(name)) NodeWriter.WriteStartNode(new NamedNode(name));
 }
Example #16
0
        //Adding Sprint
        //GET
        public ActionResult Add()
        {
            var obj = new Sprints();
            //batch list
            Batch b = new Batch();
            b.BatchList = new SelectList(b.GetAllBatches(),"BatchID","BatchDescription");
            obj.Batch = b;

            return View(obj);
        }
Example #17
0
        //Adding Batch
        //GET
        public ActionResult Add()
        {
            //object Batch
            var obj = new Batch();
            //sites list
            Sites s = new Sites();
            s.SitesList = new SelectList(s.GetAllSites(), "SiteID", "SiteName");
            obj.Sites = s;

            return View(obj);
        }
Example #18
0
 private void AddIndicesAndVerticesForGlyph(Batch batch, GlyphDrawData glyph)
 {
     batch.AddIndices();
     batch.verticesColorUV[batch.verticesIndex++] = new VertexPosition2DColorUV(
         position + glyph.DrawArea.TopLeft, color, glyph.UV.TopLeft);
     batch.verticesColorUV[batch.verticesIndex++] = new VertexPosition2DColorUV(
         position + glyph.DrawArea.TopRight, color, glyph.UV.TopRight);
     batch.verticesColorUV[batch.verticesIndex++] = new VertexPosition2DColorUV(
         position + glyph.DrawArea.BottomRight, color, glyph.UV.BottomRight);
     batch.verticesColorUV[batch.verticesIndex++] = new VertexPosition2DColorUV(
         position + glyph.DrawArea.BottomLeft, color, glyph.UV.BottomLeft);
 }
 public EventHubEventProcessor(
     IPartitionKeyGenerator generator,
     ISettings settings,
     IBatchSender batchSender,
     IJsonConverter jsonConverter)
 {
     this.MaxBatchSize = 1024 * settings.GetInt32("MaxBatchSizeKB", 192);
       this.keyGenerator = generator;
       this.batchSender = batchSender;
       this.jsonConverter = jsonConverter;
       this.currentBatch = Batch<EventData>.Empty(MaxBatchSize);
 }
Example #20
0
 public Batch<Tuple<FileInfo, string>> Abfrage_beimischen(Batch<FileInfo> dateien)
 {
     var filteraufträge = new Batcher<Tuple<FileInfo, string>>(dateien.Elements.Length);
     dateien.ForEach(t =>
                         {
                             var suchvorgang = _suchvorgänge[dateien.CorrelationId];
                             var filterauftrag = new Tuple<FileInfo, string>(t, suchvorgang.Abfrage);
                             filteraufträge.Add(filterauftrag);
                         });
     if (dateien.GetType() == typeof(EndOfStreamBatch<FileInfo>))
         return filteraufträge.GrabAsEndOfStream(dateien.CorrelationId);
     return filteraufträge.Grab(dateien.CorrelationId);
 }
Example #21
0
        public void WhenCallingAddShouldAddNewMessage()
        {
            var batchMessage = new Message(new Uri("http://post.com/1/info"), "payload");
            batchMessage.Id = 1;
            var batch = new Batch();
            batch.Add(batchMessage);

            Assert.Equal(1, batch.Events.Count);
            var message = batch.Events[0];
            Assert.Equal("http://post.com/1/info", message.Url.AbsoluteUri);
            Assert.Equal(1, message.ReynaId);
            Assert.Equal("payload", message.Payload);
        }
Example #22
0
 public static bool TryReadBatch(Stream stream, out Batch batch)
 {
     try
     {
         batch = serializer.Deserialize<Batch>(new StreamReader(stream).ReadToEnd());
         return true;
     }
     catch (Exception)
     {
         batch = null;
         return false;
     }
 }
Example #23
0
        public void Filtern(Batch<Tuple<FileInfo, string>> aufträge, Action<Tuple<string,FileInfo>> gefunden)
        {
            aufträge.ForEach(t =>
                                    {
                                        var datei = t.Item1;
                                        var abfrage = t.Item2;

                                        if (datei.Name.IndexOf(abfrage) >= 0)
                                            gefunden(new Tuple<string, FileInfo>(aufträge.CorrelationId, datei));
                                    });

            if (aufträge.GetType() == typeof(EndOfStreamBatch<Tuple<FileInfo,string>>))
                gefunden(new Tuple<string, FileInfo>(aufträge.CorrelationId, null));
        }
Example #24
0
        public void WhenRemoveLastMessageAndOnlyOneMessageAvailableShouldNotRemoveIt()
        {
            var batchMessage = new Message(new Uri("http://post.com/api"), "payload");
            batchMessage.Id = 1;
            var batch = new Batch();
            batch.Add(batchMessage);

            batch.RemoveLastMessage();

            Assert.Equal(1, batch.Events.Count);
            var message = batch.Events[0];
            Assert.Equal("http://post.com/api", message.Url.ToString());
            Assert.Equal(1, message.ReynaId);
            Assert.Equal("payload", message.Payload);
        }
        static void loadBatch(BatchSvc svc, int m_CompanyID)
        {
            Batch oBatch = new Batch();
            oBatch.CompanyId = m_CompanyID;

            oBatch.BatchTypeId = "TransactionImport"; //This is required, will tell our service what you're importing.
            BatchFile file = new BatchFile();
            oBatch.Name = "test.csv";
            file.Name = oBatch.Name; //You need to set a Batch.Name and a Batch.BatchFile.Name, but they can be the same.
            string path = "C:\\Analysis\\test\\test1.csv"; //This is your filepath for the file you want to load
            file.ContentType = "application/CSV"; //You can only load CSV, XLS, or XLSX files.
            file.Ext = ".csv";
            file.FilePath = path;

            //Here I'm just loading in the data from the csv file to the BatchFile
            try
            {
                    FileStream oStream = new FileStream(path, FileMode.Open, FileAccess.Read);
                    BinaryReader oBinreader = new BinaryReader(oStream);
                    file.Size = (Int32)oStream.Length;
                    file.Content = oBinreader.ReadBytes(file.Size);

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            oBatch.Files = new BatchFile[1];
            oBatch.Files[0] = file; //It looks like you can load an array of files, but you can really only save the batch with one file in the array.
            BatchSaveResult sres = new BatchSaveResult();
            sres = svc.BatchSave(oBatch); //Calling the service with the batch

            Console.WriteLine(sres.ResultCode.ToString());

            //fetching the batch we just loaded
            FetchRequest ofetchRequest = new FetchRequest();
            ofetchRequest.Fields = "Files";
            ofetchRequest.Filters = "BatchId = " + sres.BatchId.ToString();

            BatchFetchResult result = svc.BatchFetch(ofetchRequest); //this BatchFetch is to find the BatchFileId values

            ofetchRequest.Fields = "*,Content"; //since the BatchFileFetch also uses a fetchRequest, I recycled my variable.
            ofetchRequest.Filters = "BatchFileId = " + result.Batches[0].Files[1].BatchFileId.ToString(); //I just picked one of files from the result here.
            //There can be up to three files returned: input, result, and error.

            BatchFileFetchResult fetchresult = svc.BatchFileFetch(ofetchRequest);
            Console.WriteLine(Encoding.ASCII.GetString(fetchresult.BatchFiles[0].Content));//The file content is returned as a byte array, and I just wrote it to a console window to confirm that it looked OK.
        }
        public void Update()
        {
            String requestJson = GetJsonPayload("/campaigns/batchesApi/request/updateBatch.json");
            var restRequest = MockRestResponse();
            var batch = new Batch
            {
                Id = 11,
                Enabled = false
            };
            Client.BatchesApi.Update(batch);

            Assert.AreEqual(Method.PUT, restRequest.Value.Method);
            var requestBodyParam = restRequest.Value.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody);
            Assert.AreEqual(requestBodyParam.Value, requestJson);
            Assert.That(restRequest.Value.Resource, Is.StringEnding("/11"));
        }
Example #27
0
        public void Laden(Batch<string> dateipfade)
        {
            var dateien = new Batcher<FileInfo>(dateipfade.Elements.Length/5);

            dateipfade.ForEach(t => {
                                        var fi = new FileInfo(t);

                                        if (dateien.Add(fi) == BatchStatus.Full)
                                            Geladen(dateien.Grab(dateipfade.CorrelationId));
                                    });

            if (dateipfade.GetType() == typeof(EndOfStreamBatch<string>))
                Geladen(dateien.GrabAsEndOfStream(dateipfade.CorrelationId));
            else
                Geladen(dateien.Grab(dateipfade.CorrelationId));
        }
 private void FlushBatch(Batch<EventData> batch)
 {
     var client = GetOrCreateClient();
       if ( !batch.IsEmpty ) {
     Exception error = null;
     try {
       client.SendBatch(batch.Drain());
     } catch ( Exception ex ) {
       error = ex;
       this.eventHubClient.Abort();
       this.eventHubClient = null;
     }
     if ( this.notifySink != null ) {
       this.notifySink.OnSendComplete(batch, error);
     }
       }
 }
Example #29
0
    public static void LogApplication(Batch.Application app)
    {
        System.Console.WriteLine("-----------------");

        System.Console.WriteLine("Has scheme : "+app.HasScheme());
        if( app.HasScheme() )
        {
            System.Console.WriteLine("scheme : "+app.Scheme);
        }

        System.Console.WriteLine("Has bundle : "+app.HasBundleId());
        if( app.HasBundleId() )
        {
            System.Console.WriteLine("bundle : "+app.BundleId);
        }

        System.Console.WriteLine("-----------------");
    }
Example #30
0
        public void WhenCallingToJsonShouldReturnExpected()
        {
            var payload1 = "{\"Version Incremental\":\"20150514.093204\",\"User\":\"user\",\"Brand\":\"os\",\"device\":\"device\",\"Network Operator Name\":\"unknown\",\"Manufacturer\":\"MM\",\"updated\":1448534970738,\"list\":[{\"name\":\"System\",\"version\":\"4.1.1\",\"flag\":true},{\"name\":\"backupcon\",\"version\":\"4.1.1\",\"flag\":false}],\"Version Release\":\"4.1.1\",\"MAC\":\"MAC\"}";
            var batchMessage1 = new Message(new Uri("http://post.com"), payload1);
            batchMessage1.Id = 12;

            var payload2 = "{\"Brand\":\"os\",\"device\":\"device\",\"Network Operator Name\":\"unknown\",\"Manufacturer\":\"MM\",\"updated\":1448534970738,\"list\":[{\"name\":\"System\",\"version\":\"4.1.1\",\"flag\":true},{\"name\":\"backupcon\",\"version\":\"4.1.1\",\"flag\":false}],\"Version Release\":\"4.1.1\",\"MAC\":\"MAC\"}";
            var batchMessage2 = new Message(new Uri("http://post2.com"), payload2);
            batchMessage2.Id = 14;

            var batch = new Batch();
            batch.Add(batchMessage1);
            batch.Add(batchMessage2);

            var expected = "{\"events\":[{\"url\":\"http://post.com/\", \"reynaId\":12, \"payload\":{\"Version Incremental\":\"20150514.093204\",\"User\":\"user\",\"Brand\":\"os\",\"device\":\"device\",\"Network Operator Name\":\"unknown\",\"Manufacturer\":\"MM\",\"updated\":1448534970738,\"list\":[{\"name\":\"System\",\"version\":\"4.1.1\",\"flag\":true},{\"name\":\"backupcon\",\"version\":\"4.1.1\",\"flag\":false}],\"Version Release\":\"4.1.1\",\"MAC\":\"MAC\"}}, {\"url\":\"http://post2.com/\", \"reynaId\":14, \"payload\":{\"Brand\":\"os\",\"device\":\"device\",\"Network Operator Name\":\"unknown\",\"Manufacturer\":\"MM\",\"updated\":1448534970738,\"list\":[{\"name\":\"System\",\"version\":\"4.1.1\",\"flag\":true},{\"name\":\"backupcon\",\"version\":\"4.1.1\",\"flag\":false}],\"Version Release\":\"4.1.1\",\"MAC\":\"MAC\"}}]}";
            var actual = batch.ToJson();
            Assert.Equal(expected, actual);
        }
 /// <summary>
 /// Initialises a new instance of the Dynamics365RecordOperation class with the specified parent batch.
 /// </summary>
 /// <param name="parentBatch">The parent batch.</param>
 public Dynamics365RecordOperation(Batch parentBatch) : base(parentBatch)
 {
     SetTargetSource(DEFAULT_TARGET_SOURCE);
 }
 public abstract IEnumerable <Subset> GetSubsets(Batch batch, Random rand);
Example #33
0
 public override Batch <double[]> Backward(Batch <double[]> deltas)
 {
     return(DerivativeOfPooling(this.internalOutputs, deltas, this.activationMapWidth, this.activationMapHeight, GetOutputWidth(this.activationMapWidth), GetOutputHeight(this.activationMapHeight)));
 }
Example #34
0
            public void ReturnsFalseForEmptyBatch()
            {
                var batch = new Batch();

                Assert.IsFalse(batch.IsSingleActionBatch);
            }
Example #35
0
            public void ReturnsZeroForEmptyBatch()
            {
                var batch = new Batch();

                Assert.AreEqual(0, batch.ActionCount);
            }
 public async Task <ActionResponse> CreateBatch(Batch batch)
 {
     return(await _batchService.AddBatch(batch));
 }
Example #37
0
 public State(string name, Batch batch)
 {
     Name  = name;
     Batch = batch;
 }
Example #38
0
 public ISharePointGroup AddBatch(Batch batch, string name)
 {
     return(AddBatchAsync(batch, name).GetAwaiter().GetResult());
 }
Example #39
0
        public static ResultGeneric BatchRegistration(string logJobName, string batchNumber, string batchAlias, JobExtended job)
        {
            ResultGeneric result = new ResultGeneric();

            result.ReturnCode   = 0;
            result.Message      = "";
            result.RecordsCount = 0;

            try
            {
                lock (lockObj)
                {
                    LogManager.Configuration.Variables["JobName"] = logJobName;
                    Batch batch = new Batch();

                    HttpClient client = new HttpClient();
                    client.Timeout = TimeSpan.FromMinutes(15);
                    string URL           = "";
                    string bodyString    = "";
                    string returnMessage = "";
                    string batchJS       = "";

                    batch.BatchNumber   = batchNumber;
                    batch.StatusFlag    = "Ready to Scan";
                    batch.SubmittedBy   = "Auto Import Service";
                    batch.SubmittedDate = DateTime.Now;
                    batch.Customer      = job.CustomerName;
                    batch.ProjectName   = job.ProjectName;
                    batch.JobType       = job.JobName;
                    batch.DepName       = job.DepartmentName;
                    batch.BatchAlias    = batchAlias;

                    batchJS = JsonConvert.SerializeObject(batch, Newtonsoft.Json.Formatting.Indented);
                    batchJS = batchJS.Replace(@"\", "\\\\");

                    URL = AutoImportService.BaseURL + "Batches/BatchRegistration";

                    bodyString = "'" + batchJS + "'";
                    HttpContent body_for_new = new StringContent(bodyString);
                    body_for_new.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    HttpResponseMessage response_for_new = client.PostAsync(URL, body_for_new).Result;

                    if (!response_for_new.IsSuccessStatusCode)
                    {
                        nlogger.Error("Error:" + "\r\n" + response_for_new.ReasonPhrase + "\r\n" + response_for_new.RequestMessage);
                        Console.WriteLine("Error:" + "\r\n" + response_for_new.ReasonPhrase + "\r\n" + response_for_new.RequestMessage);
                        result.Message    = "Error:" + "\r\n" + response_for_new.ReasonPhrase + "\r\n" + response_for_new.RequestMessage;
                        result.ReturnCode = -1;
                    }
                    else
                    {
                        using (HttpContent content = response_for_new.Content)
                        {
                            Task <string> resultTemp = content.ReadAsStringAsync();
                            returnMessage = resultTemp.Result;
                            result        = JsonConvert.DeserializeObject <ResultGeneric>(returnMessage);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                lock (lockObj)
                {
                    LogManager.Configuration.Variables["JobName"] = logJobName;
                    nlogger.Fatal(General.ErrorMessage(ex));
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(General.ErrorMessage(ex));
                    Console.ForegroundColor = ConsoleColor.White;
                    result.Message          = General.ErrorMessage(ex);
                    result.ReturnCode       = -2;
                }
            }
            return(result);
        }
        private async Task <BulkWriteBatchResult> ExecuteBatchAsync(RetryableWriteContext context, Batch batch, CancellationToken cancellationToken)
        {
            BulkWriteOperationResult         result;
            MongoBulkWriteOperationException exception = null;

            try
            {
                var operation = CreateUnmixedBatchOperation(batch);
                result = await operation.ExecuteAsync(context, cancellationToken).ConfigureAwait(false);
            }
            catch (MongoBulkWriteOperationException ex)
            {
                result    = ex.Result;
                exception = ex;
            }

            return(BulkWriteBatchResult.Create(result, exception, batch.IndexMap));
        }
Example #41
0
        public async Task MakeRequest(Batch batch)
        {
            Stopwatch watch = new Stopwatch();

            try
            {
                Uri uri = new Uri(_client.Config.Host + "/v1/import");

                // set the current request time
                batch.SentAt = DateTime.Now.ToString("o");

                string json = JsonConvert.SerializeObject(batch);

                // Basic Authentication
                // https://segment.io/docs/tracking-api/reference/#authentication
#if NET35
                _httpClient.Headers.Set("Authorization", "Basic " + BasicAuthHeader(batch.WriteKey, string.Empty));
                _httpClient.Headers.Set("Content-Type", "application/json; charset=utf-8");
#else
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", BasicAuthHeader(batch.WriteKey, string.Empty));
#endif
                // Prepare request data;
                var requestData = Encoding.UTF8.GetBytes(json);

                // Compress request data if compression is set
                if (_client.Config.Gzip)
                {
#if NET35
                    _httpClient.Headers.Add(HttpRequestHeader.ContentEncoding, "gzip");
#else
                    //_httpClient.DefaultRequestHeaders.Add("Content-Encoding", "gzip");
#endif

                    // Compress request data with GZip
                    using (MemoryStream memory = new MemoryStream())
                    {
                        using (GZipStream gzip = new GZipStream(memory, CompressionMode.Compress, true))
                        {
                            gzip.Write(requestData, 0, requestData.Length);
                        }
                        requestData = memory.ToArray();
                    }
                }

                Logger.Info("Sending analytics request to Segment.io ..", new Dict
                {
                    { "batch id", batch.MessageId },
                    { "json size", json.Length },
                    { "batch size", batch.batch.Count }
                });

                // Retries with exponential backoff
                int    statusCode  = (int)HttpStatusCode.OK;
                string responseStr = "";

                while (!_backo.HasReachedMax)
                {
#if NET35
                    watch.Start();

                    try
                    {
                        var response = Encoding.UTF8.GetString(_httpClient.UploadData(uri, "POST", requestData));
                        watch.Stop();

                        Succeed(batch, watch.ElapsedMilliseconds);
                        statusCode = 200;
                        break;
                    }
                    catch (WebException ex)
                    {
                        watch.Stop();

                        var response = (HttpWebResponse)ex.Response;
                        if (response != null)
                        {
                            statusCode = (int)response.StatusCode;
                            if ((statusCode >= 500 && statusCode <= 600) || statusCode == 429)
                            {
                                // If status code is greater than 500 and less than 600, it indicates server error
                                // Error code 429 indicates rate limited.
                                // Retry uploading in these cases.
                                Thread.Sleep(_backo.AttemptTime());
                                continue;
                            }
                            else if (statusCode >= 400)
                            {
                                responseStr  = String.Format("Status Code {0}. ", statusCode);
                                responseStr += ex.Message;
                                break;
                            }
                        }
                    }
#else
                    watch.Start();

                    ByteArrayContent content = new ByteArrayContent(requestData);
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    if (_client.Config.Gzip)
                    {
                        content.Headers.ContentEncoding.Add("gzip");
                    }

                    var response = await _httpClient.PostAsync(uri, content).ConfigureAwait(false);

                    watch.Stop();
                    statusCode = (int)response.StatusCode;

                    if (statusCode == (int)HttpStatusCode.OK)
                    {
                        Succeed(batch, watch.ElapsedMilliseconds);
                        break;
                    }
                    else
                    {
                        if ((statusCode >= 500 && statusCode <= 600) || statusCode == 429)
                        {
                            // If status code is greater than 500 and less than 600, it indicates server error
                            // Error code 429 indicates rate limited.
                            // Retry uploading in these cases.
                            await _backo.AttemptAsync();

                            continue;
                        }
                        else if (statusCode >= 400)
                        {
                            responseStr  = String.Format("Status Code {0}. ", response.StatusCode);
                            responseStr += await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                            break;
                        }
                    }
#endif
                }

                if (_backo.HasReachedMax || statusCode != (int)HttpStatusCode.OK)
                {
                    Fail(batch, new APIException("Unexpected Status Code", responseStr), watch.ElapsedMilliseconds);
                }
            }
            catch (System.Exception e)
            {
                watch.Stop();
                Fail(batch, e, watch.ElapsedMilliseconds);
            }
        }
Example #42
0
        protected override async Task Act(IFlowContext context, BatchArguments arguments, Batch batch, int?fileIndex)
        {
            var info = await batch.Drop();

            await context.SetData(info);
        }
        public override void RenderColor(UIElement element, UIRenderingContext context)
        {
            base.RenderColor(element, context);

            var scrollingText = (ScrollingText)element;

            if (scrollingText.Font == null || scrollingText.TextToDisplay == null)
            {
                return;
            }

            var offset          = scrollingText.ScrollingOffset;
            var textWorldMatrix = element.WorldMatrix;

            textWorldMatrix.M41 += textWorldMatrix.M11 * offset;
            textWorldMatrix.M42 += textWorldMatrix.M12 * offset;
            textWorldMatrix.M43 += textWorldMatrix.M13 * offset;
            textWorldMatrix.M44 += textWorldMatrix.M14 * offset;

            // create the scrolling text draw command
            var drawCommand = new SpriteFont.InternalUIDrawCommand
            {
                Color     = scrollingText.RenderOpacity * scrollingText.TextColor,
                DepthBias = context.DepthBias + 1,
                RealVirtualResolutionRatio = element.LayoutingContext.RealVirtualResolutionRatio,
                RequestedFontSize          = scrollingText.ActualTextSize,
                Batch       = Batch,
                SnapText    = context.ShouldSnapText && !scrollingText.DoNotSnapText,
                Matrix      = textWorldMatrix,
                Alignment   = TextAlignment.Left,
                TextBoxSize = new Vector2(scrollingText.ActualWidth, scrollingText.ActualHeight)
            };

            // flush the current content of the UI image batch
            Batch.End();

            // draw a clipping mask
            Batch.Begin(context.GraphicsContext, ref context.ViewProjectionMatrix, BlendStates.ColorDisabled, IncreaseStencilValueState, context.StencilTestReferenceValue);
            Batch.DrawRectangle(ref element.WorldMatrixInternal, ref element.RenderSizeInternal, ref blackColor, context.DepthBias);
            Batch.End();

            // draw the element it-self with stencil test value of "Context.Value + 1"
            Batch.Begin(context.GraphicsContext, ref context.ViewProjectionMatrix, BlendStates.AlphaBlend, KeepStencilValueState, context.StencilTestReferenceValue + 1);
            if (scrollingText.Font.FontType == SpriteFontType.SDF)
            {
                Batch.End();

                Batch.BeginCustom(context.GraphicsContext, 1);
            }

            Batch.DrawString(scrollingText.Font, scrollingText.TextToDisplay, ref drawCommand);
            Batch.End();

            // un-draw the clipping mask
            Batch.Begin(context.GraphicsContext, ref context.ViewProjectionMatrix, BlendStates.ColorDisabled, DecreaseStencilValueState, context.StencilTestReferenceValue + 1);
            Batch.DrawRectangle(ref element.WorldMatrixInternal, ref element.RenderSizeInternal, ref blackColor, context.DepthBias + 2);
            Batch.End();

            // restart the Batch session
            Batch.Begin(context.GraphicsContext, ref context.ViewProjectionMatrix, BlendStates.AlphaBlend, KeepStencilValueState, context.StencilTestReferenceValue);
        }
 public Task <ActionResponse> UpdateBatch(Batch batch)
 {
     return(_batchService.UpdateBatch(batch));
 }
Example #45
0
            public void ReturnsTrueForEmptyBatch()
            {
                var batch = new Batch();

                Assert.IsTrue(batch.IsEmptyBatch);
            }
Example #46
0
        //public Stock NewItem(InputDeliveryLine parent)
        //{
        //    this.NewItem(Stock.NewChild(parent));
        //    return this[Count - 1];
        //}
        //public Stock NewItem(OutputDeliveryLine parent)
        //{
        //    this.NewItem(Stock.NewChild(parent));
        //    return this[Count - 1];
        //}
        //public Stock NewItem(LineaPedido parent)
        //{
        //    this.NewItem(Stock.NewChild(parent));
        //    return this[Count - 1];
        //}

        public Stock NewItem(Batch parent, ETipoStock tipo)
        {
            return(NewItem(parent, null, tipo));
        }
Example #47
0
        public virtual void CalculateMetrics(FeatureSubsetModel <IPredictorProducing <TOutput> > model,
                                             ISubsetSelector subsetSelector, Subset subset, Batch batch, bool needMetrics)
        {
            if (!needMetrics || model == null || model.Metrics != null)
            {
                return;
            }

            using (var ch = Host.Start("Calculate metrics"))
            {
                RoleMappedData testData = subsetSelector.GetTestData(subset, batch);
                // Because the training and test datasets are drawn from the same base dataset, the test data role mappings
                // are the same as for the train data.
                IDataScorerTransform scorePipe      = ScoreUtils.GetScorer(model.Predictor, testData, Host, testData.Schema);
                RoleMappedData       scoredTestData = new RoleMappedData(scorePipe,
                                                                         GetColumnRoles(testData.Schema, scorePipe.Schema));
                // REVIEW: Should we somehow allow the user to customize the evaluator?
                // By what mechanism should we allow that?
                IEvaluator evaluator = GetEvaluator(Host);
                // REVIEW: with the new evaluators, metrics of individual models are no longer
                // printed to the Console. Consider adding an option on the combiner to print them.
                // REVIEW: Consider adding an option to the combiner to save a data view
                // containing all the results of the individual models.
                var metricsDict = evaluator.Evaluate(scoredTestData);
                if (!metricsDict.TryGetValue(MetricKinds.OverallMetrics, out IDataView metricsView))
                {
                    throw Host.Except("Evaluator did not produce any overall metrics");
                }
                // REVIEW: We're assuming that the metrics of interest are always doubles here.
                var metrics = EvaluateUtils.GetMetrics(metricsView, getVectorMetrics: false);
                model.Metrics = metrics.ToArray();
            }
        }
        private IExecutableInRetryableWriteContext <BulkWriteOperationResult> CreateUnmixedBatchOperation(Batch batch)
        {
            switch (batch.BatchType)
            {
            case WriteRequestType.Delete: return(CreateBulkDeleteOperation(batch));

            case WriteRequestType.Insert: return(CreateBulkInsertOperation(batch));

            case WriteRequestType.Update: return(CreateBulkUpdateOperation(batch));

            default: throw new ArgumentException("Invalid batch type.", nameof(batch));
            }
        }
        //student will see in the wall
        public List <StudentContentShowViewModel> StudentContentShowViewModels(Student _Student, Batch _Batch)
        {
            //teacher post
            var _Content1 =
                db.ShareContents.Where(r => r.DepartmentID == _Student.DepartmentId && r.BatchId == _Batch.Id && r.Flag == 0)
                .Join(db.Teachers, r2 => r2.PosterId, cc => cc.Id, (r2, cc) => new { r2, cc })
                .Select(
                    x => new StudentContentShowViewModel
            {
                Title       = x.r2.Title,
                Message     = x.r2.Message,
                DateTime    = x.r2.DateTime,
                TeacherName = x.cc.TeacherName,
                Designation = x.cc.Designation,
                Id          = x.r2.Id,
                FilePath    = x.r2.FilePath,
                PhotoPath   = x.cc.PhotoPath
            }).ToList().OrderByDescending(x => x.DateTime);

            //Adminpost
            var _Content2 =
                db.ShareContents.Where(r => r.DepartmentID == _Student.DepartmentId && r.BatchId == _Batch.Id && r.Flag == 1)
                .Join(db.Admins, r2 => r2.PosterId, cc => cc.UserId, (r2, cc) => new { r2, cc })
                .Select(
                    x => new StudentContentShowViewModel
            {
                Title       = x.r2.Title,
                Message     = x.r2.Message,
                DateTime    = x.r2.DateTime,
                TeacherName = x.cc.FirstName + x.cc.LastName,
                Designation = x.cc.Designation,
                Id          = x.r2.Id,
                FilePath    = x.r2.FilePath,
                PhotoPath   = x.cc.PhotoPath
            }).ToList().OrderByDescending(x => x.DateTime);

            //StudentContentShowViewModel _Content = null;
            var _Content = _Content1.Union(_Content2).ToList().OrderByDescending(x => x.DateTime).ToList();

            return(_Content);
        }
 public static void AddBatch(Batch b)
 {
     s_instance.GetBatches().Add(b);
 }
Example #51
0
        public override void CalculateMetrics(FeatureSubsetModel <IPredictorProducing <TOutput> > model,
                                              ISubsetSelector subsetSelector, Subset subset, Batch batch, bool needMetrics)
        {
            base.CalculateMetrics(model, subsetSelector, subset, batch, needMetrics);

            var vm = model.Predictor as IValueMapper;

            Host.Check(vm != null, "Predictor doesn't implement the expected interface");
            var map = vm.GetMapper <VBuffer <Single>, TOutput>();

            TOutput[] preds = new TOutput[100];
            int       count = 0;
            var       data  = subsetSelector.GetTestData(subset, batch);

            using (var cursor = new FeatureFloatVectorCursor(data, CursOpt.AllFeatures))
            {
                while (cursor.MoveNext())
                {
                    Utils.EnsureSize(ref preds, count + 1);
                    map(in cursor.Features, ref preds[count]);
                    count++;
                }
            }
            Array.Resize(ref preds, count);
            _predictions[model] = preds;
        }
 public static void RemoveBatch(Batch r)
 {
     s_instance.GetBatches().Remove(r);
 }
 public override void UpdateParentReferences(Batch parentBatch)
 {
     base.UpdateParentReferences(parentBatch);
     Target?.UpdateParentReferences(this);
 }
Example #54
0
 public IFolder AddBatch(Batch batch, string name)
 {
     return(AddBatchAsync(batch, name).GetAwaiter().GetResult());
 }
        private IExecutableInRetryableWriteContext <BulkWriteOperationResult> CreateBulkUpdateOperation(Batch batch)
        {
            var requests = batch.Requests.Cast <UpdateRequest>();

            return(new BulkUpdateOperation(_collectionNamespace, requests, _messageEncoderSettings)
            {
                BypassDocumentValidation = _bypassDocumentValidation,
                IsOrdered = _isOrdered,
                Let = _let,
                MaxBatchCount = _maxBatchCount,
                MaxBatchLength = _maxBatchLength,
                WriteConcern = batch.WriteConcern,
                RetryRequested = _retryRequested
            });
        }
 private bool Verification()
 {
     if (EN_No.Text == "G")
     {
         EN_No.Focus();
         string errorEnrollmentNumber = "Please Provide Enrollment Number";
         errorPro.SetError(EN_No, errorEnrollmentNumber);
         MessageBox.Show("Please Provide Enrollment Number");
         return(false);
     }
     if (C_Name.Text == string.Empty)
     {
         C_Name.Focus();
         string errorCousrse = "Please Choose Course";
         errorPro.SetError(C_Name, errorCousrse);
         return(false);
     }
     if (C_Sem.Text == string.Empty)
     {
         C_Sem.Focus();
         string errorSemester = "Please Choose Semester";
         errorPro.SetError(C_Sem, errorSemester);
         MessageBox.Show("Please Choose Semester");
         return(false);
     }
     if (Batch.Text == string.Empty)
     {
         Batch.Focus();
         string errorBatch = "Please Choose Batch";
         errorPro.SetError(Batch, errorBatch);
         return(false);
     }
     if (S_FName.Text == string.Empty)
     {
         S_FName.Focus();
         string errorFname = "Please Provide First Name";
         errorPro.SetError(S_FName, errorFname);
         MessageBox.Show("Please Provide First Name");
         return(false);
     }
     if (DOB.Text == string.Empty)
     {
         DOB.Focus();
         string errorDOB = "Please Provide Date Of Birth";
         errorPro.SetError(DOB, errorDOB);
         return(false);
     }
     if (Father.Text == string.Empty)
     {
         Father.Focus();
         string errorFather = "Please Provide Father Name";
         errorPro.SetError(Father, errorFather);
         return(false);
     }
     if (MtxtFContact.Text == "+91-")
     {
         MtxtFContact.Focus();
         string errorMtxtFContact = "Please Provide Father Contact Number";
         errorPro.SetError(MtxtFContact, errorMtxtFContact);
         return(false);
     }
     return(true);
 }
Example #57
0
 public Stock NewItem(Batch parent, Stock stock, ETipoStock tipo)
 {
     this.NewItem(Stock.NewChild(parent, stock, tipo));
     return(this[Count - 1]);
 }
        public async Task Update(Batch batch)
        {
            _batchRepository.Update(batch);

            await _batchRepository.UnitOfWork.SaveChangesAsync().ConfigureAwait(false);
        }
        public void Shutdown()
        {
            RequestBatch <BatchReturnType, RequestResponseType, RequestArgumentType> currentBatch = Batch.GetAndSet(null);

            if (currentBatch != null)
            {
                currentBatch.Shutdown();
            }

            if (_timerListenerReference.Value != null)
            {
                // if the timer was started we'll clear it so it stops ticking
                _timerListenerReference.Value.Dispose();
            }
        }
Example #60
0
        /// <summary>
        /// Batches the load of the list from the remote data source, eventually selecting custom properties or using a default set of properties
        /// </summary>
        /// <param name="dataModelLoad"></param>
        /// <param name="batch">Batch add this request to</param>
        /// <param name="expressions">The properties to select</param>
        /// <returns>The Domain Model object</returns>
        internal static IBatchResult LoadBatch <TModel>(this IDataModelCollectionLoad <TModel> dataModelLoad, Batch batch, params Expression <Func <TModel, object> >[] expressions)
        {
            if (dataModelLoad == null)
            {
                throw new ArgumentNullException(nameof(dataModelLoad));
            }

            return(dataModelLoad.LoadBatchAsync(batch, expressions).GetAwaiter().GetResult());
        }