public void ShouldReturnExpected_ForListOfListsOfTestStruct_WithToStringMethod()
        {
            // Arrange
            var array = new List <List <TestStruct> > {
                new List <TestStruct> {
                    new TestStruct {
                        Byte = 0
                    }
                }, new List <TestStruct> {
                    new TestStruct {
                        Byte = 1
                    }, new TestStruct {
                        Byte = 2
                    }
                }
            };

            // Act
            var actual1 = array.ToCsv();
            var actual2 = array.ToCsv("-");

            // Assert
            actual1.Should().Be("Byte: 0\nByte: 1,Byte: 2");
            actual2.Should().Be("Byte: 0\nByte: 1-Byte: 2");
        }
Example #2
0
        public void TestToCsv()
        {
            var l = new List <int> {
            };

            Assert.IsTrue(l.ToCsv() == string.Empty);

            l = null;
            Assert.IsTrue(l.ToCsv() == string.Empty);

            l = new List <int> {
                1, 2, 3
            };
            Assert.IsTrue(l.ToCsv() == "1,2,3");
        }
        /// <summary>
        /// Test program
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            var people = new List <Person>();

            people.Add(new Person()
            {
                FirstName = "Luke", LastName = "Skywalker", Age = 32
            });
            people.Add(new Person()
            {
                FirstName = "Han", LastName = "Solo"
            });
            people.Add(new Person()
            {
                FirstName = "Leia", LastName = "Organa", Age = 3
            });
            people.Add(new Person()
            {
                FirstName = "Wedge", LastName = "Antilles", Age = 2
            });

            var csv = people.ToCsv("")
                      .Column("First", f => f.FirstName)
                      .Column("Last", f => f.LastName)
                      .Column("Age", f => f.Age)
                      .ToString();

            Console.WriteLine(csv);
            Console.ReadLine();
        }
        public void Does_use_CsvConfig()
        {
            CsvConfig.ItemSeperatorString = "|";
            CsvConfig.ItemDelimiterString = "`";
            CsvConfig.RowSeparatorString  = "\n\n";

            var dtos = new[] {
                new ModelWithIdAndName {
                    Id = 1, Name = "Value"
                },
                new ModelWithIdAndName {
                    Id = 2, Name = "Value|Escaped"
                },
            };

            var csv = dtos.ToCsv();

            Assert.That(csv, Is.EqualTo("Id|Name\n\n1|Value\n\n2|`Value|Escaped`\n\n"));

            var maps = new List <Dictionary <string, object> >()
            {
                new Dictionary <string, object> {
                    { "Id", "1" }, { "Name", "Value" }
                },
                new Dictionary <string, object> {
                    { "Id", "2" }, { "Name", "Value|Escaped" }
                },
            };

            csv = maps.ToCsv();
            Assert.That(csv, Is.EqualTo("Id|Name\n\n1|Value\n\n2|`Value|Escaped`\n\n"));

            CsvConfig.Reset();
        }
        public void Can_serialize_Dynamic_Objects()
        {
            List <object> rows = Names.Map(Create);
            var           csv  = rows.ToCsv();

            Assert.That(csv, Is.EqualTo("id,name\r\n1,Foo\r\n2,Bar\r\n"));
        }
Example #6
0
        public static void ToCsv___Should_return_all_elements_separated_by_comma_with_a_well_known_token_used_for_null_elements___When_enumerable_has_null_elements_and_nullValueEncoding_is_a_well_known_token()
        {
            // Arrange
            const string nullValueEncoding = "<null>";

            var values1a = new List <string> {
                null
            };
            string expected1a = "<null>";
            var    values1b   = new List <string> {
                "first", "second", null
            };
            const string Expected1b = "first,second,<null>";

            var values2a = new List <string> {
                null, "second"
            };
            const string Expected2a = "<null>,second";
            var          values2b   = new List <string> {
                "first", null, "third"
            };
            const string Expected2b = "first,<null>,third";

            // Act
            var actual1a = values1a.ToCsv(nullValueEncoding: nullValueEncoding);
            var actual1b = values1b.ToCsv(nullValueEncoding: nullValueEncoding);
            var actual2a = values2a.ToCsv(nullValueEncoding: nullValueEncoding);
            var actual2b = values2b.ToCsv(nullValueEncoding: nullValueEncoding);

            // Assert
            Assert.Equal(expected1a, actual1a);
            Assert.Equal(Expected1b, actual1b);
            Assert.Equal(Expected2a, actual2a);
            Assert.Equal(Expected2b, actual2b);
        }
Example #7
0
        private static void DataTableExtensions()
        {
            var people = new List <Person>
            {
                new Person
                {
                    FamilyName = "Anderson",
                    GivenNames = "James",
                    Notes      = @"Some
notes
with new
lines"
                },
                new Person
                {
                    FamilyName = "Anderson",
                    GivenNames = "Jane",
                    Notes      = @"Some
notes
with new
lines 2"
                }
            };

            var table = people.ToDataTable();

            string csv = table.ToCsv();

            string csv2 = people.ToCsv();

            Console.WriteLine("CSV: " + csv);
        }
Example #8
0
        public static void ToCsv___Should_make_all_non_CSV_safe_elements_safe_before_adding_to_string___When_enumerable_has_elements_that_are_not_CSV_safe()
        {
            // Arrange
            var values1 = new List <string> {
                "first", null, "se\"c\"ond"
            };
            const string Expected1 = "first,,\"se\"\"c\"\"ond\"";

            var values2 = new List <string> {
                "  first  ", "sec,ond"
            };
            const string Expected2 = "\"  first  \",\"sec,ond\"";

            var values3 = new List <string> {
                "first", null, "se\"c\"ond"
            };
            const string Expected3 = "first,<null>,\"se\"\"c\"\"ond\"";

            // Act
            var actual1 = values1.ToCsv();
            var actual2 = values2.ToCsv();
            var actual3 = values3.ToCsv(nullValueEncoding: "<null>");

            // Assert
            Assert.Equal(Expected1, actual1);
            Assert.Equal(Expected2, actual2);
            Assert.Equal(Expected3, actual3);
        }
