//[ValidateAntiForgeryToken]
        public async Task <JsonResult> Create([Bind(Include = "Id,DistributorId,CampaignTitle,SocialMediaId,IndustryId,City,Gender,Message,CampaignType, LaunchDate")] CampaignViewModel campaignViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(Json(new { success = false, Response = "", Error = ErrorHelper.GetModelStateErrorMessages(ModelState) }, JsonRequestBehavior.AllowGet));
            }

            var errorMessage = "";
            var distributor  = new Distributor();

            if (!IdentityHelper.TryGetDistributor(User, out distributor, out errorMessage))
            {
                return(Json(new { success = false, Response = "", Error = errorMessage }, JsonRequestBehavior.AllowGet));
            }

            try
            {
                var createdCampaign = _campaignAdapter.Create(campaignViewModel, distributor);
                return(Json(new { success = true, Response = createdCampaign, Error = "" }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception exception)
            {
                return(Json(new { success = false, Response = "", Error = exception.Message }, JsonRequestBehavior.AllowGet));
            }
        }
        public async Task <DistributorEditOutput> ExecuteNew(DistributorEditInput input)
        {
            var distributor = new Distributor(input.Name, input.Description);
            var added       = await this._distributorRepository.AddAsync(distributor);

            if (added != null)
            {
                var count = await this._unitOfWork.Save();

                if (count > 0)
                {
                    return(new DistributorEditOutput(added, true, "Success: Distributor Added"));
                }
                else
                {
                    await this._unitOfWork.Undo();

                    return(new DistributorEditOutput(null, false, "Error: Add Failed, Please Contact Admin"));
                }
            }
            else
            {
                await this._unitOfWork.Undo();

                return(new DistributorEditOutput(null, false, "Error: Add Failed, Please Contact Admin"));
            }
        }
        public string VoteAction(ChooserLbMessage message)
        {
            var      _storage = NodeStorage.GetInstance();
            NodeData worker;
            var      selected_Nodes = Distributor.FormateNodeList(3, out worker);
            var      neighbors      = Mapping.Mapper.Map <List <NodeNeighbor> >(selected_Nodes);

            var request_data = new NodeVoteMessage()
            {
                Message    = message,
                Neighbours = neighbors
            };

            var serialized = JsonConvert.SerializeObject(request_data);
            var content    = new StringContent(serialized, Encoding.UTF8, "application/json");

            try
            {
                var response = worker.Sender.PostAsync(new Uri(new Uri(worker.IpAddress), "api/Vote"), content).Result;
                return(response.Content.ReadAsStringAsync().Result);
            }
            catch (Exception e)
            {
                return("Error connection to Node" + e.Message);
            }
        }
        public bool CancelContract(int id, string reason)
        {
            logger.Info("Start Service to cancel a contract...");

            Contract con = new Contract();

            //Distributor dis = new Distributor();

            con        = Get(id);
            con.status = false;
            con.note   = reason;
            Distributor dis = con.Distributor1;

            dis.status = false;
            dis.debt   = 0;
            dis.note   = "Chấm dứt hợp đồng";

            bool result = true;

            try
            {
                repo_con.Update(con);
                repo_dis.Update(dis);
                service_account.UpdateStatus(dis.UserName, dis.note, false);
                uow.SaveChange();
            }
            catch (Exception ex)
            {
                logger.Info(ex.Message);
                result = false;
            }
            return(result);
        }
        public NodeRegResponse RegistrationAction(RegistrationMessage message)
        {
            var nodeMessage = new NodeRegMessage {
                Message = message
            };

            NodeData worker;
            var      neighbors = Distributor.FormateNodeList(3, out worker);

            nodeMessage.NeighBours = neighbors;

            var serializedMessage = JsonConvert.SerializeObject(nodeMessage);
            var content           = new StringContent(serializedMessage, Encoding.UTF8, "application/json");

            try
            {
                var response         = worker.Sender.PostAsync(new Uri(new Uri(worker.IpAddress), "api/Register"), content).Result.Content.ReadAsStringAsync();
                var responseFromNode = JsonConvert.DeserializeObject <NodeRegResponse>(response.Result);
                return(responseFromNode);
            }
            catch (AggregateException e)
            {
                return(new NodeRegResponse {
                    Status = false, Message = "Eroare de connectare la server LB:" + e.InnerException.ToString(), ProcessedTime = DateTime.Now
                });
            }
        }
        public async Task InsertDistributorWithFieldForceAsync()
        {
            Distributor distributor = new Distributor()
            {
                Address = "9420 Key West Avenue", CreatedBy = "Unit Test", Code = "D1", Name = "DrFirst"
            };
            FieldForce fieldForce = new FieldForce()
            {
                Code = "F1", CreatedBy = "Unit Test", Address = new FieldForceAddress()
                {
                    AddressLine1 = "7101 Richmond Hwy", CreatedBy = "Unit Test", City = "Alexandria", State = "VA", Zip = "22306", AddressLine2 = "Apt 2"
                }, Name = "Faisal Ahmed", Phone = "571-409-8588"
            };

            distributor.FieldForces.Add(fieldForce);

            UnitOfWork.Distributors.Add(distributor);

            await UnitOfWork.CompleteAsync();

            Distributor dbDistributor = UnitOfWork.Distributors.Get(distributor.Id);

            Assert.IsNotNull(dbDistributor);

            Assert.AreEqual(distributor.Code, dbDistributor.Code);
            Assert.AreEqual(distributor.Name, dbDistributor.Name);
            Assert.IsTrue(dbDistributor.FieldForces.Count > 0);
            Assert.AreEqual(dbDistributor.FieldForces[0].Code, fieldForce.Code);
            Assert.AreEqual(dbDistributor.FieldForces[0].Name, fieldForce.Name);
        }
Example #7
0
        public async Task <ActionResult> DeleteConfirmed(int?id)
        {
            if (id == null)
            {
                return(Json(new { success = false, Response = "", Error = "Id is null, please provide it in the request." }, JsonRequestBehavior.AllowGet));
            }

            var errorMessage = "";
            var distributor  = new Distributor();

            if (!IdentityHelper.TryGetDistributor(User, out distributor, out errorMessage))
            {
                return(Json(new { success = false, Response = "", Error = errorMessage }, JsonRequestBehavior.AllowGet));
            }

            try
            {
                _postAdapter.Delete(id.Value, distributor);

                return(Json(new { success = true, Response = "", Error = "" }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception exception)
            {
                return(Json(new { success = false, Response = "", Error = exception.Message }, JsonRequestBehavior.AllowGet));
            }
        }
        public async Task <JsonResult> PublishCampaign(int?campaignId)
        {
            if (campaignId == null)
            {
                return(Json(new { success = false, Response = "", Error = "Id is null, please provide it in the request." }, JsonRequestBehavior.AllowGet));
            }

            var errorMessage = "";
            var distributor  = new Distributor();

            if (!IdentityHelper.TryGetDistributor(User, out distributor, out errorMessage))
            {
                return(Json(new { success = false, Response = "", Error = errorMessage }, JsonRequestBehavior.AllowGet));
            }

            try
            {
                if (await _campaignAdapter.TryPublishCampaign(campaignId.Value, distributor))
                {
                    return(Json(new { success = true, Response = "Campaign is on the way to the advocates.", Error = "" }, JsonRequestBehavior.AllowGet));
                }

                return(Json(new { success = false, Response = "", Error = "Campaing could not be sent, see logs." }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception exception)
            {
                return(Json(new { success = false, Response = "", Error = exception.Message }, JsonRequestBehavior.AllowGet));
            }
        }
Example #9
0
        private void btnEditLoginPassword_Click(object sender, EventArgs e)
        {
            Distributor user = SubsiteStoreHelper.GetDistributor();

            if (string.IsNullOrEmpty(txtOldPassword.Text))
            {
                ShowMsg("旧登录密码不能为空", false);
            }
            else if ((string.IsNullOrEmpty(txtNewPassword.Text) || (txtNewPassword.Text.Length > 20)) || (txtNewPassword.Text.Length < 6))
            {
                ShowMsg("新登录密码不能为空,长度限制在6-20个字符之间", false);
            }
            else if (txtNewPassword.Text != txtPasswordCompare.Text)
            {
                ShowMsg("两次输入的密码不一致", false);
            }
            else if (user.ChangePassword(txtOldPassword.Text, txtNewPassword.Text))
            {
                Messenger.UserPasswordChanged(user, txtNewPassword.Text);
                user.OnPasswordChanged(new UserEventArgs(user.Username, txtNewPassword.Text, null));
                ShowMsg("登录密码修改成功", true);
            }
            else
            {
                ShowMsg("登录密码修改失败", false);
            }
        }
Example #10
0
 public Counterman(Distributor manager, float min, float max, GridType type)
 {
     this.min     = min;
     this.max     = max;
     this.manager = manager;
     this.type    = type;
 }
Example #11
0
        public void FullTestModification()
        {
            MockRepository   mock        = new MockRepository();
            IQuoteRepository mockedRepos = mock.CreateMock <IQuoteRepository>();

            Quote q = new Quote();

            Distributor expDistributor = new Distributor();

            expDistributor.AddContact("Sebastian", "Real", "*****@*****.**");
            expDistributor.AddContact("Emiliano", "Galizio", "*****@*****.**");
            expDistributor.AddContact("Santiago", "Lanus", "*****@*****.**");

            q.Distributor = expDistributor;

            foreach (Contact contact in expDistributor.Contacts)
            {
                q.AddNotification(contact, string.Empty, string.Empty);
            }

            Expect.Call(mockedRepos.GetById(12)).Return(q);
            mock.ReplayAll();
            QuoteController qc = new QuoteController(mockedRepos);

            Quote test = qc.GetById(12);

            test.AddNotification(null, "Alejandro Bezares", "*****@*****.**");

            Assert.AreEqual(4, test.QuoteNotifications.Count);
        }
Example #12
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack || string.IsNullOrEmpty(Request.QueryString["Id"]))
            {
                return;
            }

            Distributor d = ControllerManager.Distributor.GetById(Convert.ToInt32(Request.QueryString["Id"]));

            if (d != null && d.PriceList != null)
            {
                PublishList pl = ControllerManager.PublishList.GetCurrentList(d.PriceList.ID);
                if (pl != null)
                {
                    PriceMasterList1.PublishListID = pl.ID;
                }

                PriceMasterList1.DistributorID = d.ID;
                PriceMasterList1.DataBind();
            }
            else
            {
                PriceMasterList1.Visible = false;
                lblNoPriceList.Visible   = true;
            }
        }
Example #13
0
        public DistributorUserModel(DistributorUser distributorUser, Distributor distributor)
        {
            _distributorUser = distributorUser;
            _distributor     = distributor;

            Roles = distributorUser.Roles.Select(x => x.DisplayName).ToList();
        }
Example #14
0
        public async Task <ActionResult> Create([Bind(Include = "Id,DistributorId,PostTitle,PostMessage,MediaType,OriginalMediaLink,ThumbnailLink")] PostViewModel postViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(Json(new { success = false, Response = "", Error = ErrorHelper.GetModelStateErrorMessages(ModelState) }, JsonRequestBehavior.AllowGet));
            }

            var errorMessage = "";
            var distributor  = new Distributor();

            if (!IdentityHelper.TryGetDistributor(User, out distributor, out errorMessage))
            {
                return(Json(new { success = false, Response = "", Error = errorMessage }, JsonRequestBehavior.AllowGet));
            }

            try
            {
                //uploading post photo to azure storage.
                string url = ConnectToAzure.UploadPostImage(postViewModel.DistributorId, postViewModel.Id, Request.Files[0].FileName, Request.Files[0].InputStream);
                postViewModel.OriginalMediaLink = url;

                var createdPost = _postAdapter.Create(postViewModel, distributor);
                return(Json(new { success = true, Response = createdPost, Error = "" }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception exception)
            {
                return(Json(new { success = false, Response = "", Error = exception.Message }, JsonRequestBehavior.AllowGet));
            }
        }
Example #15
0
 public void UpdateDistributor(Distributor distributor)
 {
     try
     {
         using (IMDBEntities7 dbContext = new IMDBEntities7())
         {
             var fest = dbContext.Distributors.Where(b => b.Id == distributor.Id).FirstOrDefault();
             if (fest != null)
             {
                 fest.Name    = distributor.Name;
                 fest.Deleted = distributor.Deleted;
                 dbContext.Entry(fest).State = EntityState.Modified;
                 dbContext.SaveChanges();
             }
         }
     }
     catch (SqlException ex)
     {
         System.Diagnostics.Debug.WriteLine("Sql Exception:" + ex.Message);
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.WriteLine("Exception" + ex.Message);
     }
 }
Example #16
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["Id"]))
                {
                    int         distributorId = Convert.ToInt32(Request.QueryString["Id"]);
                    Distributor d             = ControllerManager.Distributor.GetById(distributorId);


                    if (d.PriceList != null)
                    {
                        if (d.PriceList.CategoryPages.Count > 0)
                        {
                            IList <CatalogPage> lst = new List <CatalogPage>();
                            foreach (CatalogPage cp in d.PriceList.CategoryPages)
                            {
                                lst.Add(cp);
                            }

                            rpterDistributors.DataSource = lst;
                            rpterDistributors.DataBind();
                        }
                        else
                        {
                            litNoItems.Visible = true;
                        }
                    }
                    else
                    {
                        litNoItems.Visible = true;
                    }
                }
            }
        }
        internal async Task <VoteLbResponse> VoteAction(ChooserLbMessage chooser)
        {
            var distribuitor = new Distributor(new VoteSender());

            distribuitor.FormateNodeList(3);
            var message = distribuitor.FormateMessage(chooser);

            var response = await distribuitor.Send(distribuitor.Executor, message);

            try
            {
                var voteresponse = JsonConvert.DeserializeObject <NodeVoteResponse>(response);
                return(new VoteLbResponse
                {
                    Status = voteresponse.Status,
                    Block = voteresponse.Block,
                    Message = voteresponse.Message,
                    ProcessedTime = voteresponse.ProcessedTime
                });
            }
            catch (AggregateException ex)
            {
                return(new VoteLbResponse {
                    Status = false, Message = "Eroare de conectare la server LB:" + ex.InnerException.ToString(), ProcessedTime = DateTime.Now
                });
            }
        }
        public void DistributeAsync_DistributesMultipleAtATimeByDefault()
        {
            var distributable1 = new FakeDistributable();
            var distributable2 = new FakeDistributable();
            var recipient = new FakeRecipient();
            var endpoint = new FakeEndpoint();

            var distributor = new Distributor<FakeDistributable, FakeRecipient>();

            var deliverer = new FakeLoggedDeliverer<FakeDistributable, FakeEndpoint>(new TimeSpan(0, 0, 0, 0, 100));

            var endpointRepository = new Mock<IEndpointRepository<FakeRecipient>>();
            endpointRepository.Setup(e => e.GetEndpointsForRecipient(recipient))
                .Returns(new[] { endpoint });

            distributor.RegisterDeliverer(deliverer);
            distributor.RegisterEndpointRepository(endpointRepository.Object);

            var task1 = distributor.DistributeAsync(distributable1, recipient);
            var task2 = distributor.DistributeAsync(distributable2, recipient);

            Task.WaitAll(task1, task2);

            var lastStartTime = deliverer.LogEntries.Max(e => e.StartDateTime);
            var firstEndTime = deliverer.LogEntries.Min(e => e.EndDateTime);

            lastStartTime.ShouldBeLessThan(firstEndTime);
        }
