Пример #1
0
 public Site()
 {
     BrokerContext.Initialize(Constants.BaseApplicationToken.ToString(), Constants.UserToken);
     if (HttpContext.Current != null && HttpContext.Current.Handler is Page)
     {
         (HttpContext.Current.Handler as Page).Error += new EventHandler(Page_Error);
     }
 }
Пример #2
0
 /// <summary>
 /// Returns a ReadOnltcollection of all the travel
 /// companies created using this broker.
 /// </summary>
 /// <returns></returns>
 public ReadOnlyCollection <string> KnownTravelCompanies()
 {
     using (var c = new BrokerContext(_brokerconnectionstring))
     {
         var travelCompanyNames = c.TravelCompanies.Select(tc => tc.Name);
         return(travelCompanyNames.ToList().AsReadOnly());
     }
 }
Пример #3
0
        /// <summary>
        /// Setup the namespace.
        /// </summary>
        /// <returns></returns>
        public async Task SetupAsync()
        {
            // create broker context
            _brokerContext = await BrokerContext.CreateAsync(_connectionUri.ToString());

            // create broker
            _broker = await _brokerContext.CreateBrokerAsync(_node.Configuration.ApplicationId);

            // add returned handler
            _broker.Returned += delegate(object s, BrokerReturnedEventArgs e) {
                if (e.ID != Guid.Empty)
                {
                    TaskCompletionSource <Envelope> tcs;

                    lock (_replyWaits) {
                        // try and get the reply wait
                        if (!_replyWaits.TryGetValue(e.ID, out ReplyWait replyWait))
                        {
                            return;
                        }

                        // if this is a multi-reply do nothing
                        if (replyWait.Results != null)
                        {
                            return;
                        }

                        // remove and set exception
                        tcs = replyWait.CompletionSource;
                        _replyWaits.Remove(e.ID);
                    }

                    tcs.TrySetException(new ServiceNotFoundException("The envelope was returned before delivery"));
                }
            };

            // create reply queue
            try {
                // declare queue with unique name
                using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) {
                    // get unique string
                    byte[] uniqueId = new byte[20];
                    rng.GetBytes(uniqueId);
                    string uniqueIdStr = BitConverter.ToString(uniqueId).Replace("-", "").ToLower();

                    // add the reply queue
                    _replyQueue = await _broker.CreateQueueAsync(string.Format("~reply:{1}%{0}", _node.UUID, uniqueIdStr), false, true, "", "", true, true, new Dictionary <string, object>() {
                        { "x-expires", (int)TimeSpan.FromMinutes(15).TotalMilliseconds }
                    }).ConfigureAwait(false);

                    // subscribe to reply queue
                    _replyQueue.AsObservable().Subscribe(new ReplyObserver(this));
                }
            } catch (Exception ex) {
                throw new InvalidOperationException("Failed to create node reply queue", ex);
            }
        }
Пример #4
0
 /// <summary>
 /// Load the read-only interface to a given travel company
 /// </summary>
 /// <param name="name"></param>
 /// <returns></returns>
 public IReadOnlyTravelCompany Get(string name)
 {
     CheckName(name);
     using (var c = new BrokerContext(_brokerconnectionstring))
     {
         return(new ReadOnlyTravelCompany(c.TravelCompanies.Single(tc => tc.Name == name).ConnectionString,
                                          name));
     }
 }
Пример #5
0
        public ActionResult AddShare()
        {
            var share = new Share();

            using (var db = new BrokerContext())
            {
                share.Countries = new SelectList(db.Countries.ToList(), "Id", "Name");
            }
            return(View(share));
        }
Пример #6
0
            public void CreateDataProviders_FunkyType_None()
            {
                BrokerContext.Initialize(CprBroker.Utilities.Constants.BaseApplicationToken.ToString(), "");
                var facade = new FacadeStub();
                IEnumerable <FunkyDataProvider> provs;
                var ret = facade.CreateDataProviders(out provs);

                Assert.IsEmpty(provs.ToArray());
                Assert.AreEqual("503", ret.StatusKode);
            }
