Exemplo n.º 1
0
 /* Refresh Config Method
  * Used to load the configuration into the assembly
  */
 internal async static Task RefreshConfig()
 {
     using (var reader = new StreamReader(ConfigPath))
         Config = JsonConvert.DeserializeObject <Config>((await reader.ReadToEndAsync()).Trim());
 }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            
            #region st

            var str = @"{
    ""InvoiceId"": 214,
    ""InvoiceNumber"": ""INV-214"",
    ""InvoiceIssuedStatus"": ""PaymentSuccess"",
    ""InvoiceStatus"": ""Paid"",
    ""Order"": {
        ""Id"": 238,
        ""CustomerId"": ""***************"",
        ""TotalPrice"": 538,
        ""TotalDiscount"": 117,
        ""BillingAddress"": {
            ""Id"": 0,
            ""ApartmentNumber"": ""***************"",
            ""Street"": ""***************"",
            ""Locality"": ""*************** restaurant"",
            ""City"": ""***************"",
            ""State"": ""***************"",
            ""Country"": ""***************"",
            ""ISOCountryCode"": null,
            ""ZipCode"": ""***************""
        },
        ""ShippingAddress"": {
            ""Id"": 0,
            ""ApartmentNumber"": ""***************"",
            ""Street"": ""***************"",
            ""Locality"": ""*************** restaurant"",
            ""City"": ""***************"",
            ""State"": ""***************"",
            ""Country"": ""***************"",
            ""ISOCountryCode"": null,
            ""ZipCode"": ""***************""
        },
        ""Items"": [
            {
                ""Id"": 268,
                ""ProductId"": 4653,
                ""SkuId"": ""***************840050338308"",
                ""SellerId"": ""***************"",
                ""ActualPrice"": 195,
                ""ActualPriceWithoutTax"": 185.48,
                ""DiscountedPrice"": 156,
                ""TotalDiscount"": 39,
                ""Qty"": 1,
                ""Tax"": 0,
                ""BundleId"": null,
                ""ShipmentId"": 264,
                ""IsSelfPickup"": false,
                ""ProductSnapshot"": {
                    ""ProductName"": ""***************"",
                    ""ProductGroup"": null,
                    ""ProductType"": ""Configurable"",
                    ""Images"": [
                        ""G1 FV _Pink dark_thumbnail.jpg"",
                        ""G1 SV _Pink dark rani.jpg"",
                        ""G1 BV _Pink dark.jpg"",
                        ""G1 FV _BLUE DARK_thumbnail.jpg"",
                        ""G1 SV _ navy Blue.jpg"",
                        ""G1 SV _ navy Blue.jpg"",
                        ""G1 FV _Black_thumbnail.jpg"",
                        ""G1 SV _Black.jpg"",
                        ""G1 BV _Black.jpg""
                    ],
                    ""AttributeValues"": [
                        {
                            ""AttributeId"": 85,
                            ""ValueId"": 227,
                            ""AttributeName"": ""Size"",
                            ""Value"": ""B36\\90""
                        },
                        {
                            ""AttributeId"": 84,
                            ""ValueId"": 188,
                            ""AttributeName"": ""Color"",
                            ""Value"": ""Pink dark""
                        }
                    ],
                    ""DiscountSplit"": {
                        ""PartnerDiscount"": 0,
                        ""SpecialDiscount"": 39
                    },
                    ""BundleSnapshot"": null,
                    ""ExternalId"": null
                },
                ""CreatedDateTime"": ""2020-08-01T10:33:31.129825"",
                ""OrderItemStatusHistories"": [
                    {
                        ""Id"": 0,
                        ""OrderId"": 0,
                        ""OrderStatus"": ""Created"",
                        ""CreatedDateTime"": ""2020-08-01T10:33:31.129883""
                    },
                    {
                        ""Id"": 0,
                        ""OrderId"": 0,
                        ""OrderStatus"": ""PaymentSuccess"",
                        ""CreatedDateTime"": ""2020-08-02T10:24:12.525215""
                    },
                    {
                        ""Id"": 0,
                        ""OrderId"": 0,
                        ""OrderStatus"": ""SellerProcessing"",
                        ""CreatedDateTime"": ""2020-08-03T05:29:52.006403""
                    },
                    {
                        ""Id"": 0,
                        ""OrderId"": 0,
                        ""OrderStatus"": ""Shipping"",
                        ""CreatedDateTime"": ""2020-08-03T09:51:07.530111""
                    }
                ],
                ""OrderItemStatus"": ""Shipping"",
                ""SelfPickUpOptions"": null,
                ""OrderReturnDetails"": null,
                ""OrderCancelDetails"": null,
                ""TaxDetails"": {
                    ""TotalTaxPaid"": 9.52,
                    ""TaxGroupId"": 3,
                    ""TaxGroupName"": ""GST-5"",
                    ""TaxSplits"": [
                        {
                            ""TaxId"": 5,
                            ""TaxName"": ""CGST"",
                            ""TaxPercentage"": 2.5,
                            ""TaxAmount"": 0,
                            ""TaxAmountPaid"": 4.76,
                            ""TaxType"": ""TaxPercentage""
                        },
                        {
                            ""TaxId"": 6,
                            ""TaxName"": ""SGST"",
                            ""TaxPercentage"": 2.5,
                            ""TaxAmount"": 0,
                            ""TaxAmountPaid"": 4.76,
                            ""TaxType"": ""TaxPercentage""
                        }
                    ]
                },
                ""LoanDetail"": null,
                ""Shipment"": {
                    ""Id"": 264,
                    ""ProviderName"": ""***************"",
                    ""ShipmentFee"": 70,
                    ""ExpectedDeliveryDate"": ""2020-08-05T10:33:21.693771"",
                    ""TrackingCode"": null,
                    ""ShiprocketResponse"": {
                        ""pickup_location_added"": 0,
                        ""order_created"": 1,
                        ""awb_generated"": 1,
                        ""label_generated"": 1,
                        ""pickup_generated"": 1,
                        ""manifest_generated"": 1,
                        ""pickup_scheduled_date"": ""2020-08-04T09:00:00"",
                        ""order_id"": 50016171,
                        ""shipment_id"": 234234,
                        ""awb_code"": ""***************"",
                        ""courier_company_id"": 1,
                        ""courier_name"": null,
                        ""assigned_date_time"": null,
                        ""applied_weight"": 5.4,
                        ""cod"": false,
                        ""label_url"": ""https://kr-******************************.pdf"",
                        ""manifest_url"": ""https://******************************.pdf"",
                        ""routing_code"": ""TGD/TGD"",
                        ""pickup_token_number"": ""Reference No:***************""
                    }
                },
                ""SellerName"": ""******************************"",
                ""Metadata"": {
                    ""QuoteSnapshot"": null,
                    ""IsSelfPickup"": false,
                    ""DeliveryCode"": null,
                    ""SelfPickupOptions"": null,
                    ""LoanDetailSnapShot"": null,
                    ""ShipmentFeePerSeller"": 70,
                    ""PartnerDiscountDetails"": null
                },
                ""ActualUnitPrice"": 195
            },
            {
                ""Id"": 269,
                ""ProductId"": 4653,
                ""SkuId"": ""***************840050338353"",
                ""SellerId"": ""***************"",
                ""ActualPrice"": 195,
                ""ActualPriceWithoutTax"": 185.48,
                ""DiscountedPrice"": 156,
                ""TotalDiscount"": 39,
                ""Qty"": 1,
                ""Tax"": 0,
                ""BundleId"": null,
                ""ShipmentId"": 264,
                ""IsSelfPickup"": false,
                ""ProductSnapshot"": {
                    ""ProductName"": ""KNITTED - ***************"",
                    ""ProductGroup"": null,
                    ""ProductType"": ""Configurable"",
                    ""Images"": [
                        ""G1 FV _Pink dark_thumbnail.jpg"",
                        ""G1 SV _Pink dark rani.jpg"",
                        ""G1 BV _Pink dark.jpg"",
                        ""G1 FV _BLUE DARK_thumbnail.jpg"",
                        ""G1 SV _ navy Blue.jpg"",
                        ""G1 SV _ navy Blue.jpg"",
                        ""G1 FV _Black_thumbnail.jpg"",
                        ""G1 SV _Black.jpg"",
                        ""G1 BV _Black.jpg""
                    ],
                    ""AttributeValues"": [
                        {
                            ""AttributeId"": 84,
                            ""ValueId"": 189,
                            ""AttributeName"": ""Color"",
                            ""Value"": ""Blue dark""
                        },
                        {
                            ""AttributeId"": 85,
                            ""ValueId"": 227,
                            ""AttributeName"": ""Size"",
                            ""Value"": ""B36\\90""
                        }
                    ],
                    ""DiscountSplit"": {
                        ""PartnerDiscount"": 0,
                        ""SpecialDiscount"": 39
                    },
                    ""BundleSnapshot"": null,
                    ""ExternalId"": null
                },
                ""CreatedDateTime"": ""2020-08-01T10:33:31.129825"",
                ""OrderItemStatusHistories"": [
                    {
                        ""Id"": 0,
                        ""OrderId"": 0,
                        ""OrderStatus"": ""Created"",
                        ""CreatedDateTime"": ""2020-08-01T10:33:31.129898""
                    },
                    {
                        ""Id"": 0,
                        ""OrderId"": 0,
                        ""OrderStatus"": ""PaymentSuccess"",
                        ""CreatedDateTime"": ""2020-08-02T10:24:12.525324""
                    },
                    {
                        ""Id"": 0,
                        ""OrderId"": 0,
                        ""OrderStatus"": ""SellerProcessing"",
                        ""CreatedDateTime"": ""2020-08-03T05:29:54.97333""
                    },
                    {
                        ""Id"": 0,
                        ""OrderId"": 0,
                        ""OrderStatus"": ""Shipping"",
                        ""CreatedDateTime"": ""2020-08-03T09:51:07.530112""
                    }
                ],
                ""OrderItemStatus"": ""Shipping"",
                ""SelfPickUpOptions"": null,
                ""OrderReturnDetails"": null,
                ""OrderCancelDetails"": null,
                ""TaxDetails"": {
                    ""TotalTaxPaid"": 9.52,
                    ""TaxGroupId"": 3,
                    ""TaxGroupName"": ""GST-5"",
                    ""TaxSplits"": [
                        {
                            ""TaxId"": 5,
                            ""TaxName"": ""CGST"",
                            ""TaxPercentage"": 2.5,
                            ""TaxAmount"": 0,
                            ""TaxAmountPaid"": 4.76,
                            ""TaxType"": ""TaxPercentage""
                        },
                        {
                            ""TaxId"": 6,
                            ""TaxName"": ""SGST"",
                            ""TaxPercentage"": 2.5,
                            ""TaxAmount"": 0,
                            ""TaxAmountPaid"": 4.76,
                            ""TaxType"": ""TaxPercentage""
                        }
                    ]
                },
                ""LoanDetail"": null,
                ""Shipment"": {
                    ""Id"": 264,
                    ""ProviderName"": ""***************"",
                    ""ShipmentFee"": 70,
                    ""ExpectedDeliveryDate"": ""2020-08-05T10:33:21.693771"",
                    ""TrackingCode"": null,
                    ""ShiprocketResponse"": {
                        ""pickup_location_added"": 0,
                        ""order_created"": 1,
                        ""awb_generated"": 1,
                        ""label_generated"": 1,
                        ""pickup_generated"": 1,
                        ""manifest_generated"": 1,
                        ""pickup_scheduled_date"": ""2020-08-04T09:00:00"",
                        ""order_id"": 50016171,
                        ""shipment_id"": 49713763,
                        ""awb_code"": ""***************"",
                        ""courier_company_id"": 1,
                        ""courier_name"": null,
                        ""assigned_date_time"": null,
                        ""applied_weight"": 5.4,
                        ""cod"": false,
                        ""label_url"": ""https://******************************9713763-***************.pdf"",
                        ""manifest_url"": ""h******************************.pdf"",
                        ""routing_code"": ""TGD/TGD"",
                        ""pickup_token_number"": ""Reference No: ***************""
                    }
                },
                ""SellerName"": ""***************"",
                ""Metadata"": {
                    ""QuoteSnapshot"": null,
                    ""IsSelfPickup"": false,
                    ""DeliveryCode"": null,
                    ""SelfPickupOptions"": null,
                    ""LoanDetailSnapShot"": null,
                    ""ShipmentFeePerSeller"": 70,
                    ""PartnerDiscountDetails"": null
                },
                ""ActualUnitPrice"": 195
            },
            {
                ""Id"": 270,
                ""ProductId"": 4653,
                ""SkuId"": ""***************840050338278"",
                ""SellerId"": ""***************"",
                ""ActualPrice"": 195,
                ""ActualPriceWithoutTax"": 23448,
                ""DiscountedPrice"": 234,
                ""TotalDiscount"": 39,
                ""Qty"": 1,
                ""Tax"": 0,
                ""BundleId"": null,
                ""ShipmentId"": 264,
                ""IsSelfPickup"": false,
                ""ProductSnapshot"": {
                    ""ProductName"": ""***************"",
                    ""ProductGroup"": null,
                    ""ProductType"": ""Configurable"",
                    ""Images"": [
                        ""G1 FV _Pink dark_thumbnail.jpg"",
                        ""G1 SV _Pink dark rani.jpg"",
                        ""G1 BV _Pink dark.jpg"",
                        ""G1 FV _BLUE DARK_thumbnail.jpg"",
                        ""G1 SV _ navy Blue.jpg"",
                        ""G1 SV _ navy Blue.jpg"",
                        ""G1 FV _Black_thumbnail.jpg"",
                        ""G1 SV _Black.jpg"",
                        ""G1 BV _Black.jpg""
                    ],
                    ""AttributeValues"": [
                        {
                            ""AttributeId"": 85,
                            ""ValueId"": 227,
                            ""AttributeName"": ""Size"",
                            ""Value"": ""B36\\90""
                        },
                        {
                            ""AttributeId"": 84,
                            ""ValueId"": 194,
                            ""AttributeName"": ""Color"",
                            ""Value"": ""Black""
                        }
                    ],
                    ""DiscountSplit"": {
                        ""PartnerDiscount"": 0,
                        ""SpecialDiscount"": 39
                    },
                    ""BundleSnapshot"": null,
                    ""ExternalId"": null
                },
                ""CreatedDateTime"": ""2020-08-01T10:33:31.129825"",
                ""OrderItemStatusHistories"": [
                    {
                        ""Id"": 0,
                        ""OrderId"": 0,
                        ""OrderStatus"": ""Created"",
                        ""CreatedDateTime"": ""2020-08-01T10:33:31.129902""
                    },
                    {
                        ""Id"": 0,
                        ""OrderId"": 0,
                        ""OrderStatus"": ""PaymentSuccess"",
                        ""CreatedDateTime"": ""2020-08-02T10:24:12.525336""
                    },
                    {
                        ""Id"": 0,
                        ""OrderId"": 0,
                        ""OrderStatus"": ""SellerProcessing"",
                        ""CreatedDateTime"": ""2020-08-03T05:29:59.6706""
                    },
                    {
                        ""Id"": 0,
                        ""OrderId"": 0,
                        ""OrderStatus"": ""Shipping"",
                        ""CreatedDateTime"": ""2020-08-03T09:51:07.529963""
                    },
                    {
                        ""Id"": 0,
                        ""OrderId"": 0,
                        ""OrderStatus"": ""SellerProcessing"",
                        ""CreatedDateTime"": ""2020-08-03T09:51:07.530096""
                    },
                    {
                        ""Id"": 0,
                        ""OrderId"": 0,
                        ""OrderStatus"": ""Shipping"",
                        ""CreatedDateTime"": ""2020-08-03T09:51:07.53011""
                    }
                ],
                ""OrderItemStatus"": ""Shipping"",
                ""SelfPickUpOptions"": null,
                ""OrderReturnDetails"": null,
                ""OrderCancelDetails"": null,
                ""TaxDetails"": {
                    ""TotalTaxPaid"": 9.52,
                    ""TaxGroupId"": 3,
                    ""TaxGroupName"": ""GST-5"",
                    ""TaxSplits"": [
                        {
                            ""TaxId"": 5,
                            ""TaxName"": ""CGST"",
                            ""TaxPercentage"": 2.5,
                            ""TaxAmount"": 0,
                            ""TaxAmountPaid"": 4.76,
                            ""TaxType"": ""TaxPercentage""
                        },
                        {
                            ""TaxId"": 6,
                            ""TaxName"": ""SGST"",
                            ""TaxPercentage"": 2.5,
                            ""TaxAmount"": 0,
                            ""TaxAmountPaid"": 4.76,
                            ""TaxType"": ""TaxPercentage""
                        }
                    ]
                },
                ""LoanDetail"": null,
                ""Shipment"": {
                    ""Id"": 264,
                    ""ProviderName"": ""***************"",
                    ""ShipmentFee"": 70,
                    ""ExpectedDeliveryDate"": ""2020-08-05T10:33:21.693771"",
                    ""TrackingCode"": null,
                    ""ShiprocketResponse"": {
                        ""pickup_location_added"": 0,
                        ""order_created"": 1,
                        ""awb_generated"": 1,
                        ""label_generated"": 1,
                        ""pickup_generated"": 1,
                        ""manifest_generated"": 1,
                        ""pickup_scheduled_date"": ""2020-08-04T09:00:00"",
                        ""order_id"": 234234,
                        ""shipment_id"": 234234,
                        ""awb_code"": ""***************"",
                        ""courier_company_id"": 1,
                        ""courier_name"": null,
                        ""assigned_date_time"": null,
                        ""applied_weight"": 5.4,
                        ""cod"": false,
                        ""label_url"": ""https://kr-shipmult***************6448260_shipp***************.pdf"",
                        ""manifest_url"": ""https://s3-ap-s***************IFEST-0012.pdf"",
                        ""routing_code"": ""TGD/TGD"",
                        ""pickup_token_number"": ""***************""
                    }
                },
                ""SellerName"": ""***************"",
                ""Metadata"": {
                    ""QuoteSnapshot"": null,
                    ""IsSelfPickup"": false,
                    ""DeliveryCode"": null,
                    ""SelfPickupOptions"": null,
                    ""LoanDetailSnapShot"": null,
                    ""ShipmentFeePerSeller"": 70,
                    ""PartnerDiscountDetails"": null
                },
                ""ActualUnitPrice"": 234234
            }
        ],
        ""PaymentSplits"": [
            {
                ""Id"": 0,
                ""PaymentMode"": ""Online"",
                ""Price"": 23423423
            }
        ],
        ""OrderStatus"": ""SellerProcessing"",
        ""OrderStatusHistories"": [
            {
                ""Id"": 0,
                ""OrderId"": 0,
                ""OrderStatus"": ""Created"",
                ""CreatedDateTime"": ""2020-08-01T10:33:31.129905""
            },
            {
                ""Id"": 0,
                ""OrderId"": 0,
                ""OrderStatus"": ""PaymentSuccess"",
                ""CreatedDateTime"": ""2020-08-02T10:24:12.525043""
            },
            {
                ""Id"": 0,
                ""OrderId"": 0,
                ""OrderStatus"": ""SellerProcessing"",
                ""CreatedDateTime"": ""2020-08-03T05:29:59.670581""
            }
        ],
        ""CreatedDateTime"": ""2020-08-01T10:33:31.129825"",
        ""CustomerName"": ""***************"",
        ""Metadata"": {
            ""QuoteId"": 0,
            ""ShipmentFee"": 70
        },
        ""CustomerPhone"": ""***************"",
        ""DiscountSplits"": []
    },
    ""BusinessDetails"": {
        ""Name"": ""***************"",
        ""Gstin"": ""***************"",
        ""Cin"": ""***************"",
        ""Tan"": null,
        ""Pan"": ""***************"",
        ""Phone"": """",
        ""Mobile"": ""***************"",
        ""Email"": ""online@***************.com""
    },
    ""BusinessAddress"": {
        ""Id"": 0,
        ""ApartmentNumber"": ""No 6"",
        ""Street"": ""******************************"",
        ""Locality"": ""***************, ***************"",
        ""City"": ""*************** "",
        ""State"": ""***************"",
        ""Country"": ""***************"",
        ""ISOCountryCode"": null,
        ""ZipCode"": ""***************""
    }
}";
          #endregion
          
          var ob = JsonConvert.DeserializeObject<Model.GetInvoiceDto>(str);
          
          
        }
Exemplo n.º 3
0
        public static List <Trip> GetTrips()
        {
            _random = new Random();
            Trip trip1 = new Trip {
                UserId = "Scott"
            };

            trip1.Name     = trip1.UserId + " - Redmond";
            trip1.Distance = 34;
            trip1.Photos   = new List <Photo>();
            var startTime = DateTime.UtcNow;

            trip1.RecordedTimeStamp = startTime;
            trip1.EndTimeStamp      = startTime;
            var timeIncrement = 1;

            AddTripDetails(trip1, 1, 47.738928, -122.185165, startTime);
            AddTripDetails(trip1, 2, 47.738929, -122.185166, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip1, 3, 47.738930, -122.185167, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip1, 4, 47.738928, -122.185167, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip1, 5, 47.738926, -122.185166, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip1, 6, 47.738923, -122.185166, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip1, 7, 47.738924, -122.185166, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip1, 8, 47.738924, -122.185168, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip1, 9, 47.738925, -122.185168, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip1, 10, 47.738926, -122.185167, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip1, 11, 47.738927, -122.185167, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip1, 12, 47.738928, -122.185166, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip1, 13, 47.738929, -122.185166, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip1, 14, 47.738929, -122.185167, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip1, 15, 47.738939, -122.185169, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip1, 16, 47.738915, -122.185122, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip1, 17, 47.738377, -122.185458, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip1, 18, 47.738578, -122.185435, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip1, 19, 47.738579, -122.185436, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip1, 20, 47.739069, -122.185258, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip1, 21, 47.739172, -122.185237, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip1, 22, 47.738971, -122.185252, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip1, 23, 47.739356, -122.185168, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip1, 24, 47.738992, -122.185225, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip1, 25, 47.738988, -122.185227, startTime.AddMinutes(timeIncrement++));


            Trip trip5 = new Trip {
                UserId = "Amanda"
            };

            trip5.Name     = trip5.UserId + " - SF";
            trip5.Distance = 3;

            startTime = DateTime.Now.AddYears(-4);
            trip5.RecordedTimeStamp = startTime;
            trip5.EndTimeStamp      = startTime;
            timeIncrement           = 1;
            AddTripDetails(trip5, 2, 37.63973671, -122.44194609, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 3, 37.63997584, -122.44214793, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 4, 37.64021602, -122.44235831, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 5, 37.64045755, -122.44257364, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 6, 37.64069467, -122.44278177, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 7, 37.64093544, -122.44298813, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 8, 37.64117709, -122.44319877, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 9, 37.64141413, -122.44341636, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 10, 37.64164233, -122.44364393, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 11, 37.64186609, -122.44387452, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 12, 37.64209642, -122.44410611, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 13, 37.64230429, -122.44437793, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 14, 37.64250521, -122.44464263, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 15, 37.64270168, -122.44491739, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 16, 37.64289488, -122.44520296, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 17, 37.64307505, -122.44550295, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 18, 37.6432535, -122.44579707, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 19, 37.64341758, -122.44610972, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 20, 37.6435871, -122.4464253, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 21, 37.64375562, -122.44674171, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 22, 37.6439212, -122.44706014, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 23, 37.64408553, -122.44736776, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 24, 37.64425086, -122.44768593, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 25, 37.64442776, -122.44799045, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 26, 37.64460123, -122.44828122, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 27, 37.64480118, -122.44856712, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 28, 37.6450036, -122.44884951, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 29, 37.64522434, -122.4491044, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 30, 37.64544914, -122.44932703, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 31, 37.64568224, -122.44954965, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 32, 37.64593185, -122.44975467, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 33, 37.64618218, -122.44995475, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 34, 37.64643992, -122.45012096, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 35, 37.64671535, -122.45027846, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 36, 37.64697783, -122.45043973, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 37, 37.64724442, -122.45059714, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 38, 37.64750744, -122.45075656, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 39, 37.64777453, -122.45090651, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 40, 37.64803999, -122.45107063, startTime.AddMinutes(timeIncrement++));
            AddTripDetails(trip5, 41, 37.64830846, -122.45123173, startTime.AddMinutes(timeIncrement++));


            Trip trip6 = null;

            try
            {
                var json =
                    ResourceLoader.GetEmbeddedResourceString(
                        Assembly.Load(new AssemblyName("MyDriving.DataStore.Mock")), "sampletrip.json");
                trip6        = JsonConvert.DeserializeObject <Trip>(json);
                trip6.Photos = new List <Photo>();
                foreach (var pt in trip6.Points)
                {
                    pt.EngineLoad     = _random.Next(25, 75);
                    pt.EngineFuelRate = _random.Next(19, 25);
                    pt.Speed          = _random.Next(30, 60);
                    pt.HasOBDData     = true;
                    pt.MassFlowRate   = _random.Next(50, 100);
                }

                trip6.Points[0].Speed = 0.0;
            }
            catch (Exception ex)
            {
            }


            var items = new List <Trip>
            {
                trip1,
                trip5,
                trip6
            };


            foreach (var item in items)
            {
                item.Rating = _random.Next(30, 100);
                var point = item.Points.ElementAt(item.Points.Count / 2);
                if (Logger.BingMapsAPIKey != "____BingMapsAPIKey____")
                {
                    item.MainPhotoUrl =
                        $"http://dev.virtualearth.net/REST/V1/Imagery/Map/Road/{point.Latitude.ToString(CultureInfo.InvariantCulture)},{point.Longitude.ToString(CultureInfo.InvariantCulture)}/15?mapSize=500,220&key={Logger.BingMapsAPIKey}";
                }
            }

            return(items);
        }
Exemplo n.º 4
0
        private void CreateImages(string sBaseImagePath)
        {
            var vOutPath = AppDomain.CurrentDomain.BaseDirectory;
            var vFileName = Path.GetFileNameWithoutExtension(sBaseImagePath);
            var vImageOutPath = vOutPath + @"\" + vFileName;
            Directory.CreateDirectory(vOutPath);
            var log = false; var verbose = false; var quiet = false;
            Logger.Init(vOutPath, log, verbose, quiet);
            Logger.WriteLine("Begin Resizing Images!");
            Logger.WriteVerbose("Writing files to {0}", vOutPath);
            if (chkiOS.Checked)
            {
                var viOSOutputPath = vImageOutPath + @"\iOSImages";
                Directory.CreateDirectory(viOSOutputPath);
                Logger.WriteVerbose("Created directory {0} for iOS Images", viOSOutputPath);

                var viOSizesFile = vOutPath + @"\SizeJsons\iOSizes.json";
                var vLoadedFileJson = File.ReadAllText(viOSizesFile);
                var viOsSizes = JsonConvert.DeserializeObject<IEnumerable<AppImage>>(vLoadedFileJson).OrderBy(x => x.Width);
                for (int iCount = 0; iCount < chkLstiOS.CheckedItems.Count; iCount++)
                {
                    var vSelSize = chkLstiOS.CheckedItems[iCount].ToString();
                    var vSelectedImage = (from SelImage in viOsSizes
                                          where SelImage.ImageName == vSelSize
                                          select SelImage).SingleOrDefault();
                    Logger.WriteVerbose("Creating Image for {0} of iOS Images", vSelSize);
                    var vNewImageName = viOSOutputPath + "\\" + vFileName + vSelectedImage.ImageName + ".png";

                    var width = Convert.ToInt32(vSelectedImage.Width);
                    var height = Convert.ToInt32(vSelectedImage.Height);
                    if (!ckbWidth.Checked || !ckbHeight.Checked)
                    {
                        var imageBase = Image.FromFile(sBaseImagePath);
                        if (ckbWidth.Checked)
                        {
                            height = width * imageBase.Height / imageBase.Width;
                        }
                        else
                        {
                            width = height * imageBase.Width / imageBase.Height;
                        }
                    }

                    var vNewIMage = Scale(width, height, sBaseImagePath);
                    vNewIMage.Save(vNewImageName);
                    Logger.WriteVerbose("Created Image for {0} of iOS Images", vSelSize);
                }

                if (chkLstiOS.CheckedItems.Count > 0)
                {
                    var vSelectedImage = viOsSizes.Last();
                    Logger.WriteVerbose("Creating Image for last of iOS Images");
                    var vNewImageName = viOSOutputPath + "\\" + vFileName + ".png";

                    var width = Convert.ToInt32(vSelectedImage.Width);
                    var height = Convert.ToInt32(vSelectedImage.Height);
                    if (!ckbWidth.Checked || !ckbHeight.Checked)
                    {
                        var imageBase = Image.FromFile(sBaseImagePath);
                        if (ckbWidth.Checked)
                        {
                            height = width * imageBase.Height / imageBase.Width;
                        }
                        else
                        {
                            width = height * imageBase.Width / imageBase.Height;
                        }
                    }

                    var vNewIMage = Scale(width, height, sBaseImagePath);
                    vNewIMage.Save(vNewImageName);
                    Logger.WriteVerbose("Created Image for last of iOS Images");
                }

                lbliOSTitle.Visible = true;
                lbliOSValue.Text = viOSOutputPath;
                lbliOSValue.Visible = true;
            }
            if (chkAndroid.Checked)
            {
                var vAndroidPath = vImageOutPath + @"\AndroidImages";
                Directory.CreateDirectory(vAndroidPath);
                Logger.WriteVerbose("Created directory {0} for Android Images", vAndroidPath);

                var vDroidSizesFile = vOutPath + @"\SizeJsons\AndroidSizes.json";
                var vDroidSizeJson = File.ReadAllText(vDroidSizesFile);
                var vDroidSizes = JsonConvert.DeserializeObject<IEnumerable<AppImage>>(vDroidSizeJson).OrderBy(x => x.Width);
                for (int iCount = 0; iCount < chlLstAndroid.CheckedItems.Count; iCount++)
                {
                    var vSelSize = chlLstAndroid.CheckedItems[iCount].ToString();
                    var vSelectedImage = (from SelImage in vDroidSizes
                                          where SelImage.ImageName == vSelSize
                                          select SelImage).SingleOrDefault();

                    Logger.WriteVerbose("Creating Image for {0} of Android Images", vSelSize);

                    var imagePath = Path.Combine(vAndroidPath, vSelectedImage.Path);
                    Directory.CreateDirectory(imagePath);

                    var vNewImageName = imagePath + "\\" + vFileName + ".png";

                    var width = Convert.ToInt32(vSelectedImage.Width);
                    var height = Convert.ToInt32(vSelectedImage.Height);
                    if (!ckbWidth.Checked || !ckbHeight.Checked)
                    {
                        var imageBase = Image.FromFile(sBaseImagePath);
                        if (ckbWidth.Checked)
                        {
                            height = width * imageBase.Height / imageBase.Width;
                        }
                        else
                        {
                            width = height * imageBase.Width / imageBase.Height;
                        }
                    }

                    var vNewIMage = Scale(width, height, sBaseImagePath);

                    vNewIMage.Save(vNewImageName);
                    Logger.WriteVerbose("Created Image for {0} of Android Images", vSelSize);
                }


                if (chlLstAndroid.CheckedItems.Count > 0)
                {
                    var vSelectedImage = vDroidSizes.Last();
                    Logger.WriteVerbose("Creating Image for last of Android Images");

                    var vNewImageName = vAndroidPath + "\\" + vFileName + ".png";

                    var width = Convert.ToInt32(vSelectedImage.Width);
                    var height = Convert.ToInt32(vSelectedImage.Height);
                    if (!ckbWidth.Checked || !ckbHeight.Checked)
                    {
                        var imageBase = Image.FromFile(sBaseImagePath);
                        if (ckbWidth.Checked)
                        {
                            height = width * imageBase.Height / imageBase.Width;
                        }
                        else
                        {
                            width = height * imageBase.Width / imageBase.Height;
                        }
                    }

                    var vNewIMage = Scale(width, height, sBaseImagePath);

                    vNewIMage.Save(vNewImageName);
                    Logger.WriteVerbose("Created Image for last of Android Images");
                }


                lblAndroid.Visible = true;
                lblAndroidValue.Text = vAndroidPath;
                lblAndroidValue.Visible = true;
            }
            if (chkUwp.Checked)
            {
                var vUwpPath = vImageOutPath + @"\UwpImages";
                Directory.CreateDirectory(vUwpPath);
                Logger.WriteVerbose("Created directory {0} for Uwp Images", vUwpPath);

                var vUwpSizesFile = vOutPath + @"\SizeJsons\UwpSizes.json";
                var vUwpSizeJson = File.ReadAllText(vUwpSizesFile);
                var vUwpSizes = JsonConvert.DeserializeObject<IEnumerable<AppImage>>(vUwpSizeJson).OrderBy(x => x.Width);
                for (int iCount = 0; iCount < chkLstUwp.CheckedItems.Count; iCount++)
                {
                    var vSelSize = chkLstUwp.CheckedItems[iCount].ToString();
                    var vSelectedImage = (from SelImage in vUwpSizes
                                          where SelImage.ImageName == vSelSize
                                          select SelImage).SingleOrDefault();

                    Logger.WriteVerbose("Creating Image for {0} of UWP Images", vSelSize);
                    var vNewImageName = vUwpPath + "\\" + vFileName + vSelectedImage.ImageName + ".png";

                    var width = Convert.ToInt32(vSelectedImage.Width);
                    var height = Convert.ToInt32(vSelectedImage.Height);
                    if (!ckbWidth.Checked || !ckbHeight.Checked)
                    {
                        var imageBase = Image.FromFile(sBaseImagePath);
                        if (ckbWidth.Checked)
                        {
                            height = width * imageBase.Height / imageBase.Width;
                        }
                        else
                        {
                            width = height * imageBase.Width / imageBase.Height;
                        }
                    }

                    var vNewIMage = Scale(width, height, sBaseImagePath);


                    vNewIMage.Save(vNewImageName);
                    Logger.WriteVerbose("Created Image for {0} of UWP Images", vSelSize);
                }


                if (chkLstUwp.CheckedItems.Count > 0)
                {
                    var vSelectedImage = vUwpSizes.Last();

                    Logger.WriteVerbose("Creating Image for last of UWP Images");
                    var vNewImageName = vUwpPath + "\\" + vFileName + ".png";

                    var width = Convert.ToInt32(vSelectedImage.Width);
                    var height = Convert.ToInt32(vSelectedImage.Height);
                    if (!ckbWidth.Checked || !ckbHeight.Checked)
                    {
                        var imageBase = Image.FromFile(sBaseImagePath);
                        if (ckbWidth.Checked)
                        {
                            height = width * imageBase.Height / imageBase.Width;
                        }
                        else
                        {
                            width = height * imageBase.Width / imageBase.Height;
                        }
                    }

                    var vNewIMage = Scale(width, height, sBaseImagePath);


                    vNewIMage.Save(vNewImageName);
                    Logger.WriteVerbose("Created Image for last of UWP Images");
                }

                lblUWPTitle.Visible = true;
                lblUWPValues.Text = vUwpPath;
                lblUWPValues.Visible = true;
            }
        }
Exemplo n.º 5
0
        public static object DeserializeObject(string input)
        {
            object returnValue = JsonConvert.DeserializeObject(input);

            return(returnValue);
        }
 public async Task<int> GetRangeAsync(int count)
 {
     var response = await _client.GetAsync($"data/range/{count}");
     var testItems = JsonConvert.DeserializeObject<List<TestItem>>(await response.Content.ReadAsStringAsync());
     return testItems.Count;
 }
Exemplo n.º 7
0
        public static ShipInfoData GetToutiaoShipInfoById(int id)
        {
            List <ShipInfoData> shipInfo = JsonConvert.DeserializeObject <List <ShipInfoData> >(ShipInfoDataString);

            return(shipInfo.FirstOrDefault(t => t.Id == id));
        }
Exemplo n.º 8
0
 /// <summary>
 /// Decodes the invitation from base64 to strongly typed object
 /// </summary>
 /// <returns>The invitation.</returns>
 /// <param name="invitation">Invitation.</param>
 public ConnectionInvitationMessage DecodeInvitation(string invitation)
 {
     return(JsonConvert.DeserializeObject <ConnectionInvitationMessage>(Encoding.UTF8.GetString(Convert.FromBase64String(invitation))));
 }
Exemplo n.º 9
0
        private async Task <GroupResult_t> GetEnemyPage(int page)
        {
            string data = await HttpHelper.GetStringFromURL(string.Format("https://api.roblox.com/groups/{0}/enemies?page={1}", ID, page));

            return(JsonConvert.DeserializeObject <GroupResult_t>(data));
        }
Exemplo n.º 10
0
        /// <summary>
        /// [生成] 考核记录
        /// </summary>
        /// <param name="kpiId">考核方案</param>
        /// <returns></returns>
        public Result GeneratedManage(KpiPlan kpiId)
        {
            try
            {
                var dtNow = DateTime.Now;
                var currTime = 0;
                var currYear = dtNow.Year;

                switch (kpiId)
                {
                    case KpiPlan.Monthly:
                        currTime = dtNow.Month;
                        break;
                    case KpiPlan.Quarter:
                        currTime = TimeHelper.GetQurater(dtNow);
                        break;
                    case KpiPlan.HalfYear:
                        currTime = dtNow.Month < 7 ? 1 : 2;
                        break;
                    case KpiPlan.Annual:
                        currTime = 1;
                        break;
                }
                var kpiDate = currTime.ToString();

                using (TransactionScope ts = new TransactionScope())
                {
                    var dbTplRecord = _tplRecordBusiness.QueryByGenerated(kpiId, currYear, kpiDate);
                    if (dbTplRecord.Count <= 0)
                    {
                        return Result.Fail("没有需要生成的数据", "201");
                    }

                    //考核管理统计
                    var dbMagTotal = _magTotalBusiness.Query(p => p.KpiId == kpiId && p.Year == currYear);

                    //考核管理统计
                    var lsNotExistMagTotal = new List<KpiManageTotal>();
                    var lsExistMagTotal = new List<KpiManageTotal>();
                    //考核管理记录
                    var lsNotExistMagRecord = new List<KpiManageRecord>();
                    //考核管理明细
                    var lsNotExistMagDetail = new List<KpiManageDetail>();
                    foreach (var tplRecord in dbTplRecord)
                    {
                        #region 考核管理统计
                        KpiManageTotal modelMagTotal = null;
                        if (dbMagTotal.Count > 0)
                        {
                            modelMagTotal = dbMagTotal.FirstOrDefault(p => p.KpiType == tplRecord.KpiType && p.CompanyId == tplRecord.CompanyId && p.DptId == tplRecord.DptId && p.EmployeeId == tplRecord.EmployeeId);
                        }
                        if (modelMagTotal == null)
                        {
                            modelMagTotal = new KpiManageTotal()
                            {
                                Id = 0,
                                KpiType = tplRecord.KpiType,
                                KpiId = tplRecord.KpiId,
                                KpiName = tplRecord.KpiName,
                                CompanyId = tplRecord.CompanyId,
                                CompanyName = tplRecord.CompanyName,
                                DptId = tplRecord.DptId,
                                DptName = tplRecord.DptName,
                                EmployeeId = tplRecord.EmployeeId,
                                UserName = tplRecord.UserName,
                                Year = currYear
                            };
                            for (int i = 0; i < 12; i++)
                            {
                                DynaimcHelper.DynamicFileds[i].Score.SetValue(modelMagTotal, (decimal)0);
                                if ((i + 1) < currTime)
                                {
                                    DynaimcHelper.DynamicFileds[i].Status.SetValue(modelMagTotal, KpiStatus.Invalid);
                                }
                                else if ((i + 1) == currTime)
                                {
                                    DynaimcHelper.DynamicFileds[i].Status.SetValue(modelMagTotal, KpiStatus.Assess);
                                }
                                else
                                {
                                    DynaimcHelper.DynamicFileds[i].Status.SetValue(modelMagTotal, KpiStatus.NotStarted);
                                }
                            }
                            lsNotExistMagTotal.Add(modelMagTotal);
                        }
                        else
                        {
                            for (int i = 0; i < 12; i++)
                            {
                                if ((i + 1) == currTime)
                                {
                                    DynaimcHelper.DynamicFileds[i].Status.SetValue(modelMagTotal, KpiStatus.Assess);
                                }
                            }
                            lsExistMagTotal.Add(modelMagTotal);
                        }
                        #endregion

                        lsNotExistMagRecord.Add(new KpiManageRecord()
                        {
                            Id = 0,
                            KpiTemplateRecordId = tplRecord.Id,
                            KpiType = tplRecord.KpiType,
                            KpiId = tplRecord.KpiId,
                            KpiName = tplRecord.KpiName,
                            CompanyId = tplRecord.CompanyId,
                            CompanyName = tplRecord.CompanyName,
                            DptId = tplRecord.DptId,
                            DptName = tplRecord.DptName,
                            EmployeeId = tplRecord.EmployeeId,
                            UserName = tplRecord.UserName,
                            Year = currYear,
                            KpiDate = kpiDate,
                            Steps = KpiSteps.Zero,
                            StepsCompanyId = tplRecord.CompanyId,
                            StepsCompanyName = tplRecord.CompanyName,
                            StepsDptId = tplRecord.DptId,
                            StepsDptName = tplRecord.DptName,
                            StepsEmployeeId = tplRecord.EmployeeId,
                            StepsUserName = tplRecord.UserName,
                            AddDate = dtNow,
                            Score = 0,
                            Status = KpiStatus.Assess
                        });
                    }

                    _magRecordBusiness.AddRange(lsNotExistMagRecord);

                    foreach (var magTecord in lsNotExistMagRecord)
                    {
                        var modelTplRecord = dbTplRecord.FirstOrDefault(p => p.Id == magTecord.KpiTemplateRecordId);
                        if (modelTplRecord != null)
                        {
                            var lsTplContents = JsonConvert.DeserializeObject<List<KpiTemplateContentsDto>>(modelTplRecord.Contents).OrderBy(p => p.EvaluationId);
                            foreach (var tplContent in lsTplContents)
                            {
                                lsNotExistMagDetail.Add(new KpiManageDetail
                                {
                                    Id = 0,
                                    KpiManageRecordId = magTecord.Id,
                                    CompanyId = magTecord.CompanyId,
                                    DptId = magTecord.DptId,
                                    EmployeeId = magTecord.EmployeeId,
                                    EvaluationId = tplContent.EvaluationId,
                                    EvaluationName = tplContent.EvaluationName,
                                    EvaluationType = tplContent.EvaluationType,
                                    Weight = tplContent.Weight,
                                    Explain = tplContent.Explain,
                                    Year = magTecord.Year,
                                    KpiDate = magTecord.KpiDate,
                                    SelfScore = 0,
                                    OneScore = 0,
                                    TwoScore = 0
                                });
                            }
                        }
                    }
                    if (lsNotExistMagDetail.Count > 0)
                    {
                        _magDetailBusiness.AddRange(lsNotExistMagDetail);
                    }

                    _magTotalBusiness.AddRange(lsNotExistMagTotal);
                    if (lsExistMagTotal.Count > 0)
                    {
                        _magTotalBusiness.UpdateRange(lsExistMagTotal);
                    }

                    ts.Complete();
                    return Result.Success();
                }
            }
            catch (Exception ex)
            {
                return Result.Fail("失败:" + ex.Message);
            }
        }
 public static T ToEntity <T>(string jsonStr) where T : class, new()
 {
     return(JsonConvert.DeserializeObject <T>(jsonStr));
 }
Exemplo n.º 12
0
 public async Task<T> GetResponse<T>(string path)
 {
     return JsonConvert.DeserializeObject<T>(await GetWebRequestResultAsync(path));
 }
Exemplo n.º 13
0
        private static void Commander(command_data_client CMD)
        {
            //Console.WriteLine("Command] {0} : ", ((Command_Client)CMD.Command_code).ToString());
            switch (CMD.Command_code)
            {
                case (int)Command_Client.Updated_Connection_Account: //현재 로그인할수 있는 연결들을 관리하는 메니저.
                    {
                        i_Updated_Connection_Account iuca = (i_Updated_Connection_Account)CMD.data; //내부에서 호출하기 땜에 시리얼라이즈하지 않는다.

                        DataRow[] C = DB_Connection.Select("No = " + iuca.Connect_No);
                        if (C.Length == 1)
                        {
                            C[0]["State_Account_on_connected"] = iuca.State;
                        }
                    }
                    break;
                case (int)Command_Client.Managing_Account: //현재 로그인할수 있는 연결들을 관리하는 메니저.
                    {
                        //Trying_Login 상태인 연결들을 찾아 로그인 체크,
                        DataRow[] C = DB_Connection.Select("State_Account_on_connected =" + (int)State_Account_on_connected.Trying_Login);
                        if (C.Length > 0)
                        {
                            foreach (DataRow Cnt in C)
                            {
                                Make_Client_Event(Unit_Event_Type.Account_Check_Login, (int)Cnt["No"]);
                            }
                        }

                        //상태가 setting 인 연결을 찾아 새로그인을 시킨다.
                        C = DB_Connection.Select("State_Account_on_connected =" + (int)State_Account_on_connected.Setting);
                        if (C.Length > 0)
                        {
                            foreach (DataRow Cnt in C)
                            {
                                i_Account_Set IAS = new i_Account_Set(
                                    (Type_Order)Cnt["Type_order"],
                                    (int)Cnt["No"],
                                    (int)Cnt["Login_Account_no"],
                                    (string)Cnt["Account_ID"],
                                    (string)Cnt["Account_PW"],
                                    (int)Cnt["Order_No"]
                                    );
                                Cnt["State_Account_on_connected"] = State_Account_on_connected.Trying_Login;
                                Make_Client_Event(Unit_Event_Type.Account_Login, new List<object> { IAS });
                            }
                        }
                        //Failure_Login 인 연결은 글쌔..
                    }
                    break;
                case (int)Command_Client.Account_Set: //개별적인 연결에 로그인 계정을 임명하는 명령어. 
                    {
                        //Add_Response((int)candidate[candidate_No]["Unit_No"], Command_Client.Account_Set, ias);
                        i_Account_Set ils = JsonConvert.DeserializeObject<i_Account_Set>(CMD.data.ToString());

                        DataRow[] C = DB_Connection.Select("No =" + ils.Connect_No);

                        if (C.Length != 1)
                            return;

                        C[0]["Login_Account_no"] = ils.Account_No;
                        C[0]["Account_ID"] = ils.ID;
                        C[0]["Account_PW"] = ils.PW;
                        C[0]["State_Account_on_connected"] = State_Account_on_connected.Setting; //첫 세팅.

                        //
                        //여기서 직접 로긴 명령을 내리는것이 아니라 메니저에서 별도로 로긴명령을 내린다.
                        //디비에 정보를 저장하고
                        //이벤트로 크롬드라이브에 로그인 명령을 내린다
                    }
                    break;
                case (int)Command_Client.Close_connect:
                    {
                        int connect_no = int.Parse(CMD.data.ToString());

                        DataRow[] CC = DB_Connection.Select(
                            "No = " + connect_no + " and not State = " + (int)State_Connect.Closing +
                            " and not State = " + (int)State_Connect.Close
                            ); //이미 닫혔거나 닫고 있지 않은경우 실행한다.
                        if (CC.Length == 1)
                        {
                            Make_Client_Event(
                                    Unit_Event_Type.Disconnect_connect,
                                    new List<object> {new i_connect(
                                            (int)CC[0]["No"],
                                            (int)CC[0]["Order_No"],
                                            (string)CC[0]["Connect_URL"],
                                            (Type_Order)CC[0]["Type_order"],
                                            (string)CC[0]["Proxy_host"]) }
                                    );
                        }
                    }
                    break;
                case (int)Command_Client.Set_UnitNo:
                    {
                        int No = Convert.ToInt32(CMD.data);
                        
                        Unit_No = No;
                        Console.WriteLine("Set Unit No] {0}.", Unit_No.ToString());

                        if (None_proxy) //자신의 아이피를 프록시 서버 호스트로 지정.
                            Add_Command(Command_Client.Set_Proxy, Client_IP);
                        else
                            Unit_State = State_Unit.Wait_proxy;

                        Console.WriteLine("Updated State_Unit [{0}]", Unit_State.ToString());
                    }
                    break;
                case (int)Command_Client.Login_success:
                    {
                        i_Login_success ils = JsonConvert.DeserializeObject<i_Login_success>(CMD.data.ToString());

                        User_No = ils.User_No;
                        //Unit_State = State_Unit.Logged;
                        Session = ils.Session;
                        Type_user = ils.Type_user;
                    }
                    break;
                case (int)Command_Client.Set_Proxy: //서버로 부터 프록시 배정 신호가 온다.
                    {
                        string host = (string)CMD.data;

                        if (None_proxy) //다이렉트 아이피 모드
                        {
                            Proxy_host = host;
                            Setted_proxy = true;
                            Console.WriteLine("Setted Direct ip : {0}.", Proxy_host);
                        }
                        else if (host.Length > 8 && Test_proxy(host))
                        {
                            Proxy_host = host;
                            Setted_proxy = true;
                            Console.WriteLine("Setted Proxy : {0}.", Proxy_host);
                            Add_Response(Command_Server.Sucsses_Proxy, host);
                        }
                        else
                        {
                            Setted_proxy = false;
                            Unit_State = State_Unit.Wait_proxy;
                            Add_Response(Command_Server.Failure_Proxy, host);
                            Console.WriteLine("Error Set_Proxy : {0}.", host);
                        }
                    }
                    break;
                case (int)Command_Client.Managing_State: //일단 현재의 상태를 주기적으로 보내는 것으로 하자.
                    {
                        ///=====================================================
                        /// 유닛의 상태를 자동으로 결정하는코드
                        if (Unit_No < 0)
                            return;


                        if (Setted_proxy)
                        {
                            DataRow[] C = DB_Connection.Select("State = " + (int)State_Connect.Connecting
                            + " or State = " + (int)State_Connect.Wait + "");
                            if(Unit_State != State_Unit.Logged && Proxy_host != "")
                                if (C.Length > 0)
                                    Unit_State = State_Unit.Ordering; //연결 상태를 오더 처리중으로 변경.
                                else
                                    Unit_State = State_Unit.Enable; //연결 상태를 오더 처리중으로 변경.
                        }
                        
                        //==========================================
                        //현재의 상태를 주기적으로 보내는 코드.

                        i_State istate = new i_State();

                        istate.State_unit = Unit_State;
                        istate.State_connect = new List<i_Updated_Connection>();

                        foreach (DataRow R in DB_Connection.Rows) //모든 내용.
                        {
                            i_Updated_Connection iuc = new i_Updated_Connection((int)R["No"], i_Updated_Connection_Type.State_Connect, (State_Connect)R["State"]);
                            istate.State_connect.Add(iuc); //모든 커넥션을 추가.

                            if (R["State_Account_on_connected"] != null)
                            {
                                i_Updated_Connection iuc2 = new i_Updated_Connection((int)R["No"], i_Updated_Connection_Type.State_Account_on_connected, (State_Account_on_connected)R["State_Account_on_connected"]);
                                istate.State_connect.Add(iuc2); //모든 커넥션을 추가.
                            }

                            if (R["Login_Account_no"] != null)
                            {
                                i_Updated_Connection iuc3 = new i_Updated_Connection((int)R["No"], i_Updated_Connection_Type.Login_Account_no, (int)R["Login_Account_no"]);
                                istate.State_connect.Add(iuc3); //모든 커넥션을 추가.
                            }

                            //반으시 닫힘을 알리고 삭제되어야 하므로Managing_connecting에서 별도 처리 하기 보다 한번에 여기서 순서에 맞춰 먼저 보내고 삭제,
                            if ((int)R["State"] == (int)State_Connect.Close) //만약 종료되었음을 알리는 신호라면,
                            {
                                Console.WriteLine("Deleted Connection [C[{0}]", iuc.Connect_No);
                                DB_Connection.Rows.Remove(R); //정말 지워지는지 검증필요
                                break;
                            }

                        }
                        Add_Response(Command_Server.State, istate);
                    }
                    break;
                case (int)Command_Client.Managing_connecting:
                    {
                        //연결되어 있는 브라우저의 방송이 종료되었는지 체크하여
                        //종료되었으면 방송을 닫는다.

                        DataRow[] Cr = DB_Connection.Select("State = " + (int)State_Connect.Connected);
                        List<object> i_connect_list = new List<object>();

                        foreach (DataRow R in Cr) //연결된 상태에 있는 커넥션들을 가져와서 이벤트를 발생시킨다.
                        {
                            i_connect ic = new i_connect(
                                            (int)R["No"],
                                            (int)R["Order_No"],
                                            (string)R["Connect_URL"],
                                            (Type_Order)R["Type_order"],
                                            (string)R["Proxy_host"]);
                            i_connect_list.Add(ic);
                        }

                        try
                        {
                            Make_Client_Event(Unit_Event_Type.Check_End_broadcast, i_connect_list);
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }

                        //실패한 연결을 닫는 명령을 내린다.
                        foreach (DataRow C in DB_Connection.Rows)
                        {
                            if((State_Connect)C["State"] == State_Connect.Failure)
                            {
                                Make_Client_Event(
                                    Unit_Event_Type.Disconnect_connect, 
                                    new List<object> {new i_connect(
                                            (int)C["No"],
                                            (int)C["Order_No"],
                                            (string)C["Connect_URL"],
                                            (Type_Order)C["Type_order"],
                                            (string)C["Proxy_host"]) }
                                    );

                            }
                        }

                    }
                    break;
                case (int)Command_Client.set_proxy_success_ok: //일단 현재의 상태를 주기적으로 보내는 것으로 하자.
                    {
                        if (Tester)
                        {
                            Add_Response(Command_Server.Login, new i_Login(
                                Unit_No,
                                "Test_" + Unit_No,
                                "",
                                Type_User.Tester_Unit
                                ));
                        }
                        
                        Unit_State = State_Unit.Enable; //사용가능 상태로 바꿈.
                    }
                    break;
                case (int)Command_Client.order_connect: //연결 명령.
                    {
                        i_connect C = JsonConvert.DeserializeObject<i_connect>(CMD.data.ToString());

                        //Unit_State = State_Unit.Ordering; //연결 상태를 오더 처리중으로 변경.

                        DB_Connection.Rows.Add(C.No, C.Order_No, C.URL, Proxy_host, C.order_type, State_Connect.Connecting, -1,"","", State_Account_on_connected.NotSet);
                        //디비에 등록.
                        try
                        {
                            if (Tefreeca_client_event != null)
                            {
                                Tefreeca_client_EventArgs TC_EvtArgs = new Tefreeca_client_EventArgs();
                                TC_EvtArgs.type = Unit_Event_Type.Order_Connect;

                                i_connect iC = JsonConvert.DeserializeObject<i_connect>(CMD.data.ToString());

                                if(iC.Proxy.Length < 6) //프록시가 지정되어 있지 않은 채 명령이 들어오면 유닛에 지정된 ip를 사용한다.
                                    iC.Proxy = Proxy_host;

                                TC_EvtArgs.data_string = JsonConvert.SerializeObject(iC);
                                
                                // TC_EvtArgs.Data_object_list = new List<object>(new object[] { C }); //connect가 들어있는 리스트를 매개변수로 넘김.
                                Tefreeca_client_event(null, TC_EvtArgs);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                    break;
                case (int)Command_Client.Updated_Connection:
                    {
                        i_Updated_Connection iuc = (i_Updated_Connection)CMD.data;

                        switch (iuc.Updated_Connection_Type)
                        {
                            case i_Updated_Connection_Type.State_Connect:
                                {
                                    State_Connect State_connect = (State_Connect)iuc.Data;
                                    DataRow[] C = DB_Connection.Select("No = " + iuc.Connect_No + "");

                                    if (C.Length == 1)
                                    {
                                        if ((int)C[0]["State"] == (int)State_connect)
                                            return; //변동없으면 패스.

                                        if ((int)C[0]["State"] == (int)State_Connect.Connecting && //연결상태가 연결중에서 종료쪽으로 바뀌면,
                                            (   State_connect == State_Connect.Failure  ||
                                                State_connect == State_Connect.Close    ||
                                                State_connect == State_Connect.Closing  ))
                                        {
                                            Make_Client_Event(Unit_Event_Type.Connect_sideBreak, iuc.Connect_No);
                                        }

                                        C[0]["State"] = (int)State_connect;
                                        Console.WriteLine("Updated Connection [C[{0}] {1}]", iuc.Connect_No, State_connect.ToString());

                                        if (State_connect == State_Connect.Failure) //연결 실패로 바꾸는 경우.
                                        {
                                            Add_Command(Command_Client.Failure_Counter, (int)C[0]["Order_No"]); //실패 카운트함.
                                        }
                                    }
                                    else
                                        Console.WriteLine("Error Updated_Connection.");
                                }
                                break;
                            case i_Updated_Connection_Type.Login_Account_no:
                                {
                                }
                                break;
                            case i_Updated_Connection_Type.State_Account_on_connected:
                                {
                                }
                                break;

                        }
                    }
                    break;
                case (int)Command_Client.Failure_Counter:
                    {
                        int order_no = (int)CMD.data;

                        ///order에 해당하는 엔트리가 있는지 Faliure_counting에서 검사해 
                        ///Faliure_counting에 있으면
                        ///발생한 애러의 order를 가지고 Faliure_counting에서 조회해 해당 카운트를 올린다.
                        ///없으면 새로 생성,
                        ///Faliure_counting를 관리하는데.. 
                        ///connected인 상태가 하나라도 있으면 삭제,
                        ///
                        ///10을 넘어가는 카운트가 있으면
                        ///실패신호를 보내게 된다. 그리고나면 삭제.
                        ///그리고 실패신호를 저장해두었다가  10회가 넘으면 해당 order를 종료시킨다.

                        if (Faliure_counting.Has_int_key(order_no)) //키가 존재하면, +1한 카운트로 업데이트 하고,
                            Faliure_counting.Update(order_no, (int)Faliure_counting.Select_key(order_no) + 1);
                        else //없으면
                            Faliure_counting.Insert(order_no, 1); //새 테이블을 생성.

                        DataRow[] R = DB_Connection.Select("Order_No = " + order_no + " and State = " + (int)State_Connect.Connected);
                        //해당 order중 연결된 상태의 커넥션이 있다면
                        if (R.Length > 0)
                            if (Faliure_counting.Has_int_key(order_no)) //키가 존재하면, 
                                Faliure_counting.Remove(order_no);  //삭제.

                        if (Faliure_counting.Has_int_key(order_no)) //키가 존재하면, +1한 카운트로 업데이트 하고,
                            if ((int)Faliure_counting.Select_key(order_no) >= 5) //5가 되면,
                                Add_Response(Command_Server.Failure_Connect, order_no);
                    }
                    break;
                case (int)Command_Client.Change_Proxy: //연결실패로 프록시를 바꾸자 하면..
                    {
                        ///모든 연결을 닫고, 그럴 필요 없다. 이미 접속된 연결을 그대로 두고,
                        /// 실패한 접속은 자동으로 닫힐테고,
                        /// 프록시 실패 명령을 보내면 서버는 그 프록시를 사용불가 처리 할 것이다
                        /// 그리고 상태를 wait_proxy로 바꾸면 새로운 프록시가 배정된다.
                        /// 그리고 다시 돌아갈 수 있다.

                        if(Proxy_host != "")
                            Add_Response(Command_Server.Failure_Proxy, Proxy_host);
                        else
                            Console.WriteLine("Error Command_Client.Change_Proxy, host:{0}", Proxy_host.ToString());


                        Unit_State = State_Unit.Wait_proxy;
                    }
                    break;
                case (int)Command_Client.Set_Tester: //연결실패로 프록시를 바꾸자 하면..
                    {
                        Console.WriteLine("Set_Tester_Unit.");
                        if (!Tester)
                        {
                            Tester = true;
                            Add_Response(Command_Server.Login, new i_Login(
                                    Unit_No,
                                    "Test_" + Unit_No,
                                    "",
                                    Type_User.Tester_Unit
                                    ));
                            //모든 연결을 닫는 코드 필요.
                        }
                    }
                    break;
                case (int)Command_Client.Order_Info: //연결실패로 프록시를 바꾸자 하면..
                    {

                    }
                    break;
                case (int)Command_Client.HeartBeat: //연결실패로 프록시를 바꾸자 하면..
                    {
                        
                    }
                    break;
                default:
                    {
                        Command_Client S = (Command_Client)CMD.Command_code;
                        Console.WriteLine("Unknown Command : {0}", S.ToString());
                    }
                    break;
            }
        }
Exemplo n.º 14
0
        private void LoginToServer(AccountSettings accountSettings, bool friendsList, bool bookmarksList)
        {

            GetApiTicketRequest requestObject = new GetApiTicketRequest()
            {
                password = accountSettings.AccountPassword,
                account = accountSettings.AccountName,
                no_bookmarks = bookmarksList? "false" : "true",
                no_characters = "true",
                no_friends = friendsList ? "false" : "true"
            };

            string webserver = GetApiTicketUrl;
            //parameters are what is actually used to get the api ticket rather than the post body content
            string parameters = "?account=" + requestObject.account + "&password="******"&no_characters=" + 
                requestObject.no_characters + "&no_friends=" + requestObject.no_friends + "&no_bookmarks=" + 
                requestObject.no_bookmarks;

            WebRequest request = Utils.CreateWebRequest(webserver + parameters, requestObject);
            WebResponse webResponse = null;

            try
            {
                webResponse = (HttpWebResponse)request.GetResponse();

                if (webResponse != null)
                {
                    System.IO.StreamReader sr = new System.IO.StreamReader(webResponse.GetResponseStream());
                    string rtnValue = sr.ReadToEnd();

                    if (BotMain._debug)
                    {
                        Console.WriteLine("LoginToServer return message: " + rtnValue);
                        Utils.AddToLog("LoginToServer return message: " + rtnValue, null);
                    }

                    GetApiTicketResponse rpt = JsonConvert.DeserializeObject<GetApiTicketResponse>(rtnValue);
                    awaitingReturn = false;

                    if (rpt != null)
                    {
                        ApiTicketResult = rpt;
                    }
                    else
                    {
                        Console.WriteLine("Error: failed to parse result into GetApiTicketResponse");
                        Utils.AddToLog("Error: failed to parse result into GetApiTicketResponse", null);
                    }

                    string saaaaaa = rtnValue + " ";
                }
            }
            catch (WebException ex)
            {
                Console.WriteLine("WebException on LoginToServer Call: " + ex.Message);
                Console.WriteLine("Retrying...");

                Utils.AddToLog("WebException on LoginToServer Call: " + ex.Message, accountSettings);
                LoginToServer(accountSettings, friendsList, bookmarksList);
            }
        }
 public static T GetObject<T>(this ISession session, string key)
 {
     var value = session.GetString(key);
     return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
 }
Exemplo n.º 16
0
 private static Recipe LoadRecipeFromJson(string json)
 {
     return(JsonConvert.DeserializeObject <Recipe>(json, Converter.Settings));
 }
 public async Task<int> GetAsync(int index)
 {
     var response = await _client.GetAsync($"data/{index}");
     var testItem = JsonConvert.DeserializeObject<TestItem>(await response.Content.ReadAsStringAsync());
     return testItem.Index;
 }
Exemplo n.º 18
0
        public TaskFilterObject(string base64String)
        {
            if (string.IsNullOrEmpty(base64String)) return;

            var json = Encoding.UTF8.GetString(Convert.FromBase64String(base64String));

            var jsonArray = json.Split(';');

            foreach (var filterItem in jsonArray)
            {
                var filterObj = JObject.Parse(filterItem);

                var paramString = filterObj.Value<string>("params");

                if (string.IsNullOrEmpty(paramString)) continue;

                var filterParam = Global.JObjectParseWithDateAsString(Encoding.UTF8.GetString(Convert.FromBase64String(paramString)));

                switch (filterObj.Value<string>("id"))
                {
                    case "sorter":
                        SortBy = filterParam.Value<string>("id");
                        SortOrder = filterParam.Value<string>("sortOrder");
                        break;

                    case "text":
                        FilterValue = filterParam.Value<string>("value");
                        break;

                    case "my":
                    case "responsibleID":
                        ResponsibleId = new Guid(filterParam.Value<string>("value"));
                        break;

                    case "overdue":
                    case "today":
                    case "theNext":
                        var valueString = filterParam.Value<string>("value");
                        var fromToArray = JsonConvert.DeserializeObject<List<string>>(valueString);
                        if (fromToArray.Count != 2) continue;
                        FromDate = !String.IsNullOrEmpty(fromToArray[0])
                                              ? Global.ApiDateTimeParse(fromToArray[0]) : DateTime.MinValue;
                        ToDate = !String.IsNullOrEmpty(fromToArray[1])
                                            ? Global.ApiDateTimeParse(fromToArray[1]) : DateTime.MinValue;
                        break;

                    case "fromToDate":
                        FromDate = filterParam.Value<DateTime>("from");
                        ToDate = (filterParam.Value<DateTime>("to")).AddDays(1).AddSeconds(-1);
                        break;

                    case "categoryID":
                        CategoryId = filterParam.Value<int>("value");
                        break;

                    case "openTask":
                    case "closedTask":
                        IsClosed = filterParam.Value<bool>("value");
                        break;

                    case "contactID":
                        ContactId = filterParam.Value<int>("id");
                        break;
                }
            }
        }
Exemplo n.º 19
0
        async Task <Purchase> PurchaseAsync(string productSku, string itemType, string payload, IInAppBillingVerifyPurchase verifyPurchase)
        {
            lock (purchaseLocker)
            {
                if (tcsPurchase != null && !tcsPurchase.Task.IsCompleted)
                {
                    return(null);
                }

                Bundle buyIntentBundle = serviceConnection.Service.GetBuyIntent(3, Context.PackageName, productSku, itemType, payload);
                var    response        = GetResponseCodeFromBundle(buyIntentBundle);

                switch (response)
                {
                case 0:
                    //OK to purchase
                    break;

                case 1:
                    //User Cancelled, should try again
                    throw new InAppBillingPurchaseException(PurchaseError.UserCancelled);

                case 2:
                    //Network connection is down
                    throw new InAppBillingPurchaseException(PurchaseError.ServiceUnavailable);

                case 3:
                    //Billing Unavailable
                    throw new InAppBillingPurchaseException(PurchaseError.BillingUnavailable);

                case 4:
                    //Item Unavailable
                    throw new InAppBillingPurchaseException(PurchaseError.ItemUnavailable);

                case 5:
                    //Developer Error
                    throw new InAppBillingPurchaseException(PurchaseError.DeveloperError);

                case 6:
                    //Generic Error
                    throw new InAppBillingPurchaseException(PurchaseError.GeneralError);

                case 7:
                    //already purchased
                    throw new InAppBillingPurchaseException(PurchaseError.AlreadyOwned);
                }


                var pendingIntent = buyIntentBundle.GetParcelable(RESPONSE_BUY_INTENT) as PendingIntent;
                if (pendingIntent == null)
                {
                    throw new InAppBillingPurchaseException(PurchaseError.GeneralError);
                }

                tcsPurchase = new TaskCompletionSource <PurchaseResponse>();

                Context.StartIntentSenderForResult(pendingIntent.IntentSender, PURCHASE_REQUEST_CODE, new Intent(), 0, 0, 0);
            }

            var result = await tcsPurchase.Task;

            if (result == null)
            {
                return(null);
            }

            var data = result.PurchaseData;
            var sign = result.DataSignature;

            //for some reason the data didn't come back
            if (string.IsNullOrWhiteSpace(data))
            {
                var purchases = await GetPurchasesAsync(itemType, verifyPurchase);

                return(purchases.FirstOrDefault(p => p.ProductId == productSku && payload.Equals(p.DeveloperPayload ?? string.Empty)));
            }

            var purchase = JsonConvert.DeserializeObject <Purchase>(data);

            if (verifyPurchase == null || await verifyPurchase.VerifyPurchase(data, sign, productSku, purchase.OrderId))
            {
                if (purchase.ProductId == productSku && payload.Equals(purchase.DeveloperPayload ?? string.Empty))
                {
                    return(purchase);
                }
            }

            return(null);
        }
Exemplo n.º 20
0
        public DealFilterObject(string base64String)
        {
            if (string.IsNullOrEmpty(base64String)) return;

            var json = Encoding.UTF8.GetString(Convert.FromBase64String(base64String));

            var jsonArray = json.Split(';');

            foreach (var filterItem in jsonArray)
            {
                var filterObj = JObject.Parse(filterItem);

                var paramString = filterObj.Value<string>("params");

                if (string.IsNullOrEmpty(paramString)) continue;

                var filterParam = Global.JObjectParseWithDateAsString(Encoding.UTF8.GetString(Convert.FromBase64String(paramString)));

                switch (filterObj.Value<string>("id"))
                {
                    case "sorter":
                        SortBy = filterParam.Value<string>("id");
                        SortOrder = filterParam.Value<string>("sortOrder");
                        break;

                    case "text":
                        FilterValue = filterParam.Value<string>("value");
                        break;

                    case "my":
                    case "responsibleID":
                        ResponsibleId = new Guid(filterParam.Value<string>("value"));
                        break;

                    case "stageTypeOpen":
                    case "stageTypeClosedAndWon":
                    case "stageTypeClosedAndLost":
                        StageType = filterParam.Value<string>("value");
                        break;

                    case "opportunityStagesID":
                        OpportunityStageId = filterParam.Value<int>("value");
                        break;

                    case "lastMonth":
                    case "yesterday":
                    case "today":
                    case "thisMonth":
                        var valueString = filterParam.Value<string>("value");
                        var fromToArray = JsonConvert.DeserializeObject<List<string>>(valueString);
                        if (fromToArray.Count != 2) continue;
                        FromDate = Global.ApiDateTimeParse(fromToArray[0]);
                        ToDate = Global.ApiDateTimeParse(fromToArray[1]);
                        break;

                    case "fromToDate":
                        FromDate = Global.ApiDateTimeParse(filterParam.Value<string>("from"));
                        ToDate = Global.ApiDateTimeParse(filterParam.Value<string>("to"));
                        break;

                    case "participantID":
                        ContactId = filterParam.Value<int>("id");
                        ContactAlsoIsParticipant = true;
                        break;

                    case "contactID":
                        ContactId = filterParam.Value<int>("id");
                        ContactAlsoIsParticipant = false;
                        break;

                    case "tags":
                        Tags = filterParam.Value<JArray>("value").ToList().ConvertAll(n => n.ToString());
                        break;
                }
            }

        }
Exemplo n.º 21
0
        public static ShipInfoData GetToutiaoShipInfoByName(string name)
        {
            List <ShipInfoData> shipInfo = JsonConvert.DeserializeObject <List <ShipInfoData> >(ShipInfoDataString);

            return(shipInfo.FirstOrDefault(t => t.Name == name));
        }
Exemplo n.º 22
0
        public ContactFilterObject(string base64String)
        {
            ContactStage = -1;
            ContactType = -1;
            
            if (string.IsNullOrEmpty(base64String)) return;

            var json = Encoding.UTF8.GetString(Convert.FromBase64String(base64String));

            var jsonArray = json.Split(';');

            foreach (var filterItem in jsonArray)
            {
                var filterObj = JObject.Parse(filterItem);

                var paramString = filterObj.Value<string>("params");

                if (string.IsNullOrEmpty(paramString)) continue;

                var filterParam = Global.JObjectParseWithDateAsString(Encoding.UTF8.GetString(Convert.FromBase64String(paramString)));

                switch (filterObj.Value<string>("id"))
                {
                    case "sorter":
                        SortBy = filterParam.Value<string>("id");
                        SortOrder = filterParam.Value<string>("sortOrder");
                        break;

                    case "text":
                        FilterValue = filterParam.Value<string>("value");
                        break;

                    case "my":
                    case "responsibleID":
                    case "noresponsible":
                        ResponsibleId = new Guid(filterParam.Value<string>("value"));
                        break;

                    case "tags":
                        Tags = filterParam.Value<JArray>("value").ToList().ConvertAll(n => n.ToString());
                        break;

                    case "withopportunity":
                    case "person":
                    case "company":
                        ContactListView = filterParam.Value<string>("value");
                        break;

                    case "contactType":
                        ContactType = filterParam.Value<int>("value");
                        break;

                    case "contactStage":
                        ContactStage = filterParam.Value<int>("value");
                        break;

                    case "lastMonth":
                    case "yesterday":
                    case "today":
                    case "thisMonth":
                        var valueString = filterParam.Value<string>("value");
                        var fromToArray = JsonConvert.DeserializeObject<List<string>>(valueString);
                        if (fromToArray.Count != 2) continue;
                        FromDate = Global.ApiDateTimeParse(fromToArray[0]);
                        ToDate = Global.ApiDateTimeParse(fromToArray[1]);
                        break;

                    case "fromToDate":
                        FromDate = Global.ApiDateTimeParse(filterParam.Value<string>("from"));
                        ToDate = Global.ApiDateTimeParse(filterParam.Value<string>("to"));
                        break;

                    case "restricted":
                    case "shared":
                        IsShared = filterParam.Value<bool>("value");
                        break;
                }
            }
        }
Exemplo n.º 23
0
 public virtual IDictionary<string, string> GetEnvVariables()
 {
     return JsonConvert.DeserializeObject<IDictionary<string,string>>(EnvVariables);
 }
Exemplo n.º 24
0
		protected void Page_Load(object sender, EventArgs e)
		{
			this.radMatch.Items[0].Text = "模糊匹配";
			this.radMatch.Items[1].Text = "精确匹配";
			this.radDisable.Items[0].Text = "启用";
			this.radDisable.Items[1].Text = "禁用";
			this.chkNo.Enabled = (ReplyHelper.GetMismatchReply() == null);
			this.chkSub.Enabled = (ReplyHelper.GetSubscribeReply() == null);
			if (!this.chkNo.Enabled)
			{
				this.chkNo.ToolTip = "该类型已被使用";
			}
			if (!this.chkSub.Enabled)
			{
				this.chkSub.ToolTip = "该类型已被使用";
			}
			if (!string.IsNullOrEmpty(base.Request.QueryString["cmd"]) && !string.IsNullOrEmpty(base.Request.Form["MultiArticle"]))
			{
				string value = base.Request.Form["MultiArticle"];
				List<ArticleList> list = JsonConvert.DeserializeObject(value, typeof(List<ArticleList>)) as List<ArticleList>;
				if (list != null && list.Count > 0)
				{
					NewsReplyInfo newsReplyInfo = new NewsReplyInfo();
					newsReplyInfo.MessageType = MessageType.List;
					newsReplyInfo.IsDisable = (base.Request.Form["radDisable"] != "true");
					if (base.Request.Form["chkKeys"] == "true")
					{
						newsReplyInfo.Keys = base.Request.Form.Get("Keys");
					}
					if (!string.IsNullOrWhiteSpace(newsReplyInfo.Keys) && ReplyHelper.HasReplyKey(newsReplyInfo.Keys))
					{
						base.Response.Write("key");
						base.Response.End();
					}
					newsReplyInfo.MatchType = ((base.Request.Form["radMatch"] == "true") ? MatchType.Like : MatchType.Equal);
					newsReplyInfo.ReplyType = ReplyType.None;
					if (base.Request.Form["chkKeys"] == "true")
					{
						newsReplyInfo.ReplyType |= ReplyType.Keys;
					}
					if (base.Request.Form["chkSub"] == "true")
					{
						newsReplyInfo.ReplyType |= ReplyType.Subscribe;
					}
					if (base.Request.Form["chkNo"] == "true")
					{
						newsReplyInfo.ReplyType |= ReplyType.NoMatch;
					}
					List<NewsMsgInfo> list2 = new List<NewsMsgInfo>();
					foreach (ArticleList item in list)
					{
						if (item.Status != "del")
						{
							NewsMsgInfo newsMsgInfo = item;
							if (newsMsgInfo != null)
							{
								newsMsgInfo.Reply = newsReplyInfo;
								list2.Add(newsMsgInfo);
							}
						}
					}
					newsReplyInfo.NewsMsg = list2;
					foreach (NewsMsgInfo item2 in newsReplyInfo.NewsMsg)
					{
						item2.PicUrl = Globals.SaveFile("article", item2.PicUrl, "/Storage/master/", true, false, "");
					}
					if (ReplyHelper.SaveReply(newsReplyInfo))
					{
						base.Response.Write("true");
						base.Response.End();
					}
				}
			}
		}
Exemplo n.º 25
0
        public static T DeserializeObject <T>(string input)
        {
            T returnValue = JsonConvert.DeserializeObject <T>(input);

            return(returnValue);
        }
Exemplo n.º 26
0
        public override async Task Read(Dictionary <string, string> properties)
        {
            var groupId = EndPointConfig.Properties["GroupId"];
            var servers = EndPointConfig.Properties["BootstrapServers"];
            var topic   = EndPointConfig.Properties["Topic"];
            var topics  = new List <string>()
            {
                topic
            };

            var config = new ConsumerConfig
            {
                BootstrapServers     = servers,
                GroupId              = groupId,
                EnableAutoCommit     = false,
                StatisticsIntervalMs = 5000,
                SessionTimeoutMs     = 6000,
                AutoOffsetReset      = AutoOffsetReset.Earliest,
                EnablePartitionEof   = true
            };

            const int commitPeriod = 5;

            // Note: If a key or value deserializer is not set (as is the case below), the
            // deserializer corresponding to the appropriate type from Confluent.Kafka.Deserializers
            // will be used automatically (where available). The default deserializer for string
            // is UTF8. The default deserializer for Ignore returns null for all input data
            // (including non-null data).
            using (var consumer = new ConsumerBuilder <Ignore, string>(config)
                                  // Note: All handlers are called on the main .Consume thread.
                                  .SetErrorHandler((_, e) => Console.WriteLine($"Error: {e.Reason}"))
                                  .SetStatisticsHandler((_, json) => Console.WriteLine($"Statistics: {json}"))
                                  .SetPartitionsAssignedHandler((c, partitions) =>
            {
                _logger.Info($"Assigned partitions: [{0}]", string.Join(", ", partitions));
                // possibly manually specify start offsets or override the partition assignment provided by
                // the consumer group by returning a list of topic/partition/offsets to assign to, e.g.:
                //
                // return partitions.Select(tp => new TopicPartitionOffset(tp, externalOffsets[tp]));
            })
                                  .SetPartitionsRevokedHandler((c, partitions) =>
            {
                _logger.Info($"Revoking assignment: [{0}]", string.Join(", ", partitions));
            })
                                  .Build())
            {
                consumer.Subscribe(topics);

                try
                {
                    while (!Token.IsCancellationRequested)
                    {
                        try
                        {
                            var consumeResult = consumer.Consume(Token);

                            if (consumeResult.IsPartitionEOF)
                            {
                                _logger.Info($"Reached end of topic {0}, partition {1}, offset {2}.",
                                             consumeResult.Topic, consumeResult.Partition, consumeResult.Offset);
                                continue;
                            }

                            _logger.Info($"Received message at {0}: {1}", consumeResult.TopicPartitionOffset, consumeResult.Value);

                            var nameValues       = (Dictionary <string, string>)JsonConvert.DeserializeObject(consumeResult.Value, typeof(Dictionary <string, string>));
                            var entityCollection = new EntityCollection();
                            foreach (var key in nameValues.Keys)
                            {
                                entityCollection.Entities.Add(key, nameValues[key]);
                            }
                            Data.Add(entityCollection);
                            await SignalHandler(new Dictionary <string, string>());

                            if (consumeResult.Offset % commitPeriod == 0)
                            {
                                // The Commit method sends a "commit offsets" request to the Kafka
                                // cluster and synchronously waits for the response. This is very
                                // slow compared to the rate at which the consumer is capable of
                                // consuming messages. A high performance application will typically
                                // commit offsets relatively infrequently and be designed handle
                                // duplicate messages in the event of failure.
                                try
                                {
                                    consumer.Commit(consumeResult);
                                }
                                catch (KafkaException e)
                                {
                                    _logger.Error($"Commit error: {0}", e.Error.Reason);
                                }
                            }
                        }
                        catch (ConsumeException e)
                        {
                            _logger.Error($"Consume error: {0}", e.Error.Reason);
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    _logger.Debug("Closing consumer.");
                    consumer.Close();
                }
            }
        }
Exemplo n.º 27
0
 /// <inheritdoc />
 public T Deserialize<T>(string value)
 {
     return JsonConvert.DeserializeObject<T>(value, _settings);
 }
 // Copy an object by value
 private static T CloneObject <T>(T source)
 {
     return(JsonConvert.DeserializeObject <T>(JsonConvert.SerializeObject(source)));
 }
 /// <summary>
 /// Deserializes the specified response.
 /// </summary>
 /// <typeparam name="T">The type being deserialized from the response</typeparam>
 /// <param name="response">The response.</param>
 /// <returns>The object returned in the response</returns>
 public T Deserialize <T>(IRestResponse response) =>
 JsonConvert.DeserializeObject <T>(response.Content, this.GetSettings());
Exemplo n.º 30
0
 public static IEnumerable<T> AsListModel<T>(this string input)
 {
     return JsonConvert.DeserializeObject<IEnumerable<T>>(input);
 }