public void Before_each_test()
            {
                //ServicesRepository servicesRepository = new ServicesRepository(new ScutexEntities());
                //CommonRepository commonRepository = new CommonRepository(new ScutexServiceEntities());

                AsymmetricEncryptionProvider asymmetricEncryptionProvider = new AsymmetricEncryptionProvider();
                SymmetricEncryptionProvider symmetricEncryptionProvider = new SymmetricEncryptionProvider();
                ObjectSerializationProvider objectSerializationProvider = new ObjectSerializationProvider();
                NumberDataGenerator numberDataGenerator = new NumberDataGenerator();
                PackingService packingService = new PackingService(numberDataGenerator);
                MasterService masterService = new MasterService(commonRepository);

                CommonService commonService = new CommonService();
                KeyPairService keyPairService = new KeyPairService(commonService, commonRepository);

                ServiceStatusProvider serviceStatusProvider = new ServiceStatusProvider(symmetricEncryptionProvider, objectSerializationProvider, asymmetricEncryptionProvider);
                servicesService = new ServicesService(servicesRepository, serviceStatusProvider, packingService, null, null, null, null, null, null);

                controlService = new ControlService(symmetricEncryptionProvider, keyPairService, packingService, masterService, objectSerializationProvider, asymmetricEncryptionProvider);

                service = new Scutex.Model.Service();
                service.OutboundKeyPair = asymmetricEncryptionProvider.GenerateKeyPair(BitStrengths.High);
                service.InboundKeyPair = asymmetricEncryptionProvider.GenerateKeyPair(BitStrengths.High);
                service.ManagementInboundKeyPair = asymmetricEncryptionProvider.GenerateKeyPair(BitStrengths.High);
                service.ManagementOutboundKeyPair = asymmetricEncryptionProvider.GenerateKeyPair(BitStrengths.High);
            }
Пример #2
0
 public JsonResult CreateUsers(List<User> users,string type="",string role="")
 {
     var common = new CommonService();
     ViewBag.Role = role;
     common.OnRenderPartialViewToString += (model) => {
         var result = string.Empty;
         try
         {
             result = this.RenderPartialViewToString("P_Email_Input", model);
         }
         catch (Exception)
         {
             common.success = false;
             common.message = Constants.DefaultExceptionMessage;
         }
         return result;
     };
     common.OnRenderSubPartialViewToString += (model) =>
     {
         var result = string.Empty;
         try
         {
             result = this.RenderPartialViewToString("P_Email_Input_Item", model);
         }
         catch (Exception)
         {
             common.success = false;
             common.message = Constants.DefaultExceptionMessage;
         }
         return result;
     };
     common.CreateUsers(users,type);
     return Json(new {common.message,common.success,common.resultlist,common.generatedHtml });
 }
 public ActionResult Create()
 {
     db = new dbTIREntities();
     siteUser = ((SiteUser)Session["SiteUser"]);
     commonService = new CommonService(siteUser, db);
     WeightingViewModel model = new WeightingViewModel();
     FillDropDowns(model);
     return View(model);
 }
Пример #4
0
 public Delivery(CommonService.Engine.CTYPE t, List<string> P)
 {
     type = t;
     cmd = P[0];
     if (P.Count > 1)
     {
         id = P[1];
     }
 }
            public void Before_each_test()
            {
                clientLicenseRepoistory = new ClientLicenseRepository(objectSerializationProvider, symmetricEncryptionProvider);
                clientLicenseService = new ClientLicenseService(clientLicenseRepoistory);
                serviceProductsRepository = new ServiceProductsRepository(new ScutexServiceEntities());
                symmetricEncryptionProvider = new SymmetricEncryptionProvider();
                asymmetricEncryptionProvider = new AsymmetricEncryptionProvider();
                hashingProvider = new HashingProvider();
                objectSerializationProvider = new ObjectSerializationProvider();
                numberDataGenerator = new NumberDataGenerator();
                packingService = new PackingService(numberDataGenerator);
                commonRepository = new CommonRepository(new ScutexServiceEntities());
                clientRepository = new ClientRepository(new ScutexServiceEntities());
                keyGenerator = new KeyGenerator(symmetricEncryptionProvider, asymmetricEncryptionProvider, hashingProvider);
                masterService = new MasterService(commonRepository);
                activationLogRepository = new ActivationLogRepoistory(new ScutexServiceEntities());

                activationLogService = new ActivationLogService(activationLogRepository, hashingProvider);
                keyService = new KeyManagementService(clientRepository, licenseKeyService, activationLogService, hashingProvider, serviceProductsRepository);
                commonService = new CommonService();

                string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
                path = path.Replace("file:\\", "");

                var mockCommonService = new Mock<ICommonService>();
                mockCommonService.Setup(common => common.GetPath()).Returns(path + "\\Data\\Client\\");

                string masterServiceDataText;

                using (TextReader reader = new StreamReader(path + "\\Data\\MasterService.dat"))
                {
                    masterServiceDataText = reader.ReadToEnd().Trim();
                }

                masterServiceData = objectSerializationProvider.Deserialize<MasterServiceData>(masterServiceDataText);

                var mockCommonRepository = new Mock<ICommonRepository>();
                mockCommonRepository.Setup(repo => repo.GetMasterServiceData()).Returns(masterServiceData);

                keyPairService = new KeyPairService(mockCommonService.Object, mockCommonRepository.Object);
                controlService = new ControlService(symmetricEncryptionProvider, keyPairService, packingService, masterService, objectSerializationProvider, asymmetricEncryptionProvider);
                servicesRepository = new ServicesRepository(new ScutexEntities());
                serviceStatusProvider = new ServiceStatusProvider(symmetricEncryptionProvider, objectSerializationProvider, asymmetricEncryptionProvider);
                licenseActiviationProvider = new LicenseActiviationProvider(asymmetricEncryptionProvider, symmetricEncryptionProvider, objectSerializationProvider);
                servicesService = new ServicesService(servicesRepository, serviceStatusProvider, packingService, licenseActiviationProvider, null, null, null, null, null);
                licenseKeyService = new LicenseKeyService(keyGenerator, packingService, clientLicenseService);
                activationService = new ActivationService(controlService, keyService, keyPairService, objectSerializationProvider, asymmetricEncryptionProvider, null, null);

                string serviceData;

                using (TextReader reader = new StreamReader(path + "\\Data\\Service.dat"))
                {
                    serviceData = reader.ReadToEnd().Trim();
                }

                service = objectSerializationProvider.Deserialize<Service>(serviceData);
            }
 public ActionResult Index()
 {
     db = new dbTIREntities();
     siteUser = ((SiteUser)Session["SiteUser"]);
     assScoreService = new AssessmentScoreService(siteUser, db);
     commonService = new CommonService(siteUser, db);
     AssessmentScoreViewModel model = new AssessmentScoreViewModel();
     model.DistrictName = siteUser.Districts[0].Name;
     model.DistrictId = siteUser.Districts[0].Id;
     FillDropDowns(model);
     return View(model);
 }
Пример #7
0
 public ICKD(string key, CommonService.Engine.CTYPE type)
 {
     id = key;
     switch (type)
     {
         case CommonService.Engine.CTYPE.C_DELIVERY_AAE:
             companyCode = "aae";
             break;
         case CommonService.Engine.CTYPE.C_DELIVERY_ST:
             companyCode = "shentong";
             break;
         case CommonService.Engine.CTYPE.C_DELIVERY_EMS:
             companyCode = "ems";
             break;
         case CommonService.Engine.CTYPE.C_DELIVERY_SF:
             companyCode = "shunfeng";
             break;
         case CommonService.Engine.CTYPE.C_DELIVERY_YT:
             companyCode = "yuantong";
             break;
         case CommonService.Engine.CTYPE.C_DELIVERY_ZT:
             companyCode = "zhongtong";
             break;
         case CommonService.Engine.CTYPE.C_DELIVERY_GHX:
             companyCode = "pingyou";
             break;
         case CommonService.Engine.CTYPE.C_DELIVERY_TT:
             companyCode = "tiantian";
             break;
         case CommonService.Engine.CTYPE.C_DELIVERY_YD:
             companyCode = "yunda";
             break;
         case CommonService.Engine.CTYPE.C_DELIVERY_HT:
             companyCode = "huitong";
             break;
         case CommonService.Engine.CTYPE.C_DELIVERY_QF:
             companyCode = "quanfeng";
             break;
         case CommonService.Engine.CTYPE.C_DELIVERY_CG:
             companyCode = "chengguang";
             break;
         case CommonService.Engine.CTYPE.C_DELIVERY_ZJS:
             companyCode = "zhaijisong";
             break;
     }
 }
Пример #8
0
        private bool TryGetAllItems(out IEnumerable<Project> results)
        {
            string cacheKey = "aditi:gis:arm:data:project-all";
            if (!cache.TryGet(cacheKey, out results))
            {
                CommonService<ProjectModel, Project> service = new CommonService<ProjectModel, Project>();
                results = service.GetList();
                if (results.IsNullOrEmpty())
                {
                    results = null;
                    return false;
                }

                cache.Set(cacheKey, results, InMemoryCache.OneDay);
            }

            return true;
        }
Пример #9
0
        private bool TryGetAllItems(out IEnumerable<Stream> results)
        {
            string cacheKey = "aditi:gis:arm:data:stream-all";
            if (!cache.TryGet(cacheKey, out results))
            {
                CommonService<StreamModel, Stream> service = new CommonService<StreamModel, Stream>();
                results = service.GetList();
                if (results.IsNullOrEmpty())
                {
                    results = null;
                    return false;
                }

                cache.Set(cacheKey, results);
            }

            return true;
        }
 private async void LoadTheme()
 {
     ICommonService<Theme> themeService = new CommonService<Theme>();
     Theme result = await themeService.GetObjectAsync("4", "theme", _id);
     if (result != null)
     {
         this.Theme = new Theme();
         this.Theme.Stories = result.Stories;
         this.Theme.Name = result.Name;
         this.Theme.Editors = result.Editors;
         this.IsActive = false;
     }
     else
     {
         MessageDialog msg = new MessageDialog(themeService.ExceptionsParameter);
         await msg.ShowAsync();
     }
 }
