public PayPalPaymentProcessor(
     OrderService orderService,
     SettingService settingService)
 {
     _orderService = orderService;
     _settingsService = settingService;
 }
示例#2
0
 public iDealController(
     SettingService keyValueService,
     PaymentService paymentService,
     PaymentMethodService paymentMethodService)
 {
     _keyValueService = keyValueService;
     _paymentService = paymentService;
     _paymentMethodService = paymentMethodService;
 }
示例#3
0
        public ActionResult Index(FormCollection formcollection)
        {
            SettingService service = new SettingService();

            for (int i = 0; i < formcollection.Count; i++ )
                {
                    string key = formcollection.AllKeys[i];

                    string value = formcollection[i];
                    service.Update(key, value);
                }
            return RedirectToAction("Index");
        }
示例#4
0
 public ProductController(
         SettingService settingService,
         ProductService productService,
         ProductTypeService productTypeService,
         BrandService brandService,
         CategoryService categoryService)
 {
     _settingService = settingService;
     _productService = productService;
     _productTypeService = productTypeService;
     _brandService = brandService;
     _categoryService = categoryService;
 }
        public void Setup()
        {
            pageData = new Mock<IPageData>();
            var settingData = new Mock<ISettingData>();
            var log = new Mock<LoggingService>();
            var userData = new Mock<IUserData>();
            var configurationManager = new Mock<IConfigurationAdapter>();


            SettingService settingService = new SettingService(settingData.Object, configurationManager.Object);

            PageService pageService = new PageService(pageData.Object, settingData.Object, log.Object,
                                                       userData.Object, null);

            c = new HomeController(pageService, settingService, log.Object);
        }
        private void InitGlobalSettings(CommerceInstance instance)
        {
            var settings = new GlobalSettings
            {
                Image = new ImageSettings
                {
                    Types =
                    {
                        new ImageType("List", 240, 240),
                        new ImageType("Detail", 300, 300, true),
                        new ImageType("Thumbnail", 240, 240),
                        new ImageType("Cart", 50, 50)
                    }
                }
            };

            var service = new SettingService(instance.Database);
            service.Set(settings);
        }
示例#7
0
        public IActionResult Storage(string storage_default, string qiniu_bucket, string qiniu_access_key, string qiniu_secret_key, string qiniu_domain)
        {
            var     setting = SettingService.GetFirstEntity(l => l.wxapp_id == GetAdminSession().wxapp_id&& l.key == QuickKeys.UploadSetting);
            JObject model   = JObject.Parse(setting.values);

            if ("qiniu".Equals(storage_default))
            {
                model["default"] = "qiniu";
                model["engine"]["qiniu"]["bucket"]     = qiniu_bucket;
                model["engine"]["qiniu"]["access_key"] = qiniu_access_key;
                model["engine"]["qiniu"]["secret_key"] = qiniu_secret_key;
                model["engine"]["qiniu"]["domain"]     = qiniu_domain;
            }
            else
            {
                model["default"] = "local";
            }

            try
            {
                var result = model.ObjectToJson();
                var time   = DateTimeExtensions.GetCurrentTimeStamp();
                SettingService.Update(x => new yoshop_setting()
                {
                    values = result, update_time = time
                }, l => l.key == setting.key && l.wxapp_id == setting.wxapp_id);

                //初始化系统设置参数
                CommonHelper.SystemSettings = SettingService.LoadEntities(l => l.wxapp_id == setting.wxapp_id).ToList().ToDictionary(s => s.key, s => JObject.Parse(s.values));
            }
            catch (Exception e)
            {
                LogManager.Error(GetType(), e);
                return(No(e.Message));
            }

            return(Yes("更新成功"));
        }
