예제 #1
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,
                              ILoggerFactory loggerFactory, LibraryContext libraryContext)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            AutoMapper.Mapper.Initialize(config =>
            {
                config.CreateMap <Entities.Author, Library.API.Models.AuthorDetails>()
                .ForMember(dest => dest.Name, Opt => Opt.MapFrom(src =>
                                                                 $"{src.FirstName} {src.LastName}"))
                .ForMember(dest => dest.Age, Opt => Opt.MapFrom(src =>
                                                                DateTimeOffsetExtensions.GetCurrentAge(src.DateOfBirth)));
            });

            app.UseHttpsRedirection();
            libraryContext.EnsureSeedDataForContext();
            app.UseMvc();
        }
예제 #2
0
        public List <PepperiImportDetailTemp> MapFileImportDetailToTemp(string businessName,
                                                                        PepperiTransactionTempModel.SalesTransactionTransactionLine[] tls,
                                                                        PepperiTransactionTempModel.SalesTransactionTransactionHeader th,
                                                                        UserModel taskUser,
                                                                        ScheduledTask task)
        {
            List <PepperiImportDetailTemp> details = new List <PepperiImportDetailTemp>();
            var lineNumber = 0;

            var company  = CompanyService.FindCompanyFriendlyNameModel(businessName);
            var customer = GetCustomer(company, th, taskUser);

            if (company != null)
            {
                if (tls.Length != 0)
                {
                    foreach (PepperiTransactionTempModel.SalesTransactionTransactionLine tl in tls)
                    {
                        var pidt = new PepperiImportDetailTemp();
                        pidt.CompanyId = company.Id;

                        var product = ProductService.FindProductModel(tl.ItemFields.ItemExternalID, null, company, false);
                        // Stop import if product is false
                        pidt.ProductId                    = product.Id;
                        pidt.BrandCategoryId              = ProductService.FindProductBrandCategoryModel(company.Id, pidt.ProductId.Value).Id;
                        pidt.ItemWrntyId                  = tl.ItemFields.ItemWrntyID;
                        pidt.ItemExternalId               = tl.ItemFields.ItemExternalID;
                        pidt.ItemMainCategory             = tl.ItemFields.ItemMainCategory;
                        pidt.ItemMainCategoryCode         = tl.ItemFields.ItemMainCategoryCode;
                        pidt.ItemName                     = tl.ItemFields.ItemName.Replace(",", "").Replace("'", "");
                        pidt.ItemPrice                    = tl.ItemFields.ItemPrice;
                        pidt.ItemInStockQuantity          = tl.ItemFields.ItemInStockQuantity;
                        pidt.TSANextAvailableDate         = (tl.ItemFields.TSANextAvailableDate == "") ? (DateTimeOffset?)null : DateTimeOffsetExtensions.ParseDate(DateTimeOffset.Parse(tl.ItemFields.TSANextAvailableDate), (TimeZoneInfo.Local.BaseUtcOffset.Hours * 60));
                        pidt.TSATotalAvailable            = (string.IsNullOrEmpty(tl.ItemFields.TSATotalAvailable)) ? 0 : Convert.ToInt32(tl.ItemFields.TSATotalAvailable);
                        pidt.TSADuePDF                    = tl.TransactionLineCustomFields.TSADuePDF as string;
                        pidt.TSALineAmount                = tl.TransactionLineCustomFields.TSALineAmount;
                        pidt.UnitsQuantity                = tl.TransactionLineFields.UnitsQuantity;
                        pidt.UnitPrice                    = tl.TransactionLineFields.UnitPrice;
                        pidt.UnitDiscountPercentage       = tl.TransactionLineFields.UnitDiscountPercentage;
                        pidt.UnitPriceAfterDiscount       = tl.TransactionLineFields.UnitPriceAfterDiscount;
                        pidt.TotalUnitsPriceAfterDiscount = tl.TransactionLineFields.TotalUnitsPriceAfterDiscount;
                        pidt.DeliveryDate                 = DateTimeOffsetExtensions.ParseDate(DateTimeOffset.Parse(tl.TransactionLineFields.DeliveryDate), (TimeZoneInfo.Local.BaseUtcOffset.Hours * 60));
                        pidt.TransactionWrntyId           = tl.TransactionLineFields.TransactionWrntyID;
                        pidt.TransactionExternalId        = (tl.TransactionLineFields.TransactionExternalID as string == null) ? (long?)null : Convert.ToInt64(tl.TransactionLineFields.TransactionExternalID);
                        pidt.LineNumber                   = lineNumber;
                        pidt.TaxCodeId                    = customer.TaxCodeId;
                        pidt.DiscountPercent              = tl.TransactionLineFields.UnitDiscountPercentage;
                        details.Add(pidt);

                        lineNumber += 100;
                    }
                }
            }
            else
            {
                TaskService.WriteTaskLog(task, $"Error: Failed to find company '{businessName}' - @MapFileImportDetailToTemp", LogSeverity.Severe);
            }

            return(details);
        }
        public void FromMonthIndex_ValidIndex_ExpectedMonth(DateTimeOffset expected, int index)
        {
            // Act
            var month = DateTimeOffsetExtensions.FromMonthIndex(index);

            // Assert
            Assert.Equal(expected, month);
        }
        public void datetimeoffset_conversion_extension()
        {
            var sourceDateTime = new DateTime(2012, 1, 2, 3, 4, 5, DateTimeKind.Local);
            var offsetInt      = 5;

            var targetDateTimeOffsetTz = DateTimeOffsetExtensions.ToDateTimeOffsetTz(sourceDateTime, offsetInt);

            _output.WriteLine(targetDateTimeOffsetTz.ToJson());
        }
예제 #5
0
        protected DateTimeOffset GetDateTimeOffsetValue(string propertyName)
        {
            Debug.Assert(_realm != null, "Object is not managed, but managed access was attempted");

            var rowIndex = _rowHandle.RowIndex;

            var unixTimeSeconds = NativeTable.get_datetime_seconds(_metadata.Table, _metadata.ColumnIndices[propertyName], (IntPtr)rowIndex);

            return(DateTimeOffsetExtensions.FromUnixTimeSeconds(unixTimeSeconds));
        }