Пример #11
0
 public JsonResult AssignTestToStudent(int userId, int testId)
 {
     var common = new CommonService();
     common.OnRenderPartialViewToString+=(model)=>{
         var result = string.Empty;
         try
         {
             result=this.RenderPartialViewToString("P_Assign_Test_To_Student", model);
         }
         catch (Exception)
         {
             common.success = false;
             common.message = Constants.DefaultExceptionMessage;
         }
         return result;
     };
     common.AssignTestToStudent(userId, testId);
     return Json(new { common.success, common.message,common.generatedHtml });
 }
Пример #12
0
        public JsonResult AddNewQuestion(int testid, string type)
        {
            var common = new CommonService();
            common.OnRenderPartialViewToString += (model) =>
                {
                    var result = string.Empty;
                    try
                    {
                        result = this.RenderPartialViewToString("P_Question_Instance", model);
                    }
                    catch (Exception)
                    {
                        common.success = false;
                        common.message = Constants.DefaultExceptionMessage;

                    }
                    return result;
                };
            common.AddNewQuestion(testid, type);
            return Json(new { common.generatedHtml, common.success, common.message });
        }
Пример #13
0
        public JsonResult AddListQuestion(int testid, List<Question> listquestion)
        {
            var common = new CommonService();
            common.OnRenderPartialViewToString += (model) =>
            {
                var result = string.Empty;
                try
                {
                    result = this.RenderPartialViewToString("P_Question_Instance", model);
                }
                catch (Exception)
                {
                    common.success = false;
                    common.message = Constants.DefaultExceptionMessage;

                }
                return result;
            };
            common.AddListQuestion(testid, listquestion);
            return Json(new { common.arraylist, common.success, common.message });
        }
        private void LoadComments()
        {
            Task.Run(async () =>
            {
                ICommonService<Comments> newsContentService = new CommonService<Comments>();
                var result = await newsContentService.GetObjectAsync("4", "story", _id, _type);

                await DispatcherHelper.RunAsync(async () =>
                {
                    if (result != null)
                    {
                        this.Comments = result;
                        this.IsActive = false;
                    }
                    else
                    {
                        MessageDialog msg = new MessageDialog(newsContentService.ExceptionsParameter, "提示");
                        await msg.ShowAsync();
                    }
                });
            });
        }
        private async void LoadNewsContent(string id)
        {
            try
            {
                ICommonService<NewsContent> newsContentService = new CommonService<NewsContent>();
                var task1 = newsContentService.GetObjectAsync("4", "news", id);

                ICommonService<StoryExtra> storyExtraService = new CommonService<StoryExtra>();
                var task2 = storyExtraService.GetObjectAsync("4", "story-extra", id);

                await Task.WhenAll(task2, task1);

                NewsContent content = task1.Result;
                StoryExtra extra = task2.Result;

                if (content != null)
                {
                    this.StoryExtra = extra;
                    this.NewsContent = content;
                    var obj = new { Body = content.Body, CSS = content.Css[0], Image = content.Image, Title = content.Title, ImageSource = content.ImageSource, ShareUrl = content.ShareUrl };
                    Messenger.Default.Send<NotificationMessage>(new NotificationMessage(obj, "OnLoadCompleted"));
                    //Delay to destroy animation
                    await Task.Delay(500);
                    this.IsActive = false;
                }
                else
                {
                    MessageDialog msg = new MessageDialog(newsContentService.ExceptionsParameter, "提示");
                    await msg.ShowAsync();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

        }
Пример #16
0
        public List <SelectListItem> AllPOs()
        {
            List <SelectListItem> Suppliers    = new List <SelectListItem>();
            CommonService         service      = new CommonService();
            List <PO>             SupplierList = service.AllPOs();

            Suppliers.Add(new SelectListItem
            {
                Text  = "Select",
                Value = ""
            });
            foreach (var item in SupplierList)
            {
                var newItem = new SelectListItem
                {
                    Text  = item.PONo,
                    Value = item.POId.ToString()
                };

                Suppliers.Add(newItem);
            }

            return(Suppliers);
        }
Пример #17
0
        public IActionResult Delete(DelObj delObj)
        {
            // 获取当前登录用户名
            string _currentUserName = CommonService.GetCurrentUser(HttpContext).UserName;

            for (int i = 0; i < delObj.Id.Count(); i++)
            {
                var obj = _context.WorkTicket.Find(delObj.Id[i]);
                if (obj == null)
                {
                    return(NotFound());
                }
                obj.IsDeleted   = true;
                obj.Status      = WorkTicketStatus.已删除.ToString();
                obj.Description = obj.Description + "\n【删除工单】操作人:" + _currentUserName + ",时间:" + DateTime.Now;

                obj.LastUpdateTime = DateTime.Now;
                obj.LastUpdateUser = _currentUserName;
                _context.WorkTicket.Update(obj);
                _context.SaveChanges();
            }

            return(NoContent());
        }
        public ActionResult Index()
        {
            SchoolModel        objModel   = new SchoolModel();
            SchoolService      objService = new SchoolService();
            List <SchoolModel> lstSchool  = new List <SchoolModel>();

            int uid = 0;
            int rid = 0;
            int did = 0;

            if (Session["UID"] != null)
            {
                uid = Convert.ToInt32(Session["UID"].ToString());
                rid = Convert.ToInt32(Session["RoleID"].ToString());
                did = Convert.ToInt32(Session["DID"].ToString());
            }

            lstSchool           = objService.getSchool(did);
            objModel.ListSchool = new List <SchoolModel>();
            objModel.ListSchool.AddRange(lstSchool);

            CommonService    objCService = new CommonService();
            List <CityModel> lstCity     = new List <CityModel>();

            lstCity           = objCService.getActiveCity(did);
            objModel.ListCity = new List <CityModel>();
            objModel.ListCity.AddRange(lstCity);

            List <ZoneModel> lstZone = new List <ZoneModel>();

            lstZone           = objCService.getActiveZone(did);
            objModel.ListZone = new List <ZoneModel>();
            objModel.ListZone.AddRange(lstZone);

            return(View(objModel));
        }
Пример #19
0
        private void SaveExpressPrintConfig(object obj)
        {
            //var ss = ExpressPrintConfig;

            var m = CommonService.GetBarTenderPrintConfigXX(User.ID, 3, HostName);

            if (m == null)
            {
                ExpressPrintConfig.UserId           = User.ID;
                ExpressPrintConfig.TemplateTypeId   = 3;
                ExpressPrintConfig.TemplateTypeName = "松润样油快递单打印";
                ExpressPrintConfig.HostName         = HostName;
                var r = CommonService.InsertBarTenderPrintConfigXX(ExpressPrintConfig);
                if (r > 0)
                {
                    ExpressPrintConfig.Id = r;
                    MessageBox.Show("保存成功");
                }
                else
                {
                    MessageBox.Show("保存失败,请联系管理员");
                }
            }
            else
            {
                var r = CommonService.UpdateBarTenderPrintConfigXX(ExpressPrintConfig);
                if (r)
                {
                    MessageBox.Show("保存成功");
                }
                else
                {
                    MessageBox.Show("保存失败,请联系管理员");
                }
            }
        }
Пример #20
0
        private void SendWeChatMessage(int id, string type)
        {
            string reply          = string.Empty;
            string msg            = string.Empty;
            var    BaseUrl        = CommonService.GetSysConfig("WeChatUrl", "");
            var    appId          = CommonService.GetSysConfig(HseAppIdKey, "");
            var    managerLillyId = CommonService.GetSysConfig("HSELillyID", "");

            if (type == "SafetyTrouble")
            {
                msg   = "您好,微信中有员工已提交安全隐患事件,请尽快查看。谢谢!点击";
                reply = string.Format(msg + "<a href=\"{0}/HSE/HseAccident/SafetyTroubleDetail?appid={1}&id={2}\">这里</a>打开报告",
                                      BaseUrl, appId, id);
            }
            else
            {
                msg   = "您好,微信中有员工已提交安全汇报事件,请尽快查看。谢谢!点击";
                reply = string.Format(msg + "<a href=\"{0}/HSE/HseAccident/SafetyIncidentDetail?appid={1}&id={2}\">这里</a>打开报告",
                                      BaseUrl, appId, id);
            }

            WechatCommon.SendMsg(int.Parse(appId), "text", managerLillyId, "", "", reply, null);
            _Logger.Error <string>(string.Format("SendWeChatMessage_safetyReport:{0}", reply));
        }
Пример #21
0
        public ResultObj Update(Driver newObj)
        {
            // 获取当前登录用户名
            string _currentUserName = CommonService.GetCurrentUser(HttpContext).UserName;

            ResultObj resultObj = new ResultObj();

            var obj = _context.Driver.Find(newObj.PK);

            if (obj == null)
            {
                resultObj.IsSuccess = false;
                resultObj.ErrMsg    = "修改对象不存在。";
                return(resultObj);
            }

            if (IsExistSame(newObj))
            {
                resultObj.IsSuccess = false;
                resultObj.ErrMsg    = "该名称已存在。";
                return(resultObj);
            }

            obj.Company = newObj.Company;
            obj.Name    = newObj.Name;
            obj.Remark  = newObj.Remark;

            obj.LastUpdateTime = DateTime.Now;
            obj.LastUpdateUser = _currentUserName;

            _context.Driver.Update(obj);
            _context.SaveChanges();

            resultObj.IsSuccess = true;
            return(resultObj);
        }
Пример #22
0
        public ResultObj Add(User obj)
        {
            // 获取当前登录用户名
            string    _currentUserName = CommonService.GetCurrentUser(HttpContext).UserName;
            ResultObj resultObj        = new ResultObj();

            if (IsExistSame(obj))
            {
                resultObj.IsSuccess = false;
                resultObj.ErrMsg    = "该登录名已存在。";
                return(resultObj);
            }

            obj.CreateUser     = _currentUserName;
            obj.CreateTime     = DateTime.Now;
            obj.LastUpdateUser = _currentUserName;
            obj.LastUpdateTime = DateTime.Now;

            _context.User.Add(obj);
            _context.SaveChanges();

            resultObj.IsSuccess = true;
            return(resultObj);
        }
Пример #23
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            try
            {
                // Get the common web service instance.

                ServiceAccess           serviceLoader = ServiceAccess.GetInstance();
                FarmService.FarmService farmService   = serviceLoader.GetFarm();
                if (IsAgentRole)
                {
                    AgentListDropDownList.Items.Clear();
                    AgentListDropDownList.Items.Add(new ListItem(LoginUserId.ToString(), LoginUserId.ToString()));
                    AgentListDropDownList.SelectedIndex = 0;
                    AgentListPanel.Visible = false;
                }
                else
                {
                    AgentListPanel.Visible = true;
                    CommonService commonService = serviceLoader.GetCommon();
                    AgentListDropDownList.DataSource     = commonService.GetAgentsList();
                    AgentListDropDownList.DataValueField = "UserId";
                    AgentListDropDownList.DataTextField  = "UserName";
                    AgentListDropDownList.DataBind();
                    AgentListDropDownList.Items.Insert(0, "All Agents");
                }
                FarmStatusDropDownList.Items.Add(new ListItem("Firmed Up", "Firmed Up"));
                FarmStatusDropDownList.Items.Add(new ListItem("Not Firmed Up", "Not Firmed Up"));
            }
            catch (Exception exception)
            {
                log.Error("UNKNOWN ERROR WHILE LOADING FARM MANAGEMENT:", exception);
            }
        }
    }