Example #9
0
        public async Task WriteCsvAdvanced()
        {
            var data = new List <TestClass>
            {
                new TestClass
                {
                    TestBool   = true,
                    TestString = "test1",
                    TestDate   = new DateTime(1987, 11, 2, 4, 20, 0),
                    TestInt    = 1
                },
                new TestClass
                {
                    TestBool   = false,
                    TestString = "test2",
                    TestDate   = new DateTime(1981, 11, 18, 4, 20, 0),
                    TestInt    = 2
                }
            };
            var config = CsvConfig.Empty
                         .UseHeader(false)
                         .UseQuoteQualification(false)
                         .UseSeperator("|")
                         .IgnoreProperty("TestBool")
                         .UseFilter <DateTime>("MM/dd/yyyy")
                         .UseFilter <int>("P");
            var result = await data.ToCsv(config);

            var truth = new StringBuilder(2);

            truth.AppendLine("test1|11/02/1987|100.00%");
            truth.AppendLine("test2|11/18/1981|200.00%");
            Assert.AreEqual(truth.ToString(), Encoding.ASCII.GetString(result));
        }
        public ActionResult DownloadVendor(Guid?id)
        {
            List <DynamicCodingLookupVm> links = Db.DynamicCodingLookups
                                                 .Where(x => x.CampaignId == id).ToList()
                                                 .Select(x => DynamicCodingLookupVm.FromLookup(x))
                                                 .ToList();

            if (links.Count == 0)
            {
                return(null);
            }

            string linksDataFileName = $"{links.FirstOrDefault().OrderNumber}links.csv";

            var filePath = $"{DownloadPath}\\{linksDataFileName}";

            links.ToCsv(filePath, new CsvDefinition()
            {
                EndOfLine      = "\r\n",
                FieldSeparator = ',',
                TextQualifier  = '"',
                Columns        =
                    new List <string>
                {
                    "URL",
                    "Quantity",
                }
            });
            return(File(filePath, "text/csv", linksDataFileName));
        }
        /// <summary>
        ///
        /// </summary>
        public static void RegisterAllModules(this ContainerBuilder containerBuilder, params string[] searchPatterns)
        {
            ReflectionService reflectionService = new ReflectionService();

            Log.Trace("Searching for and registering all Autofac Modules");
            List <Assembly> assemblies = reflectionService.GetLocalAssemblies(searchPatterns);

            Log.Trace(m => m(
                          "Found {0} assemblies: {1}"
                          , assemblies.Count
                          , assemblies.ToCsv(", ", a => a.GetName().Name)));

            List <Type> allTypesFromAllAssemblies = reflectionService.GetAllTypes(assemblies);

            List <Type> candidateAutofacAssemblyTypes = (
                from t in allTypesFromAllAssemblies
                .Where(type => typeof(Autofac.Module).IsAssignableFrom(type))
                .Where(type => type.GetConstructor(Type.EmptyTypes) != null)
                select t
                ).ToList();

            Log.Trace(m => m("Found {0} candidate AutofacModule types: {1}", candidateAutofacAssemblyTypes.Count, candidateAutofacAssemblyTypes.ToCsv(", ", t => t.FullName)));

            candidateAutofacAssemblyTypes
            .Select(Activator.CreateInstance)
            .Cast <IModule>()
            .ToList()
            .ForEach(module =>
            {
                Log.Trace(m => m("Registering Autofac Module: '{0}'", module.GetType().FullName));
                containerBuilder.RegisterModule(module);
            });
        }
    internal static void Go()
    {
      var filePath = @"e:\bondsToAddIfNotThere.csv";

      var fieldList = new[] {"ID_ISIN", "TICKER"};
      var results = new List<ResultClass>();

      var strB = new StringBuilder();

      foreach (var line in CsvFile.Read<IdClass>(filePath))
      {
        var refData = BbgTalk.HistoryRequester.GetReferenceData(line.Id, fieldList, null);

        results.Add(new ResultClass()
        {
          ISIN=refData.GetValue<string>("ID_ISIN"),
          Market=refData.GetValue<string>("TICKER"),
        });

        strB.Append(refData.GetValue<string>("ID_ISIN")).Append(" ");
      }

      Logger.Debug(strB.ToString(), typeof (AddBondsFromBbgList));

      results.ToCsv(@"e:\bondsToAddIsins.csv");
    }
Example #13
0
        public ErrorLog(Exception ex)
        {
            if (HttpContext.Current != null)
            {
                HttpRequest = HttpContext.Current?.Request?.ToRaw();
                List <string> parametersWithValues = HttpContext.Current?.Request.Params.AllKeys.Select(param => $"{param} => {HttpContext.Current.Request.Params[param]}").ToList();
                ParametersCsv = parametersWithValues.ToCsv();
            }
            Date = DateTime.Now;
            if (Thread.CurrentPrincipal.Identity.IsAuthenticated)
            {
                string userId = Thread.CurrentPrincipal.Identity.GetUserId();
                UserId = userId;
            }

            ErrorMessage = ex.Message;
            var st = new StackTrace(ex, true);
            // Get the top stack frame
            var frame = st.GetFrame(0);

            // Get the line number from the stack frame
            var line       = frame.GetFileLineNumber();
            var methodName = frame.GetMethod().DeclaringType?.FullName + " =>" + frame.GetMethod().Name;

            this.Line       = line;
            this.MethodName = methodName;
            StackTrace      = ex.StackTrace;
            if (ex.InnerException != null)
            {
                InnerExceptionErrorMessage = ex.InnerException?.Message;
                InnerExceptionErrorMessage = ex.InnerException?.StackTrace;
            }
        }
Example #14
0
        public static void ToCsv___Should_return_all_elements_separated_by_comma_with_null_elements_treated_as_empty_string___When_enumerable_has_null_elements_and_nullValueEncoding_is_the_empty_string()
        {
            // Arrange
            var values1a = new List <string> {
                null
            };
            string expected1a = string.Empty;
            var    values1b   = new List <string> {
                "first", "second", null
            };
            const string Expected1b = "first,second,";

            var values2a = new List <string> {
                null, "second"
            };
            const string Expected2a = ",second";
            var          values2b   = new List <string> {
                "first", null, "third"
            };
            const string Expected2b = "first,,third";

            // Act
            var actual1a = values1a.ToCsv();
            var actual1b = values1b.ToCsv();
            var actual2a = values2a.ToCsv();
            var actual2b = values2b.ToCsv();

            // Assert
            Assert.Equal(expected1a, actual1a);
            Assert.Equal(Expected1b, actual1b);
            Assert.Equal(Expected2a, actual2a);
            Assert.Equal(Expected2b, actual2b);
        }
        public ActionResult DownloadProgress(Guid?id)
        {
            List <DynamicCodingLinkVm> links = Db.DynamicCodingLinks
                                               .Where(x => x.CampaignId == id).ToList()
                                               .Select(x => DynamicCodingLinkVm.FromLink(x))
                                               .ToList();

            if (links.Count == 0)
            {
                return(null);
            }

            string linksDataFileName = $"{links.FirstOrDefault().OrderNumber}links_progress.csv";

            var filePath = $"{DownloadPath}\\{linksDataFileName}";

            links.ToCsv(filePath, new CsvDefinition()
            {
                EndOfLine      = "\r\n",
                FieldSeparator = ',',
                TextQualifier  = '"',
                Columns        =
                    new List <string>
                {
                    "SalesMasterId",
                    "URLType",
                    "VerumURL",
                    "PartnerURL",
                    "IfURLRedemed"
                }
            });
            return(File(filePath, "text/csv", linksDataFileName));
        }
Example #16
0
        public void TestToCsvFromNull()
        {
            List <int> list = null;

            var csv = list.ToCsv();

            Assert.IsEmpty(csv);
        }
Example #17
0
        public string SerializeEmployeeListToCSV(List <Employee> ListToSerialize)
        {
            if (ListToSerialize.Count == 0)
            {
                return("");
            }

            return(ListToSerialize.ToCsv());
        }
        private string MakeStringFromPropertyValue(object propertyValue, Type serializerType, Type elementSerializerType)
        {
            new { propertyValue }.Must().NotBeNull();

            var propertyType = propertyValue.GetType();

            if (this.configuredTypeToSerializerMap.ContainsKey(propertyType))
            {
                var serializer = this.configuredTypeToSerializerMap[propertyType];
                var ret        = serializer.SerializeToString(propertyValue);
                return(ret);
            }
            else if (serializerType != null)
            {
                if (!this.cachedAttributeSerializerTypeToObjectMap.ContainsKey(serializerType))
                {
                    var newAttributeOnClassSerializer = serializerType.Construct <IStringSerializeAndDeserialize>();
                    this.cachedAttributeSerializerTypeToObjectMap.Add(serializerType, newAttributeOnClassSerializer);
                }

                var attributeOnClassSerializer = this.cachedAttributeSerializerTypeToObjectMap[serializerType];
                var ret = attributeOnClassSerializer.SerializeToString(propertyValue);
                return(ret);
            }
            else if (propertyValue is DateTime)
            {
                return(NaosDateTimeStringSerializer.SerializeDateTimeToString((DateTime)propertyValue));
            }
            else
            {
                if (propertyType != typeof(string) && propertyValue is IEnumerable propertyValueAsEnumerable)
                {
                    var values = new List <string>();
                    foreach (var item in propertyValueAsEnumerable)
                    {
                        var serializedItem = item == null
                                                 ? null
                                                 : this.MakeStringFromPropertyValue(
                            item,
                            elementSerializerType ?? item?.GetType().GetSerializerTypeFromAttribute(),
                            null);
                        values.Add(serializedItem);
                    }

                    return(values.ToCsv(this.dictionaryStringSerializer.NullValueEncoding));
                }
                else if (propertyValue is ISerializeToString propertyValueAsSerializeToString)
                {
                    return(propertyValueAsSerializeToString.SerializeToString());
                }
                else
                {
                    return(propertyValue.ToString());
                }
            }
        }