예제 #6
0
        /// <summary>
        /// Gets the current server time.
        /// </summary>
        /// <returns>The current time on the server</returns>
        public async Task <DateTimeOffset?> GetTime()
        {
            ReplyPacket reply = await this.SendAndListen(new MethodPacket("getTime"));

            if (reply != null && reply.resultObject["time"] != null)
            {
                return(DateTimeOffsetExtensions.FromUTCUnixTimeMilliseconds((long)reply.resultObject["time"]));
            }
            return(null);
        }
예제 #7
0
        protected DateTimeOffset?GetNullableDateTimeOffsetValue(string propertyName)
        {
            Debug.Assert(_realm != null, "Object is not managed, but managed access was attempted");

            var rowIndex = _rowHandle.RowIndex;

            long unixTimeSeconds = 0;
            var  hasValue        = MarshalHelpers.IntPtrToBool(NativeTable.get_nullable_datetime_seconds(_metadata.Table, _metadata.ColumnIndices[propertyName], (IntPtr)rowIndex, ref unixTimeSeconds));

            return(hasValue ? DateTimeOffsetExtensions.FromUnixTimeSeconds(unixTimeSeconds) : (DateTimeOffset?)null);
        }
예제 #8
0
    public static string ConvertTime(double t, int offset = 0)
    {
        DateTimeOffset dto = DateTimeOffsetExtensions.FromUnixTimeSeconds((long)t).AddHours(offset);

        if (dto.Hour < DateTime.Parse(missionStart).Hour)
        {
            dto = dto.AddHours(5); //GMT + 5 offset
        }
        DateTimeOffset dt = DateTimeOffset.Parse(dto.ToString());

        return(dt.ToString("HH:mm:ss"));
    }
예제 #9
0
        public void ConversionToUnixEpochInMicroseconds_back_and_forward()
        {
            // Arrange
            var dt = new DateTimeOffset(2016, 7, 16, 16, 42, 11, 999, TimeSpan.FromHours(1));

            // Act
            var nixVersion = DateTimeOffsetExtensions.ToNixTimeMicro(dt);
            var restored   = DateTimeOffsetExtensions.FromLong(nixVersion);

            // Assert
            restored.Should().Be(dt);
        }
예제 #10
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,
                              ILoggerFactory loggerFactory, LibraryContext libraryContext)
        {
            //asp.netcore 1.x this also work for asp.netcore 2.x
            //loggerFactory.AddConsole().AddDebug(LogLevel.Information);

            //configuracion de Nlog para almacenar los loggers en un file XML
            //loggerFactory.AddNLog();


            Mapper.Initialize((config) =>
            {
                config.CreateMap <Author, AuthorToReturn>()
                .ForMember(t => t.Age, Ex => Ex.MapFrom(t => DateTimeOffsetExtensions.GetCurrentAge(t.DateOfBirth)))
                .ForMember(t => t.Name, Ex => Ex.MapFrom(t => $"{t.FirstName} {t.LastName}"));

                config.CreateMap <Book, BookToReturn>().ReverseMap();

                config.CreateMap <AuthorDtoCreating, Author>().ReverseMap();
                config.CreateMap <BookCreationDto, Book>().ReverseMap();
                config.CreateMap <BookUpdate, Book>().ReverseMap();
                config.CreateMap <AuthorUpdate, Author>().ReverseMap();
            });

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler((AppBuilder) =>
                {
                    AppBuilder.Run(async context =>
                    {
                        var ExceptionHandler = context.Features.Get <IExceptionHandlerFeature>();
                        if (ExceptionHandler != null)
                        {
                            var logger = loggerFactory.CreateLogger("general logger");
                            logger.LogError(500, ExceptionHandler.Error,
                                            ExceptionHandler.Error.Message);
                        }

                        context.Response.StatusCode = 500;
                        await context.Response.WriteAsync("this is a global exception define in the StartUp CLas only for production environments");
                    });
                });
            }

            libraryContext.EnsureSeedDataForContext();

            app.UseMvc();
        }
        public void spring_forward_issue_with_converttime()
        {
            // https://www.timeanddate.com/worldclock/converted.html?iso=20160313T04&p1=179&p2=80
            var tzi       = TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time");
            var localTime = new DateTime(2016, 3, 13, 4, 0, 0);

            var actual = DateTimeOffsetExtensions.AdjustTimeZoneOffsetConvertTime(localTime, tzi);

            _output.WriteLine(actual.ToString());

            var expected = new DateTime(2016, 3, 13, 1, 0, 0);

            Assert.Equal(expected, actual);
        }
        public void spring_forward_issue()
        {
            // https://www.timeanddate.com/worldclock/converted.html?iso=20160313T04&p1=179&p2=80
            var tzi       = TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time");
            var localTime = new DateTime(2016, 3, 13, 4, 0, 0);

            var actual = DateTimeOffsetExtensions.AdjustTimeZoneOffset(localTime, tzi);

            _output.WriteLine(actual.ToString());

            var expected = new DateTime(2016, 3, 13, 1, 0, 0);

            Assert.NotEqual(expected, actual);
            // Xunit.Sdk.EqualException: Assert.Equal() Failure
            // Expected: 2016-03-13T01:00:00.0000000
            // Actual:   2016-03-13T02:00:00.0000000
        }