Example #19
0
        public ActionResult Dist_Deal(bool isDistributor = true)
        {
            Distributor    oDist = new Distributor();
            clsSubmitModel oCon  = new clsSubmitModel();

            var vwCate = from a in db.tblDistributors where a.DistributorID == 0 select new { a.DisName, a.MstCode };

            ViewBag.vwDistributor = new SelectList(vwCate, "MstCode", "DisName");

            ViewBag.isDistributor = isDistributor;

            var vwState = from a in db.citydets where a.cityType == 67 && a.cityrute == 3 orderby a.cityname select new { a.citycode, a.cityname };

            ViewBag.vwState = new SelectList(vwState, "citycode", "cityname");

            if (isDistributor == true)
            {
                oDist.Dis_ID = (db.tblDistributors.Where(x => x.DistributorID == 0).Count()).ToString();
            }
            else
            {
                oDist.Dis_ID = (db.tblDistributors.Where(x => x.DistributorID != 0).Count()).ToString();
            }

            oDist.IsDistributor = isDistributor;

            oDist.lstBrand   = oCon.GetList(61);
            oDist.lstProduct = oCon.GetProduct();
            return(View(oDist));
        }
Example #20
0
        public void Find_WithoutExplicitType()
        {
            Distributor distributor = _transaction.ExecuteInScope(() => Distributor.NewObject());

            Assert.That(distributor.Properties.Contains(typeof(Distributor).FullName + ".ContactPerson"), Is.False);
            Assert.That(distributor.Properties.Find("ContactPerson"), Is.EqualTo(distributor.Properties[typeof(Partner), "ContactPerson"]));
        }