Example #19
0
        public void TestToCsvFromListOfIntsWithCustomSeparators()
        {
            var list = new List <int> {
                1, 2, 3
            };

            var csv = list.ToCsv(", ", " and ");

            Assert.AreEqual("1, 2 and 3", csv);
        }
Example #20
0
        public void TestToCsvFromListWithOneEntry()
        {
            var list = new List <int> {
                1
            };

            var csv = list.ToCsv();

            Assert.AreEqual("1", csv);
        }
Example #21
0
        public void TestToCsvFromListOfStringsWithCustomSeparators()
        {
            var list = new List <string> {
                "One", "Two", "Three"
            };

            var csv = list.ToCsv(", ", " and ");

            Assert.AreEqual("One, Two and Three", csv);
        }
Example #22
0
        public void TestToCsvFromListOfInts()
        {
            var list = new List <int> {
                1, 2, 3
            };

            var csv = list.ToCsv();

            Assert.AreEqual("1,2,3", csv);
        }
        public void ShouldReturnExpected_ForListOfListsOfInteger()
        {
            // Arrange
            var list = new List <List <int> > {
                new List <int> {
                    1, 2, 3
                }, new List <int> {
                    4, 5, 6
                }
            };

            // Act
            var actual1 = list.ToCsv();
            var actual2 = list.ToCsv("-");

            // Assert
            actual1.Should().Be("1,2,3\n4,5,6");
            actual2.Should().Be("1-2-3\n4-5-6");
        }
Example #24
0
        /// <summary>
        /// Simple dump of an object, designed to make a ToString easy to implement
        /// </summary>
        /// <remarks>
        /// Not useful for the real intention of ObjectDumper which is a clean tabular representation
        /// </remarks>
        public override string ToString()
        {
            List <string> nameValuePairs = new List <string>();

            for (int i = 0; i < Data.Count; i++)
            {
                nameValuePairs.Add(string.Format("{0}={1}", Headers[i], Data[i]));
            }
            return(nameValuePairs.ToCsv(", "));
        }
        public void ShouldReturnExpected_ForListOfListsOfBoolean()
        {
            // Arrange
            var list = new List <List <bool> > {
                new List <bool> {
                    true, true
                }, new List <bool> {
                    true, false
                }
            };

            // Act
            var actual1 = list.ToCsv();
            var actual2 = list.ToCsv("-");

            // Assert
            actual1.Should().Be("True,True\nTrue,False");
            actual2.Should().Be("True-True\nTrue-False");
        }
Example #26
0
        public static void ToCsv___Should_return_null___When_enumerable_is_empty()
        {
            // Arrange
            var values = new List <string>();

            // Act
            var actual = values.ToCsv();

            // Assert
            Assert.Null(actual);
        }
Example #27
0
    public static void Go2()
    {
      var yearOfFile = 2015;

      var ricList = new[] { "ED", "FEI", "FGBL", "FGBM", "FGBS", "FGBS", "TY", "FLG", "FSS", "FGB", "FBTP", "FOAT" };

      var contractMonths = new[] { MonthCode.H, MonthCode.M, MonthCode.N, MonthCode.Q, MonthCode.U, MonthCode.V, MonthCode.X, MonthCode.Z };
      contractMonths = (MonthCode[])Enum.GetValues(typeof(MonthCode));

      var processedDir = @"E:\futuresData\Processed";
      var markDir = @"e:\futuresData\MarkEllis2";

      foreach (var ricStart in ricList)
      {
        foreach (var contractYear in new[] { 2015, 2016, 2017 })
        {
          foreach (var monthOfFile in new[] { 6, 7 })
          {
            foreach (var contractMonth in contractMonths)
            {
              var searchString = string.Format("*{0}-{1}-{2}{3}{4}.csv", yearOfFile, monthOfFile.ToString("00"), ricStart, contractMonth, contractYear - 2010);

              var files = Directory.GetFiles(processedDir, searchString);

              if (files.Length == 0)
                continue;

              var list = new List<FuturesIntradaySaver.FuturesLineItem>();
              foreach (var item in CsvFile.Read<FuturesIntradaySaver.FuturesLineItem>(files[0]))
              {
                if (item.gmtDate.HasValue && (item.gmtDate.Value.Minute == 32 || item.gmtDate.Value.Minute == 2))
                {
                  item.Date = TimeZoneHelper.ConvertGmtTimeToLondon(item.gmtDate.Value);
                  item.Time = string.Empty;

                  if (item.Date.Hour < 8)
                    continue;

                  if (item.Date.Hour > 17)
                    continue;

                  list.Add(item);
                }
              }

              list.ToCsv(string.Join("\\", markDir,
                string.Format("{0}-{1}-{2}{3}{4}", yearOfFile, monthOfFile.ToString("00"), UpdateStaticDataForFutures.MAPS[ricStart].Item1, contractMonth, contractYear - 2010)));

            }
          }
        }
      }

    }
Example #28
0
 static void SaveList(List <Archive> archives, FileType extension)
 {
     if (extension == FileType.CSV)
     {
         Console.WriteLine(archives.ToCsv());
     }
     else if (extension == FileType.JSON)
     {
         Console.WriteLine(archives.ToJson());
     }
 }
Example #29
0
 static void SaveLog(List <Log> logs, FileType extension)
 {
     if (extension == FileType.JSON)
     {
         Console.WriteLine(logs.ToJson());
     }
     if (extension == FileType.CSV)
     {
         Console.WriteLine(logs.ToCsv());
     }
 }
Example #30
0
        public void ShouldSerializeAListOfThings_When()
        {
            var thingList = new List <Thing> {
                new Thing("beans", 4),
                new Thing("eggs", 1),
                new Thing("cheese", 2)
            };

            var result = thingList.ToCsv();

            Assert.Equal(result, "beans[4],eggs[1],cheese[2]");
        }
        public static void WriteCsv <T>(List <T> Obj, string filename) where T : class
        {
            var Response = HttpContext.Current.Response;

            Response.Clear();
            Response.ContentType = "text/csv";
            Response.AddHeader("Content-Disposition", $"attachment; filename={filename}.csv");

            var csv = Obj.ToCsv();

            WriteRaw(csv, Response);
        }
        private string MakeStringFromObject(
            object value)
        {
            if (value == null)
            {
                return(null);
            }

            var propertyType = value.GetType();

            if (this.configuredTypeToSerializerMap.ContainsKey(propertyType))
            {
                var serializer = this.configuredTypeToSerializerMap[propertyType];

                var result = serializer.SerializeToString(value);

                return(result);
            }
            else if (value is DateTime propertyValueAsDateTime)
            {
                var result = ObcDateTimeStringSerializer.SerializeToString(propertyValueAsDateTime);

                return(result);
            }
            else
            {
                string result;

                if ((propertyType != typeof(string)) && (value is IEnumerable propertyValueAsEnumerable))
                {
                    var values = new List <string>();

                    foreach (var element in propertyValueAsEnumerable)
                    {
                        var serializedItem = this.MakeStringFromObject(element);

                        values.Add(serializedItem);
                    }

                    result = values.ToCsv(this.dictionaryStringSerializer.NullValueEncoding);
                }
                else if (value is ISerializeToString propertyValueAsSerializeToString)
                {
                    result = propertyValueAsSerializeToString.SerializeToString();
                }
                else
                {
                    result = value.ToString();
                }

                return(result);
            }
        }
        public void DeleteExcept(List<int> helpIds)
        {
            if (null == helpIds || helpIds.Count == 0)
                return;

            using (var connection = SqlConnectionFactory.GetConnection())
            using (var command = connection.CreateCommand())
            {
                command.CommandType = CommandType.Text;
                command.CommandText = SqlScripts.FirstTimeHelp_DeleteExcept.Replace("@pageIds", helpIds.ToCsv());

                connection.Open();
                command.ExecuteNonQuery();
            }
        }