Пример #7
0
 protected void Page_Load(object sender, EventArgs e)
 {
     BrokerContext.Initialize(Constants.BaseApplicationToken.ToString(), Constants.UserToken);
     if (!IsPostBack)
     {
         dataProviderTypesGridView.DataBind();
         dataProvidersGridView.DataBind();
         newDataProviderDropDownList.DataBind();
         newDataProviderGridView.DataBind();
     }
 }
Пример #8
0
 protected void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (db != null)
         {
             db.Dispose();
             db = null;
         }
     }
 }
Пример #9
0
        public IActionResult GetHistoryPeiceShare(int?id)
        {
            var historyPrice = new List <HistoryPriceShare>();

            using (var db = new BrokerContext())
            {
                historyPrice = db.HistoryPriceShares.Where(x => x.ShareId == id).ToList();
            }
            string json = JsonSerializer.Serialize(historyPrice);

            return(Ok(historyPrice));
        }
            public void FinalizeSubscriptionCriteriaLists_Normal(string municipalityCode)
            {
                BrokerContext.Initialize(CprBroker.Utilities.Constants.BaseApplicationToken.ToString(), "");
                var soegObject = Utils.CreateSoegObject(municipalityCode);

                new Subscriptions.SubscriptionDataProvider().SubscribeOnCriteria(new FileShareChannelType()
                {
                    Path = "C:\\"
                }, soegObject);

                Notifications.DataChangeEventEnqueuer.UpdateSubscriptionCriteriaLists();
            }
        /// <summary>
        /// Load the specified TravelCompany from a Name

        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public ITravelCompany Get(string name)
        {
            CheckName(name);
            using (var c = new BrokerContext(_brokerconnectionstring))
            {
                var travelAgency = c.TravelCompanies.SingleOrDefault(EqualsNameExp(name));
                if (travelAgency == null)
                {
                    throw new NonexistentTravelCompanyException("Travel Agency not exist");
                }
                return(new TravelCompany(travelAgency.ConnectionString, name));
            }
        }
Пример #12
0
        public IActionResult PayShare(int ShareId, int UserId)
        {
            if (ShareId == 0 || UserId == 0)
            {
                return(BadRequest());
            }
            var comment = "";

            using (var db = new BrokerContext())
            {
                var user      = db.Users.FirstOrDefault(x => x.Id == UserId);
                var share     = db.Shares.FirstOrDefault(x => x.Id == ShareId);
                var portfolio = db.Portfolios.FirstOrDefault(x => x.UserId == UserId);
                if (user != null)
                {
                    if (portfolio == null)
                    {
                        var newPortfolio = new Portfolio()
                        {
                            UserId = user.Id
                        };
                        db.Portfolios.Add(newPortfolio);
                        db.SaveChanges();
                        portfolio = db.Portfolios.FirstOrDefault(x => x.UserId == user.Id);
                    }
                    if (user.Balance < share.CurrentPrice)
                    {
                        comment = "Недостаточно средств";
                    }
                    else
                    {
                        user.Balance -= share.CurrentPrice;
                        var shareAndPortfolio = new PortfolioShare()
                        {
                            BuyPrice = share.CurrentPrice, PortfolioId = portfolio.Id, ShareId = share.Id
                        };
                        db.Users.Update(user);
                        db.PortfolioShares.Add(shareAndPortfolio);
                        db.SaveChanges();
                        comment = $"Операция прошла успешна. Ваш текущий баланс {user.Balance}";
                    }
                }
                else
                {
                    comment = "Произошла ошибка данный пользователь не найден!!!";
                }
            }
            return(Ok(comment));
        }