Пример #24
0
        public ActivityDTO[] GetByUserId(string mobile)
        {
            using (MyDbContext dbc = new MyDbContext())
            {
                CommonService <ActivityEntity> cs = new CommonService <ActivityEntity>(dbc);
                foreach (var activity in cs.GetAll())
                {
                    if (DateTime.Now < activity.StartTime)
                    {
                        activity.StatusId = 5;
                    }
                    else if (DateTime.Now >= activity.StartTime && DateTime.Now < activity.ExamEndTime)
                    {
                        activity.StatusId = 6;
                    }
                    else if (DateTime.Now >= activity.ExamEndTime && DateTime.Now < activity.RewardTime)
                    {
                        activity.StatusId = 7;
                    }
                    else
                    {
                        activity.StatusId = 8;
                    }
                }
                dbc.SaveChanges();
                CommonService <UserEntity> ucs = new CommonService <UserEntity>(dbc);
                var user = ucs.GetAll().SingleOrDefault(u => u.Mobile == mobile);
                if (user == null)
                {
                    user = new UserEntity();
                }
                //return dbc.Database.SqlQuery<ActivityDTO>("select top(10) a.ID,a.Num,a.Name,a.Description,a.ImgUrl,a.StatusId,i.Name as StatusName,a.PaperId,t.TestTitle as PaperTitle,a.PrizeName,a.PrizeImgUrl,a.WeChatUrl,a.VisitCount,a.ForwardCount,a.AnswerCount,a.HavePrizeCount,a.PrizeCount,a.StartTime,a.ExamEndTime,a.RewardTime from T_Activities as a left join t_idnames i on i.id=a.statusid left join T_TestPapers t on t.Id=a.PaperId, (select ActivityId from T_UserActivities where UserId=@id) as u where a.Id=u.ActivityId and a.IsDeleted=0", new SqlParameter("@id",id)).ToArray();

                return(user.Activities.Where(a => a.IsDeleted == false).OrderByDescending(a => a.CreateDateTime).Take(20).ToList().Select(a => ToDTO(a)).ToArray());
            }
        }
Пример #25
0
        public void CreateFile(string contenttoprint)
        {
            string FilesPath = string.Empty;

            try
            {
                string Folderpath = Directory.GetCurrentDirectory();
                FilesPath = Path.Combine(Folderpath, BulkUpload, UploadFiles);

                if (!Directory.Exists(FilesPath))
                {
                    Directory.CreateDirectory(FilesPath);
                }

                string fileName = FilesPath + "/File_" + DateTime.Now.ToString("dd_MM_yyyy_hh_mm_ss") + ".txt";
                //DateTime.Now.ToString("dd_MM_yyyy_hh_mm_ss")

                CommonService.SaveFile(fileName, contenttoprint);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public JsonResult SendSocialDataToBack(int appId, string SocialChannel, string SocialType, string SocialSubject, string SocialContent)
        {
            try
            {
                _Logger.Debug("openId:{0}", ViewBag.WeChatUserID);
                string openId = ViewBag.WeChatUserID;
                if (!string.IsNullOrEmpty(openId) && appId == 27)
                {
                    var agent        = new WebServiceAgent(CommonService.GetSysConfig("WentangshequService", ""));
                    var methods      = agent.Methods;
                    var sendtoAvator = agent.Invoke("AddSocialData", "WechatID", openId, SocialChannel, SocialType, SocialSubject, SocialContent);

                    _Logger.Debug("UpdateCustomerNo WechatID:{0} 社交数据类型:{1} 社交数据主题:{2}", openId, SocialType, SocialSubject);

                    dynamic resultd = JsonConvert.DeserializeObject(sendtoAvator.ToString());
                    _Logger.Debug("send success status: {0}, remark:{1} ", resultd.Status, resultd.Remark);
                }
            }
            catch (Exception e)
            {
                _Logger.Error(e);
            }
            return(Json("ok"));
        }
 public bool Sendmail(string Subject, string body, string To)
 {
     try
     {
         //HttpPostedFile file = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files[0] : null;
         return(CommonService.SendEmail(Subject, body, To, "", false));
     }
     catch (TimeoutException)
     {
         throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.RequestTimeout)
         {
             Content      = new StringContent("An error occurred, please try again or contact the administrator."),
             ReasonPhrase = "Critical Exception"
         });
     }
     catch (Exception)
     {
         throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
         {
             Content      = new StringContent("An error occurred, please try again or contact the administrator."),
             ReasonPhrase = "Critical Exception"
         });
     }
 }
        public Material ImportMaterial(Article article, string filename, byte[] data, DateTime?date = null, string title = "", string comment = "")
        {
            if (article == null)
            {
                throw new CustomNotFoundException("Invalid Article specified!");
            }

            var blob = FileBlob.Create(article.Code + "/", filename, CommonService.GetMD5(data), data.Length);

            //this.UnitOfWork.Create(blob);

            this.FileStorageService.SaveFile(blob.GetPath(), data);

            var material = article.AddMaterial(blob);

            material.ChangeInfo(date, title, comment);

            this.UnitOfWork.ArticleRepository.Update(article);
            this.UnitOfWork.MaterialRepository.Add(material);

            this.SaveChanges();

            return(material);
        }
Пример #29
0
        public async Task <ActionResult> Create([Bind(Include = "Id,Name,Price,ListItemId,ImageFile,Status,Description,Type")] ItemDetailLocal itemDetail)
        {
            itemDetail.CreationDate = itemDetail.EditDate = CommonService.GetSystemTime();
            itemDetail.Image        = "img added";
            var item = itemDetail.ItemDetailMapper();

            if (ModelState.IsValid)
            {
                db.ItemDetails.Add(item);
                await db.SaveChangesAsync();

                var relativePath = ConfigurationManager.AppSettings["saveImagesIn"];

                if (itemDetail.ImageFile != null)
                {
                    Functions.SaveFile(itemDetail.ImageFile, relativePath, Server.MapPath(relativePath), item.ListItemId + "_Menu_" + item.Id);
                }

                return(RedirectToAction("Index", new { id = item.ListItemId }));
            }

            ViewBag.ListItemId = new SelectList(db.ListItems, "Id", "Name", item.ListItemId);
            return(View(itemDetail));
        }
Пример #30
0
        private void GetOilSamplePrintConfig()
        {
            OilSampleTemplateSelectedItem = new BarTenderTemplateModel();

            OilSamplePrintConfig = CommonService.GetBarTenderPrintConfig(User.ID, 2, HostName);
            if (OilSamplePrintConfig != null)
            {
                OilSampleTemplates = CommonService.GetTenderPrintTemplates(OilSamplePrintConfig.TemplateFolderPath);

                //验证打印机和模板路径是否存在
                if (!File.Exists(OilSamplePrintConfig.TemplateFullName))
                {
                    MessageBox.Show(" 模板路径不存在,请手动选择模板目录 \r\n");
                    OilSampleTemplateSelectedItem           = null;
                    OilSamplePrintConfig.TemplateFullName   = null;
                    OilSamplePrintConfig.TemplateFileName   = null;
                    OilSamplePrintConfig.TemplateFolderPath = null;
                    OilSamplePrintConfig.TemplatePerPage    = 0;
                    return;
                }
                if (!ComputerPrinters.Contains(OilSamplePrintConfig.PrinterName))
                {
                    MessageBox.Show("打印机错误或不存在,请手动选择 打印机 \r\n");
                    OilSamplePrintConfig.PrinterName = null;
                    return;
                }
                OilSampleTemplateSelectedItem.TemplatePerPage    = OilSamplePrintConfig.TemplatePerPage;
                OilSampleTemplateSelectedItem.TemplateFileName   = OilSamplePrintConfig.TemplateFileName;
                OilSampleTemplateSelectedItem.TemplateFullName   = OilSamplePrintConfig.TemplateFullName;
                OilSampleTemplateSelectedItem.TemplateFolderPath = OilSamplePrintConfig.TemplateFolderPath;
            }
            else
            {
                OilSamplePrintConfig = new BarTenderPrintConfigModel();
            }
        }
 public List <ContactDTO> ReadExcelFile(int ClientId, string FilePath, bool IsValid)
 {
     try
     {
         //HttpPostedFile file = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files[0] : null;
         return(CommonService.ReadExcelFile(ClientId, FilePath, IsValid));
     }
     catch (TimeoutException)
     {
         throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.RequestTimeout)
         {
             Content      = new StringContent("An error occurred, please try again or contact the administrator."),
             ReasonPhrase = "Critical Exception"
         });
     }
     catch (Exception)
     {
         throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
         {
             Content      = new StringContent("An error occurred, please try again or contact the administrator."),
             ReasonPhrase = "Critical Exception"
         });
     }
 }