Example #34
0
        private static void RunSimulations(ProgramOptions options)
        {
            TimeSpan ts = new TimeSpan(365 * options.Years, 0, 0, 0);
            ts = new TimeSpan(ts.Ticks / options.Steps); // note that ts.TotalDays / 365.0 <=> t / n

            Random rnd = new Random(options.Seed);

            List<StockEstimate> paths = new List<StockEstimate>();
            for (int i = 0; i < options.Count; ++i)
            {
                PathSimulate(options, ts, rnd, paths);
            }

            File.WriteAllText("output.txt", paths.ToCsv());

            PrintEndInfo(options, paths);
        }
Example #35
0
        private void Export()
        {
            if (_salesPendingExport.Any())
            { 
                var orders = _salesPendingExport.Select(OrderExportHelper.MapSalesExport).ToList();
                var orderToCsv = new List<ExportSaleItem>();
                foreach (var order in orders)
                {
                    orderToCsv.AddRange(order);
                }
                var outputFileDescription = new CsvFileDescription
                {
                    // cool - I can specify my own separator!
                    SeparatorChar = ',',
                    FirstLineHasColumnNames =
                        false,
                    QuoteAllFields = true,
                    EnforceCsvColumnAttribute =
                        true
                };
                try
                {
                    Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + " Attempting to export {0} sales", orders.Count);
                    //var cc = new CsvContext();
                    //cc.Write(orderToCsv, OrderExportHelper.GetExportFileName("AllSales"), outputFileDescription);

                    DumpExportFilesAsync(orderToCsv.ToCsv(),OrderExportHelper.GetExportFileName("AllSales"));

                    _salesPendingExport.OrderBy(p => p.GenericOrderReference).Distinct().ToList().ForEach(
                        OrderExportHelper.MarkAsExported);
                   Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format(" Export compeleted for={0} sales", orders.Count));
                   _salesPendingExport.Clear();
                }
                catch (Exception ex)
                {
                    Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + "Error occured while exporting..See error logs for details");
                    FileUtility.LogError(ex.Message);
                }

            }
            else
            {
                Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + " No  sales exported");
            }
        }
Example #36
0
        static void Main(string[] args)
        {
            //ConsoleClient d = new ConsoleClient();
            //d.Start();

            Client client = new Client();
            // /Search/Motors/Used.xml?Make=Honda&Model=Jazz
            // /Search/Motors/Used.xml?make=Honda&model=Jazz
            var tmp = client.SearchUsedMotors("/Search/Motors/Used.xml?Make=Honda&Model=Jazz");
            var totalCount = tmp.TotalCount;
            var cars = new List<Car>();
            int page = 1;
            while (cars.Count < totalCount)
            {
                string query = string.Format("/Search/Motors/Used.xml?Make=Honda&Model=Jazz&page={0}", page);
                cars.AddRange(client.SearchUsedMotors(query).List);
                page++;
            }

            //car.ListingId	703207653	int
            //car.Year	2006	int
            //car.Odometer
            //car.Model	"Fit / Jazz LOW KM"	string
            //car.EngineSize	1300	int
            //car.PriceDisplay
            //car.Transmission	"Automatic"	string
            //car.StereoDescription	"CD(s), Stereo"	string
            //car.Doors	5	int
            //car.BodyStyle	"Hatchback"	string
            //car.IsDealer	true	bool
            //car.Region	"Auckland"	string
            //car.BuyNowPrice	0	decimal
            //car.BuyNowPriceSpecified
            //car.IsReserveMet	true	bool
            //car.IsNew	false	bool
            //car.BidCount	32	int
            cars.ToCsv("data.csv");
        }
Example #37
0
 public bool RecoverManySuspendedTickets(List<long> ids)
 {
     var resource = string.Format("suspended_tickets/recover_many.json?ids={0}", ids.ToCsv());
     var res = RunRequest(resource, "PUT");            
     return res.HttpStatusCode == HttpStatusCode.OK;            
 }
Example #38
0
 public bool DeleteMultiple(List<long> ids)
 {
     return GenericDelete(string.Format("{0}/destroy_many.json?ids={1}", _tickets, ids.ToCsv()));
 }
Example #39
0
 public async Task<GroupTopicResponse> GetMultipleTopicsByIdAsync(List<long> topicIds)
 {
     return await GenericPostAsync<GroupTopicResponse>(string.Format("topics/show_many?ids={0}.json", topicIds.ToCsv()));
 }
Example #40
0
 public virtual void WriteLogs(List<RequestLogEntry> logs, string logFile)
 {
     try
     {
         var csv = logs.ToCsv();
         if (!files.FileExists(logFile))
         {
             files.WriteFile(logFile, csv);
         }
         else
         {
             var csvRows = csv.Substring(csv.IndexOf('\n') + 1);
             files.AppendFile(logFile, csvRows);
         }
     }
     catch (Exception ex)
     {
         log.Error(ex);
     }
 }
 private TransactionResponse MapTransactionResponse(List<ShellOrderExportDto> orders)
 {
     
     var response = new TransactionResponse();
     if(orders==null ||!orders.Any())
     {
         response.ErrorInfo = "Success";
         response.Result = "Order not found";
         response.ResultInfo = "No transaction to export";
         return response;
     }
     response.TransactionData = orders.ToCsv();
     return response;
 }
    public static void Go(bool makeChanges_=false)
    {
      string path = @"e:\TreasuryOTRHistory.csv";
      var missingBonds = new List<MissingBond>();

      using (var dc = SymmetryDataSource.ReadWrite())
      {
        var earliestMaturity = new DateTime(2008, 1, 1);

        foreach (var l in CsvFile.Read<Line>(path).Where(x=>x.MaturityAsDate>=earliestMaturity))
        {
          var cusipIdentifier =
            dc.FIIdentifiers.FirstOrDefault(
              x => String.Compare(l.CUSIP, x.Identifier, StringComparison.OrdinalIgnoreCase) == 0);

          if (cusipIdentifier == null)
          {
            // can we find by assuming that the cusip is contained with the ISIN...

            var fi = dc.FIs.FirstOrDefault(x => x.InstrumentType == Symmetry.Data.Enums.InstrumentType.Bond
                                                && x.SymmetryCode.Contains(l.CUSIP));

            if (fi == null)
            {
              Logger.Error(string.Format("Couldn't find a bond for cusip={0}, Term={1}", l.CUSIP,l.Term),
                typeof(ProcessUSTreasuryAuctionsFile));
              missingBonds.Add(new MissingBond {CUSIP = l.CUSIP, Maturity=l.MaturityString});
              continue;
            }

            if (!makeChanges_) continue;

            // we need to create a cusip identifier too
            cusipIdentifier = new FIIdentifier()
            {
              FIID = fi.FIID,
              FI = fi,
              Identifier = l.CUSIP,
              IdentifierType = Symmetry.Data.Enums.IdentifierType.CUSIP
            };

            Logger.Info(string.Format("Adding in cusip identifer for bond={0} (cusip={1})", fi.SymmetryCode, l.CUSIP),
              typeof (ProcessUSTreasuryAuctionsFile));

            dc.FIIdentifiers.Add(cusipIdentifier);

          }

          if (!makeChanges_)
            continue;

          bool found = false;

          foreach (var auction in dc.FIBondAuctions.Where(x => x.FIID == cusipIdentifier.FIID))
          {
            if (auction.AuctionDate == l.AuctionDateAsDate)
            {
              Logger.Info(string.Format("Auction already set up for {0} on {1}", l.CUSIP, l.AuctionDateAsDate),
                typeof (ProcessUSTreasuryAuctionsFile));

              if (!auction.EffectiveDate.HasValue)
              {
                Logger.Info(string.Format("Updating effectivedate"), typeof (ProcessUSTreasuryAuctionsFile));
                auction.EffectiveDate = l.IssueDateAsDate;
                FIChangeTracking.SetModified(auction, dc);
              }
              found = true;
              break;
            }
          }

          if (found) 
            continue;

          Logger.Info(string.Format("Setting up auction for {0} on {1}", l.CUSIP, l.AuctionDateAsDate),
            typeof (ProcessUSTreasuryAuctionsFile));

          var newauction = new FIBondAuction()
          {
            FIID = cusipIdentifier.FIID,
            FIBond = dc.FIBonds.FirstOrDefault(x => x.FIID == cusipIdentifier.FIID),
            AuctionDate = l.AuctionDateAsDate,
            EffectiveDate=l.IssueDateAsDate,
            Term = Convert.ToInt32(Math.Round((l.MaturityAsDate - l.AuctionDateAsDate).TotalDays/365.2, 0))
          };

          dc.FIBondAuctions.Add(newauction);
        }

        if(makeChanges_) dc.SaveChanges();

       
      }

      if (missingBonds.Count > 0)
        missingBonds.ToCsv(@"e:\missingUSBonds.csv");
    }