示例#8
0
文件: Fxcm.cs 项目: urugang/Algoloop
        public void Download(MarketModel model, SettingService settings, IList <string> symbols)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            Config.Set("map-file-provider", "QuantConnect.Data.Auxiliary.LocalDiskMapFileProvider");
            Config.Set("data-directory", settings.DataFolder);
            switch (model.Access)
            {
            case MarketModel.AccessType.Demo:
                Config.Set("fxcm-terminal", "Demo");
                break;

            case MarketModel.AccessType.Real:
                Config.Set("fxcm-terminal", "Real");
                break;
            }

            Config.Set("fxcm-user-name", model.Login);
            Config.Set("fxcm-password", model.Password);

            string   resolution = model.Resolution.Equals(Resolution.Tick) ? "all" : model.Resolution.ToString();
            DateTime fromDate   = model.LastDate.Date;

            if (fromDate < DateTime.Today)
            {
                FxcmDownloaderProgram.FxcmDownloader(symbols, resolution, fromDate, fromDate);
                model.LastDate = fromDate.AddDays(1);
            }

            model.Active = model.LastDate < DateTime.Today;
        }
示例#9
0
        protected override async Task OnInitializedAsync()
        {
            try
            {
                profiles = await ProfileService.GetProfilesAsync(PageState.Site.SiteId);

                userid = Int32.Parse(PageState.QueryString["id"]);
                var user = await UserService.GetUserAsync(userid, PageState.Site.SiteId);

                if (user != null)
                {
                    username    = user.Username;
                    email       = user.Email;
                    displayname = user.DisplayName;

                    if (user.PhotoFileId != null)
                    {
                        photofileid = user.PhotoFileId.Value;
                    }

                    settings = await SettingService.GetUserSettingsAsync(user.UserId);

                    createdby  = user.CreatedBy;
                    createdon  = user.CreatedOn;
                    modifiedby = user.ModifiedBy;
                    modifiedon = user.ModifiedOn;
                    deletedby  = user.DeletedBy;
                    deletedon  = user.DeletedOn;
                    isdeleted  = user.IsDeleted.ToString();
                }
            }
            catch (Exception ex)
            {
                await logger.LogError(ex, "Error Loading User {UserId} {Error}", userid, ex.Message);

                AddModuleMessage("Error Loading User", MessageType.Error);
            }
        }