Пример #13
0
        public IActionResult GetShare(int?id)
        {
            var share = new Share();

            using (var db = new BrokerContext())
            {
                share = db.Shares.Include(x => x.Country).FirstOrDefault(x => x.Id == id);
            }
            if (share != null)
            {
                string json = JsonSerializer.Serialize(share);
                return(Ok(json));
            }
            return(BadRequest());
        }
        /// <summary>
        /// Creates a new broker for travel companies.The database denoted by dbConnectionString is initialized (previousdata, if any, will be lost)
        /// and will be used to store information about the travel companies managed by the resulting broker.
        /// </summary>
        /// <param name="dbConnectionString"></param>
        /// <returns></returns>
        public ITravelCompanyBroker CreateNewBroker(string dbConnectionString)
        {
            CheckConnectionString(dbConnectionString);
            if (Database.Exists(dbConnectionString))
            {
                Database.Delete(dbConnectionString);
            }

            using (var c = new BrokerContext(dbConnectionString))
            {
                c.Database.Create();
                c.SaveChanges();
            }
            return(new TravelCompanyBroker(dbConnectionString));
        }
Пример #15
0
        public IActionResult GetUser(int id)
        {
            var user = new User();

            using (var db = new BrokerContext())
            {
                user = db.Users.FirstOrDefault(x => x.Id == id);
            }
            if (user != null)
            {
                string json = JsonSerializer.Serialize <User>(user);
                return(Ok(json));
            }
            return(BadRequest());
        }
Пример #16
0
        public override void ProcessPerson(string personRegId)
        {
            BrokerContext.Initialize(this.ApplicationToken, this.UserToken);

            var personRegistrationId = new Guid(personRegId);

            using (var dataContext = new PartDataContext(this.BrokerConnectionString))
            {
                CprBroker.Engine.Local.Admin.AddNewLog(System.Diagnostics.TraceEventType.Information, GetType().Name, string.Format("Processing registration {0}", personRegId), "", "");

                try
                {
                    var dbReg = dataContext.PersonRegistrations.Where(pr => pr.PersonRegistrationId == personRegistrationId).First();
                    var pnr   = dataContext.PersonMappings.Where(pm => pm.UUID == dbReg.UUID).Select(pm => pm.CprNumber).First();
                    Func <string, Guid> cpr2uuidFunc = relPnr =>
                    {
                        relPnr = relPnr.PadLeft(10, ' ');
                        return(dataContext.PersonMappings.Where(pm => pm.CprNumber == relPnr).Select(pm => pm.UUID).First());
                    };

                    //string oldContentsXml, oldSourceXml, newContentsXml, newSourceXml;

                    //TakeCopies(dbReg, out oldContentsXml, out oldSourceXml);

                    var oioReg = CreateXmlType(pnr, dbReg, cpr2uuidFunc);

                    dbReg.SourceObjects = System.Xml.Linq.XElement.Parse(oioReg.SourceObjectsXml);
                    dbReg.SetContents(oioReg);

                    //TakeCopies(dbReg, out newContentsXml, out newSourceXml);

                    //CompareContents(oioReg, oldContentsXml, newContentsXml);
                    //CompareSource(oldSourceXml, newSourceXml);

                    dataContext.SubmitChanges();
                    CprBroker.Engine.Local.Admin.AddNewLog(System.Diagnostics.TraceEventType.Information, GetType().Name, string.Format("Finished registration {0}", personRegId), "", "");
                }
                catch (Exception ex)
                {
                    CprBroker.Engine.Local.Admin.LogException(ex);
                    throw ex;
                }
            }
        }
Пример #17
0
        public void Firefox_Notification_Should_Throw_Error_If_Payload_Exceed_Limit()
        {
            var settings = Settings.Instance;
            var ctx      = new BrokerContext();

            ctx.Start();

            var subsription = settings.WebPush.FirefoxSubscription;

            var notif = new WebPushNotification(subsription);
            var value = new string('a', 1024 * 5);

            notif.Payload = JObject.Parse($"{{ \"somekey\" : \"{value}\" }}");
            ctx.Broker.QueueNotification(notif);

            ctx.Broker.Stop();

            ctx.AssertPayloadExceedLimit();
        }
Пример #18
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            BrokerContext.Initialize(Constants.EventBrokerApplicationToken.ToString(), Constants.UserToken);

            try
            {
                string        s = CprBroker.Config.Properties.Settings.Default.CprBrokerConnectionString;
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]
                {
                    new BackendService()
                };
                ServiceBase.Run(ServicesToRun);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #19