Example #43
0
 public GroupViewCountResponse GetViewCounts(List<long> viewIds)
 {
     return GenericGet<GroupViewCountResponse>(string.Format("views/count_many.json?ids={0}", viewIds.ToCsv()));
 }
		public void RunQuery()
		{
			ValidateQuery();

			var leanKitAuth = new LeanKitBasicAuth
			{
				Hostname = _args.Host,
				Username = _args.User,
				Password = _args.Password
			};

			// For internal development testing
			if (_args.Host.Equals("kanban-cibuild", StringComparison.InvariantCultureIgnoreCase)) 
				leanKitAuth.UrlTemplateOverride = "http://{0}.localkanban.com";

			WriteInfo("Connecting to LeanKit account...");
			var api = new LeanKitClientFactory().Create(leanKitAuth);

			if (_args.Boards)
			{
				WriteInfo("Getting all boards...");
				var boards = api.GetBoards();
				var boardList = boards.Select(Mapper.Map<BoardLiteView>);
				var output = _args.Csv ? boardList.ToCsv() : _args.Json ? boardList.ToJson() : boardList.Dump();
				Console.WriteLine(output);
			}
			else if (_args.Board > 0)
			{
				WriteInfo(string.Format("Getting board [{0}]...", _args.Board));
				var board = api.GetBoard(_args.Board);
				if (_args.Lanes || _args.Lane > 0 || _args.Cards)
				{
					// Get lanes
					var boardLanes = new List<Lane>();
					if (_args.Lane > 0)
					{
						WriteInfo(string.Format("Getting lane [{0}]...", _args.Lane));
						boardLanes.AddRange(board.AllLanes().Where(lane => lane.Id == _args.Lane));
					}
					else
					{
						if (_args.IncludeBacklog) boardLanes.AddRange(board.Backlog);
						boardLanes.AddRange(board.Lanes);
						if (_args.IncludeArchive) boardLanes.AddRange(board.Archive);
					}

					if (_args.Cards)
					{
						WriteInfo("Getting cards...");
						var cards = new List<MappedCardView>();
						foreach (var lane in boardLanes)
						{
							cards.AddRange(lane.Cards.Select(Mapper.Map<MappedCardView>));
						}
						// Archived cards is a separate API call
						if (_args.IncludeArchive)
						{
							var archivedCards = api.GetArchiveCards(_args.Board);
							cards.AddRange(archivedCards.Select(Mapper.Map<MappedCardView>));
						}
						var output = _args.Csv ? cards.ToCsv() : _args.Json ? cards.ToJson() : cards.Dump();
						Console.WriteLine(output);
					}
					else
					{
						var lanes = boardLanes.Select(Mapper.Map<LaneView>);
						var output = _args.Csv ? lanes.ToCsv() : _args.Json ? lanes.ToJson() : lanes.Dump();
						Console.WriteLine(output);
					}
				}
				else
				{
					var boardView = Mapper.Map<BoardView>(board);
					var output = _args.Csv ? boardView.ToCsv() : _args.Json ? boardView.ToJson() : boardView.Dump();
					Console.WriteLine(output);
				}
			}
		}
Example #45
0
 public GroupTicketResponse GetMultipleTickets(List<long> ids)
 {                        
     return GenericGet<GroupTicketResponse>(string.Format("{0}/show_many?ids={1}.json", _tickets, ids.ToCsv()));
 }
Example #46
0
 public async Task<bool> RecoverManySuspendedTicketsAsync(List<long> ids)
 {
     var resource = string.Format("suspended_tickets/recover_many.json?ids={0}", ids.ToCsv());
     var res = RunRequestAsync(resource, "PUT");
     return await res.ContinueWith(x => x.Result.HttpStatusCode == HttpStatusCode.OK);            
 }
Example #47
0
 public async Task<JobStatusResponse> BulkUpdateAsync(List<long> ids, BulkUpdate info)
 {
     var body = new { ticket = info };
     return await GenericPutAsync<JobStatusResponse>(string.Format("{0}/update_many.json?ids={1}", _tickets, ids.ToCsv()), body);            
 }