Пример #32
0
        public ResponseModel UpdateOrderStatus(ChangeOrderStatusRequesrModel model)
        {
            var response = new ResponseModel
            {
                Success  = false,
                Messages = new List <string>()
            };

            if (model == null || string.IsNullOrEmpty(model.OrderId) || string.IsNullOrEmpty(model.NewStatus) || string.IsNullOrEmpty(model.UserId))
            {
                response.Messages.Add("Data not mapped");
                response.Data = model;
            }
            else if (!CommonService.VerifyOrderStatus(model.NewStatus))
            {
                response.Messages.Add("Invalid order status");
                response.Data = model;
            }
            else
            {
                try
                {
                    var currentOrderStatus = OrderService.GetOrderCurrentStatus(model.OrderId);
                    var newOrderStatus     = OrderHistoryEnu.GetOrderStatus(model.NewStatus);

                    if (currentOrderStatus == null || newOrderStatus == null)
                    {
                        response.Success = false;
                        response.Messages.Add("Invalid orderId/Order Status.");
                        response.Data = model;
                        return(response);
                    }
                    else if (currentOrderStatus.Value == newOrderStatus.Value)
                    {
                        response.Success = false;
                        response.Messages.Add("Current status already is : " + currentOrderStatus.Value);
                        response.Data = model;
                        return(response);
                    }

                    if (newOrderStatus.Order - currentOrderStatus.Order > 1)
                    {
                        response.Success = false;
                        response.Messages.Add("Invalid order status shifting. Current status is :" + currentOrderStatus.Value);
                        response.Data = currentOrderStatus.Value + " -> " + newOrderStatus.Value;
                        return(response);
                    }

                    response.Success = OrderService.ChangeOrderStatus(model);
                    if (response.Success)
                    {
                        response.Data = "status has been changed";
                    }
                    else
                    {
                        response.Data = "Order does not exist with id " + model.OrderId;
                    }
                    response.Messages.Add("Success");
                }
                catch (Exception excep)
                {
                    response.Messages.Add("Something bad happened.");
                }
            }
            return(response);
        }
 public WalletAccessRightService(IWalletsProvider db, CommonService commonService)
 {
     this._wallets = db;
     this._commonService = commonService;
     this._validator = new WalletAccessRightValidator();
 }
Пример #34
0
 public static Dictionary <string, DynamicObject> GetDataTypeInfo(Context ctx)
 {
     return(CommonService.GetInfoWithQueryService(ctx, "KDS_RptItemDataType", "FDATATYPEID,FNUMBER,FDATATYPE", "FDOCUMENTSTATUS='C'", "").ToDictionary <DynamicObject, string>(p => Convert.ToString(p["FNUMBER"])));
 }
Пример #35
0
        private void LoadService()
        {
            foreach (Control cmain in panel1.Controls)
            {
                if (cmain is Panel)
                {
                    foreach (Control c in cmain.Controls)
                    {
                        if (c is PictureBox && ((PictureBox)c).Image != null)
                        {
                            ((PictureBox)c).Image = null;
                            ((PictureBox)c).Tag   = null;
                        }
                        if (c is CheckBox)
                        {
                            ((CheckBox)c).Checked = false;
                        }
                        c.Refresh();
                    }
                }
            }

            imgList = null;

            //dlService.GetAttachmentByBatchIDAsync(_batchID, _carID);
            //dlService.GetAttachmentByBatchIDCompleted += new Entity.CarWebService.GetAttachmentByBatchIDCompletedEventHandler(dlService_GetAttachmentByBatchIDCompleted);

            IUploadService us = FactoryService.CreateInstance();

            imgList = us.GetCarImages(_carID, _shopCode);
            if (imgList != null)
            {
                int            row = 0;
                List <Control> cc  = new List <Control>();
                foreach (Control cmain in panel1.Controls)
                {
                    cc.Add(cmain);
                }
                CommonService.QuickSort <Control>(cc, "TabIndex");
                foreach (Control cmain in cc)
                {
                    if (cmain is Panel)
                    {
                        if (row < imgList.Rows.Count)
                        {
                            DataRow dr = imgList.Rows[row];
                            if (DBNull.Value != dr["ThumbnailIMG"])
                            {
                                foreach (Control c in cmain.Controls)
                                {
                                    if (c is PictureBox && ((PictureBox)c).Image == null)
                                    {
                                        Stream s = new MemoryStream(Convert.FromBase64String(dr["ThumbnailIMG"].ToString()));
                                        ((PictureBox)c).Image = Image.FromStream(s);
                                        ((PictureBox)c).Tag   = dr["ID"];

                                        toolTip1.SetToolTip(c, "点击查看原图");
                                    }
                                    else if (c is CheckBox)
                                    {
                                        CheckBox cb = (CheckBox)c;
                                        cb.Text = dr["CreateTime"].ToString();
                                    }
                                }
                            }
                            row++;
                        }
                    }
                }
            }
        }
Пример #36
0
        public static PurchaseOrderInfo LoadPurchaseOrderInfo(int poSysNo, int sellerSysNo)
        {
            //1.加载采购单基本信息
            PurchaseOrderInfo poInfo = ProductPurchaseDA.LoadPOMaster(poSysNo, sellerSysNo);

            if (poInfo == null)
            {
                return(poInfo);
            }
            PurchaseOrderETATimeInfo getCheckETMTimeInfo = ProductPurchaseDA.LoadPOETATimeInfo(poInfo.SysNo.Value);

            if (null != getCheckETMTimeInfo)
            {
                poInfo.PurchaseOrderBasicInfo.ETATimeInfo = getCheckETMTimeInfo;
            }
            //2.加载采购单商品列表:
            poInfo.POItems = ProductPurchaseDA.LoadPOItems(poInfo.SysNo.Value);
            foreach (var item in poInfo.POItems)
            {
                ////获取本地货币:
                if (poInfo.PurchaseOrderBasicInfo.CurrencyCode.HasValue)
                {
                    item.CurrencyCode = poInfo.PurchaseOrderBasicInfo.CurrencyCode.Value;
                    CurrencyInfo localCurrency = CommonService.GetCurrencyBySysNo(item.CurrencyCode.Value);
                    item.CurrencySymbol = localCurrency == null ? String.Empty : localCurrency.CurrencySymbol;
                }
            }
            //3.加载采购单供应商信息
            poInfo.VendorInfo = StoreService.LoadVendorInfo(sellerSysNo);

            //4.获取polog的入库总金额
            PurchaseOrderLogInfo poLogInfo = ProductPurchaseDA.LoadPOLogInfo(poInfo.SysNo.Value);

            if (null != poLogInfo)
            {
                poInfo.PurchaseOrderBasicInfo.TotalActualPrice = poLogInfo.SumTotalAmt;
            }
            if (poInfo.PurchaseOrderBasicInfo.TotalActualPrice == 0)
            {
                foreach (PurchaseOrderItemInfo pitem in poInfo.POItems)
                {
                    poInfo.PurchaseOrderBasicInfo.TotalActualPrice += pitem.OrderPrice.Value * pitem.Quantity;
                }
            }

            //5.加载采购单收货信息:
            poInfo.ReceivedInfoList = new List <PurchaseOrderReceivedInfo>();
            poInfo.ReceivedInfoList = ProductPurchaseDA.LoadPurchaseOrderReceivedInfo(poInfo.SysNo.Value);
            foreach (PurchaseOrderReceivedInfo revInfo in poInfo.ReceivedInfoList)
            {
                foreach (PurchaseOrderItemInfo item in poInfo.POItems)
                {
                    if (revInfo.ProductSysNo == item.ProductSysNo)
                    {
                        revInfo.PurchaseQty = (item.PurchaseQty.HasValue ? item.PurchaseQty.Value : 0);
                        revInfo.WaitInQty   = revInfo.PurchaseQty - revInfo.ReceivedQuantity;
                    }
                }
            }
            //返回PO实体:
            return(poInfo);
        }
Пример #37
0
        public static PurchaseOrderInfo CreatePO(PurchaseOrderInfo poInfo)
        {
            //获取ExchangeRate:
            poInfo.PurchaseOrderBasicInfo.CurrencyCode = 1;
            CurrencyInfo localCurrency = CommonService.GetCurrencyBySysNo(poInfo.PurchaseOrderBasicInfo.CurrencyCode.Value);

            poInfo.PurchaseOrderBasicInfo.ExchangeRate        = localCurrency.ExchangeRate;
            poInfo.PurchaseOrderBasicInfo.PurchaseOrderStatus = PurchaseOrderStatus.Created;
            poInfo.PurchaseOrderBasicInfo.PurchaseOrderType   = PurchaseOrderType.Normal;
            ////SellerPortal创建的采购单的账期属性为代销
            //采购单代销属性从供应商上取得
            //poInfo.PurchaseOrderBasicInfo.ConsignFlag = PurchaseOrderConsignFlag.Consign;
            poInfo.PurchaseOrderBasicInfo.TaxRateType = PurchaseOrderTaxRate.Percent000;
            poInfo.PurchaseOrderBasicInfo.TaxRate     = ((decimal)poInfo.PurchaseOrderBasicInfo.TaxRateType) / 100;
            PreCheckCreatePO(poInfo);

            List <PurchaseOrderItemInfo> poItems = new List <PurchaseOrderItemInfo>();

            foreach (var item in poInfo.POItems)
            {
                PurchaseOrderItemInfo poItem = AddNewPurchaseOrderItem(new PurchaseOrderItemProductInfo()
                {
                    SysNo          = item.ProductSysNo.Value,
                    ProductID      = item.ProductID,
                    PrePurchaseQty = item.PrePurchaseQty.Value,
                    PurchasePrice  = item.PurchasePrice.Value
                }, int.Parse(poInfo.VendorInfo.VendorID));
                poItems.Add(poItem);
            }
            poInfo.POItems = poItems;
            poInfo.PurchaseOrderBasicInfo.TotalAmt = poInfo.POItems.Sum(item => item.OrderPrice.Value * item.PrePurchaseQty.Value);

            using (ITransaction trans = ECommerce.Utility.TransactionManager.Create())
            {
                //设置初始化值:
                poInfo.SysNo = ProductPurchaseDA.CreatePOSequenceSysNo();
                poInfo.PurchaseOrderBasicInfo.PurchaseOrderID = poInfo.SysNo.Value.ToString();
                poInfo.PurchaseOrderBasicInfo.CreateDate      = System.DateTime.Now;
                poInfo.PurchaseOrderBasicInfo.IsApportion     = 0;

                //创建操作:
                ProductPurchaseDA.CreatePO(poInfo);
                //ETA时间申请
                poInfo.PurchaseOrderBasicInfo.ETATimeInfo.POSysNo = poInfo.SysNo;
                poInfo.PurchaseOrderBasicInfo.ETATimeInfo.Status  = 1;
                poInfo.PurchaseOrderBasicInfo.ETATimeInfo.InUser  = poInfo.InUserName;
                ProductPurchaseDA.CreatePOETAInfo(poInfo.PurchaseOrderBasicInfo.ETATimeInfo);
                foreach (PurchaseOrderItemInfo item in poInfo.POItems)
                {
                    item.Quantity = 0;
                    //将采购数量初始化为PrePurchaseQty
                    item.PurchaseQty = item.PrePurchaseQty;
                    item.POSysNo     = poInfo.SysNo;
                    //创建PO Item:
                    ProductPurchaseDA.CreatePOItem(item);
                }
                trans.Complete();
            }

            return(poInfo);
        }