0
        public void Chrome_Should_Throw_Correct_Error_For_OutDated_Subscription()
        {
            var settings = Settings.Instance;
            var ctx      = new BrokerContext();

            ctx.Start();

            var subsription = settings.WebPush.ChromeOutdatedSubscription;

            var notif = new WebPushNotification(subsription);

            notif.Payload = JObject.Parse("{ \"somekey\" : \"somevalue\" }");
            ctx.Broker.QueueNotification(notif);

            ctx.Broker.Stop();

            Assert.AreEqual(0, ctx.Succeeded);
            ctx.AssertSubscriptionExpired();
        }
Пример #20
0
        public void Firefox_Notification_With_Payload_Test()
        {
            var settings = Settings.Instance;
            var ctx      = new BrokerContext();

            ctx.Start();

            var subsription = settings.WebPush.FirefoxSubscription;

            var notif = new WebPushNotification(subsription);

            notif.Payload = JObject.Parse("{ \"somekey\" : \"somevalue\" }");
            ctx.Broker.QueueNotification(notif);

            ctx.Broker.Stop();

            Assert.AreEqual(1, ctx.Succeeded);
            Assert.AreEqual(0, ctx.Failed);
        }
Пример #21
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, BrokerContext dbContext)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            dbContext.Database.EnsureCreated();
            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGrpcService <SwarmingFleetService>();

                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
                });
            });
        }
Пример #22
0
        public IActionResult DeleteShare(int Id)
        {
            string comment = "";

            using (var db = new BrokerContext())
            {
                var share = db.Shares.FirstOrDefault(x => x.Id == Id);
                if (share != null)
                {
                    db.Shares.Remove(share);
                    db.SaveChanges();
                    comment = "Удаление произошло успешно";
                }
                else
                {
                    comment = "Произошла ошибка, возможно акция уже удалена";
                }
            }
            return(Ok(comment));
        }
Пример #23
0
            public void CallBatch_MixedSuccess_Correct()
            {
                BrokerContext.Initialize(CprBroker.Utilities.Constants.BaseApplicationToken.ToString(), "");
                var facade = new CallSingle.FacadeStub();

                CallSingle.FacadeStub.Element[] ret;
                var prov     = new CallSingle.FacadeStub.ProviderStub();
                var elements = new CallSingle.FacadeStub.ElementStub[] {
                    new CallSingle.FacadeStub.ElementStub()
                    {
                        Input = "DDD", Succeeded = false, Updatable = false
                    },
                    new CallSingle.FacadeStub.ElementStub()
                    {
                        Input = "SSS", Succeeded = true, Updatable = true
                    }
                };

                facade.CallBatch(prov, elements, out ret);
                Assert.AreEqual(1, ret.Length);
            }
Пример #24
0
 public IActionResult AddShare(int CountryId, double CurrentPrice, string ImgSrc, string CompanyName)
 {
     using (var db = new BrokerContext())
     {
         var share = new Share();
         share.CompanyName  = CompanyName;
         share.ImgSrc       = ImgSrc;
         share.Country      = db.Countries.FirstOrDefault(x => x.Id == CountryId);
         share.CurrentPrice = CurrentPrice;
         db.Shares.Add(share);
         db.SaveChanges();
         var idShare      = db.Shares.FirstOrDefault(x => x.CompanyName == share.CompanyName).Id;
         var historyPrice = new HistoryPriceShare()
         {
             DateHistory = DateTime.Now, Price = share.CurrentPrice, ShareId = idShare
         };
         db.HistoryPriceShares.Add(historyPrice);
         db.SaveChanges();
     }
     return(Ok());
 }
Пример #25
0
        public JsonResult GetShares()
        {
            var Shares           = new List <Share>();
            var sharesViewModels = new List <ShareViewModels>();

            using (var db = new BrokerContext())
            {
                //var role1 = new Role() { Name = "Admin" };
                //db.Roles.Add(role1);
                //db.SaveChanges();
                Shares           = db.Shares.Include(x => x.Country).Include(x => x.HistoryPriceShares).ToList();
                sharesViewModels = Shares.Select(x => new ShareViewModels()
                {
                    Id     = x.Id,
                    Name   = x.CompanyName,
                    Price  = x.CurrentPrice,
                    ImgSrc = x.ImgSrc
                }).ToList();
            }

            return(Json(sharesViewModels));
        }