Example #48
0
 public bool DeleteManySuspendedTickets(List<long> ids)
 {
     return GenericDelete(string.Format("suspended_tickets/destroy_many.json?ids={0}", ids.ToCsv()));
 }
    private static void goTwo()
    {
      var list = new List<SetupItem>();
      list.Add(new SetupItem { BbgTicker = "IKH13 Comdty", StartDate = new DateTime(2013, 01, 25), EndDate = new DateTime(2013, 02, 13), StartHour = 7, EndHour = 18 });
      list.Add(new SetupItem { BbgTicker = "IKH13 Comdty", StartDate = new DateTime(2013, 01, 22), EndDate = new DateTime(2013, 03, 01), StartHour = 7, EndHour = 18 });

      list.Add(new SetupItem { BbgTicker = "IKM13 Comdty", StartDate = new DateTime(2013, 03, 22), EndDate = new DateTime(2013, 04, 02), StartHour = 7, EndHour = 18 });
      list.Add(new SetupItem { BbgTicker = "IKM13 Comdty", StartDate = new DateTime(2013, 04, 23), EndDate = new DateTime(2013, 05, 02), StartHour = 7, EndHour = 18 });
      list.Add(new SetupItem { BbgTicker = "IKM13 Comdty", StartDate = new DateTime(2013, 05, 27), EndDate = new DateTime(2013, 06, 03), StartHour = 7, EndHour = 18 });

      list.Add(new SetupItem { BbgTicker = "IKU13 Comdty", StartDate = new DateTime(2013, 06, 24), EndDate = new DateTime(2013, 07, 01), StartHour = 7, EndHour = 18 });
      list.Add(new SetupItem { BbgTicker = "IKU13 Comdty", StartDate = new DateTime(2013, 07, 25), EndDate = new DateTime(2013, 08, 01), StartHour = 7, EndHour = 18 });
      list.Add(new SetupItem { BbgTicker = "IKU13 Comdty", StartDate = new DateTime(2013, 08, 26), EndDate = new DateTime(2013, 09, 02), StartHour = 7, EndHour = 18 });

      list.Add(new SetupItem { BbgTicker = "IKZ3 Comdty", StartDate = new DateTime(2013, 09, 24), EndDate = new DateTime(2013, 10, 01), StartHour = 7, EndHour = 18 });
      list.Add(new SetupItem { BbgTicker = "IKZ3 Comdty", StartDate = new DateTime(2013, 10, 25), EndDate = new DateTime(2013, 11, 01), StartHour = 7, EndHour = 18 });
      list.Add(new SetupItem { BbgTicker = "IKZ3 Comdty", StartDate = new DateTime(2013, 11, 23), EndDate = new DateTime(2013, 12, 02), StartHour = 7, EndHour = 18 });

      list.Add(new SetupItem { BbgTicker = "IKH4 Comdty", StartDate = new DateTime(2013, 12, 24), EndDate = new DateTime(2014, 01, 02), StartHour = 7, EndHour = 18 });
      list.Add(new SetupItem { BbgTicker = "IKH4 Comdty", StartDate = new DateTime(2014, 01, 25), EndDate = new DateTime(2014, 02, 03), StartHour = 7, EndHour = 18 });
      list.Add(new SetupItem { BbgTicker = "IKH4 Comdty", StartDate = new DateTime(2014, 02, 23), EndDate = new DateTime(2014, 03, 03), StartHour = 7, EndHour = 18 });


      var outputList = new List<OutputItem>();

      foreach (var setup in list)
      {
        var contract = Singleton<IntradayFuturesContracts>.Instance.Where(x => x.BbgTicker.Equals(setup.BbgTicker)).FirstOrDefault();

        if (contract == null) System.Diagnostics.Debugger.Break();

        var currentDate = setup.StartDate;

        while (currentDate <= setup.EndDate)
        {
          DateTime startLN = currentDate.AddHours(setup.StartHour);
          DateTime endLN = currentDate.AddHours(setup.EndHour);

          var data = contract.GetPricesBetween(startLN, endLN);

          if (data != null)
          {
            for (int i = 0; i < data.Length; ++i)
              outputList.Add(new OutputItem() { Ticker = contract.BbgTicker, GMT = data.Dates[i], Price = data.Data[i] });
          }

          currentDate = currentDate.AddDays(1d);
          while (currentDate.DayOfWeek == DayOfWeek.Saturday || currentDate.DayOfWeek == DayOfWeek.Sunday)
            currentDate = currentDate.AddDays(1d);

          //data.DisplayLineChart(setup.BbgTicker);
        }
      }

      outputList.ToCsv(@"c:\kalyan2.csv");

    }
    internal List<OutputLine> getFixingsOutputList()
    {
      var list = new List<OutputLine>();

      #region USD

      list.Add(new OutputLine()
      {
        BbgCode = "FEDL01 Index",
        OT_ID = "Interest:Fixing:USD:FEDFUNDS:1D",
        Tenor = "o/n",
        Ccy = "USD",
        Description = "Federal Funds Effective Rate U",
        InstType = InstrumentType.IRFixing,
        RIC = "USONFFE=",
      });

      list.Add(new OutputLine()
      {
        BbgCode="US0001W Index",
        OT_ID="Interest:Cash:USD:LIBOR:1W",
        Tenor="1w",
        Ccy="USD",
        Description="ICE LIBOR USD 1 Week",
        InstType=InstrumentType.IRFixing,
        RIC="USDSWFSR=",
      });

      list.Add(new OutputLine()
      {
        BbgCode = "US0001M Index",
        OT_ID = "Interest:Cash:USD:LIBOR:1M",
        Tenor = "1m",
        Ccy = "USD",
        Description = "ICE LIBOR USD 1 Month",
        InstType = InstrumentType.IRFixing,
        RIC = "USD1MFSR=",
      });

      list.Add(new OutputLine()
      {
        BbgCode = "US0002M Index",
        OT_ID = "Interest:Cash:USD:LIBOR:2M",
        Tenor = "2m",
        Ccy = "USD",
        Description = "ICE LIBOR USD 2 Month",
        InstType = InstrumentType.IRFixing,
        RIC = "USD2MFSR=",
      });

      list.Add(new OutputLine()
      {
        BbgCode = "US0003M Index",
        OT_ID = "Interest:Cash:USD:LIBOR:3M",
        Tenor = "3m",
        Ccy = "USD",
        Description = "ICE LIBOR USD 3 Month",
        InstType = InstrumentType.IRFixing,
        RIC = "USD3MFSR=",
      });

      #endregion

      #region EUR

      list.Add(new OutputLine()
      {
        BbgCode = "EONIA Index",
        OT_ID = "Interest:Fixing:EUR:EONIA:1D",
        Tenor = "o/n",
        Ccy = "EUR",
        Description = "Effective Overnight Index Aver",
        InstType = InstrumentType.IRFixing,
        RIC = "EONIA=",
      });

      list.Add(new OutputLine()
      {
        BbgCode = "EUR001W Index",
        OT_ID = "Interest:Cash:EUR:EURIBOR:1W",
        Tenor = "1w",
        Ccy = "EUR",
        Description = "Euribor 1 Week ACT/360",
        InstType = InstrumentType.IRFixing,
        RIC = "EURIBORSWD=",
      });

      list.Add(new OutputLine()
      {
        BbgCode = "EUR002W Index",
        OT_ID = "Interest:Cash:EUR:EURIBOR:2W",
        Tenor = "2w",
        Ccy = "EUR",
        Description = "Euribor 2 Week ACT/360",
        InstType = InstrumentType.IRFixing,
        RIC = "EURIBOR2WD=",
      });

      list.Add(new OutputLine()
      {
        BbgCode = "EUR001M Index",
        OT_ID = "Interest:Cash:EUR:EURIBOR:1M",
        Tenor = "1m",
        Ccy = "EUR",
        Description = "Euribor 1 Month ACT/360",
        InstType = InstrumentType.IRFixing,
        RIC = "EURIBOR1MD=",
      });

      list.Add(new OutputLine()
      {
        BbgCode = "EUR002M Index",
        OT_ID = "Interest:Cash:EUR:EURIBOR:2M",
        Tenor = "2m",
        Ccy = "EUR",
        Description = "Euribor 2 Month ACT/360",
        InstType = InstrumentType.IRFixing,
        RIC = "EURIBOR2MD=",
      });

      list.Add(new OutputLine()
      {
        BbgCode = "EUR003M Index",
        OT_ID = "Interest:Cash:EUR:EURIBOR:3M",
        Tenor = "3m",
        Ccy = "EUR",
        Description = "Euribor 3 Month ACT/360",
        InstType = InstrumentType.IRFixing,
        RIC = "EURIBOR3MD=",
      });

      list.Add(new OutputLine()
      {
        BbgCode = "EUR006M Index",
        OT_ID = "Interest:Cash:EUR:EURIBOR:6M",
        Tenor = "6m",
        Ccy = "EUR",
        Description = "Euribor 6 Month ACT/360",
        InstType = InstrumentType.IRFixing,
        RIC = "EURIBOR6MD=",
      });

      #endregion

      #region GBP

      list.Add(new OutputLine()
      {
        BbgCode = "BP00O/N Index",
        //OT_ID = "Interest:Cash:GBP:LIBOR:1D",
        Tenor = "o/n",
        Ccy = "GBP",
        Description = "ICE LIBOR GBP Overnight",
        InstType = InstrumentType.IRFixing,
        RIC = "GBPONFSR=",
      });

      list.Add(new OutputLine()
      {
        BbgCode = "BP0001M Index",
        OT_ID = "Interest:Cash:GBP:LIBOR:1M",
        Tenor = "1m",
        Ccy = "GBP",
        Description = "ICE LIBOR GBP 1 Month",
        InstType = InstrumentType.IRFixing,
        RIC = "GBP1MFSR=",
      });

      list.Add(new OutputLine()
      {
        BbgCode = "BP0002M Index",
        OT_ID = "Interest:Cash:GBP:LIBOR:2M",
        Tenor = "2m",
        Ccy = "GBP",
        Description = "ICE LIBOR GBP 2 Month",
        InstType = InstrumentType.IRFixing,
        RIC = "GBP2MFSR=",
      });

      list.Add(new OutputLine()
      {
        BbgCode = "BP0003M Index",
        OT_ID = "Interest:Cash:GBP:LIBOR:3M",
        Tenor = "3m",
        Ccy = "GBP",
        Description = "ICE LIBOR GBP 3 Month",
        InstType = InstrumentType.IRFixing,
        RIC = "GBP3MFSR=",
      });

      list.Add(new OutputLine()
      {
        BbgCode = "BP0006M Index",
        OT_ID = "Interest:Cash:GBP:LIBOR:6M",
        Tenor = "6m",
        Ccy = "GBP",
        Description = "ICE LIBOR GBP 6 Month",
        InstType=InstrumentType.IRFixing,
        RIC = "GBP6MFSR=",
      });


      #endregion

      #region CAD

      list.Add(new OutputLine()
      {
        BbgCode = "CDOR01 Index",
        OT_ID = "Interest:Cash:CAD:CDOR:1M",
        Tenor = "1m",
        Ccy = "CAD",
        Description = "Canada Bankers Acceptances 1 Month",
        InstType = InstrumentType.IRFixing,
        RIC = "CA1MBA=",
      });

      list.Add(new OutputLine()
      {
        BbgCode = "CDOR02 Index",
        OT_ID = "Interest:Cash:CAD:CDOR:2M",
        Tenor = "2m",
        Ccy = "CAD",
        Description = "Canada Bankers Acceptances 2 Month",
        InstType = InstrumentType.IRFixing,
        RIC = "CA2MBA=",
      });

      list.Add(new OutputLine()
      {
        BbgCode = "CDOR03 Index",
        OT_ID = "Interest:Cash:CAD:CDOR:3M",
        Tenor = "3m",
        Ccy = "CAD",
        Description = "Canada Bankers Acceptances 3 Month",
        InstType = InstrumentType.IRFixing,
        RIC = "CA3MBA=",
      });

      list.Add(new OutputLine()
      {
        BbgCode = "CDOR06 Index",
        OT_ID = "Interest:Cash:CAD:CDOR:6M",
        Tenor = "6m",
        Ccy = "CAD",
        Description = "Canada Bankers Acceptances 6 Month",
        InstType = InstrumentType.IRFixing,
        RIC = "CA6MBA=",
      });


      #endregion


      list.ToCsv(new CsvDestination(@"c:\irFutures.csv"));
      return list;
    }