Пример #38
0
 public JsonResult RemoveNonRegisteredUser(int userid)
 {
     var common = new CommonService();
     common.RemoveNonRegisteredUser(userid);
     return Json(new { common.success, common.message });
 }
Пример #39
0
 public JsonResult AddTagToQuestion(int questionid, int tagid, string tagname)
 {
     var common = new CommonService();
     common.OnRenderPartialViewToString += (model) =>
     {
         var result = string.Empty;
         try
         {
             result = this.RenderPartialViewToString("P_Tag_Item", model);
         }
         catch (Exception)
         {
             common.success = false;
             common.message = Constants.DefaultExceptionMessage;
         }
         return result;
     };
     common.AddTagToQuestion(questionid, tagid, tagname);
     return Json(new { common.success, common.message, common.generatedHtml });
 }
 private void FillDropDowns(WeightingViewModel model)
 {
     siteUser = ((SiteUser)Session["SiteUser"]);
     commonService = new CommonService(siteUser, db);
     model.AssessmentTypes = commonService.GetAssessmentType();
     model.Subjects = commonService.GetSubjects();
     model.SchoolYears = commonService.GetSchoolYear();
     model.Districts = commonService.GetDistrict();
 }
Пример #41
0
 public JsonResult IsMatchOldPass(string pass)
 {
     var common = new CommonService();
     var ismatch = common.IsMatchOldPass(pass);
     return Json(new { ismatch, common.message, common.success });
 }
Пример #42
0
 public JsonResult UsersSearch(string term)
 {
     var common = new CommonService();
     common.UsersSearch(term);
     return Json(new { common.resultlist, common.message, common.success });
 }
Пример #43
0
 public JsonResult UpdateUserName(int userId, string userName)
 {
     var common = new CommonService();
     common.UpdateUserName(userId, userName);
     return Json(new { common.success, common.message });
 }
Пример #44
0
        // [Route("gis/arm/country/{country}/location")]
        // [HttpGet]
        public HttpResponseMessage GetLocationsByCountry(string country)
        {
            if (string.IsNullOrEmpty(country))
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            CommonService<LocationModel, Location> locationService = new CommonService<LocationModel, Location>();
            IEnumerable<Location> locations = locationService.GetListByFilter(new Specification<LocationModel>(l => l.CountryId == country));
            if (locations.IsNullOrEmpty())
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            Response<IEnumerable<Location>> results = new Response<IEnumerable<Location>>(locations);
            return Request.CreateResponse(HttpStatusCode.OK, results);
        }
            public void Before_each_test()
            {
                clientLicenseRepoistory      = new ClientLicenseRepository(objectSerializationProvider, symmetricEncryptionProvider);
                clientLicenseService         = new ClientLicenseService(clientLicenseRepoistory);
                serviceProductsRepository    = new ServiceProductsRepository(new ScutexServiceEntities());
                symmetricEncryptionProvider  = new SymmetricEncryptionProvider();
                asymmetricEncryptionProvider = new AsymmetricEncryptionProvider();
                hashingProvider             = new HashingProvider();
                objectSerializationProvider = new ObjectSerializationProvider();
                numberDataGenerator         = new NumberDataGenerator();
                packingService             = new PackingService(numberDataGenerator);
                commonRepository           = new CommonRepository(new ScutexServiceEntities());
                clientRepository           = new ClientRepository(new ScutexServiceEntities());
                keyGenerator               = new KeyGenerator(symmetricEncryptionProvider, asymmetricEncryptionProvider, hashingProvider);
                masterService              = new MasterService(commonRepository);
                hardwareFingerprintService = new HardwareFingerprintService(new WmiDataProvider(), new HashingProvider());
                keyGeneratorLarge          = new Scutex.Generators.StaticKeyGeneratorLarge.KeyGenerator(symmetricEncryptionProvider, asymmetricEncryptionProvider, hashingProvider, hardwareFingerprintService);

                var mockActivationLogRepository = new Mock <IActivationLogRepoistory>();

                mockActivationLogRepository.Setup(log => log.SaveActivationLog(It.IsAny <Scutex.Model.ActivationLog>()));

                activationLogService = new ActivationLogService(mockActivationLogRepository.Object, hashingProvider);
                commonService        = new CommonService();

                string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);

                path = path.Replace("file:\\", "");

                var mockCommonService = new Mock <ICommonService>();

                mockCommonService.Setup(common => common.GetPath()).Returns(path + "\\Data\\Client\\");

                string masterServiceDataText;

                using (TextReader reader = new StreamReader(path + "\\Data\\MasterService.dat"))
                {
                    masterServiceDataText = reader.ReadToEnd().Trim();
                }

                masterServiceData = objectSerializationProvider.Deserialize <MasterServiceData>(masterServiceDataText);

                var mockCommonRepository = new Mock <ICommonRepository>();

                mockCommonRepository.Setup(repo => repo.GetMasterServiceData()).Returns(masterServiceData);

                masterService = new MasterService(mockCommonRepository.Object);

                keyPairService             = new KeyPairService(mockCommonService.Object, mockCommonRepository.Object);
                controlService             = new ControlService(symmetricEncryptionProvider, keyPairService, packingService, masterService, objectSerializationProvider, asymmetricEncryptionProvider);
                servicesRepository         = new ServicesRepository(new ScutexEntities());
                serviceStatusProvider      = new ServiceStatusProvider(symmetricEncryptionProvider, objectSerializationProvider, asymmetricEncryptionProvider);
                licenseActiviationProvider = new LicenseActiviationProvider(asymmetricEncryptionProvider, symmetricEncryptionProvider, objectSerializationProvider);
                servicesService            = new ServicesService(servicesRepository, serviceStatusProvider, packingService, licenseActiviationProvider, null, null, null, null, null);
                licenseKeyService          = new LicenseKeyService(keyGenerator, keyGeneratorLarge, packingService, clientLicenseService);
                keyService        = new KeyManagementService(clientRepository, licenseKeyService, activationLogService, hashingProvider, serviceProductsRepository);
                activationService = new ActivationService(controlService, keyService, keyPairService, objectSerializationProvider, asymmetricEncryptionProvider, activationLogService, masterService, commonService, null);

                string serviceData;

                using (TextReader reader = new StreamReader(path + "\\Data\\Service.dat"))
                {
                    serviceData = reader.ReadToEnd().Trim();
                }

                service = objectSerializationProvider.Deserialize <Service>(serviceData);
            }
Пример #46
0
 public JsonResult UpdateProfile(User profile)
 {
     var common = new CommonService();
     common.UpdateProfile(profile);
     return Json(new { common.message, common.success });
 }
Пример #47
0
 public AdminMasterController(AdminMasterService adminMasterService, CommonService commonService)
 {
     this.adminMasterService = adminMasterService;
     this.commonService      = commonService;
 }
Пример #48
0
 public JsonResult SortTagToTest(int testid, List<int> ids)
 {
     var common = new CommonService();
     common.SortTagToTest(testid, ids);
     return Json(new { common.success, common.message });
 }