示例#10
0
        public StrategyViewModel(StrategiesViewModel parent, StrategyModel model, MarketService markets, AccountService accounts, SettingService settings)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            _parent   = parent;
            Model     = model;
            _markets  = markets;
            _accounts = accounts;
            _settings = settings;

            StartCommand                = new RelayCommand(() => DoRunStrategy(), () => true);
            StopCommand                 = new RelayCommand(() => { }, () => false);
            CloneCommand                = new RelayCommand(() => DoCloneStrategy(), () => true);
            CloneAlgorithmCommand       = new RelayCommand(() => DoCloneAlgorithm(), () => !string.IsNullOrEmpty(Model.AlgorithmName));
            ExportCommand               = new RelayCommand(() => DoExportStrategy(), () => true);
            DeleteCommand               = new RelayCommand(() => _parent?.DoDeleteStrategy(this), () => true);
            DeleteAllTracksCommand      = new RelayCommand(() => DoDeleteTracks(null), () => true);
            DeleteSelectedTracksCommand = new RelayCommand <IList>(m => DoDeleteTracks(m), m => true);
            UseParametersCommand        = new RelayCommand <IList>(m => DoUseParameters(m), m => true);
            AddSymbolCommand            = new RelayCommand(() => DoAddSymbol(), () => true);
            DeleteSymbolsCommand        = new RelayCommand <IList>(m => DoDeleteSymbols(m), m => SelectedSymbol != null);
            ImportSymbolsCommand        = new RelayCommand(() => DoImportSymbols(), () => true);
            ExportSymbolsCommand        = new RelayCommand <IList>(m => DoExportSymbols(m), trm => SelectedSymbol != null);
            TrackDoubleClickCommand     = new RelayCommand <TrackViewModel>(m => DoSelectItem(m));
            MoveUpSymbolsCommand        = new RelayCommand <IList>(m => OnMoveUpSymbols(m), m => SelectedSymbol != null);
            MoveDownSymbolsCommand      = new RelayCommand <IList>(m => OnMoveDownSymbols(m), m => SelectedSymbol != null);
            SortSymbolsCommand          = new RelayCommand(() => Symbols.Sort(), () => true);

            Model.NameChanged          += StrategyNameChanged;
            Model.MarketChanged        += MarketChanged;
            Model.AlgorithmNameChanged += AlgorithmNameChanged;
            DataFromModel();

            Model.EndDate = DateTime.Now;
        }
 public void EditSetting(SettingDTO SettingDTO)
 {
     try
     {
         SettingService.Edit(SettingDTO);
     }
     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 void TestGetSettingByItem()
        {
            var db           = new StoreContext();
            var itemToDelete = db.Settings.Where(p => p.SettingGroup == "TestSettingGroup" && p.SettingItem == "TestSettingItem" && p.SettingValue == "TestSettingValue");

            db.Settings.RemoveRange(itemToDelete);
            db.SaveChanges();

            var itemToAdd = new Setting
            {
                SettingItem  = "TestSettingItem",
                SettingGroup = "TestSettingGroup",
                SettingValue = "TestSettingValue"
            };

            db.Settings.Add(itemToAdd);
            db.SaveChanges();

            SettingService unit         = new SettingService(db);
            var            itemToAssert = this.GetSettingByItem("TestSettingItem");

            Assert.IsNotNull(itemToAssert);
        }
        public async Task SetSetting_NewKey_CreatesEntry()
        {
            // Arrange
            const string key   = "TestKeyNew";
            const string value = "TestValueNew";

            var request = new SettingRequest
            {
                Key   = key,
                Value = value
            };

            await using var context = new CoreDbContext(ContextOptions);
            var service = new SettingService(new UnitOfWork(context), _localizerMock);

            // Act
            await service.SetSettingAsync(request);

            // Assert
            var created = await context.Setting.AnyAsync(setting => setting.Key == key && setting.Value == value);

            Assert.True(created);
        }
        public async Task RestoreIndexTypeSettingFromFileOrFull()
        {
            var fakeAmazonDataService = new FakeAmazonDataService();

            fakeAmazonDataService.FakeAvailableTypes = new SearchIndexType[]
            {
                SearchIndexType.Apparel,
                SearchIndexType.Appliances,
            };
            var fakeSettingStore = new FakeSettingStore();
            var fakeSerializer   = new FakeSerializer();
            var settingService   = new SettingService(fakeAmazonDataService, fakeSettingStore, fakeSerializer);

            await settingService.RefleshAvailableTypes();

            await settingService.RestoreIndexTypeSettingFromFileOrFull();

            Assert.IsNotNull(settingService.IndexTypeSettings);
            Assert.IsTrue(settingService.IndexTypeSettings.Any(x => x.IndexType == SearchIndexType.Apparel));
            Assert.IsTrue(settingService.IndexTypeSettings.Any(x => x.IndexType == SearchIndexType.Appliances));
            Assert.AreEqual(2, settingService.IndexTypeSettings.Count());
            Assert.AreEqual(2, settingService.IndexTypeSettings.Count(x => x.On));
        }
示例#15
0
        public static void Initialize()
        {
            if (SettingService.GetInstance()["App_Theme"] == null)
            {
                isBlack = true;
            }
            else
            {
                //SettingService s = SettingService.GetInstance();
                isBlack =
                    SettingService.GetInstance()["App_Theme"] == (object)Theme.Dark;
            }


            if (isBlack)//黑变白
            {
                SetDarkTheme();
            }
            else//白变黑
            {
                SetLightTheme();
            }
        }
示例#16
0
        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterInstance(argumentsProvider);
            ISettingService settingService = new SettingService();

            //if (Debugger.IsAttached)
            //    settingService.Reset();

            containerRegistry.RegisterInstance(settingService);
            containerRegistry.RegisterInstance <IUntappdService>(new UntappdService(settingService));

            IDialogService dialogService = containerRegistry.GetContainer().Resolve <IDialogService>();

            containerRegistry.RegisterInstance <IInteractionRequestService>(new InteractionRequestService(dialogService));
            containerRegistry.RegisterDialog <NotificationDialog>();
            containerRegistry.RegisterDialog <AskDialog>();
            containerRegistry.RegisterDialog <TextBoxDialog>();

            containerRegistry.Register <IWebDownloader, WebDownloader>();
            containerRegistry.Register <IWebApiClient, Client>();

            containerRegistry.Register <IReportingService, ReportingService>();
        }