Example #51
0
 public async Task<GroupTicketResponse> GetMultipleTicketsAsync(List<long> ids)
 {                        
     return await GenericGetAsync<GroupTicketResponse>(string.Format("{0}/show_many?ids={1}.json", _tickets, ids.ToCsv()));
 }
Example #52
0
        static void GetSalesmenAndRoutes()
        {
            bool boolSessionBegun = false;
           
            QBSessionManager sessionManager = new QBSessionManager();
            try
            {
                IMsgSetRequest requestMsgSet;
                IMsgSetResponse responseMsgSet;
                sessionManager.OpenConnection("", _appName);
                sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare);
                boolSessionBegun = true;
                requestMsgSet = GetLatestMsgSetRequest(sessionManager);
                requestMsgSet.Attributes.OnError = ENRqOnError.roeStop;
                // ISalesTaxCodeRetList

                ISalesRepQuery repsQuery = requestMsgSet.AppendSalesRepQueryRq();
               // repsQuery.ORListQuery.FullNameList.Add(name);
                responseMsgSet = sessionManager.DoRequests(requestMsgSet);

                IResponse response = responseMsgSet.ResponseList.GetAt(0);
                ISalesRepRetList repsList = response.Detail as ISalesRepRetList;
                var salemen = new List<Salesman>();
                if (repsList != null && repsList.Count > 0)
                {
                    var company = GetCurrentCompany();
                    for (var i = 0; i < repsList.Count; i++)
                    {
                        ISalesRepRet rep = repsList.GetAt(i);
                    
                        if (rep != null && rep.IsActive.GetValue())
                        {
                            var result = new Salesman()
                                         {
                                             distributrCode =company!=null?company.CompanyName.GetValue(): "",
                                             name = rep.SalesRepEntityRef != null ? rep.Initial.GetValue() : "",//rep.SalesRepEntityRef != null ? rep.SalesRepEntityRef.FullName.GetValue() : "",
                                             salesmanCode = rep.SalesRepEntityRef != null ? rep.Initial.GetValue() : "",
                                             mobileNumber =""
                                         };
                           salemen.Add(result);


                        }

                    }
                  
                }

                sessionManager.EndSession();
                boolSessionBegun = false;
                sessionManager.CloseConnection();
                if (salemen.Any())
                {
                    
                    DumpExportFilesAsync(salemen.ToCsv(), MasterDataCollective.DistributorSalesman.ToString());
                    var routes = salemen.Select(n=>new
                                                       {
                                                           Name=n.name,
                                                           Code = n.salesmanCode,
                                                           Region="default" //todo=>Figute out how to determine regions for each route
                                                       }).ToCsv();
                    DumpExportFilesAsync(routes, MasterDataCollective.Route.ToString());

                }
            }
            catch (Exception ex)
            {
                if (boolSessionBegun)
                {
                    sessionManager.EndSession();
                    sessionManager.CloseConnection();
                }
                string error = (ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application");
                Log(error);
                MessageBox.Show(error);

            }
          
        }
Example #53
0
 public async Task<bool> DeleteMultipleAsync(List<long> ids)
 {
     return await GenericDeleteAsync(string.Format("{0}/destroy_many.json?ids={1}", _tickets, ids.ToCsv()));
 }
Example #54
0
        public bool RecoverManySuspendedTickets(List<long> ids)
        {
            var request = new RestRequest
            {
                Method = Method.PUT,
                Resource = string.Format("suspended_tickets/recover_many.json?ids={0}", ids.ToCsv()),
                RequestFormat = DataFormat.Json
            };

            var res = Execute(request);
            return res.StatusCode == HttpStatusCode.OK;
        }
Example #55
0
 public async Task<bool> DeleteManySuspendedTicketsAsync(List<long> ids)
 {
     return await GenericDeleteAsync(string.Format("suspended_tickets/destroy_many.json?ids={0}", ids.ToCsv()));
 }
Example #56
0
         static void PullCustomers()
        {
            bool boolSessionBegun = false;
            QBSessionManager sessionManager = new QBSessionManager();
            List<OutletImport> customers = new List<OutletImport>();
            List<RouteRegionInfo> routeRegionInfos=new List<RouteRegionInfo>();
            try
            {
                IMsgSetRequest requestMsgSet;
                IMsgSetResponse responseMsgSet;
                sessionManager.OpenConnection("", _appName);
                sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare);
                boolSessionBegun = true;
                requestMsgSet = GetLatestMsgSetRequest(sessionManager);
                requestMsgSet.Attributes.OnError = ENRqOnError.roeStop;

                ICustomerQuery custQ = requestMsgSet.AppendCustomerQueryRq();
               // custQ.ORCustomerListQuery.FullNameList.
                responseMsgSet = sessionManager.DoRequests(requestMsgSet);

                IResponse response = responseMsgSet.ResponseList.GetAt(0);
                ICustomerRetList customerRetList = response.Detail as ICustomerRetList;

                
                if (customerRetList != null && customerRetList.Count != 0)
                {
                    var company = GetCurrentCompany();
                    for (var i = 0; i < customerRetList.Count; i++)
                    {
                       ICustomerRet  customerRet = customerRetList.GetAt(i);
                       if (customerRet != null && customerRet.IsActive.GetValue())
                        {
                            var outlet = new OutletImport
                                             {
                                                 DistributrCode = company != null ? company.CompanyName.GetValue() : "default",
                                                 OutletName = customerRet.FullName != null ? customerRet.FullName.GetValue() : "",
                                                 OutletCode = customerRet.Name != null ? customerRet.Name.GetValue() : ""
                                             };
                            if(customerRet.CustomerTypeRef !=null)
                                outlet.Outletype = customerRet.CustomerTypeRef.FullName.GetValue();
                            if (customerRet.SalesTaxCodeRef != null)
                                outlet.VatClassCode = "";//customerRet.SalesTaxCodeRef.FullName.GetValue();
                            if (customerRet.PriceLevelRef !=null)
                            outlet.PricingTierCode = customerRet.PriceLevelRef.FullName.GetValue();
                           
                            if (customerRet.SalesRepRef !=null)
                            {
                                outlet.RouteCode = customerRet.SalesRepRef.FullName.GetValue();
                              
                            }
                            else
                            {
                                continue;
                            }
                            if (customerRet.ShipAddress != null)
                            {
                                var address = customerRet.ShipAddress;
                              var route=  new RouteRegionInfo()
                                    {
                                        Salemanref = outlet.RouteCode,
                                        Region = address.State != null ? address.State.GetValue() : ""
                                    };
                              if (route != null && string.IsNullOrEmpty(route.Region))
                                  routeRegionInfos.Add(route);
                            }

                            
                            customers.Add(outlet);
                        }
                    }
                }

                sessionManager.EndSession();
                boolSessionBegun = false;
                sessionManager.CloseConnection();
                if (customers.Any())
                {
                    DumpExportFilesAsync(customers.ToCsv(), MasterDataCollective.Outlet.ToString());
                }
                if(routeRegionInfos.Any())
                {
                    
                }
            }
            catch (Exception ex)
            {
                if (boolSessionBegun)
                {
                    sessionManager.EndSession();
                    sessionManager.CloseConnection();
                }
                string error = (ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application");
                Log(error);
                MessageBox.Show(error);

            }
          
        }