Пример #49
0
        public ResponseModel BulkUploadStoreSLA(int SLAFor = 3)
        {
            string                DownloadFilePath    = string.Empty;
            string                BulkUploadFilesPath = string.Empty;
            bool                  errorfilesaved      = false;
            bool                  successfilesaved    = false;
            int                   count            = 0;
            List <string>         CSVlist          = new List <string>();
            StoreSLACaller        newSLA           = new StoreSLACaller();
            StoreFileUploadCaller fileU            = new StoreFileUploadCaller();
            ResponseModel         objResponseModel = new ResponseModel();
            int                   StatusCode       = 0;
            string                statusMessage    = "";
            string                fileName         = "";
            string                finalAttchment   = "";
            string                timeStamp        = DateTime.Now.ToString("ddmmyyyyhhssfff");
            DataSet               DataSetCSV       = new DataSet();

            string[] filesName = null;


            try
            {
                var files = Request.Form.Files;

                string       _token       = Convert.ToString(Request.Headers["X-Authorized-Token"]);
                Authenticate authenticate = new Authenticate();
                authenticate = SecurityService.GetAuthenticateDataFromToken(_radisCacheServerAddress, SecurityService.DecryptStringAES(_token));



                if (files.Count > 0)
                {
                    for (int i = 0; i < files.Count; i++)
                    {
                        fileName += files[i].FileName.Replace(".", "_" + authenticate.UserMasterID + "_" + timeStamp + ".") + ",";
                    }
                    finalAttchment = fileName.TrimEnd(',');
                }

                #region FilePath
                string Folderpath = Directory.GetCurrentDirectory();
                filesName = finalAttchment.Split(",");


                BulkUploadFilesPath = Path.Combine(Folderpath, BulkUpload, UploadFiles, CommonFunction.GetEnumDescription((EnumMaster.FileUpload)SLAFor));
                DownloadFilePath    = Path.Combine(Folderpath, BulkUpload, DownloadFile, CommonFunction.GetEnumDescription((EnumMaster.FileUpload)SLAFor));


                if (!Directory.Exists(BulkUploadFilesPath))
                {
                    Directory.CreateDirectory(BulkUploadFilesPath);
                }



                if (files.Count > 0)
                {
                    for (int i = 0; i < files.Count; i++)
                    {
                        using (var ms = new MemoryStream())
                        {
                            files[i].CopyTo(ms);
                            var          fileBytes = ms.ToArray();
                            MemoryStream msfile    = new MemoryStream(fileBytes);
                            FileStream   docFile   = new FileStream(Path.Combine(BulkUploadFilesPath, filesName[i]), FileMode.Create, FileAccess.Write);
                            msfile.WriteTo(docFile);
                            docFile.Close();
                            ms.Close();
                            msfile.Close();
                            string s = Convert.ToBase64String(fileBytes);
                            byte[] a = Convert.FromBase64String(s);
                            // act on the Base64 data
                        }
                    }
                }

                #endregion



                DataSetCSV = CommonService.csvToDataSet(Path.Combine(BulkUploadFilesPath, filesName[0]));
                CSVlist    = newSLA.StoreSLABulkUpload(new StoreSLAService(_connectioSting), authenticate.TenantId, authenticate.UserMasterID, DataSetCSV);


                #region Create Error and Success files and  Insert in FileUploadLog

                string SuccessFileName = "Store_SLASuccessFile_" + timeStamp + ".csv";
                string ErrorFileName   = "Store_SLAErrorFile_" + timeStamp + ".csv";

                string SuccessFileUrl = !string.IsNullOrEmpty(CSVlist[0]) ?
                                        rootPath + BulkUpload + "/" + DownloadFile + "/" + CommonFunction.GetEnumDescription((EnumMaster.FileUpload)SLAFor) + "/Success/" + SuccessFileName : string.Empty;
                string ErrorFileUrl = !string.IsNullOrEmpty(CSVlist[1]) ?
                                      rootPath + BulkUpload + "/" + DownloadFile + "/" + CommonFunction.GetEnumDescription((EnumMaster.FileUpload)SLAFor) + "/Error/" + ErrorFileName : string.Empty;

                if (!string.IsNullOrEmpty(CSVlist[0]))
                {
                    successfilesaved = CommonService.SaveFile(Path.Combine(DownloadFilePath, "Success", SuccessFileName), CSVlist[0]);
                }

                if (!string.IsNullOrEmpty(CSVlist[1]))
                {
                    errorfilesaved = CommonService.SaveFile(Path.Combine(DownloadFilePath, "Error", ErrorFileName), CSVlist[1]);
                }

                count = fileU.CreateFileUploadLog(new StoreFileUploadService(_connectioSting), authenticate.TenantId, filesName[0], true,
                                                  ErrorFileName, SuccessFileName, authenticate.UserMasterID, "Store_SLA", SuccessFileUrl, ErrorFileUrl, SLAFor);
                #endregion

                StatusCode                    = count > 0 ? (int)EnumMaster.StatusCode.Success : (int)EnumMaster.StatusCode.RecordNotFound;
                statusMessage                 = CommonFunction.GetEnumDescription((EnumMaster.StatusCode)StatusCode);
                objResponseModel.Status       = true;
                objResponseModel.StatusCode   = StatusCode;
                objResponseModel.Message      = statusMessage;
                objResponseModel.ResponseData = count;
            }
            catch (Exception)
            {
                throw;
            }
            return(objResponseModel);
        }
Пример #50
0
 public JsonResult SearchUserItems(int testid, string term, string type)
 {
     var common = new CommonService();
     common.OnRenderPartialViewToString += (model) =>
     {
         var result = string.Empty;
         try
         {
             result = this.RenderPartialViewToString("P_User_Item", model);
         }
         catch (Exception)
         {
             common.success = false;
             common.message = Constants.DefaultExceptionMessage;
         }
         return result;
     };
     common.SearchUserItems(testid, term, type);
     return Json(new { common.message, common.success, common.resultlist });
 }
Пример #51
0
        public static PurchaseOrderItemInfo AddNewPurchaseOrderItem(PurchaseOrderItemProductInfo productInfo, int sellerSysNo)
        {
            if (productInfo == null)
            {
                throw new BusinessException(L("采购商品不能为空"));
            }
            if (productInfo.PrePurchaseQty <= 0)
            {
                throw new BusinessException(L("采购数量必须大于0"));
            }
            if (productInfo.PurchasePrice < 0m)
            {
                throw new BusinessException(L("采购价不能小于0"));
            }
            PurchaseOrderItemInfo item = ProductPurchaseDA.AddPurchaseOrderItemByProductSysNo(productInfo.SysNo, sellerSysNo);

            if (item == null)
            {
                throw new BusinessException(L("采购商品不存在"));
            }
            //if (item.ProductTradeType != TradeType.FTA)
            //{
            //    throw new BusinessException(L("商品【{0}】不是自贸商品,只能采购交易类型为自贸的商品", item.BriefName));
            //}

            item.OrderPrice     = productInfo.PurchasePrice;
            item.PrePurchaseQty = productInfo.PrePurchaseQty;
            //当前成本:
            item.CurrentUnitCost       = item.UnitCost;
            item.UnitCostWithoutTax    = item.UnitCostWithoutTax;
            item.LineReturnedPointCost = item.UnitCost * productInfo.PrePurchaseQty;
            item.Quantity    = 0;
            item.PurchaseQty = 0;
            //调用IM接口,获取Item价格信息:
            item.LastOrderPrice = ProductPurchaseDA.GetLastPriceBySysNo(item.ProductSysNo.Value);

            Entity.Product.ProductInventoryInfo productInventoryInfo = ProductPurchaseDA.GetProductInventoryByProductSysNO(item.ProductSysNo.Value);
            if (productInventoryInfo != null)
            {
                item.AvailableQty    = productInventoryInfo.AvailableQty;
                item.UnActivatyCount = productInventoryInfo.UnActivatyCount;
            }
            item.ApportionAddOn = 0;
            ////获取本地货币:
            item.CurrencyCode = 1;
            CurrencyInfo localCurrency = CommonService.GetCurrencyBySysNo(item.CurrencyCode.Value);

            item.CurrencySymbol = localCurrency == null ? String.Empty : localCurrency.CurrencySymbol;

            PurchaseOrderItemInfo getExendPOitem = ProductPurchaseDA.GetExtendPurchaseOrderItemInfo(productInfo.SysNo);

            if (getExendPOitem != null)
            {
                item.LastAdjustPriceDate = getExendPOitem.LastAdjustPriceDate;
                item.LastInTime          = getExendPOitem.LastInTime;
                item.UnActivatyCount     = getExendPOitem.UnActivatyCount;
            }
            if (ProductPurchaseDA.IsVirtualStockPurchaseOrderProduct(item.ProductSysNo.Value))
            {
                item.IsVirtualStockProduct = true;
            }
            return(item);
        }
 private void FillDropDowns(AssessmentClassScoreViewModel model, bool isPostBack)
 {
     siteUser = ((SiteUser)Session["SiteUser"]);
     db = new dbTIREntities();
     commonService = new CommonService(siteUser, db);
     modelServices = new ModelServices();
     model.DropDown = new DropDownData();
     int schoolYearId = int.Parse(model.SchoolYearId);
     model.DistrictName = siteUser.Districts[0].Name;
     model.DistrictId = siteUser.Districts[0].Id;
     model.Assessment = commonService.GetAssessmentType();
     model.SchoolYears = commonService.GetSchoolYear();
     model.SchoolTerms = commonService.GetSchoolTerm();
     model.Subjects = commonService.GetSubjects();
     int[] userSchools = modelServices.getSchoolsByUserId(siteUser.EdsUserId).ToArray();
     model.DropDown.School = new SchoolDropDown(modelServices.GetSchoolDropDownData(siteUser.EdsUserId, schoolYearId), true, "--SELECT--", "");
     int[] schoolsTeacher = modelServices.getTeachersBySchoolsId(userSchools).ToArray();
     if (isPostBack)
     {
         model.DropDown.Teacher = new TeacherDropDown(modelServices.TeacherDropDownDataBySchoolAndYear(new int[] { int.Parse(model.SchoolId) }, schoolYearId, model.DistrictId), "--SELECT--", "");
         model.DropDown.SchoolClass = new ClassDropDown(modelServices.GetClassesByTeacher(schoolYearId, new[] { int.Parse(model.TeacherId) }), "--SELECT--", "");
     }
     else
     {
         model.DropDown.Teacher = new TeacherDropDown(modelServices.TeacherDropDownDataBySchoolAndYear(userSchools, schoolYearId, model.DistrictId), "--SELECT--", "");
         model.DropDown.SchoolClass = new ClassDropDown(modelServices.GetClassesByTeacher(schoolYearId, schoolsTeacher), "--SELECT--", "");
     }
 }