示例#17
0
        public async Task GetSetting_ShouldReturnSetting()
        {
            // Arange
            List <Setting> settings = new()
            {
                Settings.Breakfast,
                Settings.AllInclusive
            };

            ApplicationDbContext context = await InMemoryFactory.InitializeContext()
                                           .SeedAsync(settings);

            var service = new SettingService(context);

            // Act
            var result = await service.GetAsync(Settings.Breakfast.Key);

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(Settings.Breakfast.Value, result.Value);
            Assert.AreEqual(Settings.Breakfast.Type, result.Type);
            Assert.AreEqual(Settings.Breakfast.Key, context.Settings.First(x => x.Value == result.Value).Key);
        }
示例#18
0
        public App()
        {
            if (SettingService.Current != null)
            {
                if (string.IsNullOrWhiteSpace(SettingService.Current.CurrentDatabase))
                {
                    if (SettingService.Current.Databases == null || SettingService.Current.Databases.Count == 0)
                    {
                        var defaultDatabase = ConfigurationManager.AppSettings["DefaultDatabaseName"];

                        if (string.IsNullOrWhiteSpace(defaultDatabase))
                        {
                            throw new Exception("Could not find default database");
                        }

                        SettingService.Current.Databases = new[] { defaultDatabase };
                    }

                    SettingService.Current.CurrentDatabase = SettingService.Current.Databases[0];
                    SettingService.Save();
                }
            }
        }