Пример #26
0
        public async Task <IActionResult> Login(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                using (var _context = new BrokerContext())
                {
                    User user = await _context.Users
                                .Include(u => u.Role)
                                .FirstOrDefaultAsync(u => u.Email == model.Email && u.Password == model.Password);

                    if (user != null)
                    {
                        Response.Cookies.Append("idUser", user.Id.ToString());
                        Response.Cookies.Append("login", user.Email);
                        Response.Cookies.Append("role", user.Role.Name);
                        return(Ok("true"));
                    }
                    return(Ok());
                }
            }
            return(BadRequest());
        }
Пример #27
0
        public async Task <IActionResult> SetBalance(int IdUser, double Balance)
        {
            if (ModelState.IsValid)
            {
                using (var _context = new BrokerContext())
                {
                    User user = await _context.Users
                                .Include(u => u.Role)
                                .FirstOrDefaultAsync(u => u.Id == IdUser);

                    if (user != null && Balance > 0)
                    {
                        user.Balance += Balance;
                        _context.Users.Update(user);
                        _context.SaveChanges();
                        return(Ok("true"));
                    }
                    return(Ok());
                }
            }
            return(BadRequest());
        }
Пример #28
0
        public async Task <ActionResult> Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                using (var _context = new BrokerContext())
                {
                    User user = await _context.Users.FirstOrDefaultAsync(u => u.Email == model.Email);

                    if (user == null)
                    {
                        // добавляем пользователя в бд
                        user = new User {
                            Email = model.Email, Password = model.Password, FirstName = model.FirstName, SecondName = model.SecondName, Balance = 0
                        };
                        Role userRole = await _context.Roles.FirstOrDefaultAsync(r => r.Name == "User");

                        if (userRole != null)
                        {
                            user.Role = userRole;
                        }

                        _context.Users.Add(user);
                        await _context.SaveChangesAsync();

                        Response.Cookies.Append("idUser", user.Id.ToString());
                        Response.Cookies.Append("login", user.Email);
                        Response.Cookies.Append("role", user.Role.Name);

                        return(Ok("True Registry"));
                    }
                    else
                    {
                        return(Ok("Такой пользователь уже есть"));
                    }
                }
            }
            return(BadRequest());
        }
Пример #29
0
        public override string[] LoadCprNumbers()
        {
            Utilities.UpdateConnectionString(this.BrokerConnectionString);
            BrokerContext.Initialize(this.ApplicationToken, "");
            brokerContext = BrokerContext.Current;

            string[] ret = null;

            if (string.IsNullOrEmpty(SourceFile))
            {
                using (var dataContext = new DPRDataContext(OtherConnectionString))
                {
                    ret = dataContext.PersonTotals.Select(t => t.PNR).ToArray().Select(pnr => pnr.ToPnrDecimalString()).ToArray();
                }
            }
            else
            {
                ret = Utilities.LoadCprNumbersOneByOne(SourceFile);
            }

            UuidCache.PreLoadExistingMappings();
            return(ret);
        }
Пример #30
0
 public IActionResult SaleShare(int IdSharePortfolio)
 {
     if (IdSharePortfolio != 0)
     {
         string comment = "";
         var    user    = new User();
         using (var db = new BrokerContext())
         {
             var portfolioShare = db.PortfolioShares.FirstOrDefault(x => x.Id == IdSharePortfolio);
             var share          = db.Shares.FirstOrDefault(X => X.Id == portfolioShare.ShareId);
             var portfolio      = db.Portfolios.FirstOrDefault(x => x.Id == portfolioShare.PortfolioId);
             user          = db.Users.FirstOrDefault(x => x.Id == portfolio.UserId);
             user.Balance += share.CurrentPrice;
             db.PortfolioShares.Remove(portfolioShare);
             db.Users.Update(user);
             db.SaveChanges();
         }
         return(Ok(user.Balance));
     }
     else
     {
         return(BadRequest());
     }
 }