Пример #53
0
        /// <summary>
        /// This method get recipient number & corresponding message from campaign file & sent it to smsoutbox.in gateway
        /// </summary>
        public void AddToSMSQueue()
        {
            General.WriteInFile("Sending file : " + baseFileName);
            HttpWebRequest  oHttpRequest;
            HttpWebResponse oHttpWebResponse;

            //GatewayInfo oGatewayInfo = new GatewayInfo(oClient.campaignId, oClient.IsInternal);

            if (ClientDTO.SenderCode != "" && ClientDTO.SenderCode != null)
            {
                GATEWAY_URL = ConfigurationManager.AppSettings["TransactionalGateWay"].ToString();
                GATEWAY_URL = GATEWAY_URL.Replace("[gateway]", ClientDTO.SenderCode.ToString());
                GatewayID   = "RouteSMS";// ClientDTO.SenderCode;
            }
            else
            {
                GATEWAY_URL = ConfigurationManager.AppSettings["PromotionalGateWay"].ToString();
                GatewayID   = "RouteSMS";// "022751";
            }

            GATEWAY_URL = GATEWAY_URL.Replace("%26", "&");;

            //GatewayID = oGatewayInfo.GatewayId;


            string strURL;
            string sMobileNo = null, mymsg = null, msgtype = null;
            int    recipientNumberCount       = 0; // count of recipient Mobile number.
            int    errorCount                 = 0; // Error count.
            int    creditConsumed             = 0; // Credit consumed to sent message.
            int    sentMsgCount               = 0; // this count indicates how many msg sent successfully
            int    creditRequiredForSingleMsg = 0; // Credit required to send message in the case of single message to multiple recipients.

            creditsRequired = 0;
            bool IsMultipleMsg;

            XmlNodeList MessageToSend           = baseFileXML.SelectNodes("/packet/numbers/message");
            XmlNodeList RecipientsToSendMessage = baseFileXML.SelectNodes("/packet/numbers/number");

            recipientNumberCount = RecipientsToSendMessage.Count;

            // Check for is it an MsgBlaster Testing user or not
            ////if (oClient.IsInternal)
            ////{
            ////    General.WriteInFile(oClient.campaignId + " is a Graceworks team member.");
            ////}

            // check for packet contains multiple messages or not.
            if (MessageToSend.Count == RecipientsToSendMessage.Count && MessageToSend.Count != 1)
            {
                IsMultipleMsg = true;
            }
            else
            {
                IsMultipleMsg = false;
                // In the case of single msg to all recipents calculate the credit required to send this message
                if (CampaignDTO.IsUnicode == false)
                {
                    creditRequiredForSingleMsg = GetMessageCount(ReformatMsg(baseFileXML.GetElementsByTagName("message").Item(0).InnerText.TrimEnd()));
                }
                else
                {
                    creditRequiredForSingleMsg = GetUnicodeMessageCount(ReformatMsg(baseFileXML.GetElementsByTagName("message").Item(0).InnerText.TrimEnd()));
                }
                mymsg = MsgCorrect(baseFileXML.GetElementsByTagName("message").Item(0).InnerText.TrimEnd(), CampaignDTO.IsUnicode);
            }

            foreach (XmlNode currentnode in baseFileXML.DocumentElement.GetElementsByTagName("number")) // loop through the each recipient number in this file
            {
                if (currentnode.Attributes.Count == 0)                                                  // check for this number message is send or not
                {
                    // Remove unwanted characters from number
                    sMobileNo = currentnode.InnerText.Replace(" ", "");
                    sMobileNo = sMobileNo.Replace("-", "");
                    sMobileNo = sMobileNo.Replace("(", "");
                    sMobileNo = sMobileNo.Replace(")", "");
                    sMobileNo = sMobileNo.Replace(",", "");
                    sMobileNo = sMobileNo.Replace("+", "");
                    double number;
                    bool   IsNumeric = double.TryParse(sMobileNo, out number); // Check the number is in Numeric form or not
                    if (sMobileNo.Length < MINMOBILELENGTH || sMobileNo.Length > MAXMOBILELENGTH || !IsNumeric)
                    {
                        // Recipient numbers is invalid so skip this number
                        XmlAttribute errorStamp;
                        errorStamp       = baseFileXML.CreateAttribute("notSent");
                        errorStamp.Value = "Invalid recipient number.";
                        currentnode.Attributes.Append(errorStamp);
                        sentMsgCount++;
                        continue;
                    }
                    else
                    {
                        sMobileNo = sMobileNo.Substring(sMobileNo.Length - MINMOBILELENGTH); // Get last 10 digits from number
                        sMobileNo = "91" + sMobileNo;                                        // Add country code to Recipient number
                    }

                    if (IsMultipleMsg) // prepared separate message for this number
                    {
                        mymsg = MsgCorrect(currentnode.NextSibling.InnerText.TrimEnd(), CampaignDTO.IsUnicode);
                    }

                    if (mymsg == "")// Check for empty message.
                    {
                        // If message is empty than dont send this message & add resone why not send to that recipient number.
                        XmlAttribute errorStamp;
                        errorStamp       = baseFileXML.CreateAttribute("notSent");
                        errorStamp.Value = "Empty message.";
                        currentnode.Attributes.Append(errorStamp);
                        sentMsgCount++;
                        continue;
                    }

                    int creditRequiredToSendMsg = 0;

                    if (IsMultipleMsg)
                    {
                        creditRequiredToSendMsg = GetMessageCount(ReformatMsg(currentnode.NextSibling.InnerText.TrimEnd()));
                    }
                    else
                    {
                        creditRequiredToSendMsg = creditRequiredForSingleMsg;
                    }


                    //if ((ClientDTO.SMSCredit - creditConsumed) < creditRequiredToSendMsg)//Check for available Credits
                    //{
                    //    baseFileXML.Save(sourceQFile);
                    //    if (IsMultipleMsg)
                    //    {
                    //        if (sentMsgCount > 0)
                    //        {
                    //            General.WriteInFile(baseFileName + " is skiped due to unsufficient credits.\r\nMessages sent upto recipient : " + currentnode.PreviousSibling.PreviousSibling.InnerText);
                    //        }
                    //        else
                    //        {
                    //            General.WriteInFile(baseFileName + " is skiped due to unsufficient credits.");
                    //        }
                    //    }
                    //    else
                    //    {
                    //        if (sentMsgCount > 0)
                    //        {
                    //            General.WriteInFile(baseFileName + " is skiped due to unsufficient credits.\r\nMessages sent upto recipient : " + currentnode.PreviousSibling.InnerText);
                    //        }
                    //        else
                    //        {
                    //            General.WriteInFile(baseFileName + " is skiped due to unsufficient credits.");
                    //        }
                    //    }
                    //    break;
                    //}

                    #region " Submiting to Gateway "

                    strURL = GATEWAY_URL.Replace("[recipient]", sMobileNo).Replace("[message]", mymsg);

                    if (CampaignDTO.IsUnicode == true)
                    {
                        strURL = strURL.Replace("[msgtype]", "2");
                    }
                    else
                    {
                        strURL = strURL.Replace("[msgtype]", "0");
                    }


                    sErrlocation        = "HTTP web request-Line 387";
                    oHttpRequest        = (HttpWebRequest)System.Net.WebRequest.Create(strURL);
                    oHttpRequest.Method = "GET";
TryAgain:
                    try
                    {
                        string messageID  = string.Empty;
                        bool   IsSent     = false;
                        string statuscode = string.Empty;
                        string result     = string.Empty;

                        oHttpWebResponse = (HttpWebResponse)oHttpRequest.GetResponse();
                        StreamReader response = new StreamReader(oHttpWebResponse.GetResponseStream());
                        result = response.ReadToEnd();
                        oHttpWebResponse.Close();

                        switch (GatewayID)
                        {
                        case "RouteSMS":
                            if (result.Contains('|'))
                            {
                                statuscode = result.Substring(0, result.IndexOf('|'));
                            }
                            else
                            {
                                statuscode = result;
                            }

                            switch (statuscode)
                            {
                            case "11":
                                messageID = "Invalid destination";
                                IsSent    = true;
                                break;

                            case "1701":
                                messageID = result.Substring(result.IndexOf(':') + 1, result.Length - result.IndexOf(':') - 1);
                                IsSent    = true;
                                break;

                            case "1702":
                                messageID = "Invalid url error";
                                break;

                            case "1703":
                                messageID = "Invalid value in username or password";
                                break;

                            case "1704":
                                messageID = "Invalid value in type field";
                                break;

                            case "1705":
                                messageID = "Invalid Message";
                                IsSent    = true;
                                break;

                            case "1706":
                                messageID = "Destination does not exist";
                                IsSent    = true;
                                break;

                            case "1707":
                                messageID = "Invalid source (Sender)";
                                break;

                            case "1708":
                                messageID = "Invalid value for dlr field";
                                break;

                            case "1709":
                                messageID = "User validation failed";
                                break;

                            case "1710":
                                messageID = "Internal Error";
                                break;

                            case "1025":
                                messageID = "Insufficient credits";
                                break;

                            case "1032":
                                messageID = "Number is in DND";
                                IsSent    = true;
                                break;

                            default:
                                General.WriteInFile("Response :" + result);
                                break;
                            }
                            break;

                        case "SMSPro":
                            //MessageSent GUID="gracew-8be9d47f999e569a" SUBMITDATE="08/26/2013 03:16:12 PM"
                            if (result.Contains("MessageSent"))
                            {
                                messageID = result.Split('"')[1];
                                IsSent    = true;
                            }
                            else
                            {
                                messageID = result;
                                General.WriteInFile(result);
                            }
                            break;

                        default:
                            break;
                        }

                        if (IsSent)
                        {
                            if (IsMultipleMsg)
                            {
                                creditConsumed += creditRequiredToSendMsg;
                            }
                            else
                            {
                                creditConsumed += creditRequiredForSingleMsg;
                            }

                            XmlAttribute timespan;
                            timespan       = baseFileXML.CreateAttribute("sentTime");
                            timespan.Value = System.DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss tt");
                            currentnode.Attributes.Append(timespan);

                            XmlAttribute gatewayID;
                            gatewayID       = baseFileXML.CreateAttribute("gatewayID");
                            gatewayID.Value = GatewayID;
                            currentnode.Attributes.Append(gatewayID);

                            XmlAttribute msgID;
                            msgID       = baseFileXML.CreateAttribute("msgID");
                            msgID.Value = messageID;
                            currentnode.Attributes.Append(msgID);

                            XmlAttribute msgCode;
                            msgCode       = baseFileXML.CreateAttribute("msgCode");
                            msgCode.Value = statuscode;
                            currentnode.Attributes.Append(msgCode);


                            XmlAttribute msgCount;
                            msgCount = baseFileXML.CreateAttribute("msgCount");
                            if (CampaignDTO.IsUnicode == false)
                            {
                                msgCount.Value = GetMessageCount(mymsg).ToString();
                                currentnode.Attributes.Append(msgCount);
                            }
                            else
                            {
                                msgCount.Value = GetUnicodeMessageCount(mymsg).ToString();
                                currentnode.Attributes.Append(msgCount);
                            }



                            XmlAttribute msgCredits;
                            SettingDTO   SettingDTO = new SettingDTO();
                            SettingDTO = SettingService.GetById(1);

                            msgCredits = baseFileXML.CreateAttribute("msgCredits");
                            if (IsMultipleMsg)
                            {
                                msgCredits.Value = creditRequiredToSendMsg.ToString();
                                double credit     = Convert.ToDouble(msgCredits.Value);
                                double reqCredits = credit * SettingDTO.NationalCampaignSMSCount;
                                msgCredits.Value = reqCredits.ToString();
                            }
                            else
                            {
                                msgCredits.Value = creditRequiredForSingleMsg.ToString(); // GetMessageCount(mymsg).ToString();

                                double credit     = Convert.ToDouble(msgCredits.Value);
                                double reqCredits = credit * SettingDTO.NationalCampaignSMSCount;
                                msgCredits.Value = reqCredits.ToString();
                            }
                            currentnode.Attributes.Append(msgCredits);


                            sentMsgCount++;
                            errorCount = 0;

                            //oClient.ReduceCredit = creditConsumed;
                            //if (sentMsgCount % UPDATEBALAFTER == 0)
                            //{
                            //    ClientDBOperation.UpdateCredit(oClient, creditConsumed);
                            //    creditsRequired += creditConsumed;
                            //    baseFileXML.Save(sourceQFile);
                            //    creditConsumed = 0;
                            //}

                            creditConsumed = 0;
                        }
                        else
                        {
                            errorCount += 1;
                            if (errorCount > MAXCHECKFORRESPONSE)
                            {
                                General.WriteInFile("Message sending stoped due to BAD response from Gateway (i.e" + messageID + ")");
                                break;
                            }
                            else
                            {
                                goto TryAgain;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        errorCount += 1;
                        baseFileXML.Save(sourceQFile);
                        if (errorCount > MAXCHECKFORCONNECTION)
                        {
                            General.WriteInFile(sErrlocation + "\r\nGateway connection unavailable." + "\r\n" + ex.Message);
                            break;
                        }
                        else
                        {
                            goto TryAgain;
                        }
                    }
                    #endregion
                }
                else
                {
                    sentMsgCount++;
                    if (IsMultipleMsg)
                    {
                        creditsRequired += GetMessageCount(currentnode.NextSibling.InnerText.TrimEnd());
                    }
                    else
                    {
                        creditsRequired += creditRequiredForSingleMsg;
                    }
                }
            }

            baseFileXML.Save(sourceQFile);
            xmlfiledata = CommonService.ReadXMLFile(sourceQFile);

            // xmlfiledata= xmlfiledata.Replace("<?xml version="1.0"?>","");

            creditsRequired += creditConsumed;
            //oClient.TotalCreditsConsumed += creditsRequired;

            if (errorCount == 0 && sentMsgCount == recipientNumberCount) // indicates sending completed successfully
            {
                System.IO.File.Copy(sourceQFile, sentQFile, true);
                if (System.IO.File.Exists(sourceQFile))
                {
                    System.IO.File.Delete(sourceQFile);
                }
                //ClientDBOperation.UpdateCredit(oClient, creditConsumed);

                //oClient.TotalNumMessages += sentMsgCount;
                //ClientDBOperation.UpdateCreditMsgConsumed(oClient); // Update the count of total credits consumed by user till tody & Number of messages send.
                UpdateMessageLog(CampaignDTO.Id, xmlfiledata);
                General.WriteInFile(baseFileName + " is sent successfully.");
            }
            else
            {
                if (creditConsumed != 0) // creditconsumed is zero means no any message send, hence dont update credit
                {
                    //ClientDBOperation.UpdateCredit(oClient, creditConsumed);
                }
            }

            //#region "Check for Alert message"
            //// Send credit alert and sms alert
            //if (oClient.AlertOnCredit != 0 && oClient.ActualCredits < oClient.AlertOnCredit && oClient.IsAlertOnCredit)
            //{
            //    if (ClientDBOperation.SMSCredits(oClient) >= 1)
            //    {
            //        // get credit alert msg format from QueueProcessorSettings.xml
            //        sErrlocation = "Sending credit goes below minimum limit alert-Line 438";
            //        string message = queuesettingsXML.DocumentElement["lowcreditalertmsg"].InnerText;
            //        message = message.Replace("[CurrentCredits]", oClient.ActualCredits.ToString());
            //        SendAlertMsg(message, "Credit Alert", oClient);
            //        General.WriteInFile("Credit Alert message generated.");
            //        ClientDBOperation.UpdateIsAlertOnCredits(oClient);
            //    }
            //    else
            //    {
            //        sErrlocation = "Due to unsufficient balance Credit Alert message not generated";
            //    }
            //}

            //// send alert when sms count is greater than
            //if (sentMsgCount > oClient.AlertOnMessage && oClient.AlertOnMessage != 0)
            //{
            //    if (ClientDBOperation.SMSCredits(oClient) >= 1)
            //    {
            //        // get sms alert msg format from QueueProcessorSettings.xml
            //        sErrlocation = "Sending max number of Msg sent alert-Line 448";
            //        string message = queuesettingsXML.DocumentElement["maxnumsmssendalertmsg"].InnerText;
            //        message = message.Replace("[SentMsgCount]", sentMsgCount.ToString()).Replace("[MsgLimit]", oClient.AlertOnMessage.ToString());
            //        SendAlertMsg(message, "SMSCount Alert", oClient);
            //        General.WriteInFile("SMSCount Alert message generated.");
            //    }
            //    else
            //    {
            //        sErrlocation = "Due to unsufficient balance SMSCount Alert message not generated";
            //    }
            //}
            //#endregion

            General.WriteInFile("Closing Balance = " + ClientDTO.SMSCredit + "\r\n"); // ClientDBOperation.ActualCredits(oClient) + "\r\n"
        }
Пример #54
0
 public BookingTourMienTrungViewComponent(CommonService commonService)
 {
     this._commonService = commonService;
 }
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            int userId = (int)value;

            return(CommonService.GetSmallAvatarUriByUserId(userId));
        }
Пример #56
0
 public JsonResult SearchTagsOnTest(int testid, string term, int maxrows)
 {
     var common = new CommonService();
     common.SearchTagsOnTest(testid, term, maxrows);
     return Json(new { common.success, common.message, common.resultlist });
 }
Пример #57
0
 public List <Website> GetWebsitesOfUser(List <string> listWebsite)
 {
     return(CommonService.GetDocumentWebsiteId(listWebsite));
 }
Пример #58
0
        private bool TryGetItem(long id, out Stream result)
        {
            string cacheKey = "aditi:gis:arm:data:stream-" + id.ToString();
            if (!cache.TryGet(cacheKey, out result))
            {
                CommonService<StreamModel, Stream> service = new CommonService<StreamModel, Stream>();
                result = service.Get(id);
                if (result == null)
                {
                    result = null;
                    return false;
                }

                result.SetDefaultLinks();
                cache.Set(cacheKey, result);
            }

            return true;
        }
Пример #59
0
        public Guid RegistrationInit(ProfileRegistrationModel model)
        {
            if (model == null)
            {
                throw new CustomArgumentException("Registration data is empty!");
            }

            // input validation
            if (String.IsNullOrWhiteSpace(model.Email))
            {
                throw new CustomInputException("Email is empty!");
            }
            if (String.IsNullOrWhiteSpace(model.Password))
            {
                throw new CustomInputException("Password is empty!");
            }
            if (!model.IsPasswordMatch())
            {
                throw new CustomInputException("Password confirmation is not equal to Passowrd!");
            }

            // security policy
            var securityPolicy = this.GetSecurityPolicy();

            if (!securityPolicy.CheckStrength(model.Password))
            {
                throw new CustomInputException("Password does not match Security Policy!");
            }

            // change valid login
            model.Login = model.GetValidLogin();

            // check if user already exists with login
            var persons = this.Persons
                          .Include(t => t.User)
                          .Where(p => p.User.Login.ToLower() == model.Login.ToLower())
                          .ToList();

            if (persons.Any())
            {
                throw new CustomInputException($"Person with login {model.Login} is already exist!");
            }

            // create activity
            var now      = CommonService.Now;
            var pin      = CommonService.GeneratePin(10);
            var activity = Activity.Create(now.AddHours(DEFAULT_ACTIVITY_EXPIRATION_HOURS), DEFAULT_ACTIVITY_TYPE_REGISTRATION, model, pin);

            _dbContext.Set <Activity>().Add(activity);
            _dbContext.SaveChanges();

            // raise event to send email
            DomainDispatcher.RaiseEvent(new RegistrationInitDomainEvent()
            {
                Email     = model.Email,
                NameFirst = model.NameFirst,
                NameLast  = model.NameLast,
                Login     = model.Login,
                PIN       = pin
            });

            return(activity.ID);
        }
        public ActionResult Create(WeightingViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    db = new dbTIREntities();
                    siteUser = ((SiteUser)Session["SiteUser"]);
                    commonService = new CommonService(siteUser, db);
                    weightingService = new WeightingService(siteUser, db);
                    bool weightingAlreadyExist = weightingService.SaveWeightingDetail(model);
                    if (!weightingAlreadyExist)
                    {
                        ViewBag.UserMessage = "Data Saved Successfully.";
                        model = new WeightingViewModel();
                        FillDropDowns(model);
                        ModelState.Clear();

                    }
                    else
                    {
                        ViewBag.UserMessage = "Data already exists.";
                        FillDropDowns(model);
                    }

                }
                catch (Exception ex)
                {
                    Logging log = new Logging();
                    log.LogException(ex);
                    return View("GeneralError");
                }
            }
            return View(model);
        }