示例#19
0
        public async Task <IActionResult> Create([Bind("Id,CrawlUrl,ExcludeWord,IgnoreCompany,MinimumWage,MaximumWage,Remarks")] FilterSetting filterSetting)
        {
            try
            {
                // 調用 SettingService 提供的函數來建立設定檔,若中途出錯則跳轉到指定的錯誤頁面
                string ErrorMessage = SettingService.CreateSetting(_context, filterSetting, User.Identity.Name);
                if (ErrorMessage != null)
                {
                    ViewBag.Error = ErrorMessage;
                    return(View("~/Views/Shared/ErrorPage.cshtml"));
                }

                // 若中途沒有出錯則寫入變更到DB,並跳轉回設定檔列表
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            catch (Exception)
            {
                ViewBag.Error = "系統忙碌中,請稍後再試 >___<";
                return(View("~/Views/Shared/ErrorPage.cshtml"));
            }
        }
示例#20
0
        protected void Submit()
        {
            if (!configForm.IsValid())
            {
                return;
            }

            try
            {
                var entity = configForm.GetValue <StartupEntity>();
                var result = SettingService.WriteConfig <StartupConfig>("Startup", opt =>
                {
                    opt.Cache.Type = entity.CacheType;
                    opt.Cache.Redis.ConnectionString = entity.RedisConnectionString;
                    opt.Log.Operation       = entity.OperationlogOpen;
                    opt.TenantRouteStrategy = entity.TenantRouteStrategy;
                });
                _ = MessageBox.AlertAsync("更新成功");
            }
            catch (Exception ex) {
                _ = MessageBox.AlertAsync(ex.Message);
            }
        }
        public PollApiViewModelServiceTests()
        {
            var tenantProviderMock = new Mock <ITenantProvider>();

            tenantProviderMock.Setup(serv => serv.GetTenantId()).Returns("test");
            _context = Helpers.GetContext("test");
            var tenantsDbContext = Helpers.GetTenantContext();
            ITenantRepository          tenantRepository  = new EntityTenantRepository(tenantsDbContext);
            IAsyncRepository <Setting> settingRepository = new EfRepository <Setting>(_context);
            IPollRepository            pollRepository    = new EntityPollRepository(_context, tenantsDbContext);
            ISettingService            settingService    = new SettingService(settingRepository);
            ITenantService             tenantService     = new TenantService(tenantRepository, settingService, null);
            IUserRepository            userRepository    = new EntityUserRepository(_context, null);
            IUserService            userService          = new UserService(userRepository, null);
            IAsyncRepository <Vote> voteRepository       = new EfRepository <Vote>(_context);
            var          voteService = new VoteService(voteRepository, userService);
            IPollService pollService = new PollService(pollRepository, settingService, userService, tenantService,
                                                       voteService, null, null);
            var mapper = Helpers.GetMapper();

            _pollApiViewModelService = new PollApiViewModelService(tenantProviderMock.Object, pollService, mapper,
                                                                   voteService, userService, settingService);
        }
示例#22
0
        public void As_By_T_Not_Found()
        {
            MockSettingDbContext.Setup(context =>
                                       context.Settings.Find("CodeCityCrew.Settings.Test.MySetting", "Development"))
            .Returns(() => null);

            var settingService = new SettingService(MockSettingDbContext.Object, MockIWebHostEnvironment.Object);

            var mySetting = settingService.As <MySetting>();

            MockSettingDbContext.Verify(
                context => context.Settings.Find("CodeCityCrew.Settings.Test.MySetting", "Development"), Times.Once);

            MockSettingDbContext.Verify(context => context.Settings.Add(It.IsAny <Setting>()), Times.Once);

            MockSettingDbContext.Verify(context => context.SaveChanges(), Times.Once);

            Assert.NotNull(mySetting);

            Assert.AreEqual("Application", mySetting.ApplicationName);

            Assert.AreEqual(DateTime.MaxValue, mySetting.CreatedDate);
        }
示例#23
0
        public void _runPreinit()
        {
            DeviceService deviceService_ =
                __singleton <DeviceService> ._instance();

            deviceService_._runPreinit();
            LogService loginService_ =
                __singleton <LogService> ._instance();

            loginService_._runPreinit();
            SettingService settingService_ =
                __singleton <SettingService> ._instance();

            settingService_._runPreinit();
            SqlService sqlService_ =
                __singleton <SqlService> ._instance();

            sqlService_._runPreinit();
            StringService stringService_ =
                __singleton <StringService> ._instance();

            stringService_._runPreinit();
        }
示例#24
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            errorProvider1.Clear();

            if (string.IsNullOrEmpty(txtFolderName.Text))
            {
                errorProvider1.SetError(txtFolderName, "Folder name cannot be empty");
                return;
            }

            if (string.IsNullOrEmpty(txtPatterns.Text))
            {
                errorProvider1.SetError(txtPatterns, "Folder patterns cannot be empty");
                return;
            }

            var isEdit     = this.FolderSettingModel != null;
            var originName = isEdit ? this.FolderSettingModel.FolderName : null;

            this.FolderSettingModel = new DbFolderSetting()
            {
                FolderName = txtFolderName.Text.Trim(),
                Patterns   = txtPatterns.Text.Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries)
            };

            if (isEdit)
            {
                SettingService.EditSetting(originName, FolderSettingModel);
            }
            else
            {
                SettingService.AddSetting(this.FolderSettingModel);
            }

            this.IsSaved = true;
            this.Close();
        }
        public ActionResult SubmitReportForm(AdjustrefundUploadViewModel formData)
        {
            AdjustRefundUploadService service = new AdjustRefundUploadService();

            byte[] filecontent = service.SubmitFormFileCloseAndSendContent(formData);

            string shotNameTeam = string.Empty;

            shotNameTeam = SettingService.SetShortName(formData.UserRequest);
            string fileName = shotNameTeam + "_Summary Send out_" + DateTime.Now.Date.ToString("dd MMM yyyy") + "_Send Close SR & Done Activity";

            if (formData.UserRequest == "00002222" || formData.UserRequest == "00004444")
            {
                fileName = shotNameTeam + "_Summary Send out_" + DateTime.Now.Date.ToString("dd MMM yyyy") + "_result_Send out";
            }
            if (filecontent == null)
            {
                return(List());
            }
            else
            {
                return(File(filecontent, ExcelExportHelper.ExcelContentType, fileName + ".xlsx"));
            }
        }
示例#26
0
        public async Task <IActionResult> Delete(int?id, int?returnPage = 1)
        {
            try
            {
                // 調用 SettingService 提供的函數來刪除設定檔,若中途出錯則跳轉到指定的錯誤頁面
                string ErrorMessage = SettingService.DeleteSetting(_context, User.Identity.Name, id);
                if (ErrorMessage != null)
                {
                    ViewBag.Error = ErrorMessage;
                    return(View("~/Views/Shared/ErrorPage.cshtml"));
                }

                // 若中途沒有出錯則寫入變更到DB,並跳轉回之前所在的設定檔列表分頁
                await _context.SaveChangesAsync();

                int page = returnPage != null ? (int)returnPage : 1;
                return(RedirectToAction("Index", new { page }));
            }
            catch (Exception)
            {
                ViewBag.Error = "系統忙碌中,請稍後再試 >___<";
                return(View("~/Views/Shared/ErrorPage.cshtml"));
            }
        }