Example #21
0
        // GET: Posts/Details/5
        public async Task <JsonResult> Details(int?id)
        {
            if (id == null)
            {
                throw new ArgumentNullException("Id");
            }

            var errorMessage = "";
            var distributor  = new Distributor();

            if (!IdentityHelper.TryGetDistributor(User, out distributor, out errorMessage))
            {
                return(Json(new { success = false, Response = "", Error = errorMessage }, JsonRequestBehavior.AllowGet));
            }

            try
            {
                var post = _postAdapter.GetById(id.Value, distributor);
                return(Json(new { success = true, Response = post }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception exception)
            {
                return(Json(new { success = false, Response = "", Error = exception.Message }, JsonRequestBehavior.AllowGet));
            }
        }
Example #22
0
        private SeriesItem MapDictionaryToSeriesItem(Dictionary <string, string> seriesItemPairs)
        {
            SeriesItem item = new SeriesItem();

            item.Title = seriesItemPairs["Title"];

            if (seriesItemPairs.ContainsKey("Distributor"))
            {
                string distName = seriesItemPairs["Distributor"];
                if (distName.Contains("Bandai Ent", StringComparison.OrdinalIgnoreCase))
                {
                    distName = "Bandai Visual";
                }

                Distributor distributor = _distributors.Find(x => x.DistributorName.Contains(distName, StringComparison.OrdinalIgnoreCase));
                item.Distributors = new List <Distributor>
                {
                    distributor
                };
            }

            if (seriesItemPairs.ContainsKey("Run Time"))
            {
                item.Length = seriesItemPairs["Run Time"];
            }

            if (seriesItemPairs.ContainsKey("Release Date"))
            {
                DateTime.TryParse(seriesItemPairs["Release Date"], out DateTime releaseDate);
                item.ReleaseDate = releaseDate;
            }

            return(item);
        }
Example #23
0
        /// <summary>
        /// 发送HTTP请求
        /// </summary>
        /// <returns></returns>
        protected string SendHttpRequest()
        {
            string responseStr;

            Distributor distributor = SubsiteStoreHelper.GetDistributor();

            SiteSettings masterSettings = SettingsManager.GetMasterSettings(false);

            WebRequest request = WebRequest.Create("http://saas.92hi.com/CreateDistributors.aspx");

            request.Method = "POST";

            request.ContentType = "application/x-www-form-urlencoded";

            string args = "Host=" + masterSettings.SiteUrl + "&DistributorUserId=" + distributor.UserId + "&Email=" + Page.Server.UrlEncode(distributor.Email) + "&RealName=" + Page.Server.UrlEncode(distributor.RealName) + "&CompanyName=" + Page.Server.UrlEncode(distributor.CompanyName) + "&Address=" + Page.Server.UrlEncode(distributor.Address) + "&TelPhone=" + Page.Server.UrlEncode(distributor.TelPhone) + "&QQ=" + Page.Server.UrlEncode(distributor.QQ) + "&Wangwang=" + Page.Server.UrlEncode(distributor.Wangwang);

            byte[] bytes = new ASCIIEncoding().GetBytes(args);

            request.ContentLength = bytes.Length;

            //写数据
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(bytes, 0, bytes.Length);
            }

            //读数据
            using (StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.Default))
            {
                responseStr = reader.ReadToEnd();
            }

            return(responseStr);
        }
        public void Create(DistributorCreate distributorCreate)
        {
            try
            {
                Distributor distributorToAdd = new Distributor
                {
                    IsLocked = false,
                    Counter  = 0,
                    //TankDistributors = new List<TankDistributor>()
                };

                _context.Add(distributorToAdd);
                _context.SaveChanges();

                //if (distributorCreate.TankIds == null) distributorCreate.TankIds = new List<int>();

                foreach (int tankId in distributorCreate.TankIds)
                {
                    TankDistributor td = _tankDistributorService.Create(tankId, distributorToAdd.DistributorId);
                    distributorToAdd.TankDistributors.Add(td);
                    _tankService.GetById(tankId).TankDistributors.Add(td);
                }

                _context.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
Example #25
0
        public Distributor GetDistributor(Int64 Id = 0)
        {
            Distributor        d     = null;
            List <ProgramType> PT    = null;
            DynamicParameters  param = new DynamicParameters();

            param.Add("@Id", Id, DbType.Int64);
            using (IDbConnection conn = factory.GetConnection())
            {
                conn.Open();
                string SQL = @"[USP_GetDistributor]";
                d = conn.Query <Distributor>(SQL, param, commandType: CommandType.StoredProcedure).FirstOrDefault <Distributor>();

                using (var multi = conn.QueryMultiple("[USP_GetDistributorProgramType]", new { @DistributorId = Id }, commandType: CommandType.StoredProcedure))
                {
                    PT = multi.Read <ProgramType>().ToList();
                }
                if (d != null)
                {
                    if (PT != null)
                    {
                        d.ProgramTypes = PT;
                    }
                }
            }
            return(d);
        }
        public bool Update([FromBody] Distributor _oDistributor)
        {
            try
            {
                int output;
                using (var context = new DB001Core())
                {
                    var input = context.Distributors
                                .Where(w => w.DistributorID == _oDistributor.DistributorID)
                                .FirstOrDefault();

                    input.DistributorName = _oDistributor.DistributorName;
                    input.Email           = _oDistributor.Email;
                    input.MobileNo        = _oDistributor.MobileNo;
                    input.Address         = _oDistributor.Address;
                    input.IsActive        = _oDistributor.IsActive;
                    input.CityID          = _oDistributor.CityID;
                    input.DistrictID      = _oDistributor.DistrictID;
                    input.StateID         = _oDistributor.StateID;
                    input.ModifiedOn      = DateTime.Now;

                    output = context.SaveChanges();
                }
                return(Convert.ToBoolean(output));
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                context = null;
            }
        }
Example #27
0
        public async Task <ActionResult> Edit([Bind(Include = "Id,DistributorId,PostTitle,PostMessage,MediaType,OriginalMediaLink,ThumbnailLink")] PostViewModel postViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(Json(new { success = false, Response = "", Error = ErrorHelper.GetModelStateErrorMessages(ModelState) }, JsonRequestBehavior.AllowGet));
            }

            var errorMessage = "";
            var distributor  = new Distributor();

            if (!IdentityHelper.TryGetDistributor(User, out distributor, out errorMessage))
            {
                return(Json(new { success = false, Response = "", Error = errorMessage }, JsonRequestBehavior.AllowGet));
            }

            try
            {
                _postAdapter.Update(postViewModel, distributor);

                return(Json(new { success = true, Response = postViewModel, Error = "" }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception exception)
            {
                return(Json(new { success = false, Response = "", Error = exception.Message }, JsonRequestBehavior.AllowGet));
            }
        }
Example #28
0
        /// <summary>
        /// 分销商列表信息
        /// </summary>
        /// <param name="manaDTO"></param>
        /// <returns></returns>
        public ManageDTO ManageInfoExt(ManageVM manaDTO)
        {
            ManageDTO result = new ManageDTO();

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

            if (manaDTO.Ynos == 1 && manaDTO.ParentId != Guid.Empty)
            {
                var parent = Distributor.ObjectSet().FirstOrDefault(c => c.Id == manaDTO.ParentId);
                if (parent != null)
                {
                    var tuple = CBCSV.GetUserNameAndCode(parent.UserId);
                    result.ParentName = tuple.Item1;
                    result.ParentCode = tuple.Item2;
                }
            }
            var resultData = DSSBP.Instance.ManageInfo(manaDTO);

            if (resultData != null && resultData.Data != null)
            {
                result.Count   = resultData.Data.Count;
                result.Manager = resultData.Data.Manager;
            }

            LogHelper.Info(
                string.Format("DistributeBP.ManageInfoExt(AppId='{0}',ParentId='{1}'),返回:Count={2},Manager.Count={3}。",
                              manaDTO.AppId, manaDTO.ParentId, result.Count, result.Manager.Count));

            return(result);
        }
 public JObject Get(ObjectId Id)
 {
     try
     {
         var queryable = DistributorsCollection.AsQueryable();
         var query     = from p in queryable
                         where p.Id.Equals(Id)
                         select p;
         Distributor distributor = query.FirstOrDefault();
         return
             (JObject.FromObject(
                  new
         {
             status = "success",
             result = distributor
         }
                  ));
     }
     catch (Exception ex)
     {
         return
             (JObject.FromObject(
                  new
         {
             status = "Exception Thrown",
             result = false,
             message = ex.Message
         }
                  ));
     }
 }
Example #30
0
        public async Task <ActionResult <Distributor> > PostDistributor(Distributor distributor)
        {
            _context.Distributor.Add(distributor);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetDistributor", new { id = distributor.DistributorId }, distributor));
        }
Example #31
0
        public async Task <IActionResult> PutDistributor(int id, Distributor distributor)
        {
            if (id != distributor.DistributorId)
            {
                return(BadRequest());
            }

            _context.Entry(distributor).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!DistributorExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Example #32
0
        private static void Main(string[] args)
        {
            //Configure the distributor
            var distributor = new Distributor<File, Vendor>();
            distributor.RegisterEndpointRepository(new FileSystemEndpointRepository());
            distributor.RegisterEndpointRepository(new SharepointEndpointRepository());
            distributor.RegisterDeliverer(new FileSystemDeliverer());
            distributor.RegisterDeliverer(new SharepointDeliverer());
            distributor.MaximumConcurrentDeliveries(3);

            //Distribute a file to a vendor
            try
            {
                var task = distributor.DistributeAsync(FakeFile, FakeVendor);
                task.Wait();

                Console.WriteLine("\nDistribution succeeded.");
            }
            catch(AggregateException aggregateException)
            {
                Console.WriteLine("\nDistribution failed.");

                foreach (var exception in aggregateException.Flatten().InnerExceptions)
                {
                    Console.WriteLine($"* {exception.Message}");
                }
            }

            Console.WriteLine("\nPress enter to exit.");

            Console.ReadLine();
        }
Example #33
0
 public void DistributeMessages_OneChannel_Ok()
 {
     Distributor distributor = new Distributor();
     distributor.InitiateDistributionMap(@"Data\distributormaplocal2local.xml", _componentResolver);
     ChangePublisher changePublisher = InitiateLocalPublisher();
     changePublisher.PublishPackage();
     MockAllTheSubscribers(distributor.AvailableChannels,changePublisher.PublishedPackageNotDistributed[0]);
     distributor.DistributeMessages();
     Assert.AreEqual(0, changePublisher.PublishedPackageNotDistributed.Count);
 }
Example #34
0
 public void ChannelGoesDownPermanentlyOnlyOneChanelLocal_Ok()
 {
     Distributor distributor = new Distributor();
     distributor.InitiateDistributionMap(@"Data\distributormap2.xml", _componentResolver);
     Assert.IsNotNull(distributor.AvailableChannels);
     Assert.AreEqual(1, distributor.AvailableChannels.Count(c => c.Status == Status.OfflineTemporary && c.NoOfFailedAttempts == 1));
     distributor.DistributeMessages();
     Assert.AreEqual(1, distributor.AvailableChannels.Count(c => c.Status == Status.OfflineTemporary && c.NoOfFailedAttempts == 2));
     distributor.DistributeMessages();
     Assert.AreEqual(1, distributor.AvailableChannels.Count(c => c.Status == Status.OfflineTemporary && c.NoOfFailedAttempts == 3));
     distributor.DistributeMessages();
     Assert.AreEqual(1, distributor.AvailableChannels.Count(c => c.Status == Status.OfflinePermanent && c.NoOfFailedAttempts == 3));
 }
Example #35
0
        public ActionResult Edit(int id)
        {
            WaitoDistributor distributor_db = new WaitoEntities().WaitoDistributors.Where( d => d.DistributorId == id).FirstOrDefault();

            Distributor distributor = new Distributor()
            {
                DistributorId = distributor_db.DistributorId,
                Title = distributor_db.Title,
                Description = distributor_db.Description,
                Address = distributor_db.Address,
                Phone = distributor_db.Phone
            };

            return View(distributor);
        }
        public void DistributeAsync_DeliversToAnEndpointTypeWithNoDelivererThrowsAnError()
        {
            var distributable = new FakeDistributable();
            var recipient = new FakeRecipient();
            var endpoint = new FakeEndpoint();

            var endpointRepository = new Mock<IEndpointRepository<FakeRecipient>>();
            endpointRepository.Setup(e => e.GetEndpointsForRecipient(recipient))
                .Returns(new[] { endpoint });

            var distributor = new Distributor<FakeDistributable, FakeRecipient>();
            distributor.RegisterEndpointRepository(endpointRepository.Object);

            Should.ThrowAsync<InvalidOperationException>(distributor.DistributeAsync(distributable, recipient));
        }
        public void DistributeAsync_DeliversADistributableToARegisteredDeliverer()
        {
            var distributable = new FakeDistributable();
            var recipient = new FakeRecipient();
            var endpoint = new FakeEndpoint();

            var deliverer = new Mock<IDeliverer<FakeDistributable, FakeEndpoint>>();
            var endpointRepository = new Mock<IEndpointRepository<FakeRecipient>>();
            endpointRepository.Setup(e => e.GetEndpointsForRecipient(recipient))
                .Returns(new [] { endpoint });

            var distributor = new Distributor<FakeDistributable, FakeRecipient>();
            distributor.RegisterEndpointRepository(endpointRepository.Object);
            distributor.RegisterDeliverer(deliverer.Object);

            distributor.DistributeAsync(distributable, recipient).Wait();

            deliverer.Verify(eds => eds.DeliverAsync(distributable, (IEndpoint) endpoint), Times.Once);
        }
Example #38
0
 public void BasicLoadingTestWithOneLocalChannelOneRemoteChannelAndOneMixedChannel_Ok()
 {
     Distributor distributor=new Distributor();
     distributor.InitiateDistributionMap(@"Data\distributormap.xml",_componentResolver);
     Assert.IsNotNull(distributor.AvailableChannels);
     Assert.AreEqual(1,
                     distributor.AvailableChannels.Count(
                         c =>
                         c.Status == Status.Ok && c.PublisherInfo.Port==0 &&
                         c.SubscriberInfo.Port==0));
     Assert.AreEqual(1,
                     distributor.AvailableChannels.Count(
                         c =>
                         c.Status == Status.Ok && c.PublisherInfo.Port==8765 &&
                         c.SubscriberInfo.Port==8766));
     Assert.AreEqual(1,
                     distributor.AvailableChannels.Count(
                         c =>
                         c.Status == Status.Ok && c.PublisherInfo.Port==0 &&
                         c.SubscriberInfo.Port == 8766));
 }
Example #39
0
        public ActionResult Edit(Distributor distributor)
        {
            if (ModelState.IsValid)
            {
                using (WaitoEntities entities = new WaitoEntities())
                {
                    WaitoDistributor distributor_db = entities.WaitoDistributors.Where(d => d.DistributorId == distributor.DistributorId).FirstOrDefault();

                    distributor_db.Title = distributor.Title;
                    distributor_db.Description = distributor.Description;
                    distributor_db.Address = distributor.Address;
                    distributor_db.Phone = distributor.Phone;

                    entities.SaveChanges();
                }

                return RedirectToAction("Index");
            }

            return View();
        }
Example #40
0
        private static void Main(string[] args)
        {
            //Register the Delivery Service for each Endpoint
            DeliveryServiceConfig.RegisterDeliveryServices(EndpointDeliveryServices.DeliveryServices);

            var distributables = new List<DistributableFile>
            {
                new DistributableFile
                {
                    Id = Guid.NewGuid(),
                    ProfileName = "TestProfile",
                    Name = "test.pdf",
                    Contents = null
                }
            };

            //Run the Distributor
            var distributor = new Distributor<DistributableFile>();
            distributor.Distribute(distributables);

            Console.ReadLine();
        }
Example #41
0
        public ActionResult Create(Distributor distributor)
        {
            if (ModelState.IsValid)
            {
                WaitoDistributor distributor_db = new WaitoDistributor()
                {
                    Title = distributor.Title,
                    Description = distributor.Description,
                    Address = distributor.Address,
                    Phone = distributor.Phone
                };

                using (WaitoEntities entities = new WaitoEntities())
                {
                    entities.WaitoDistributors.Add(distributor_db);
                    entities.SaveChanges();
                }

                return RedirectToAction("Index");
            }

            return View();
        }
Example #42
0
        public static void InsertOrUpdateDistributor(CanonDistributor newValue)
        {
            CanonDataContext db = Cdb.Instance;

            Distributor distributor = null;
            if (newValue.ID == -1)
            {
                distributor = new Distributor();
                db.Distributors.InsertOnSubmit(distributor);
            }
            else
            {
                distributor = db.Distributors.FirstOrDefault(d => d.ID == newValue.ID);
            }

            distributor.FileAs = newValue.FileAs;
            distributor.IDDistributorType = newValue.IDDistributorType;
            distributor.Note = newValue.Note;
            distributor.ShowInImports = newValue.ShowInImports;
            distributor.ShowInReports = newValue.ShowInReports;

            db.SubmitChanges();
        }
Example #43
0
 public void LoadDistributorNoResolver()
 {
     Distributor distributor = new Distributor();
     distributor.InitiateDistributionMap(@"Data\distributormap.xml", null);
 }
Example #44
0
 public void LoadDistributorWrongMapFile()
 {
     Distributor distributor = new Distributor();
     distributor.InitiateDistributionMap(@"Data\nonmap.xml", _componentResolver);
 }
Example #45
0
 public void LoadDistributorNoMapFile()
 {
     Distributor distributor = new Distributor();
     distributor.InitiateDistributionMap(null, _componentResolver);
 }
Example #46
0
 public void LoadDistributorNoRegisteredPublishers()
 {
     Distributor distributor = new Distributor();
     distributor.InitiateDistributionMap(@"Data\distributormap.xml", new ComponentResolver());
     Assert.AreEqual(0, distributor.AvailableChannels.Count(c => c.Status == Status.Ok));
 }
Example #47
0
 public void ListAllAvailableChannels_Ok()
 {
     Distributor distributor = new Distributor();
     distributor.InitiateDistributionMap(@"Data\distributormap.xml", _componentResolver);
     var compo = distributor.ListAvailableChannels();
     Assert.IsNotNull(compo);
     Assert.AreEqual(3,compo.Channels.Count);
     Assert.IsNotNull(compo.Channels[0].SubscriberInfo);
     Assert.IsNotNull(compo.Channels[1].SubscriberInfo);
     foreach(var c1 in compo.Channels)
     {
         Assert.AreEqual(Status.Ok,c1.Status);
     }
 }
Example #48
0
 public void ListAllComponents_AndRegisterMessages_Ok()
 {
     Distributor distributor = new Distributor();
     distributor.InitiateDistributionMap(@"Data\distributormap5.xml", _componentResolver);
     ChangePublisher changePublisher = (ChangePublisher)distributor.AvailableChannels
     .FirstOrDefault(c => c.PublisherInfo.Port==0).Publisher;
     var mockItemDiscoverer = MockTestHelper.MockItemDiscoverer("root folder");
     changePublisher.Initialize("root folder",mockItemDiscoverer);
     changePublisher.QueueInsert(@"root folder\Item One");
     changePublisher.QueueInsert(@"root folder\ItemTwo");
     changePublisher.PublishPackage();
     MockAllTheSubscribers(distributor.AvailableChannels, changePublisher.PublishedPackageNotDistributed[0]);
     distributor.DistributeMessages();
     var compo = distributor.ListAvailableChannels();
     Assert.IsNotNull(compo);
     Assert.AreEqual(1, compo.Channels.Count);
     Assert.IsNotNull(compo.Channels[0].SubscriberInfo);
     Assert.AreEqual(State.Done, compo.Channels[0].PublisherInfo.CurrentPackage.State);
     Assert.AreEqual(1, compo.Channels[0].PublisherInfo.CurrentPackage.PackageMessages.Count(m => m.AbsolutePath == @"root folder\Item One"));
     Assert.AreEqual(2, compo.Channels[0].PublisherInfo.CurrentPackage.PackageMessages.Count(m => m.OperationType==OperationType.Insert));
     Assert.AreEqual(State.Done, compo.Channels[0].SubscriberInfo.CurrentPackage.State);
 }
Example #49
0
 public void InitiateDistributionMap_OneRemoteSubscriber_notWorking()
 {
     Distributor distributor = new Distributor();
     distributor.InitiateDistributionMap(@"Data\distributormap4.xml", _componentResolver);
     Assert.IsNotNull(distributor.AvailableChannels);
     Assert.AreEqual(1, distributor.AvailableChannels.Count(c => c.Status == Status.OfflineTemporary && c.NoOfFailedAttempts == 1));
 }
Example #50
0
 public void GetCurrentMap_Ok()
 {
     Distributor distributor = new Distributor();
     distributor.InitiateDistributionMap(@"Data\distributormap.xml", _componentResolver);
     var distributorMap = distributor.GetCurrentMap();
     Assert.IsNotNull(distributorMap);
     Assert.IsNotNull(distributorMap);
     Assert.AreEqual(3,distributorMap.Count());
 }
Example #51
0
 public void GetCurrentMap_Ex()
 {
     Distributor distributor = new Distributor();
     var distributorMap = distributor.GetCurrentMap();
     Assert.IsNull(distributorMap);
 }
        public void DistributeAsync_DoesNotUseTheFirstDelivererWhenTwoAreRegistered()
        {
            var distributable = new FakeDistributable();
            var recipient = new FakeRecipient();
            var endpoint = new FakeEndpoint();

            var deliverer1 = new Mock<IDeliverer<FakeDistributable, FakeEndpoint>>();
            var deliverer2 = new Mock<IDeliverer<FakeDistributable, FakeEndpoint>>();
            var endpointRepository = new Mock<IEndpointRepository<FakeRecipient>>();
            endpointRepository.Setup(e => e.GetEndpointsForRecipient(recipient))
                .Returns(new[] { endpoint });

            var distributor = new Distributor<FakeDistributable, FakeRecipient>();
            distributor.RegisterEndpointRepository(endpointRepository.Object);
            distributor.RegisterDeliverer(deliverer1.Object);
            distributor.RegisterDeliverer(deliverer2.Object);

            distributor.DistributeAsync(distributable, recipient).Wait();

            deliverer1.Verify(eds => eds.DeliverAsync(distributable, (IEndpoint) endpoint), Times.Never);
        }
        public void IdentityTest()
        {
            using (VehicleDbContext context = new VehicleDbContext())
              {
            if (context.Database.Exists()) context.Database.Delete();
            context.Database.CreateIfNotExists();

            // Identity as Guid
            Manufacturer nissan = new Manufacturer
            {
              Name = "Nissan"
            };
            Manufacturer ford = new Manufacturer
            {
              Name = "Ford"
            };
            context.Manufacturers.Add(nissan);
            context.Manufacturers.Add(ford);

            // Identity as Integer
            Distributor dis1 = new Distributor
            {
              Name = "Distributor1"
            };
            Distributor dis2 = new Distributor
            {
              Name = "Distributor2"
            };
            context.Distributors.Add(dis1);
            context.Distributors.Add(dis2);

            context.SaveChanges();

            using (MySqlConnection conn = new MySqlConnection(context.Database.Connection.ConnectionString))
            {
              conn.Open();

              // Validates Guid
              MySqlCommand cmd = new MySqlCommand("SELECT * FROM Manufacturers", conn);
              MySqlDataReader dr = cmd.ExecuteReader();
              if (!dr.HasRows)
            Assert.Fail("No records found");
              while (dr.Read())
              {
            string name = dr.GetString(1);
            switch (name)
            {
              case "Nissan":
                Assert.AreEqual(dr.GetGuid(0), nissan.ManufacturerId);
                Assert.AreEqual(dr.GetGuid(2), nissan.GroupIdentifier);
                break;
              case "Ford":
                Assert.AreEqual(dr.GetGuid(0), ford.ManufacturerId);
                Assert.AreEqual(dr.GetGuid(2), ford.GroupIdentifier);
                break;
              default:
                Assert.Fail();
                break;
            }
              }
              dr.Close();

              // Validates Integer
              cmd = new MySqlCommand("SELECT * FROM Distributors", conn);
              dr = cmd.ExecuteReader();
              if (!dr.HasRows)
            Assert.Fail("No records found");
              while (dr.Read())
              {
            string name = dr.GetString(1);
            switch (name)
            {
              case "Distributor1":
                Assert.AreEqual(dr.GetInt32(0), dis1.DistributorId);
                break;
              case "Distributor2":
                Assert.AreEqual(dr.GetInt32(0), dis2.DistributorId);
                break;
              default:
                Assert.Fail();
                break;
            }
              }
              dr.Close();
            }
              }
        }
Example #54
0
        public void DsitributeMessages_OnepublisherThreeChannels_OneNotPresentOneFailing()
        {
            Distributor distributor = new Distributor();
            distributor.InitiateDistributionMap(@"Data\distributormaplocal2localandremoteNP.xml", _componentResolver);

            ChangePublisher changePublisher = InitiateLocalPublisher();

            distributor.DistributeMessages();
            Assert.AreEqual(1, changePublisher.PublishedPackageNotDistributed.Count);
            Assert.AreEqual(2, changePublisher.PublishedPackageNotDistributed[0].ChangePushItems.Count);
        }
        private void FixupnpDistributor(Distributor previousValue, bool skipKeys = false)
        {
            if (IsDeserializing)
            {
                return;
            }

            if (previousValue != null && previousValue.npWarehouse.Contains(this))
            {
                previousValue.npWarehouse.Remove(this);
            }

            if (npDistributor != null)
            {
                if (!npDistributor.npWarehouse.Contains(this))
                {
                    npDistributor.npWarehouse.Add(this);
                }

                DistributorID = npDistributor.DistributorID;
            }
            else if (!skipKeys)
            {
                DistributorID = null;
            }

            if (ChangeTracker.ChangeTrackingEnabled)
            {
                if (ChangeTracker.OriginalValues.ContainsKey("npDistributor")
                    && (ChangeTracker.OriginalValues["npDistributor"] == npDistributor))
                {
                    ChangeTracker.OriginalValues.Remove("npDistributor");
                }
                else
                {
                    ChangeTracker.RecordOriginalValue("npDistributor", previousValue);
                }
                if (npDistributor != null && !npDistributor.ChangeTracker.ChangeTrackingEnabled)
                {
                    npDistributor.StartTracking();
                }
            }
        }
 public void Init ()
 {
     Distributor = new Distributor(new IExternalSource[] { new FakeExternalSource() , new AnotherFakeExternalSource() }, new[] {new FakeRuleStore()});
     Distributor.ExternalSources.First().StateChanges.Subscribe(e => Debug.WriteLine(e.Connection.Name + " " + e.NewState.Name));
 }
 public void Init()
 {
     FakeExternalSource = new FakeExternalSource();
     AnotherFakeExternalSource = new AnotherFakeExternalSource();
     Distributor = new Distributor(new IExternalSource[] { FakeExternalSource, AnotherFakeExternalSource }, new[] { new FakeRuleStore() });
 }