예제 #13
0
        public List <NuOrderImportTemp> MapFileToTemp(string businessName, List <Dictionary <string, string> > orderLines, UserModel taskUser)
        {
            List <NuOrderImportTemp> nuOrderImportTempList = new List <NuOrderImportTemp>();

            CompanyModel company = CompanyService.FindCompanyFriendlyNameModel(businessName);

            if (orderLines == null)
            {
                return(null);
            }
            else
            {
                foreach (var line in orderLines)
                {
                    CustomerModel customer = GetCustomer(company, line, taskUser);

                    NuOrderImportTemp noit = new NuOrderImportTemp();
                    noit.CompanyId        = company.Id;
                    noit.SourceId         = LookupService.FindLOVItemModel(LOVName.OrderSource, "Nuorder").Id;
                    noit.CustomerId       = customer.Id;
                    noit.OrderNumber      = null;
                    noit.CustomerPO       = line["Order Number"];
                    noit.RequiredDate     = DateTimeOffset.Parse(line["Order Date"]);
                    noit.CompanyName      = line["Customer Code"];
                    noit.EndUserName      = line["Buyer"];
                    noit.ShipAddress1     = line["Shipping Line 1"];
                    noit.ShipAddress2     = line["Shipping Line 2"];
                    noit.Filespec         = null;
                    noit.Telephone        = null;
                    noit.ShipAddress3     = line["Shipping Line 3"];
                    noit.ShipAddress4     = line["Shipping Line 4"];
                    noit.ShipSuburb       = line["Shipping City"];
                    noit.ShipState        = line["Shipping State"];
                    noit.ShipPostcode     = line["Shipping Zip"];
                    noit.ShipCountryId    = LookupService.FindCountryModel(line["Shipping Country"]).Id;
                    noit.SOStatus         = (int)SalesOrderHeaderStatus.ConfirmedOrder;
                    noit.SOSubstatus      = (int)SalesOrderHeaderSubStatus.Unpicked;
                    noit.SalesPersonId    = MembershipManagementService.FindUserByAliasName(line["Sales Rep"].Replace(" ", ".")).Id;
                    noit.OrderComment     = line["Order Notes"];
                    noit.LocationId       = company.DefaultLocationID.Value;
                    noit.TermsId          = customer.PaymentTermId;
                    noit.ShippingMethodId = customer.ShippingMethodId;
                    noit.TaxPercent       = LookupService.FindTaxCodeModel(customer.TaxCodeId).TaxPercentageRate / 100;
                    noit.TaxCodeId        = customer.TaxCodeId;
                    noit.WebsiteOrderNo   = line["Order Number"];
                    noit.EmailAddress     = null;
                    noit.Comments         = line["Order Notes"];
                    noit.IsError          = false;

                    // Date Fields are in US format, so need to Parse them accordingly
                    string dateFormat = "MM/dd/yyyy";
                    var    orderDate  = line["Order Date"];
                    noit.OrderDate = DateTimeOffsetExtensions.ParseDate(DateTimeOffset.ParseExact(orderDate, dateFormat, CultureInfo.InvariantCulture), TimeZoneInfo.Local.BaseUtcOffset.Hours, OffsetType.Hours);
                    var startDate = line["Ship Date Start"];
                    noit.DeliveryWindowOpen = (startDate == null || string.IsNullOrWhiteSpace(startDate)) ? noit.OrderDate : DateTimeOffsetExtensions.ParseDate(DateTimeOffset.ParseExact(startDate, dateFormat, CultureInfo.InvariantCulture), TimeZoneInfo.Local.BaseUtcOffset.Hours, OffsetType.Hours);
                    var endDate = line["Ship Date End"];
                    noit.DeliveryWindowClose = (endDate == null || string.IsNullOrWhiteSpace(endDate) ? LookupService.GetDeliveryWindow(noit.DeliveryWindowOpen.Value) : DateTimeOffsetExtensions.ParseDate(DateTimeOffset.ParseExact(endDate, dateFormat, CultureInfo.InvariantCulture), TimeZoneInfo.Local.BaseUtcOffset.Hours, OffsetType.Hours));

                    noit.ManualDWO             = false;
                    noit.ManualDWC             = true;
                    noit.ShippingMethodAccount = null;
                    noit.NextActionId          = LookupService.FindSaleNextActionId(Enumerations.SaleNextAction.None);
                    noit.IsConfirmedAddress    = true;
                    noit.IsManualFreight       = false;
                    noit.FreightRate           = customer.FreightRate;
                    noit.MinFreightPerOrder    = customer.MinFreightPerOrder;
                    noit.FreightCarrierId      = customer.FreightCarrierId;
                    noit.WarehouseInstructions = null;
                    noit.DeliveryInstructions  = null;
                    noit.DeliveryContact       = null;
                    noit.FreightTermId         = null;
                    noit.OrderTypeId           = null;
                    noit.SignedBy       = "Customer";
                    noit.DateSigned     = noit.OrderDate;
                    noit.MethodSignedId = LookupService.FindMethodSignedModel("NuOrder").Id;
                    //noit.PrintedForm = null;
                    noit.IsMSQProblem         = false;
                    noit.IsOverrideMSQ        = false;
                    noit.SiteName             = "NuOrder";
                    noit.IsProcessed          = false;
                    noit.IsRetailSale         = false;
                    noit.IsRetailHoldingOrder = false;

                    noit.LineNumber = null;
                    var product = ProductService.FindProductModel(line["Style Number"], null, company, false);
                    noit.ItemId          = product.Id;
                    noit.ItemNumber      = line["Style Number"];
                    noit.ItemDescription = product.ItemDescription;
                    noit.BrandCategoryId = ProductService.FindProductBrandCategoryModel(company.Id, product.Id).Id;
                    noit.UnitPriceExTax  = Convert.ToDecimal(line["Price Per"]);
                    noit.UnitPriceTax    = Convert.ToDecimal(line["Price Per"]) * noit.TaxPercent;
                    var volumeDiscountPercent = customer.VolumeDiscount / 100;
                    noit.Discount        = Convert.ToDecimal(line["Price Per"]) * volumeDiscountPercent;
                    noit.DiscountPercent = customer.VolumeDiscount;
                    noit.OrderQty        = Convert.ToInt32(line["Quantity"]);
                    noit.AllocQty        = 0;
                    noit.PickQty         = 0;
                    noit.InvQty          = 0;
                    noit.LineStatusId    = (int)SalesOrderLineStatus.Unpicked;
                    noit.DateCreated     = DateTimeOffset.Now;
                    noit.DateModified    = DateTimeOffset.Now;

                    nuOrderImportTempList.Add(noit);
                }
            }


            if (SaveDataToTempTables(nuOrderImportTempList))
            {
                return(nuOrderImportTempList);
            }
            else
            {
                return(null);
            }
        }