示例#27
0
        public MainViewModel(ISettingService settingService)
        {
            this.SettingService = settingService;
            _currentCountryType = SettingService.CountryType;
            //Rankings = (new RankingSource()).Rankings;

            Rankings = new ObservableCollection <Ranking>();
            var settingView = new IndexTypeSettingView();

            AddSettingPage("indexTypeSetting", "Select Item Types", settingView, width: 540, onClosed: async(_, __) =>
            {
                var vm = settingView.ViewModel;
                SettingService.IndexTypeSettings = vm.IndexTypeSettings;
                bool changed        = await SettingService.SaveIndexTypeSettings();
                changed             = changed || _currentCountryType != SettingService.CountryType;
                _currentCountryType = SettingService.CountryType;
                Load(changed);
            });
            var lisencePolicyView = new LicensePolicyView();

            AddSettingPage("LicensePolicy", "License Policy", lisencePolicyView, width: 480, onClosed: (_, __) =>
            {
            });
            _timer.Tick += (_, __) =>
            {
                var rootFrame = Window.Current.Content as Frame;
                if (rootFrame.Content.GetType() != typeof(MainView))
                {
                    Load();
                }
            };
            _timer.Start();


            Load(true);
        }
示例#28
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"
        }
示例#29
0
文件: Usa.cs 项目: Purple666/Algoloop
 public void Download(MarketModel market, SettingService settings, IList <string> symbols)
 {
     throw new System.NotImplementedException();
 }
示例#30
0
 public ChangeTime(SettingService settingService)
 {
     InitializeComponent();
     this.set = settingService;
     init();
 }
示例#31
0
        public StrategiesViewModel(StrategyService strategies, MarketService markets, AccountService accounts, SettingService settings)
        {
            Model     = strategies;
            _markets  = markets;
            _accounts = accounts;
            _settings = settings;

            AddCommand             = new RelayCommand(() => DoAddStrategy(), () => !IsBusy);
            ImportCommand          = new RelayCommand(() => DoImportStrategies(), () => !IsBusy);
            ExportCommand          = new RelayCommand(() => DoExportStrategies(), () => !IsBusy);
            SelectedChangedCommand = new RelayCommand <ITreeViewModel>((vm) => DoSelectedChanged(vm), true);

            DataFromModel();
        }
示例#32
0
 public SettingServiceTests()
 {
     _settingService = new SettingService(Session, CurrentSite);
     _settingService.ResetSettingCache();
 }
示例#33
0
文件: Oanda.cs 项目: urugang/Algoloop
 public IEnumerable <SymbolModel> GetAllSymbols(MarketModel market, SettingService settings)
 {
     throw new System.NotImplementedException();
 }
示例#34
0
 public SitesController(IDriveAccountService siteService, IDriveService driveService, SettingService setting)
 {
     this._siteService  = siteService;
     this._driveService = driveService;
     this._setting      = setting;
 }
示例#35
0
 // POST api/ip
 public ActionResult Set(string newIP)
 {
     SettingService.SetSettingContent("st_ip", newIP);
     return(Content("aaa"));
 }
示例#36
0
 public SettingController(SettingService settings, PredefinedCustomFieldService predefinedFields)
 {
     _settings = settings;
     _predefinedFields = predefinedFields;
 }
示例#37
0
 public IActionResult Footer(FooterViewModel vm)
 {
     SettingService.SaveSettings(vm);
     return(RedirectToIndex());
 }
示例#38
0
        public IActionResult Footer()
        {
            FooterViewModel vm = SettingService.GetSettings <FooterViewModel>();

            return(View(vm));
        }
示例#39
0
 public HomeController(PageService pageService, SettingService settingService, LoggingService log)
 {
     this.pageService = pageService;
     this.settingService = settingService;
     this.log = log;
 }
 public SettingsController(SettingService settingService)
 {
     this.settingService = settingService;
 }
示例#41
0
 public ProductAccessoryService(SettingService settings)
 {
     _settings = settings;
 }