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 #2
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)));

            }
          }
        }
      }

    }
        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 #4
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 #5
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 #6
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 #7
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 #8
0
 public bool DeleteMultiple(List<long> ids)
 {
     return GenericDelete(string.Format("{0}/destroy_many.json?ids={1}", _tickets, ids.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 #10
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 #11
0
 public GroupTicketResponse GetMultipleTickets(List<long> ids)
 {                        
     return GenericGet<GroupTicketResponse>(string.Format("{0}/show_many?ids={1}.json", _tickets, ids.ToCsv()));
 }
 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;
 }
Example #13
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 #14
0
 public GroupViewCountResponse GetViewCounts(List<long> viewIds)
 {
     return GenericGet<GroupViewCountResponse>(string.Format("views/count_many.json?ids={0}", viewIds.ToCsv()));
 }
Example #15
0
 public async Task<GroupTopicResponse> GetMultipleTopicsByIdAsync(List<long> topicIds)
 {
     return await GenericPostAsync<GroupTopicResponse>(string.Format("topics/show_many?ids={0}.json", topicIds.ToCsv()));
 }
Example #16
0
 public async Task<GroupViewCountResponse> GetViewCountsAsync(List<long> viewIds)
 {
     return await GenericGetAsync<GroupViewCountResponse>(string.Format("views/count_many.json?ids={0}", viewIds.ToCsv()));
 }
Example #17
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);

            }
          
        }
    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");

    }
Example #19
0
 public bool DeleteManySuspendedTickets(List<long> ids)
 {
     return GenericDelete(string.Format("suspended_tickets/destroy_many.json?ids={0}", ids.ToCsv()));
 }
    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 #21
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 #22
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 #23
0
 public async Task<bool> DeleteMultipleAsync(List<long> ids)
 {
     return await GenericDeleteAsync(string.Format("{0}/destroy_many.json?ids={1}", _tickets, ids.ToCsv()));
 }
Example #24
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 #25
0
 public async Task<bool> DeleteManySuspendedTicketsAsync(List<long> ids)
 {
     return await GenericDeleteAsync(string.Format("suspended_tickets/destroy_many.json?ids={0}", ids.ToCsv()));
 }
Example #26
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 #27
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 #28
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);
     }
 }
Example #29
0
 public GroupTopicResponse GetMultipleTopicsById(List<long> topicIds)
 {
     return GenericPost<GroupTopicResponse>(string.Format("topics/show_many?ids={0}.json", topicIds.ToCsv()));
 }
    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;
    }