예제 #14
0
        public void ToOtlpSpanTest()
        {
            var activitySource = new ActivitySource(nameof(this.ToOtlpSpanTest));

            using var rootActivity = activitySource.StartActivity("root", ActivityKind.Producer);

            var attributes = new List <KeyValuePair <string, object> >
            {
                new KeyValuePair <string, object>("bool", true),
                new KeyValuePair <string, object>("long", 1L),
                new KeyValuePair <string, object>("string", "text"),
                new KeyValuePair <string, object>("double", 3.14),
                new KeyValuePair <string, object>("int", 1),
                new KeyValuePair <string, object>("datetime", DateTime.UtcNow),
                new KeyValuePair <string, object>("bool_array", new bool[] { true, false }),
                new KeyValuePair <string, object>("int_array", new int[] { 1, 2 }),
                new KeyValuePair <string, object>("double_array", new double[] { 1.0, 2.09 }),
                new KeyValuePair <string, object>("string_array", new string[] { "a", "b" }),
            };

            foreach (var kvp in attributes)
            {
                rootActivity.SetTag(kvp.Key, kvp.Value);
            }

            var startTime = new DateTime(2020, 02, 20, 20, 20, 20, DateTimeKind.Utc);

            DateTimeOffset dateTimeOffset;

#if NET452
            dateTimeOffset = DateTimeOffsetExtensions.FromUnixTimeMilliseconds(0);
#else
            dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(0);
#endif

            var expectedUnixTimeTicks = (ulong)(startTime.Ticks - dateTimeOffset.Ticks);
            var duration = TimeSpan.FromMilliseconds(1555);

            rootActivity.SetStartTime(startTime);
            rootActivity.SetEndTime(startTime + duration);

            Span <byte> traceIdSpan = stackalloc byte[16];
            rootActivity.TraceId.CopyTo(traceIdSpan);
            var traceId = traceIdSpan.ToArray();

            var otlpSpan = rootActivity.ToOtlpSpan();

            Assert.NotNull(otlpSpan);
            Assert.Equal("root", otlpSpan.Name);
            Assert.Equal(OtlpTrace.Span.Types.SpanKind.Producer, otlpSpan.Kind);
            Assert.Equal(traceId, otlpSpan.TraceId);
            Assert.Empty(otlpSpan.ParentSpanId);
            Assert.Null(otlpSpan.Status);
            Assert.Empty(otlpSpan.Events);
            Assert.Empty(otlpSpan.Links);
            AssertOtlpAttributes(attributes, otlpSpan.Attributes);

            var expectedStartTimeUnixNano = 100 * expectedUnixTimeTicks;
            Assert.Equal(expectedStartTimeUnixNano, otlpSpan.StartTimeUnixNano);
            var expectedEndTimeUnixNano = expectedStartTimeUnixNano + (duration.TotalMilliseconds * 1_000_000);
            Assert.Equal(expectedEndTimeUnixNano, otlpSpan.EndTimeUnixNano);

            var childLinks = new List <ActivityLink> {
                new ActivityLink(rootActivity.Context, new ActivityTagsCollection(attributes))
            };
            var childActivity = activitySource.StartActivity(
                "child",
                ActivityKind.Client,
                rootActivity.Context,
                links: childLinks);

            childActivity.SetStatus(Status.Error);

            var childEvents = new List <ActivityEvent> {
                new ActivityEvent("e0"), new ActivityEvent("e1", default, new ActivityTagsCollection(attributes))
예제 #15
0
 /// <summary>
 /// Gets a <see cref="DateTimeOffset"/> object that is set to the current date, time,
 /// and offset from Coordinated Universal Time (UTC) in this time zone.
 /// </summary>
 /// <param name="timeZoneInfo">The <see cref="TimeZoneInfo"/> instance.</param>
 /// <returns>The current <see cref="DateTimeOffset"/> for the instance time zone.</returns>
 public static DateTimeOffset GetCurrentDateTimeOffset(this TimeZoneInfo timeZoneInfo)
 {
     return(DateTimeOffsetExtensions.NowInTimeZone(timeZoneInfo));
 }
예제 #16
0
        private void WorkerThread()
        {
            this.httpListener.Start();

            try
            {
                while (!this.tokenSource.IsCancellationRequested)
                {
                    Task <HttpListenerContext> ctxTask = this.httpListener.GetContextAsync();
                    ctxTask.Wait(this.tokenSource.Token);

                    var ctx = ctxTask.Result;

                    ctx.Response.StatusCode  = 200;
                    ctx.Response.ContentType = ZPagesStatsBuilder.ContentType;

                    using (Stream output = ctx.Response.OutputStream)
                    {
                        using (var writer = new StreamWriter(output))
                        {
                            writer.WriteLine("<!DOCTYPE html>");
                            writer.WriteLine("<html><head><title>RPC Stats</title>" +
                                             "<meta charset=\"utf-8\">" +
                                             "<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\">" +
                                             "<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"></script>" +
                                             "<script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"></script>" +
                                             "</head>");
                            writer.WriteLine("<body><div class=\"col-sm-1\"></div><div class=\"container col-sm-10\"><div class=\"jumbotron table-responsive\"><h1>RPC Stats</h2>" +
                                             "<table class=\"table table-bordered table-hover table-striped\">" +
                                             "<thead><tr><th>Span Name</th><th>Total Count</th><th>Count in last minute</th><th>Count in last hour</th><th>Average Latency (ms)</th>" +
                                             "<th>Average Latency in last minute (ms)</th><th>Average Latency in last hour (ms)</th><th>Total Errors</th><th>Errors in last minute</th><th>Errors in last minute</th><th>Last Updated</th></tr></thead>" +
                                             "<tbody>");

                            ConcurrentDictionary <string, ZPagesSpanInformation> currentHourSpanList   = ZPagesSpans.CurrentHourSpanList;
                            ConcurrentDictionary <string, ZPagesSpanInformation> currentMinuteSpanList = ZPagesSpans.CurrentMinuteSpanList;

                            // Put span information in each row of the table
                            foreach (var spanName in currentHourSpanList.Keys)
                            {
                                ZPagesSpanInformation minuteSpanInformation = new ZPagesSpanInformation();
                                ZPagesSpanInformation hourSpanInformation   = new ZPagesSpanInformation();
                                long countInLastMinute          = 0;
                                long countInLastHour            = 0;
                                long averageLatencyInLastMinute = 0;
                                long averageLatencyInLastHour   = 0;
                                long errorCountInLastMinute     = 0;
                                long errorCountInLastHour       = 0;

                                if (currentMinuteSpanList.ContainsKey(spanName))
                                {
                                    currentMinuteSpanList.TryGetValue(spanName, out minuteSpanInformation);
                                    countInLastMinute          = minuteSpanInformation.EndedCount + ZPagesSpans.ProcessingSpanList[spanName];
                                    averageLatencyInLastMinute = minuteSpanInformation.AvgLatencyTotal;
                                    errorCountInLastMinute     = minuteSpanInformation.ErrorCount;
                                }

                                currentHourSpanList.TryGetValue(spanName, out hourSpanInformation);
                                countInLastHour          = hourSpanInformation.EndedCount + ZPagesSpans.ProcessingSpanList[spanName];
                                averageLatencyInLastHour = hourSpanInformation.AvgLatencyTotal;
                                errorCountInLastHour     = hourSpanInformation.ErrorCount;

                                long totalAverageLatency = ZPagesSpans.TotalSpanLatency[spanName] / ZPagesSpans.TotalEndedSpanCount[spanName];

                                DateTimeOffset dateTimeOffset;

#if NET452
                                dateTimeOffset = DateTimeOffsetExtensions.FromUnixTimeMilliseconds(hourSpanInformation.LastUpdated);
#else
                                dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(hourSpanInformation.LastUpdated);
#endif

                                writer.WriteLine("<tr><td>" + hourSpanInformation.Name + "</td><td>" + ZPagesSpans.TotalSpanCount[spanName] + "</td><td>" + countInLastMinute + "</td><td>" + countInLastHour + "</td>" +
                                                 "<td>" + totalAverageLatency + "</td><td>" + averageLatencyInLastMinute + "</td><td>" + averageLatencyInLastHour + "</td>" +
                                                 "<td>" + ZPagesSpans.TotalSpanErrorCount[spanName] + "</td><td>" + errorCountInLastMinute + "</td><td>" + errorCountInLastHour + "</td><td>" + dateTimeOffset + " GMT" + "</td></tr>");
                            }

                            writer.WriteLine("</tbody></table>");
                            writer.WriteLine("</div></div></body></html>");
                        }
                    }
                }
            }
            catch (OperationCanceledException)
            {
                // this will happen when cancellation will be requested
            }
            catch (Exception)
            {
                // TODO: report error
            }
            finally
            {
                this.httpListener.Stop();
                this.httpListener.Close();
            }
        }
        internal static PasswordRecord Load(this IPasswordRecord r, byte[] key)
        {
            var record = new PasswordRecord()
            {
                RecordKey      = key,
                Uid            = r.RecordUid,
                Shared         = r.Shared,
                Owner          = r.Owner,
                ClientModified = r.ClientModifiedTime != 0
                    ? DateTimeOffsetExtensions.FromUnixTimeMilliseconds(r.ClientModifiedTime)
                    : DateTimeOffset.Now,
            };

            var data = r.Data.Base64UrlDecode();

            data = CryptoUtils.DecryptAesV1(data, key);
            using (var ms = new MemoryStream(data))
            {
                var parsedData = (RecordData)DataSerializer.ReadObject(ms);
                record.Title    = parsedData.title;
                record.Login    = parsedData.secret1;
                record.Password = parsedData.secret2;
                record.Link     = parsedData.link;
                record.Notes    = parsedData.notes;
                if (parsedData.custom != null)
                {
                    foreach (var cr in parsedData.custom)
                    {
                        record.Custom.Add(new CustomField
                        {
                            Name  = cr.name,
                            Value = cr.value,
                            Type  = cr.type
                        });
                    }
                }
            }

            if (!string.IsNullOrEmpty(r.Extra))
            {
                var extra = CryptoUtils.DecryptAesV1(r.Extra.Base64UrlDecode(), key);
                using (var ms = new MemoryStream(extra))
                {
                    var parsedExtra = (RecordExtra)ExtraSerializer.ReadObject(ms);
                    if (parsedExtra.files != null && parsedExtra.files.Length > 0)
                    {
                        foreach (var file in parsedExtra.files)
                        {
                            var atta = new AttachmentFile
                            {
                                Id           = file.id,
                                Key          = file.key,
                                Name         = file.name,
                                Title        = file.title ?? "",
                                Type         = file.type ?? "",
                                Size         = file.size ?? 0,
                                LastModified = file.lastModified != null
                                    ? DateTimeOffsetExtensions.FromUnixTimeMilliseconds(file.lastModified.Value)
                                    : DateTimeOffset.Now
                            };
                            if (file.thumbs != null)
                            {
                                atta.Thumbnails = file.thumbs
                                                  .Select(t => new AttachmentFileThumb
                                {
                                    Id   = t.id,
                                    Type = t.type,
                                    Size = t.size ?? 0
                                })
                                                  .ToArray();
                            }

                            record.Attachments.Add(atta);
                        }
                    }

                    if (parsedExtra.fields != null)
                    {
                        foreach (var field in parsedExtra.fields)
                        {
                            var fld = new ExtraField();
                            foreach (var pair in field)
                            {
                                switch (pair.Key)
                                {
                                case "id":
                                    fld.Id = pair.Value.ToString();
                                    break;

                                case "field_type":
                                    fld.FieldType = pair.Value.ToString();
                                    break;

                                case "field_title":
                                    fld.FieldTitle = pair.Value.ToString();
                                    break;

                                default:
                                    fld.Custom[pair.Key] = pair.Value;
                                    break;
                                }
                            }

                            record.ExtraFields.Add(fld);
                        }
                    }
                }
            }

            return(record);
        }
예제 #18
0
        public static Span Read(ThriftProtocol iprot)
        {
            iprot.IncrementRecursionDepth();
            var span = new Span();

            try
            {
                TField field;
                iprot.ReadStructBegin();
                while (true)
                {
                    field = iprot.ReadFieldBegin();
                    if (field.Type == TType.Stop)
                    {
                        break;
                    }
                    switch (field.ID)
                    {
                    case 1:
                        if (field.Type == TType.I64)
                        {
                            span.TraceId = iprot.ReadI64();
                        }
                        else
                        {
                            iprot.Skip(field.Type);
                        }
                        break;

                    case 3:
                        if (field.Type == TType.String)
                        {
                            span.Name = iprot.ReadString();
                        }
                        else
                        {
                            iprot.Skip(field.Type);
                        }
                        break;

                    case 4:
                        if (field.Type == TType.I64)
                        {
                            span.Id = iprot.ReadI64();
                        }
                        else
                        {
                            iprot.Skip(field.Type);
                        }
                        break;

                    case 5:
                        if (field.Type == TType.I64)
                        {
                            span.ParentId = iprot.ReadI64();
                        }
                        else
                        {
                            iprot.Skip(field.Type);
                        }
                        break;

                    case 6:
                        if (field.Type == TType.List)
                        {
                            {
                                span.Annotations = new List <Annotation>();
                                var _list0 = iprot.ReadListBegin();
                                for (int _i1 = 0; _i1 < _list0.Count; ++_i1)
                                {
                                    var annotation = AnnotationSerializer.Read(iprot);
                                    span.Annotations.Add(annotation);
                                }
                                iprot.ReadListEnd();
                            }
                        }
                        else
                        {
                            iprot.Skip(field.Type);
                        }
                        break;

                    case 8:
                        if (field.Type == TType.List)
                        {
                            {
                                span.BinaryAnnotations = new List <BinaryAnnotation>();
                                var _list3 = iprot.ReadListBegin();
                                for (int _i4 = 0; _i4 < _list3.Count; ++_i4)
                                {
//										BinaryAnnotation _elem5;
//										_elem5 = new BinaryAnnotation();
//										_elem5.Read(iprot);
//										Binary_annotations.Add(_elem5);
                                    var annotation = BinaryAnnotationSerializer.Read(iprot);
                                    span.BinaryAnnotations.Add(annotation);
                                }
                                iprot.ReadListEnd();
                            }
                        }
                        else
                        {
                            iprot.Skip(field.Type);
                        }
                        break;

                    case 9:
                        if (field.Type == TType.Bool)
                        {
                            span.IsDebug = iprot.ReadBool();
                        }
                        else
                        {
                            iprot.Skip(field.Type);
                        }
                        break;

                    case 10:
                        if (field.Type == TType.I64)
                        {
                            span.Timestamp = DateTimeOffsetExtensions.FromLong(iprot.ReadI64());
                        }
                        else
                        {
                            iprot.Skip(field.Type);
                        }
                        break;

                    case 11:
                        if (field.Type == TType.I64)
                        {
                            span.DurationInMicroseconds = iprot.ReadI64();
                        }
                        else
                        {
                            iprot.Skip(field.Type);
                        }
                        break;

                    default:
                        iprot.Skip(field.Type);
                        break;
                    }
                    iprot.ReadFieldEnd();
                }
                iprot.ReadStructEnd();
            }
            finally
            {
                iprot.DecrementRecursionDepth();
            }
            return(span);
        }
예제 #19
0
        public void ToOtlpSpanTest()
        {
            var activitySource = new ActivitySource(nameof(this.ToOtlpSpanTest));

            using var rootActivity = activitySource.StartActivity("root", ActivityKind.Producer);

            var attributes = new List <KeyValuePair <string, object> >
            {
                new KeyValuePair <string, object>("bool", true),
                new KeyValuePair <string, object>("long", 1L),
                new KeyValuePair <string, object>("string", "text"),
                new KeyValuePair <string, object>("double", 3.14),

                // TODO: update if arrays of standard attribute types are supported
                new KeyValuePair <string, object>("unknown_attrib_type", new byte[] { 1 }),
            };

            foreach (var kvp in attributes)
            {
                rootActivity.AddTag(kvp.Key, kvp.Value.ToString());
            }

            var startTime = new DateTime(2020, 02, 20, 20, 20, 20, DateTimeKind.Utc);

            DateTimeOffset dateTimeOffset;

#if NET452
            dateTimeOffset = DateTimeOffsetExtensions.FromUnixTimeMilliseconds(0);
#else
            dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(0);
#endif

            var expectedUnixTimeTicks = (ulong)(startTime.Ticks - dateTimeOffset.Ticks);
            var duration = TimeSpan.FromMilliseconds(1555);

            rootActivity.SetStartTime(startTime);
            rootActivity.SetEndTime(startTime + duration);

            Span <byte> traceIdSpan = stackalloc byte[16];
            rootActivity.TraceId.CopyTo(traceIdSpan);
            var traceId = traceIdSpan.ToArray();

            var otlpSpan = rootActivity.ToOtlpSpan();

            Assert.NotNull(otlpSpan);
            Assert.Equal("root", otlpSpan.Name);
            Assert.Equal(OtlpTrace.Span.Types.SpanKind.Producer, otlpSpan.Kind);
            Assert.Equal(traceId, otlpSpan.TraceId);
            Assert.Empty(otlpSpan.ParentSpanId);
            Assert.Null(otlpSpan.Status);
            Assert.Empty(otlpSpan.Events);
            Assert.Empty(otlpSpan.Links);
            AssertActivityTagsIntoOtlpAttributes(attributes, otlpSpan.Attributes);

            var expectedStartTimeUnixNano = 100 * expectedUnixTimeTicks;
            Assert.Equal(expectedStartTimeUnixNano, otlpSpan.StartTimeUnixNano);
            var expectedEndTimeUnixNano = expectedStartTimeUnixNano + (duration.TotalMilliseconds * 1_000_000);
            Assert.Equal(expectedEndTimeUnixNano, otlpSpan.EndTimeUnixNano);

            var childLinks = new List <ActivityLink> {
                new ActivityLink(rootActivity.Context, attributes)
            };
            var childActivity = activitySource.StartActivity(
                "child",
                ActivityKind.Client,
                rootActivity.Context,
                links: childLinks);

            childActivity.SetStatus(Status.NotFound);

            var childEvents = new List <ActivityEvent> {
                new ActivityEvent("e0"), new ActivityEvent("e1", attributes)
            };
            childActivity.AddEvent(childEvents[0]);
            childActivity.AddEvent(childEvents[1]);

            Span <byte> parentIdSpan = stackalloc byte[8];
            rootActivity.Context.SpanId.CopyTo(parentIdSpan);
            var parentId = parentIdSpan.ToArray();

            otlpSpan = childActivity.ToOtlpSpan();

            Assert.NotNull(otlpSpan);
            Assert.Equal("child", otlpSpan.Name);
            Assert.Equal(OtlpTrace.Span.Types.SpanKind.Client, otlpSpan.Kind);
            Assert.Equal(traceId, otlpSpan.TraceId);
            Assert.Equal(parentId, otlpSpan.ParentSpanId);
            Assert.Equal(OtlpTrace.Status.Types.StatusCode.NotFound, otlpSpan.Status.Code);
            Assert.Equal(Status.NotFound.Description ?? string.Empty, otlpSpan.Status.Message);
            Assert.Empty(otlpSpan.Attributes);

            Assert.Equal(childEvents.Count, otlpSpan.Events.Count);
            for (var i = 0; i < childEvents.Count; i++)
            {
                Assert.Equal(childEvents[i].Name, otlpSpan.Events[i].Name);
                AssertOtlpAttributes(childEvents[i].Attributes.ToList(), otlpSpan.Events[i].Attributes);
            }

            childLinks.Reverse();
            Assert.Equal(childLinks.Count, otlpSpan.Links.Count);
            for (var i = 0; i < childLinks.Count; i++)
            {
                AssertOtlpAttributes(childLinks[i].Attributes.ToList(), otlpSpan.Links[i].Attributes);
            }
        }
예제 #20
0
 protected DateTimeOffset Now(string tz)
 {
     return(DateTimeOffsetExtensions.Now(tz));
 }
예제 #21
0
        public static Annotation Read(ThriftProtocol iprot)
        {
            iprot.IncrementRecursionDepth();
            var annotation = new Annotation();

            try
            {
                iprot.ReadStructBegin();
                while (true)
                {
                    var field = iprot.ReadFieldBegin();
                    if (field.Type == TType.Stop)
                    {
                        break;
                    }
                    switch (field.ID)
                    {
                    case 1:
                        if (field.Type == TType.I64)
                        {
                            annotation.Timestamp = DateTimeOffsetExtensions.FromLong(iprot.ReadI64());
                        }
                        else
                        {
                            iprot.Skip(field.Type);
                        }
                        break;

                    case 2:
                        if (field.Type == TType.String)
                        {
                            annotation.Value = iprot.ReadString();
                        }
                        else
                        {
                            iprot.Skip(field.Type);
                        }
                        break;

                    case 3:
                        if (field.Type == TType.Struct)
                        {
//								Host = new Endpoint();
//								Host.Read(iprot);
                            annotation.Host = EndpointSerializer.Read(iprot);
                        }
                        else
                        {
                            iprot.Skip(field.Type);
                        }
                        break;

                    default:
                        iprot.Skip(field.Type);
                        break;
                    }
                    iprot.ReadFieldEnd();
                }
                iprot.ReadStructEnd();
            }
            finally
            {
                iprot.DecrementRecursionDepth();
            }
            return(annotation);
        }
예제 #22
0
        protected override Task <TimeSpan> DoWork(CancellationToken token)
        {
            _logger.Debug("Entered method", nameof(DoWork));

            var now = TimeProvider.GetCurrentTime();
            var employeesToWakeUp = new List <Tuple <Employee, DueTimeInfo> >();
            var earliest          = JobExtensions.Never;

            lock (_lock)
            {
                _startedWorking = true;

                foreach (var employee in _employees.Values)
                {
                    var info = employee.GetDueTimeInfoForVice(false);

                    if (!info.HasValue)
                    {
                        continue;
                    }

                    var dueTime = info.Value.GetEffectiveDueTime();

                    if (now >= dueTime)
                    {
                        // due time has come!
                        employeesToWakeUp.Add(Tuple.Create(employee, info.Value));
                    }
                    else
                    {
                        earliest = DateTimeOffsetExtensions.Min(earliest, dueTime);
                    }
                }
            }

            foreach (var tuple in employeesToWakeUp)
            {
                var employee     = tuple.Item1;
                var isOverridden = tuple.Item2.IsDueTimeOverridden();
                var reason       = isOverridden ? JobStartReason.OverriddenDueTime : JobStartReason.ScheduleDueTime;

                var startResult = employee.Start(reason, token);

                switch (startResult)
                {
                case JobStartResult.Started:
                    _logger.Information(
                        $"Job '{employee.Name}' was started. Reason: '{reason}'.",
                        nameof(DoWork));
                    break;

                case JobStartResult.CompletedSynchronously:
                    _logger.Information(
                        $"Job '{employee.Name}' completed synchronously. Reason of start was '{reason}'.",
                        nameof(DoWork));
                    break;

                case JobStartResult.AlreadyRunning:
                    _logger.Information(
                        $"Job '{employee.Name}' already running. Attempted to start due to reason '{reason}'.",
                        nameof(DoWork));
                    break;

                case JobStartResult.Disabled:
                    _logger.Information(
                        $"Job '{employee.Name}' is disabled. Attempted to start due to reason '{reason}'.",
                        nameof(DoWork));
                    break;
                }

                // when to visit you again, Employee?
                var nextDueTimeInfo = employee.GetDueTimeInfoForVice(true);

                if (nextDueTimeInfo.HasValue
                    ) // actually, should have, he could not finish work and got disposed that fast, but who knows...
                {
                    var nextDueTime = nextDueTimeInfo.Value.GetEffectiveDueTime();
                    if (nextDueTime > now)
                    {
                        earliest = DateTimeOffsetExtensions.Min(earliest, nextDueTime);
                    }
                }
            }

            var vacationTimeout = earliest - now;

            _logger.Debug($"Going to vacation, length is '{vacationTimeout}'.", nameof(DoWork));

            return(Task.FromResult(vacationTimeout));
        }
예제 #23
0
        public PepperiImportHeaderTemp MapFileImportHeaderToTemp(string businessName,
                                                                 PepperiTransactionTempModel.SalesTransactionTransactionHeader th,
                                                                 UserModel taskUser,
                                                                 ScheduledTask task)
        {
            PepperiImportHeaderTemp piht = new PepperiImportHeaderTemp();

            var company  = CompanyService.FindCompanyFriendlyNameModel(businessName);
            var customer = GetCustomer(company, th, taskUser);

            if (company != null)
            {
                piht.CompanyId                  = company.Id;
                piht.WrntyId                    = Convert.ToInt32(th.TransactionHeaderFields.WrntyID);
                piht.OrderType                  = th.TransactionHeaderFields.Type;
                piht.Status                     = th.TransactionHeaderFields.Status;
                piht.CreationDateTime           = DateTimeOffset.Parse(th.TransactionHeaderFields.CreationDateTime);
                piht.ModificationDateTime       = DateTimeOffset.Parse(th.TransactionHeaderFields.ModificationDateTime);
                piht.ActionDateTime             = DateTimeOffset.Parse(th.TransactionHeaderFields.ActionDateTime);
                piht.DeliveryDate               = DateTimeOffsetExtensions.ParseDate(DateTimeOffset.Parse(th.TransactionHeaderFields.DeliveryDate), (TimeZoneInfo.Local.BaseUtcOffset.Hours * 60));
                piht.Remark                     = th.TransactionHeaderFields.Remark as string;
                piht.CatalogId                  = th.CatalogFields.CatalogID;
                piht.CatalogDescription         = th.CatalogFields.CatalogDescription as string;
                piht.CatalogPriceFactor         = th.CatalogFields.CatalogPriceFactor;
                piht.CatalogExpirationDate      = DateTimeOffsetExtensions.ParseDate(DateTimeOffset.Parse(th.CatalogFields.CatalogExpirationDate), (TimeZoneInfo.Local.BaseUtcOffset.Hours * 60));
                piht.AgentName                  = th.SalesRepFields.AgentName;
                piht.AgentExternalId            = (th.SalesRepFields.AgentExternalID as string == null) ? 0 : Convert.ToInt64(th.SalesRepFields.AgentExternalID);
                piht.AgentEmail                 = th.SalesRepFields.AgentEmail;
                piht.AccountWrntyId             = th.AccountFields.AccountWrntyID;
                piht.AccountExternalId          = th.AccountFields.AccountExternalID;
                piht.AccountCreationDate        = DateTimeOffset.Parse(th.AccountFields.AccountCreationDate);
                piht.AccountName                = th.AccountFields.AccountName;
                piht.AccountPhone               = th.AccountFields.AccountPhone;
                piht.AccountMobile              = th.AccountFields.AccountMobile as string;
                piht.AccountFax                 = th.AccountFields.AccountFax as string;
                piht.AccountEmail               = th.AccountFields.AccountEmail;
                piht.CustomerId                 = customer.Id;
                piht.AccountStreet              = th.AccountFields.AccountStreet;
                piht.AccountCity                = th.AccountFields.AccountCity;
                piht.AccountState               = th.AccountFields.AccountState;
                piht.AccountCountryId           = LookupService.FindCountryModel(th.AccountFields.AccountCountry).Id;
                piht.AccountCountry             = th.AccountFields.AccountCountry;
                piht.AccountZipCode             = th.AccountFields.AccountZipCode;
                piht.AccountPriceLevelName      = th.AccountFields.AccountPriceLevelName as string;
                piht.BillToName                 = th.BillingFields.BillToName;
                piht.BillToStreet               = th.BillingFields.BillToStreet;
                piht.BillToCity                 = th.BillingFields.BillToCity;
                piht.BillToState                = th.BillingFields.BillToState;
                piht.BillToCountryId            = LookupService.FindCountryModel(th.BillingFields.BillToCountry).Id;
                piht.BillToCountry              = th.BillingFields.BillToCountry;
                piht.BillToZipCode              = th.BillingFields.BillToZipCode;
                piht.BillToPhone                = th.BillingFields.BillToPhone;
                piht.ShipToExternalId           = th.ShippingFields.ShipToExternalID;
                piht.ShipToName                 = th.ShippingFields.ShipToName;
                piht.ShipToStreet               = th.ShippingFields.ShipToStreet;
                piht.ShipToCity                 = th.ShippingFields.ShipToCity;
                piht.ShipToState                = th.ShippingFields.ShipToState;
                piht.ShipToCountryId            = LookupService.FindCountryModel(th.ShippingFields.ShipToCountry).Id;
                piht.ShipToCountry              = th.ShippingFields.ShipToCountry;
                piht.ShipToZipCode              = th.ShippingFields.ShipToZipCode;
                piht.ShipToPhone                = th.ShippingFields.ShipToPhone;
                piht.Currency                   = th.Totals.Currency;
                piht.TotalItemsCount            = th.Totals.TotalItemsCount;
                piht.SubTotal                   = th.Totals.SubTotal;
                piht.SubTotalAfterItemsDiscount = th.Totals.SubTotalAfterItemsDiscount;
                piht.GrandTotal                 = th.Totals.GrandTotal;
                piht.DiscountPercentage         = th.Totals.DiscountPercentage;
                piht.TaxPercentage              = th.Totals.TaxPercentage;
                piht.TSAGST                     = th.TransactionCustomFields.TSAGST;
                piht.TSADeliveryWindowOpen      = (th.TransactionCustomFields.TSADeliveryWindowOpen == "") ? DateTimeOffset.Parse(th.TransactionHeaderFields.CreationDateTime) : DateTimeOffsetExtensions.ParseDate(DateTimeOffset.Parse(th.TransactionCustomFields.TSADeliveryWindowOpen), (TimeZoneInfo.Local.BaseUtcOffset.Hours * 60));
                piht.TSADeliveryWindowClose     = (th.TransactionCustomFields.TSADeliveryWindowClose == "") ? LookupService.GetDeliveryWindow(piht.TSADeliveryWindowOpen.Value) : DateTimeOffsetExtensions.ParseDate(DateTimeOffset.Parse(th.TransactionCustomFields.TSADeliveryWindowClose), (TimeZoneInfo.Local.BaseUtcOffset.Hours * 60));
                piht.TSAOrderTakenBy            = (th.TransactionCustomFields.TSAOrderTakenBy as string == null) ? th.TransactionCustomFields.TSAOrderTakenBy as string : th.TransactionCustomFields.TSAOrderTakenBy.ToString();
                piht.TSATaxRate                 = th.TransactionCustomFields.TSATaxRate;
                piht.TSASubTotalBeforeTax       = th.TransactionCustomFields.TSASubTotalBeforeTax;
                piht.TSAGrandTotal              = th.TransactionCustomFields.TSAGrandTotal;
                piht.SalespersonId              = GetSalespersonId(th.SalesRepFields.AgentEmail);
                piht.Filespec                   = th.TransactionCustomFields.Filespec;
                piht.IsNewCustomer              = th.TransactionCustomFields.IsNewCustomer;
                piht.OrderNumber                = (int)LookupService.GetNextSequenceNumber(company, SequenceNumberType.SalesOrderNumber);
                piht.SOStatus                   = (int)SalesOrderHeaderStatus.ConfirmedOrder;
                piht.SOSubStatus                = (int)SalesOrderHeaderSubStatus.Unpicked;
                piht.LocationId                 = company.DefaultLocationID.Value;
                piht.IsConfirmedAddress         = (th.TransactionCustomFields.IsNewCustomer == true) ? false : true;
                piht.SignedBy                   = "Customer";
                piht.MethodSignedId             = LookupService.FindMethodSignedModel("Pepperi").Id;
                piht.IsMSQProblem               = false;
                piht.IsOverrideMSQ              = false;
                piht.SourceId                   = LookupService.FindLOVItemModel(LOVName.OrderSource, "Pepperi").Id;
                piht.NextActionId               = LookupService.FindSaleNextActionId(Enumerations.SaleNextAction.None);
            }
            else
            {
                TaskService.WriteTaskLog(task, $"Error: Failed to find company '{businessName}' - @MapFileImportHeaderToTemp", LogSeverity.Severe);
            }
            return(piht);
        }