Example #57
0
 public JobStatusResponse BulkUpdate(List<long> ids, BulkUpdate info)
 {
     var body = new { ticket = info };
     return GenericPut<JobStatusResponse>(string.Format("{0}/update_many.json?ids={1}", _tickets, ids.ToCsv()), body);            
 }
Example #58
0
        internal static async void PullInventory()
        {
            var fileLocation = FileUtility.GetInventoryFile("LastDateOfSync");
            var fromDate = FileUtility.ReadFile(fileLocation);
            var newSyncDate = DateTime.Now.ToString();

            bool boolSessionBegun = false;
            QBSessionManager sessionManager = new QBSessionManager();
           try
           {
            if(string.IsNullOrEmpty(fromDate))
            {
                var results = PullInitialInventory();

                var filename = "Stockline-Alidi Kenya Limited-Initial" + DateTime.Now.ToString("yyyyMMdd");
                results = results.GroupBy(n => new { n.ProductName, n.ToSiteName })
                    .Select(m => new InventoryImport { Balance = m.Sum(g => g.Balance), ProductName = m.Key.ProductName, ToSiteName = m.Key.ToSiteName }).ToList();

                DumpExportInventoryFileAsync(results.ToCsv(), filename);


                var filePath = FileUtility.GetInventoryFile(filename);
                bool success=await SendToDistributor(filePath);
                if (success)
                    DumpExportInventoryFileAsync(newSyncDate, "LastDateOfSync");
            }
            else
            {

                
                List<InventoryImport> inventory = new List<InventoryImport>();

                var distributorsList = new List<string>();
                var inventoryPerDistributor = new Dictionary<string, List<InventoryImport>>();
                var distributorsCodeDictionary = new Dictionary<string, string>();
                var distributorInventoryList = new List<InventoryImport>();

                var stockSiteCodMappingList = GetStockSiteCodeMapping();

                IMsgSetRequest requestMsgSet;
                IMsgSetResponse responseMsgSet;
                sessionManager.OpenConnection("", _appName);
                sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare);
                boolSessionBegun = true;
                requestMsgSet = GetLatestMsgSetRequest(sessionManager);
                requestMsgSet.Attributes.OnError = ENRqOnError.roeStop;

                ITransferInventoryQuery transferInventoryQuery = requestMsgSet.AppendTransferInventoryQueryRq();


                transferInventoryQuery.ORTransferInventoryQuery.TxnFilterNoCurrency.ORDateRangeFilter.
                    ModifiedDateRangeFilter.FromModifiedDate.SetValue(DateTime.Parse(fromDate), false);
                transferInventoryQuery.ORTransferInventoryQuery.TxnFilterNoCurrency.ORDateRangeFilter.
                    ModifiedDateRangeFilter.ToModifiedDate.SetValue(DateTime.Parse(newSyncDate), false);

                transferInventoryQuery.IncludeLineItems.SetValue(true);
                responseMsgSet = sessionManager.DoRequests(requestMsgSet);
                IResponse respons = responseMsgSet.ResponseList.GetAt(0);

                ITransferInventoryRetList lineRetList = respons.Detail as ITransferInventoryRetList;
                if (lineRetList != null)
                {


                    var RetCount = lineRetList.Count;
                    for (int i = 0; i < RetCount; i++)
                    {
                        if (lineRetList != null)
                        {
                            var TransferInventoryRet = lineRetList.GetAt(i);
                            if (TransferInventoryRet != null)
                            {
                                var fromSite = TransferInventoryRet.FromInventorySiteRef.FullName.GetValue();
                                var toSite = TransferInventoryRet.ToInventorySiteRef.FullName.GetValue();
                                var number = TransferInventoryRet.RefNumber.GetValue();
                                double lineItemsCount = 0.0;

                                if (TransferInventoryRet.TransferInventoryLineRetList != null)
                                {
                                    var toSiteName = TransferInventoryRet.ToInventorySiteRef.FullName.GetValue();
                                    var fromSiteName = TransferInventoryRet.FromInventorySiteRef.FullName.GetValue();
                                    var transferInventoryLineItemsCount =
                                        TransferInventoryRet.TransferInventoryLineRetList.Count;


                                    for (int j = 0; j < transferInventoryLineItemsCount; j++)
                                    {
                                        var productFullName =
                                            TransferInventoryRet.TransferInventoryLineRetList.GetAt(j).ItemRef.FullName.
                                                GetValue();
                                        var lastColonIndex = productFullName.LastIndexOf(":");
                                        var productCode =
                                            TransferInventoryRet.TransferInventoryLineRetList.GetAt(j).ItemRef.FullName.
                                                GetValue().Substring(lastColonIndex + 1);
                                        var productName = GetProductName(productCode);
                                        var balance =
                                            TransferInventoryRet.TransferInventoryLineRetList.GetAt(j).
                                                QuantityTransferred.GetValue();


                                        var distributorInventory = new InventoryImport()
                                            {
                                                ToSiteName = stockSiteCodMappingList[toSite],
                                                Balance = Convert.ToDecimal(balance),
                                                ProductName = productCode
                                            };
                                        distributorInventoryList.Add(distributorInventory);

                                    }


                                    Console.WriteLine(@"From {0} To {1} , the Ref number is {2}, Items Transfered {3}",
                                                      fromSite,
                                                      toSite, number, lineItemsCount);
                                }

                            }
                        }
                    }
                }


                sessionManager.EndSession();
                boolSessionBegun = false;
                sessionManager.CloseConnection();

                var filename = "Stockline-Alidi Kenya Limited-" + DateTime.Now.ToString("yyyyMMdd");
                distributorInventoryList = distributorInventoryList.GroupBy(n => new {n.ProductName, n.ToSiteName})
                    .Select(
                        m =>
                        new InventoryImport
                            {
                                Balance = m.Sum(g => g.Balance),
                                ProductName = m.Key.ProductName,
                                ToSiteName = m.Key.ToSiteName
                            }).ToList();

                DumpExportInventoryFileAsync(distributorInventoryList.ToCsv(), filename);


                var filePath = FileUtility.GetInventoryFile(filename);
                bool success = await SendToDistributor(filePath);
                if(success)
                    DumpExportInventoryFileAsync(newSyncDate, "LastDateOfSync");


            }

           }
            catch (Exception ex)
            {
                if (boolSessionBegun)
                {
                    sessionManager.EndSession();
                    sessionManager.CloseConnection();
                }
                string error = (ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application");
                Log(error);
                MessageBox.Show(error);

            
            }

        }
Example #59
0
 public GroupTopicResponse GetMultipleTopicsById(List<long> topicIds)
 {
     return GenericPost<GroupTopicResponse>(string.Format("topics/show_many?ids={0}.json", topicIds.ToCsv()));
 }
Example #60
0
 public async Task<GroupViewCountResponse> GetViewCountsAsync(List<long> viewIds)
 {
     return await GenericGetAsync<GroupViewCountResponse>(string.Format("views/count_many.json?ids={0}", viewIds.ToCsv()));
 }