private static void ShowError(Exception e)
 {
     ExceptionReporter reporter = new ExceptionReporter
                                      {
                                          ContactEmail = "*****@*****.**",
                                          ContactWeb = "http://www.assembla.com/wiki/show/NHibernateQueryAnalyzer",
                                          ContactPhone = "none, use email",
                                          ContactFax = "none, use email",
                                          ContactMessageTop = "An error occured that needs to be reported."
                                      };
     reporter.DisplayException(e);
 }
Exemplo n.º 2
0
        //       public static bool UpdateMsgContent(MsgSendConfig o)
        //       {
        //           try
        //           {
        //               string query = @"update MsgSendConfig set unPayType = @unPayType,payType = @payType,
        //                                shippingType = @shippingType,buyerLevel=@buyerLevel,amount = @amount,shippingNofityMsg = @shippingNofityMsg,
        //                                updateDate = GETDATE() where sellerNick = @sellerNick";

        //               SqlParameter[] param = new SqlParameter[]
        //                {
        //                    new SqlParameter("@unPayType",o.UnPayType),
        //                    new SqlParameter("@payType",o.PayType),
        //                    new SqlParameter("@shippingType",o.ShippingType),
        //                    new SqlParameter("@buyerLevel",o.BuyerLevel),
        //                    new SqlParameter("@amount",o.Amount),
        //                    new SqlParameter("@shippingNofityMsg",o.ShippingNofityMsg),
        //                    new SqlParameter("@sellerNick",o.SellerNick)
        //                };
        //               DataBase.ExecuteSql(query, param);

        //               return true;
        //           }
        //           catch (Exception ex)
        //           {
        //               ExceptionReporter.WriteLog(ex, ExceptionPostion.TBApply_Data);
        //               return false;
        //           }
        //       }

        public static bool UpdateMsgConfig(MsgSendConfig o)
        {
            try
            {
                string query = @"update MsgSendConfig 
                                set
                                unPayType = @unPayType,
                                unpayMsg = @unpayMsg,
                                unpayMsgCus = @unpayMsgCus,
                                isUnpayMsgCus = @isUnpayMsgCus,

                                payType = @payType,
                                payMsg = @payMsg,
                                payMsgCus = @payMsgCus,
                                isPayMsgCus = @isPayMsgCus,

                                shippingType  = @shippingType,
                                shippingNofityMsg = @shippingNofityMsg,
                                shippingNofityMsgCus = @shippingNofityMsgCus,
                                isShippingMsgCus = @isShippingMsgCus,
                                
                                delayShippingType  = @delayShippingType,
                                delayShippingNofityMsg = @delayShippingNofityMsg,
                                delayShippingNofityMsgCus = @delayShippingNofityMsgCus,
                                isDelayShippingMsgCus = @isDelayShippingMsgCus,

                                arrivedType = @arrivedType,
                                arrivedNofityMsg = @arrivedNofityMsg,
                                arrivedNofityMsgCus = @arrivedNofityMsgCus,
                                isArrivedMsgCus = @isArrivedMsgCus,

                                signType = @signType,
                                signNofityMsg = @signNofityMsg,
                                signNotifyMsgCus = @signNotifyMsgCus,
                                isSignMsgCus = @isSignMsgCus,
                                
                                huiZJType = @huiZJType,
                                huiZJNofityMsg = @huiZJNofityMsg,
                                huiZJNofityMsgCus = @huiZJNofityMsgCus,
                                isHuiZJMsgCus = @isHuiZJMsgCus,

                                buyerLevel= @buyerLevel,
                                amount = @amount, 
                                shopName = @shopName,
                                updateDate = GETDATE()
                                where sellerNick = @sellerNick";

                SqlParameter[] param = new SqlParameter[]
                {
                    new SqlParameter("@unPayType", o.UnPayType),
                    new SqlParameter("@unpayMsg", o.UnpayMsg),
                    new SqlParameter("@unpayMsgCus", o.UnpayMsgCus),
                    new SqlParameter("@isUnpayMsgCus", o.IsUnpayMsgCus),

                    new SqlParameter("@payType", o.PayType),
                    new SqlParameter("@payMsg", o.PayMsg),
                    new SqlParameter("@payMsgCus", o.PayMsgCus),
                    new SqlParameter("@isPayMsgCus", o.IsPayMsgCus),

                    new SqlParameter("@shippingType", o.ShippingType),
                    new SqlParameter("@shippingNofityMsg", o.ShippingNofityMsg),
                    new SqlParameter("@shippingNofityMsgCus", o.ShippingNofityMsgCus),
                    new SqlParameter("@isShippingMsgCus", o.IsShippingMsgCus),

                    new SqlParameter("@delayShippingType", o.DelayShippingType),
                    new SqlParameter("@delayShippingNofityMsg", o.DelayShippingNofityMsg),
                    new SqlParameter("@delayShippingNofityMsgCus", o.DelayShippingNofityMsgCus),
                    new SqlParameter("@isDelayShippingMsgCus", o.IsDelayShippingMsgCus),

                    new SqlParameter("@arrivedType", o.ArrivedType),
                    new SqlParameter("@arrivedNofityMsg", o.ArrivedNofityMsg),
                    new SqlParameter("@arrivedNofityMsgCus", o.ArrivedNofityMsgCus),
                    new SqlParameter("@isArrivedMsgCus", o.IsArrivedMsgCus),

                    new SqlParameter("@signType", o.SignType),
                    new SqlParameter("@signNofityMsg", o.SignNofityMsg),
                    new SqlParameter("@signNotifyMsgCus", o.SignNotifyMsgCus),
                    new SqlParameter("@isSignMsgCus", o.IsSignMsgCus),

                    new SqlParameter("@huiZJType", o.HuiZJType),
                    new SqlParameter("@huiZJNofityMsg", o.HuiZJNofityMsg),
                    new SqlParameter("@huiZJNofityMsgCus", o.HuiZJNofityMsgCus),
                    new SqlParameter("@isHuiZJMsgCus", o.IsHuiZJMsgCus),

                    new SqlParameter("@buyerLevel", o.BuyerLevel),
                    new SqlParameter("@amount", o.Amount),
                    new SqlParameter("@shopName", o.ShopName),
                    new SqlParameter("@sellerNick", o.SellerNick)
                };
                DataBase.ExecuteSql(query, param);

                return(true);
            }
            catch (Exception ex)
            {
                ExceptionReporter.WriteLog(ex, ExceptionPostion.TBApply_Data);
                return(false);
            }
        }
Exemplo n.º 3
0
        private static void Main(string[] args)
        {
            if (Thread.CurrentThread.Name == null)
            {
                Thread.CurrentThread.Name = "Main";
            }

            Logger.Info("Starting IA:GD..");
            ExceptionReporter.UrlCrashreport = "http://ribbs.dreamcrash.org/iagd/crashreport.php";
            ExceptionReporter.UrlStats       = "http://ribbs.dreamcrash.org/iagd/stats.php";
#if !DEBUG
            ExceptionReporter.LogExceptions = true;
#endif

            Logger.Info("Starting exception monitor for bug reports.."); // Phrased this way since people took it as a 'bad' thing.
            Logger.Debug("Crash reports can be seen at http://ribbs.dreamcrash.org/iagd/logs.html");
            ExceptionReporter.EnableLogUnhandledOnThread();

#if DEBUG
            //AzureUris.Initialize(AzureUris.EnvAzure);
            AzureUris.Initialize(AzureUris.EnvDev);
#else
            AzureUris.Initialize(AzureUris.EnvAzure);
#endif

            StartupService.Init();

#if DEBUG
            Test();
#endif

            // Prevent running in RELEASE mode by accident
            // And thus risking the live database
#if !DEBUG
            if (Debugger.IsAttached)
            {
                Logger.Fatal("Debugger attached, please run in DEBUG mode");
                return;
            }
#endif
            //ParsingUIBackgroundWorker tmp = new ParsingUIBackgroundWorker();

            ItemHtmlWriter.CopyMissingFiles();

            Guid guid = new Guid("{F3693953-C090-4F93-86A2-B98AB96A9368}");
            using (SingleInstance singleInstance = new SingleInstance(guid))
            {
                if (singleInstance.IsFirstInstance)
                {
                    Logger.Info("Calling run..");
                    singleInstance.ArgumentsReceived += singleInstance_ArgumentsReceived;
                    singleInstance.ListenForArgumentsFromSuccessiveInstances();
                    using (ThreadExecuter threadExecuter = new ThreadExecuter())
                    {
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        Logger.Info("Visual styles enabled..");
                        Run(args, threadExecuter);
                    }
                }
                else
                {
                    if (args != null && args.Length > 0)
                    {
                        singleInstance.PassArgumentsToFirstInstance(args);
                    }
                    else
                    {
                        singleInstance.PassArgumentsToFirstInstance(new string[] { "--ignore" });
                    }
                }
            }

            Logger.Info("IA Exited");
            LogManager.Shutdown();
        }
Exemplo n.º 4
0
 public static DataTable GetBuyerInfoToMsgMoreThan1W(string buyerNick, string lastTradeDate1, string lastTradeDate2, string grade, string num1, string num2,
                                                     string area, string tradeAmount1, string tradeAmount2, string sellerNick2, string drpDay, string tradePinNv, string buyCount)
 {
     try
     {
         string query             = @"select cellPhone,buyer_nick from Buyer 
                         where cellPhone is not null and SELLER_ID = @SELLER_ID  ";
         List <SqlParameter> list = new List <SqlParameter>();
         if (!string.IsNullOrEmpty(drpDay))
         {
             //过滤几天内发了的不再发
             query += "and cellPhone not in (select cellPhone from MsgSendHis  where DATEDIFF(dd,sendDate,getdate()) >= @filterDays and sellerNick = @SELLER_ID)";
             SqlParameter p = new SqlParameter("@filterDays", drpDay);
             list.Add(p);
         }
         if (!string.IsNullOrEmpty(buyerNick))
         {
             query += " AND buyer_nick = @buyerNick ";
             SqlParameter p1 = new SqlParameter("@buyerNick", buyerNick);
             list.Add(p1);
         }
         if (!string.IsNullOrEmpty(lastTradeDate1))
         {
             query += " AND last_trade_time >= @last_trade_time1 ";
             SqlParameter P2 = new SqlParameter("@last_trade_time1", Convert.ToDateTime(lastTradeDate1));
             list.Add(P2);
         }
         if (!string.IsNullOrEmpty(lastTradeDate2))
         {
             query += " AND last_trade_time <= @last_trade_time2 ";
             SqlParameter P3 = new SqlParameter("@last_trade_time2", Convert.ToDateTime(lastTradeDate2));
             list.Add(P3);
         }
         if (!grade.Equals("all"))
         {
             query += " AND grade = @grade ";
             SqlParameter P4 = new SqlParameter("@grade", grade);
             list.Add(P4);
         }
         if (!string.IsNullOrEmpty(num1))
         {
             query += " AND item_num >= @item_num1 ";
             SqlParameter P5 = new SqlParameter("@item_num1", num1);
             list.Add(P5);
         }
         if (!string.IsNullOrEmpty(num2))
         {
             query += " AND item_num <= @item_num2 ";
             SqlParameter P6 = new SqlParameter("@item_num2", num2);
             list.Add(P6);
         }
         if (!area.Equals("all"))
         {
             query += " AND province like @area ";
             SqlParameter P7 = new SqlParameter("@area", "%" + area + "%");
             list.Add(P7);
         }
         if (!string.IsNullOrEmpty(tradeAmount1))
         {
             query += " AND trade_amount >= @tradeAmount1 ";
             SqlParameter P8 = new SqlParameter("@tradeAmount1", tradeAmount1);
             list.Add(P8);
         }
         if (!string.IsNullOrEmpty(tradeAmount2))
         {
             query += " AND trade_amount <= @tradeAmount2 ";
             SqlParameter P9 = new SqlParameter("@tradeAmount2", tradeAmount2);
             list.Add(P9);
         }
         if (!string.IsNullOrEmpty(buyCount))
         {
             query += " AND trade_count = @buyCount ";
             SqlParameter P99 = new SqlParameter("@buyCount", buyCount);
             list.Add(P99);
         }
         //按客户购买频率
         if (!tradePinNv.Equals("all"))
         {
             if (tradePinNv.Equals("3"))
             {
                 query += " AND last_trade_time <= DateAdd(m,-3,getdate()) ";
             }
             if (tradePinNv.Equals("6"))
             {
                 query += " AND last_trade_time <= DateAdd(m,-6,getdate()) ";
             }
             if (tradePinNv.Equals("12"))
             {
                 query += " AND last_trade_time <= DateAdd(m,-12,getdate()) ";
             }
         }
         SqlParameter P11 = new SqlParameter("@SELLER_ID", sellerNick2);
         list.Add(P11);
         query += " order by last_trade_time desc ";
         SqlParameter[] strParam = list.ToArray();
         DataTable      ds       = DataBase.ExecuteDt(query, strParam, CommandType.Text);
         return(ds);
     }
     catch (Exception ex)
     {
         ExceptionReporter.WriteLog(ex, ExceptionPostion.TBApply_Data);
         return(null);
     }
 }
Exemplo n.º 5
0
        private void MainWindow_Load(object sender, EventArgs e)
        {
            if (Thread.CurrentThread.Name == null)
            {
                Thread.CurrentThread.Name = "UI";
            }
            Logger.Debug("Starting UI initialization");

            ExceptionReporter.EnableLogUnhandledOnThread();
            SizeChanged += OnMinimizeWindow;

            _transferStashService              = new TransferStashService(_playerItemDao, _databaseItemStatDao, SetFeedback, ListviewUpdateTrigger);
            _stashFileMonitor.OnStashModified += (_, __) => {
                StashEventArg args = __ as StashEventArg;
                if (_transferStashService != null && _transferStashService.TryLootStashFile(args?.Filename))
                {
                    // STOP TIMER
                    _stashFileMonitor.CancelQueuedNotify();
                } // TODO: This logic should be changed to 're queue' but only trigger once, if its slow it triggers multiple times.
            };

            if (!_stashFileMonitor.StartMonitorStashfile(GlobalPaths.SavePath))
            {
                MessageBox.Show("Ooops!\nIt seems you are synchronizing your saves to steam cloud..\nThis tool is unfortunately not compatible.\n");
                HelpService.ShowHelp(HelpService.HelpType.CloudSavesEnabled);

                if (!Debugger.IsAttached)
                {
                    Close();
                }
            }

            // Chicken and the egg..
            SearchController searchController = new SearchController(
                _databaseItemDao,
                _playerItemDao,
                _databaseItemStatDao,
                _itemSkillDao,
                _buddyItemDao,
                _transferStashService,
                _augmentationItemRepo
                );

            searchController.JsBind.SetItemSetAssociations(_databaseItemDao.GetItemSetAssociations());
            _cefBrowserHandler.InitializeChromium(searchController.JsBind, Browser_IsBrowserInitializedChanged);
            searchController.Browser             = _cefBrowserHandler;
            searchController.JsBind.OnClipboard += SetItemsClipboard;

            // Load the grim database
            string gdPath = GrimDawnDetector.GetGrimLocation();

            if (!string.IsNullOrEmpty(gdPath))
            {
            }
            else
            {
                Logger.Warn("Could not find the Grim Dawn install location");
                statusLabel.Text = "Could not find the Grim Dawn install location";

                var timer = new System.Windows.Forms.Timer();
                timer.Tick    += TimerTickLookForGrimDawn;
                timer.Interval = 10000;
                timer.Start();
            }

            // Load recipes
            foreach (string file in GlobalPaths.FormulasFiles)
            {
                if (!string.IsNullOrEmpty(file))
                {
                    bool isHardcore = file.EndsWith("gsh");
                    Logger.InfoFormat("Reading recipes at \"{0}\", IsHardcore={1}", file, isHardcore);
                    _recipeParser.UpdateFormulas(file, isHardcore);
                }
            }

            var addAndShow = UIHelper.AddAndShow;

            // Create the tab contents
            _buddySettingsWindow = new BuddySettings(delegate(bool b) { BuddySyncEnabled = b; },
                                                     _buddyItemDao,
                                                     _buddySubscriptionDao
                                                     );

            addAndShow(_buddySettingsWindow, buddyPanel);

            _authAuthService = new AzureAuthService(_cefBrowserHandler, new AuthenticationProvider());
            var backupSettings = new BackupSettings(_playerItemDao, _authAuthService);

            addAndShow(backupSettings, backupPanel);
            addAndShow(new ModsDatabaseConfig(DatabaseLoadedTrigger, _playerItemDao, _parsingService, _databaseSettingDao), modsPanel);
            addAndShow(new HelpTab(), panelHelp);
            addAndShow(new LoggingWindow(), panelLogging);
            var backupService = new BackupService(_authAuthService, _playerItemDao, _azurePartitionDao, () => Settings.Default.UsingDualComputer);

            _backupServiceWorker            = new BackupServiceWorker(backupService);
            backupService.OnUploadComplete += (o, args) => _searchWindow.UpdateListView();
            searchController.OnSearch      += (o, args) => backupService.OnSearch();

            _searchWindow = new SplitSearchWindow(_cefBrowserHandler.BrowserControl, SetFeedback, _playerItemDao, searchController, _itemTagDao);
            addAndShow(_searchWindow, searchPanel);
            _transferStashService.StashUpdated += (_, __) => {
                _searchWindow.UpdateListView();
            };

            var languagePackPicker = new LanguagePackPicker(_itemTagDao, _playerItemDao, _parsingService);

            addAndShow(
                new SettingsWindow(
                    _cefBrowserHandler,
                    _tooltipHelper,
                    ListviewUpdateTrigger,
                    _playerItemDao,
                    _searchWindow.ModSelectionHandler.GetAvailableModSelection(),
                    _transferStashService,
                    languagePackPicker
                    ),
                settingsPanel);

            new StashTabPicker(_transferStashService.NumStashTabs).SaveStashSettingsToRegistry();

#if !DEBUG
            ThreadPool.QueueUserWorkItem(m => ExceptionReporter.ReportUsage());
            _automaticUpdateChecker.CheckForUpdates();
#endif

            Shown += (_, __) => { StartInjector(); };

            //settingsController.Data.budd
            BuddySyncEnabled = (bool)Settings.Default.BuddySyncEnabled;

            // Start the backup task
            _backupBackgroundTask = new BackgroundTask(new FileBackup(_playerItemDao));

            LocalizationLoader.ApplyLanguage(Controls, GlobalSettings.Language);
            EasterEgg.Activate(this);

            // Initialize the "stash packer" used to find item positions for transferring items ingame while the stash is open
            {
                _dynamicPacker.Initialize(8, 16);

                var transferFiles = GlobalPaths.TransferFiles;
                if (transferFiles.Count > 0)
                {
                    var file  = transferFiles.MaxBy(m => m.LastAccess);
                    var stash = TransferStashService.GetStash(file.Filename);
                    if (stash != null)
                    {
                        _dynamicPacker.Initialize(stash.Width, stash.Height);
                        if (stash.Tabs.Count >= 3)
                        {
                            foreach (var item in stash.Tabs[2].Items)
                            {
                                byte[] bx = BitConverter.GetBytes(item.XOffset);
                                uint   x  = (uint)BitConverter.ToSingle(bx, 0);

                                byte[] by = BitConverter.GetBytes(item.YOffset);
                                uint   y  = (uint)BitConverter.ToSingle(by, 0);

                                _dynamicPacker.Insert(item.BaseRecord, item.Seed, x, y);
                            }
                        }
                    }
                }
            }

            _messageProcessors.Add(new ItemPositionFinder(_dynamicPacker));
            _messageProcessors.Add(new PlayerPositionTracker(Debugger.IsAttached && false));
            _messageProcessors.Add(new StashStatusHandler());
            _messageProcessors.Add(new ItemReceivedProcessor(_searchWindow, _stashFileMonitor, _playerItemDao));
            _messageProcessors.Add(new ItemInjectCallbackProcessor(_searchWindow.UpdateListViewDelayed, _playerItemDao));
            _messageProcessors.Add(new ItemSpawnedProcessor());
            _messageProcessors.Add(new CloudDetectorProcessor(SetFeedback));
            _messageProcessors.Add(new GenericErrorHandler());
            //messageProcessors.Add(new LogMessageProcessor());
#if DEBUG
            _messageProcessors.Add(new DebugMessageProcessor());
#endif

            GlobalSettings.StashStatusChanged += GlobalSettings_StashStatusChanged;

            _transferController = new ItemTransferController(
                _cefBrowserHandler,
                SetFeedback,
                SetTooltipAtmouse,
                _settingsController,
                _searchWindow,
                _dynamicPacker,
                _playerItemDao,
                _transferStashService,
                new ItemStatService(_databaseItemStatDao, _itemSkillDao)
                );
            Application.AddMessageFilter(new MousewheelMessageFilter());


            var titleTag = GlobalSettings.Language.GetTag("iatag_ui_itemassistant");
            if (!string.IsNullOrEmpty(titleTag))
            {
                this.Text += $" - {titleTag}";
            }


            // Popup login diag
            if (_authAuthService.CheckAuthentication() == AzureAuthService.AccessStatus.Unauthorized && !Settings.Default.OptOutOfBackups)
            {
                var t = new System.Windows.Forms.Timer {
                    Interval = 100
                };
                t.Tick += (o, args) => {
                    if (_cefBrowserHandler.BrowserControl.IsBrowserInitialized)
                    {
                        _authAuthService.Authenticate();
                        t.Stop();
                    }
                };
                t.Start();
            }


            _cefBrowserHandler.TransferSingleRequested += TransferSingleItem;
            _cefBrowserHandler.TransferAllRequested    += TransferAllItems;
            new WindowSizeManager(this);


            Logger.Debug("UI initialization complete");
        }
Exemplo n.º 6
0
        private static void Main(string[] args)
        {
            if (Thread.CurrentThread.Name == null)
            {
                Thread.CurrentThread.Name = "Main";
            }

            Logger.Info("Starting IA:GD..");
            ExceptionReporter.UrlCrashreport = "http://ribbs.dreamcrash.org/iagd/crashreport.php";
            ExceptionReporter.UrlStats       = "http://ribbs.dreamcrash.org/iagd/stats.php";
#if !DEBUG
            ExceptionReporter.LogExceptions = true;
#endif

            Logger.Info("Starting exception monitor for bug reports.."); // Phrased this way since people took it as a 'bad' thing.
            Logger.Debug("Crash reports can be seen at http://ribbs.dreamcrash.org/iagd/logs.html");
            ExceptionReporter.EnableLogUnhandledOnThread();

#if DEBUG
            AzureUris.Initialize(AzureUris.EnvAzure);
            //AzureUris.Initialize(AzureUris.EnvDev);
#else
            AzureUris.Initialize(AzureUris.EnvAzure);
#endif

            var      version   = Assembly.GetExecutingAssembly().GetName().Version;
            DateTime buildDate = new DateTime(2000, 1, 1)
                                 .AddDays(version.Build)
                                 .AddSeconds(version.Revision * 2);

            Logger.InfoFormat("Running version {0}.{1}.{2}.{3} from {4}", version.Major, version.Minor, version.Build, version.Revision, buildDate.ToString("dd/MM/yyyy"));


            if (!DependencyChecker.CheckNet452Installed())
            {
                MessageBox.Show("It appears .Net Framework 4.5.2 is not installed.\nIA May not function correctly", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            if (!DependencyChecker.CheckVS2013Installed())
            {
                MessageBox.Show("It appears VS 2013 (x86) redistributable is not installed.\nPlease install it to continue using IA", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            if (!DependencyChecker.CheckVS2010Installed())
            {
                MessageBox.Show("It appears VS 2010 (x86) redistributable is not installed.\nPlease install it to continue using IA", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

#if DEBUG
            Test();
#endif

            // Prevent running in RELEASE mode by accident
            // And thus risking the live database
#if !DEBUG
            if (Debugger.IsAttached)
            {
                Logger.Fatal("Debugger attached, please run in DEBUG mode");
                return;
            }
#endif
            //ParsingUIBackgroundWorker tmp = new ParsingUIBackgroundWorker();

            ItemHtmlWriter.CopyMissingFiles();

            Guid guid = new Guid("{F3693953-C090-4F93-86A2-B98AB96A9368}");
            using (SingleInstance singleInstance = new SingleInstance(guid)) {
                if (singleInstance.IsFirstInstance)
                {
                    Logger.Info("Calling run..");
                    singleInstance.ArgumentsReceived += singleInstance_ArgumentsReceived;
                    singleInstance.ListenForArgumentsFromSuccessiveInstances();
                    using (ThreadExecuter threadExecuter = new ThreadExecuter()) {
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        Logger.Info("Visual styles enabled..");
                        Run(args, threadExecuter);
                    }
                }
                else
                {
                    if (args != null && args.Length > 0)
                    {
                        singleInstance.PassArgumentsToFirstInstance(args);
                    }
                    else
                    {
                        singleInstance.PassArgumentsToFirstInstance(new string[] { "--ignore" });
                    }
                }
            }

            Logger.Info("IA Exited");
        }
Exemplo n.º 7
0
        public void RefreshReport()
        {
            Document = null;
            RaisePropertyChanged(() => Document);

            //Program ilk yüklendiğinde aktif gün başı işlemi yoktur.

            if (ReportContext.CurrentWorkPeriod == null)
            {
                return;
            }
            var memStream = new MemoryStream();

            using (var worker = new BackgroundWorker())
            {
                worker.DoWork += delegate
                {
                    LocalSettings.UpdateThreadLanguage();
                    var doc = GetReport();
                    XamlWriter.Save(doc, memStream);
                    memStream.Position = 0;
                };

                worker.RunWorkerCompleted +=
                    delegate(object sender, RunWorkerCompletedEventArgs eventArgs)
                {
                    if (eventArgs.Error != null)
                    {
                        ExceptionReporter.Show(eventArgs.Error);
                        return;
                    }

                    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(
                                                                   delegate
                    {
                        Document = (FlowDocument)XamlReader.Load(memStream);

                        foreach (var link in _links)
                        {
                            var hp = Document.FindName(link.Replace(" ", "_")) as Hyperlink;
                            if (hp != null)
                            {
                                hp.Click += (s, e) => HandleClick(((Hyperlink)s).Name.Replace("_", " "));
                            }
                        }

                        RaisePropertyChanged(() => Document);
                        RaisePropertyChanged(() => StartDateString);
                        RaisePropertyChanged(() => EndDateString);

                        CreateFilterGroups();
                        foreach (var filterGroup in FilterGroups)
                        {
                            var group = filterGroup;
                            filterGroup.ValueChanged = delegate
                            {
                                var sw = group.SelectedValue as WorkPeriod;
                                if (sw != null)
                                {
                                    ReportContext.StartDate = sw.StartDate;
                                    ReportContext.EndDate   = sw.EndDate;
                                    RefreshFiltersCommand.Execute("");
                                }
                            };
                        }
                    }));
                };

                worker.RunWorkerAsync();
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// 同步会员信息
        /// </summary>
        /// <param name="strNick"></param>
        /// <param name="strSessionKey"></param>
        /// <returns></returns>
        public Boolean SynicBuyersInformation(string strNick, string strSessionKey)
        {
            List <CrmMember> buyers = null;
            int  PageNo = 1, PageSize = 100, nProcess;
            long total = 0;

            //交易同步
            List <Trade> allTrades   = new List <Trade>();
            Int64        tradePageNo = 1;
            Boolean      hasNext     = false;
            TBTrade      tbTrade     = new TBTrade();

            do
            {
                //获取卖家3个月的交易数据
                List <Trade> partTrades = tbTrade.GetBuyerTrades(strSessionKey, tradePageNo, ref hasNext);

                if (partTrades != null && partTrades.Count > 0)
                {
                    allTrades.AddRange(partTrades);//将list加入到末尾
                }
                tradePageNo++;
            } while (hasNext);//hasNext表示是否有下一页
            if (allTrades == null)
            {
                Console.WriteLine("卖家" + strNick + "的3个月的交易量:null");
                return(false);
            }
            Console.WriteLine("卖家" + strNick + "的3个月的交易量:" + allTrades.Count.ToString());

            do
            {
                try
                {
                    //获取买家信息
                    buyers = GetTBBuyerList(strSessionKey, PageNo, PageSize, ref total);
                    if (buyers == null)
                    {
                        Console.WriteLine("卖家" + strNick + "的买家数量:null");
                        continue;
                    }
                    //Console.WriteLine("卖家" + strNick + "的买家数量:" + buyers.Count.ToString());
                    SynchronizeBuyerInfoWithSeller(strNick, strSessionKey, buyers, allTrades);
                    if (total != 0)
                    {
                        nProcess = (int)(PageNo * PageSize * 100F / total);
                    }
                    else
                    {
                        nProcess = 0;
                    }
                    if (nProcess > 100)
                    {
                        nProcess = 100;
                    }
                    SellersBLL.SetSyncProcess(strNick, nProcess);
                }
                catch (Exception ex)
                {
                    ExceptionReporter.WriteLog(ex, ExceptionPostion.TBApply_Data);
                }
            } while (PageNo++ *PageSize < total);
            return(true);
        }
Exemplo n.º 9
0
        protected void imgImportData_Click(object sender, ImageClickEventArgs e)
        {
            //Thread.Sleep(1000000);
            try
            {
                //ImageButton1.ImageUrl = @"~/Images/importing.png";
                #region 订单交易导入
                if (!String.IsNullOrEmpty(fileOrderUpload.PostedFile.FileName))
                {
                    //文件扩展名
                    string fileExtend = "";
                    string filePath   = "";
                    //文件大小
                    long fileSize = 0;
                    filePath = fileOrderUpload.PostedFile.FileName.ToLower().Trim();

                    //取得上传前的文件(存在于客户端)的文件或文件夹的名称
                    string[] names = filePath.Split('\\');
                    //取得文件名
                    string name = names[names.Length - 1];
                    //获得服务器端的根目录
                    string serverPath = Server.MapPath("~/SellerReport");

                    //判断是否有该目录
                    if (!Directory.Exists(serverPath))
                    {
                        Directory.CreateDirectory(serverPath);
                    }
                    filePath = serverPath + "\\" + name;
                    var fileImprtPath = serverPath + "\\";
                    //如果存在,删除文件
                    if (File.Exists(filePath))
                    {
                        File.Delete(filePath);
                    }
                    // 上传文件
                    fileOrderUpload.PostedFile.SaveAs(filePath);


                    //得到扩展名
                    fileExtend = filePath.Substring(filePath.LastIndexOf("."));
                    if (fileExtend != ".csv")
                    {
                        lbError.Text      = "只支持CSV格式的文件!";
                        lbError.ForeColor = Color.Red;
                        return;
                    }

                    System.IO.FileInfo f = new FileInfo(filePath);
                    fileSize = f.Length;
                    int size = Convert.ToInt32(fileSize) / (1024 * 1024);
                    if (size >= 20)
                    {
                        lbError.Text      = "最大可上传文件大小为20M!";
                        lbError.ForeColor = Color.Red;
                        return;
                    }

                    CSVHelper obj  = new CSVHelper(fileImprtPath, fileOrderUpload.FileName.ToLower().Trim());
                    DataTable tb   = obj.Read();
                    long      tick = DateTime.Now.Ticks;
                    Random    ran  = new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32));
                    //将订单交易信息写入到DB,同时更新买家表信息
                    if (tb != null && tb.Rows.Count > 0)
                    {
                        Trade  o        = null;
                        Buyers objBuyer = null;


                        foreach (DataRow row in tb.Rows)
                        {
                            try
                            {
                                o = new Trade();
                                //o.Tid = Convert.ToInt64(string.IsNullOrEmpty(row["订单编号"].ToString()) ? "000000" : row["订单编号"].ToString());
                                o.BuyerNick       = row["买家会员名"].ToString();
                                o.SellerNick      = Users.Nick;
                                o.ReceiverAddress = row["收货地址 "].ToString();
                                o.ReceiverName    = row["收货人姓名"].ToString();
                                o.ReceiverPhone   = row["联系电话 "].ToString();
                                o.ReceiverMobile  = row["联系手机"].ToString();

                                //更新买家信息表数据
                                objBuyer         = new Buyers();
                                objBuyer.Address = o.ReceiverAddress;
                                if (!String.IsNullOrEmpty(o.ReceiverAddress))
                                {
                                    string[] info = o.ReceiverAddress.Split(new char[] { ' ' });
                                    if (info.Length > 0)
                                    {
                                        objBuyer.BuyerProvince = info[0].ToString();
                                    }
                                }
                                objBuyer.BuyerId         = Convert.ToInt64(ran.Next().ToString());
                                objBuyer.BuyerNick       = o.BuyerNick;
                                objBuyer.CellPhone       = o.ReceiverMobile == null ? "" : o.ReceiverMobile.Replace("'", "");
                                objBuyer.Phone           = o.ReceiverPhone == null ? "" : o.ReceiverPhone.Replace("'", "");
                                objBuyer.Buyer_reallName = String.IsNullOrEmpty(o.ReceiverName) ? "unknown!" : o.ReceiverName;
                                objBuyer.SELLER_ID       = Users.Nick;
                                objBuyer.UpdateDate      = DateTime.Now.ToString();
                                objBuyer.LastTradeTime   = Convert.ToString(row["订单付款时间 "]);
                                objBuyer.TradeAmount     = row["买家实际支付金额"].ToString();
                                objBuyer.ItemNum         = Convert.ToInt64(row["宝贝总数量"]);
                                objBuyer.TradeCount      = 1L;
                                objBuyer.Grade           = 1;
                                objBuyer.Address         = o.ReceiverAddress;
                                if (BuyerBLL.CheckBuyerIsExit(objBuyer.BuyerNick, Users.Nick, sellerId))
                                {
                                    BuyerBLL.UpdateForHistory(objBuyer, sellerId);
                                }
                                else
                                {
                                    BuyerBLL.AddBuyerBySeller(objBuyer);
                                }
                            }
                            catch (Exception ex)
                            {
                                //ExceptionReporter.WriteLog(ex, ExceptionPostion.TBApply_Web_UI);
                                continue;
                            }
                        }
                        //将最新同步数据时间更新写入DB
                        Sellers objSeller = new Sellers();
                        objSeller.Nick = Users.Nick;
                        SellersBLL.UpdateSellerSynDate(objSeller);
                    }

                    lbError.Text = "导入报表数据成功!";
                }
                else
                {
                    lbError.Text = "请选择小于20M的CSV格式文件!";
                }
                //ImageButton1.ImageUrl = @"~/Images/import.png";
                #endregion
            }

            catch (Exception ex)
            {
                ExceptionReporter.WriteLog(ex, ExceptionPostion.TBApply_Data);
                //lbError.Text = "导入报表失败,请联系客服!";
                lbError.Text      = "导入报表失败,报表内容格式不正确!";
                lbError.ForeColor = Color.Red;
                //ImageButton1.ImageUrl = @"~/Images/import.png";
                return;
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Update the internal database with player formulas
        /// </summary>
        /// <param name="formulasGstFile">Path to player formula file, generally my games\grim dawn</param>
        public void UpdateFormulas(string formulasGstFile, bool isHardcore)
        {
            try {
                FormulaEntry         formulaEntries = ReadFormulas(formulasGstFile);
                ICollection <string> formulas       = formulaEntries.Formulas;
                if (formulas == null)
                {
                    Logger.Error("Error reading recipe file, formula file either corrupted or file format has changed");
                    return;
                }

                formulas = formulas.Where(formula => !formula.StartsWith("records/items/crafting/blueprints/component") &&
                                          !formula.StartsWith("records/items/crafting/blueprints/other/craft_elixir") &&
                                          !formula.StartsWith("records/items/crafting/blueprints/other/craft_oil") &&
                                          !formula.StartsWith("records/items/crafting/blueprints/other/craft_potion") &&
                                          !formula.StartsWith("records/items/crafting/blueprints/other/craft_special")
                                          ).ToList();



                ISet <string> alreadyProcessed = new SortedSet <string>();
                if (formulas.Count > 0)
                {
                    _recipeItemDao.DeleteAll(isHardcore);

                    // References to the actual item [eg artifactName => record]
                    IList <DatabaseItemStat> stats = _recipeItemDao.GetRecipeStats(formulas);

                    // Stats for the actual item
                    IList <DatabaseItemStat> itemStats = _recipeItemDao.GetRecipeItemStats(
                        stats.Select(m => m.TextValue).ToArray()
                        );

                    List <RecipeItem> toSave = new List <RecipeItem>();
                    foreach (string formula in formulas)
                    {
                        var q = stats.Where(s => s.Parent.Record.Equals(formula));
                        if (q.Any())
                        {
                            DatabaseItemStat item = q.First();
                            if (!string.IsNullOrEmpty(item.TextValue))
                            {
                                var minimumLevel = itemStats
                                                   .Where(m => m.Parent.Record.Equals(item.TextValue))
                                                   .Where(m => "levelRequirement".Equals(m.Stat))
                                                   .FirstOrDefault()?.Value ?? 0f;


                                if (!alreadyProcessed.Contains(item.TextValue))
                                {
                                    toSave.Add(new RecipeItem {
                                        BaseRecord   = item.TextValue,
                                        IsHardcore   = isHardcore,
                                        MinimumLevel = minimumLevel,
                                        IsExpansion1 = formulaEntries.IsExpansion1
                                    });

                                    alreadyProcessed.Add(item.TextValue);
                                }
                            }
                            else
                            {
                                Logger.Warn($"Could not parse formula \"{formula}\"");
                            }
                        }
                    }

                    _recipeItemDao.Save(toSave);
                    Logger.InfoFormat("Updated internal recipe database with {0} recipes.", formulas.Count);
                }
            }
            catch (NHibernate.MappingException ex) {
                Logger.Warn(ex.Message);
                Logger.Warn(ex.StackTrace);

                ExceptionReporter.ReportException(ex, "UpdateFormulas");
            }
            catch (Exception ex) {
                Logger.Warn(ex.Message);
                Logger.Warn(ex.StackTrace);
                ExceptionReporter.ReportException(ex, "UpdateFormulas");
            }
        }
Exemplo n.º 11
0
        protected void imgSubmit_Click(object sender, ImageClickEventArgs e)
        {
            //判断输入格式
            if (!String.IsNullOrEmpty(txtCellphone.Text.Trim()) && !Utility.IsCellPhone(txtCellphone.Text.Trim()))
            {
                lbCellPhoneError.Text = "手机号码格式不正确!";
                return;
            }
            if (string.IsNullOrEmpty(txtCellphone.Text.Trim()))
            {
                lbCellPhoneError.Text = "手机号码不能为空!";
                return;
            }

            if (!String.IsNullOrEmpty(txtPhone.Text.Trim()) && !Utility.IsPhone(txtPhone.Text.Trim()))
            {
                lbPhoneError.Text = "座机号码格式不正确!";
                return;
            }
            if (!String.IsNullOrEmpty(txtQQ.Text.Trim()) && !Utility.IsNumeric(txtQQ.Text.Trim()))
            {
                lbQQError.Text = "QQ号码应该都是数字!";
                return;
            }
            if (!String.IsNullOrEmpty(txtEmail.Text.Trim()) && !Utility.IsEmail(txtEmail.Text.Trim()))
            {
                lbQQError.Text = "Email格式不正确!";
                return;
            }
            if (!String.IsNullOrEmpty(txtZIPCode.Text.Trim()) && !Utility.IsZIPCode(txtZIPCode.Text.Trim()))
            {
                lbZIPError.Text = "邮编格式不正确!";
                return;
            }

            //相同手机号码只能添加一次
            if (BuyerBLL.CheckTheSameHPNoIsExit(Users.Nick, txtCellphone.Text.Trim()))
            {
                lbMsg.Text      = "手机号码重复,系统已经存在该号码!";
                lbMsg.ForeColor = Color.Red;
                txtCellphone.Focus();
                return;
            }

            Buyers objBuyer = new Buyers();
            long   tick     = DateTime.Now.Ticks;
            Random ran      = new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32));

            objBuyer.BuyerId         = Convert.ToInt64(ran.Next().ToString());
            objBuyer.SELLER_ID       = Users.Nick;
            objBuyer.BuyerNick       = txtNick.Text.Trim();
            objBuyer.Buyer_reallName = txtRealName.Text.Trim();
            objBuyer.CellPhone       = txtCellphone.Text.Trim();
            objBuyer.Phone           = txtPhone.Text.Trim();
            objBuyer.QQ            = txtQQ.Text.Trim();
            objBuyer.MSN           = txtMSN.Text.Trim();
            objBuyer.ZipCode       = txtZIPCode.Text.Trim();
            objBuyer.Email         = txtEmail.Text.Trim();
            objBuyer.SinaWeibo     = txtsinaWeibo.Text.Trim();
            objBuyer.QQWeibo       = txtQQWeibo.Text.Trim();
            objBuyer.BuyerProvince = drpArea.SelectedValue.ToString();
            objBuyer.City          = txtCity.Text.Trim();
            objBuyer.birthDay      = datebirthday.Value.ToString();
            objBuyer.BuyerType     = "2";
            try
            {
                if (BuyerBLL.AddBuyerBySeller(objBuyer))
                {
                    lbMsg.Text      = "会员信息添加成功!";
                    lbMsg.ForeColor = Color.Blue;
                    txtCellphone.Focus();
                    txtCellphone.Text = "";
                }
            }
            catch (Exception ex)
            {
                lbMsg.Text = "添加会员失败!";
                ExceptionReporter.WriteLog(ex, ExceptionPostion.TBApply_Web_UI);
            }
        }
Exemplo n.º 12
0
        protected void imgModify_Click(object sender, ImageClickEventArgs e)
        {
            if (String.IsNullOrEmpty(txtMin1.Text.Trim()))
            {
                lbError1.Text = "金额不能为空!";
                lbMsg.Text    = "";
                return;
            }
            if (!Utility.IsPositiveINT(txtMin1.Text.Trim()))
            {
                lbError1.Text = "金额必须为整数!";
                lbMsg.Text    = "";
                return;
            }

            if (String.IsNullOrEmpty(txtMax1.Text.Trim()))
            {
                lbError1.Text = "金额不能为空!";
                lbMsg.Text    = "";
                return;
            }
            if (!Utility.IsPositiveINT(txtMax1.Text.Trim()))
            {
                lbError1.Text = "金额必须为整数!";
                lbMsg.Text    = "";
                return;
            }


            if (String.IsNullOrEmpty(txtMin2.Text.Trim()))
            {
                lbError2.Text = "金额不能为空!";
                lbMsg.Text    = "";
                return;
            }
            if (!Utility.IsPositiveINT(txtMin2.Text.Trim()))
            {
                lbError2.Text = "金额必须为整数!";
                lbMsg.Text    = "";
                return;
            }

            if (String.IsNullOrEmpty(txtMax2.Text.Trim()))
            {
                lbError2.Text = "金额不能为空!";
                lbMsg.Text    = "";
                return;
            }
            if (!Utility.IsPositiveINT(txtMax2.Text.Trim()))
            {
                lbError2.Text = "金额必须为整数!";
                lbMsg.Text    = "";
                return;
            }

            if (String.IsNullOrEmpty(txtMin2.Text.Trim()))
            {
                lbError2.Text = "金额不能为空!";
                lbMsg.Text    = "";
                return;
            }
            if (!Utility.IsPositiveINT(txtMin2.Text.Trim()))
            {
                lbError2.Text = "金额必须为整数!";
                lbMsg.Text    = "";
                return;
            }

            if (String.IsNullOrEmpty(txtMax2.Text.Trim()))
            {
                lbError2.Text = "金额不能为空!";
                lbMsg.Text    = "";
                return;
            }
            if (!Utility.IsPositiveINT(txtMax2.Text.Trim()))
            {
                lbError2.Text = "金额必须为整数!";
                lbMsg.Text    = "";
                return;
            }

            if (String.IsNullOrEmpty(txtMin3.Text.Trim()))
            {
                lbError3.Text = "金额不能为空!";
                lbMsg.Text    = "";
                lbMsg.Text    = "";
                return;
            }
            if (!Utility.IsPositiveINT(txtMin3.Text.Trim()))
            {
                lbError3.Text = "金额必须为整数!";
                lbMsg.Text    = "";
                return;
            }

            if (String.IsNullOrEmpty(txtMax3.Text.Trim()))
            {
                lbError3.Text = "金额不能为空!";
                lbMsg.Text    = "";
                return;
            }
            if (!Utility.IsPositiveINT(txtMax3.Text.Trim()))
            {
                lbError3.Text = "金额必须为整数!";
                lbMsg.Text    = "";
                return;
            }

            if (String.IsNullOrEmpty(txtMin4.Text.Trim()))
            {
                lbError4.Text = "金额不能为空!";
                lbMsg.Text    = "";
                return;
            }
            if (!Utility.IsPositiveINT(txtMin4.Text.Trim()))
            {
                lbError4.Text = "金额必须为整数!";
                lbMsg.Text    = "";
                return;
            }

            if (String.IsNullOrEmpty(txtMax4.Text.Trim()))
            {
                lbError4.Text = "金额不能为空!";
                lbMsg.Text    = "";
                return;
            }
            if (!Utility.IsPositiveINT(txtMax4.Text.Trim()))
            {
                lbError4.Text = "金额必须为整数!";
                lbMsg.Text    = "";
                return;
            }
            try
            {
                ControlStatus(true);
                CTCRM.Entity.Grade o = new CTCRM.Entity.Grade();
                o.SellerNick = Users.Nick;
                DataTable tb        = BuyerBLL.GetGradeByID(o);
                bool      showLbMsg = true;
                if (tb != null && tb.Rows.Count > 0)
                {
                    o.Id             = Convert.ToInt32(tb.Rows[0]["id"].ToString());
                    o.TradeAmontFrom = Convert.ToInt32(txtMin1.Text.Trim().ToString());
                    o.TradeAmountTo  = Convert.ToInt32(txtMax1.Text.Trim().ToString());
                    BuyerBLL.UpdateGrade(o);
                    o.Id             = Convert.ToInt32(tb.Rows[1]["id"].ToString());
                    o.TradeAmontFrom = Convert.ToInt32(txtMin2.Text.Trim().ToString());
                    o.TradeAmountTo  = Convert.ToInt32(txtMax2.Text.Trim().ToString());
                    BuyerBLL.UpdateGrade(o);
                    o.Id             = Convert.ToInt32(tb.Rows[2]["id"].ToString());
                    o.TradeAmontFrom = Convert.ToInt32(txtMin3.Text.Trim().ToString());
                    o.TradeAmountTo  = Convert.ToInt32(txtMax3.Text.Trim().ToString());
                    BuyerBLL.UpdateGrade(o);
                    o.Id             = Convert.ToInt32(tb.Rows[3]["id"].ToString());
                    o.TradeAmontFrom = Convert.ToInt32(txtMin4.Text.Trim().ToString());
                    o.TradeAmountTo  = Convert.ToInt32(txtMax4.Text.Trim().ToString());
                    BuyerBLL.UpdateGrade(o);
                    //控制更新提示标签的状态
                    if (Convert.ToInt32(tb.Rows[0]["tradeAmontFrom"].ToString()) == Convert.ToInt32(txtMin1.Text.Trim().ToString()) &&
                        Convert.ToInt32(tb.Rows[0]["tradeAmountTo"].ToString()) == Convert.ToInt32(txtMax1.Text.Trim().ToString()) &&
                        Convert.ToInt32(tb.Rows[1]["tradeAmontFrom"].ToString()) == Convert.ToInt32(txtMin2.Text.Trim().ToString()) &&
                        Convert.ToInt32(tb.Rows[1]["tradeAmountTo"].ToString()) == Convert.ToInt32(txtMax2.Text.Trim().ToString()) &&
                        Convert.ToInt32(tb.Rows[2]["tradeAmontFrom"].ToString()) == Convert.ToInt32(txtMin3.Text.Trim().ToString()) &&
                        Convert.ToInt32(tb.Rows[2]["tradeAmountTo"].ToString()) == Convert.ToInt32(txtMax3.Text.Trim().ToString()) &&
                        Convert.ToInt32(tb.Rows[3]["tradeAmontFrom"].ToString()) == Convert.ToInt32(txtMin4.Text.Trim().ToString()) &&
                        Convert.ToInt32(tb.Rows[3]["tradeAmountTo"].ToString()) == Convert.ToInt32(txtMax4.Text.Trim().ToString())
                        )
                    {
                        showLbMsg = false;
                    }
                }
                if (showLbMsg)
                {
                    lbMsg.Text = "会员级别调整成功!";
                }
                lbMsg.ForeColor = Color.Blue;
                // ControlStatus(false);
                //更新成功后,同步会员的级别
                DataTable tbBuyer = BuyerBLL.GetBuyerInfoBySellerNick(Users.Nick);
                if (tbBuyer != null && tbBuyer.Rows.Count > 0)
                {
                    for (int i = 0; i < tbBuyer.Rows.Count; i++)
                    {
                        var    tradeAmount = tbBuyer.Rows[i]["trade_amount"].ToString();
                        Buyers obj         = new Buyers();
                        obj.BuyerId   = Convert.ToInt64(tbBuyer.Rows[i]["buyer_id"].ToString());
                        obj.SELLER_ID = Users.Nick;
                        if (Convert.ToDecimal(tradeAmount) > Convert.ToInt32(txtMin1.Text.Trim().ToString()) && Convert.ToDecimal(tradeAmount) <= Convert.ToInt32(txtMax1.Text.Trim().ToString()))
                        {
                            obj.Grade = 1;
                        }
                        if (Convert.ToDecimal(tradeAmount) > Convert.ToInt32(txtMin2.Text.Trim().ToString()) && Convert.ToDecimal(tradeAmount) <= Convert.ToInt32(txtMax2.Text.Trim().ToString()))
                        {
                            obj.Grade = 2;
                        }
                        if (Convert.ToDecimal(tradeAmount) > Convert.ToInt32(txtMin3.Text.Trim().ToString()) && Convert.ToDecimal(tradeAmount) <= Convert.ToInt32(txtMax3.Text.Trim().ToString()))
                        {
                            obj.Grade = 3;
                        }
                        if (Convert.ToDecimal(tradeAmount) > Convert.ToInt32(txtMin4.Text.Trim().ToString()) && Convert.ToDecimal(tradeAmount) <= Convert.ToInt32(txtMax4.Text.Trim().ToString()))
                        {
                            obj.Grade = 4;
                        }
                        BuyerBLL.UpdateGrade(obj);
                    }
                }
            }
            catch (Exception ex)
            {
                lbMsg.Text      = "会员级别调整失败!";
                lbMsg.ForeColor = Color.Red;
                ExceptionReporter.WriteLog(ex, ExceptionPostion.TBApply_Web_UI);
            }
        }
Exemplo n.º 13
0
        private static void Main()
        {
            ErrorHandler errorHandler = new ErrorHandler();

            log4net.ILog log;
            log4net.Config.XmlConfigurator.Configure();
            log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            Application.ThreadException += (sender, args) =>
            {
                log.Error(sender, args.Exception);
                errorHandler.EmailExceptionAndActionLogToSupport(sender, args.Exception);
                ExceptionReporter er = new ExceptionReporter
                {
                    Config =
                    {
                        AppName                   = "SPM Connect",
                        ShowFullDetail            = false,
                        CompanyName               = "SPM Automation",
                        TitleText                 = "SPM Connect Error Report",
                        EmailReportAddress        = "*****@*****.**",
                        TakeScreenshot            = true,                  // attached if sending email
                        SendMethod                = ReportSendMethod.SMTP, // also WebService/SimpleMAPI
                        SmtpServer                = "spmautomation-com0i.mail.protection.outlook.com",
                        SmtpPort                  =                                                          25,
                        SmtpUseDefaultCredentials = true,
                        SmtpFromAddress           = "*****@*****.**",
                        ReportTemplateFormat      = TemplateFormat.Markdown,
                        SmtpUseSsl                = true,
                        UserName                  = System.Security.Principal.WindowsIdentity.GetCurrent().Name,
                        RegionInfo                = "Windsor",
                        ShowAssembliesTab         = false,
                        TopMost                   = true,
                    }
                };
                er.Show(args.Exception);
                er.Send();
            };
            AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
            {
                log.Error(sender, (Exception)args.ExceptionObject);
                errorHandler.EmailExceptionAndActionLogToSupport(sender, (Exception)args.ExceptionObject);
                ExceptionReporter er = new ExceptionReporter
                {
                    Config =
                    {
                        AppName                   = "SPM Connect",
                        ShowFullDetail            = false,
                        CompanyName               = "SPM Automation",
                        TitleText                 = "SPM Connect Error Report",
                        EmailReportAddress        = "*****@*****.**",
                        TakeScreenshot            = true,                  // attached if sending email
                        SendMethod                = ReportSendMethod.SMTP, // also WebService/SimpleMAPI
                        SmtpServer                = "spmautomation-com0i.mail.protection.outlook.com",
                        SmtpPort                  =                                                          25,
                        SmtpUseDefaultCredentials = true,
                        SmtpFromAddress           = "*****@*****.**",
                        ReportTemplateFormat      = TemplateFormat.Markdown,
                        SmtpUseSsl                = true,
                        UserName                  = System.Security.Principal.WindowsIdentity.GetCurrent().Name,
                        RegionInfo                = "Windsor",
                        ShowAssembliesTab         = false,
                        TopMost                   = true,
                    }
                };
                er.Show((Exception)args.ExceptionObject);
                er.Send();
            };

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new SPM_ConnectHome());
        }
Exemplo n.º 14
0
        protected void btnByhand_Click(object sender, ImageClickEventArgs e)
        {
            if (!CheckIsOpenMsgAcount())
            {
                return;
            }

            string cellPhone = txtCellPhone.Text.Trim();

            if (string.IsNullOrEmpty(cellPhone))
            {
                lbMsg2.Text = "请填写手机号码内容!";
                txtCellPhone.Focus();
                return;
            }
            if (!Utility.IsCellPhone(cellPhone))
            {
                lbMsg2.Text = "请填写正确的手机号码内容!";
                txtCellPhone.Focus();
                return;
            }
            if (string.IsNullOrEmpty(txtByHandContent.Text.Trim()))
            {
                lbMsg.Text = "提醒内容不能为空!";
                txtByHandContent.Focus();
                return;
            }
            if (MsgBLL.CheckSellerMsgStatus())
            {
                MsgSendHis objHis = new MsgSendHis();
                objHis.TransNumber    = DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + cellPhone;//手机号码
                objHis.SellerNick     = Users.Nick;
                objHis.Buyer_nick     = "*****";
                objHis.CellPhone      = cellPhone;
                objHis.SendDate       = DateTime.Now;
                objHis.SendType       = "手工退货提醒发送";
                objHis.SendStatus     = "0";
                objHis.MsgContent     = "【" + SellersBLL.GetSignName(Users.Nick) + "】" + txtByHandContent.Text.Trim();
                objHis.HelpSellerNick = "";
                if (SmartBLL.AddMsgSendHis(objHis))
                {
                    try
                    {
                        List <string> lstCellPhoneNo = new List <string>();
                        lstCellPhoneNo.Add(cellPhone.ToString());
                        if (objHis.MsgContent.Length <= 70)
                        {
                            MsgBLL.UpdateMsgTransUseCount(Users.Nick, 1);
                        }
                        else if (objHis.MsgContent.Length > 70 && objHis.MsgContent.Length <= 134)
                        {
                            MsgBLL.UpdateMsgTransUseCount(Users.Nick, 2);
                        }
                        else if (objHis.MsgContent.Length > 134 && objHis.MsgContent.Length <= 195)
                        {
                            MsgBLL.UpdateMsgTransUseCount(Users.Nick, 3);
                        }
                        string sendStatus = Mobile.sendMsgReminder(lstCellPhoneNo, objHis.MsgContent);
                    }
                    catch (Exception ex)
                    {
                        ExceptionReporter.WriteLog(ex, ExceptionPostion.TBApply_Web_UI);
                    }
                }
                lbmsg5.Text       = "提醒发送成功";
                txtCellPhone.Text = "";
                txtCellPhone.Focus();
            }
        }
Exemplo n.º 15
0
        private void SendMessageDoTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                sendMessageDoTimer.Enabled = true;
                //查询同步过来的消息MESSAGE
                //查询主动通知信息从DB开始用于发送短信:只取交易完成的数据用于秒评
                DataTable tbTrade = DBUtil.GetTradeData("");
                //如果该卖家有消息推送
                if (!busySend && tbTrade != null && tbTrade.Rows.Count > 0)
                {
                    busySend = true;
                    foreach (DataRow row in tbTrade.Rows)//轮训通知消息
                    {
                        string   sellerNick = row["seller_nick"].ToString();
                        string   buyerNick  = row["buyer_nick"].ToString();
                        string   tid        = row["tid"].ToString();
                        DateTime createDate = Convert.ToDateTime(row["createDate"]);

                        // 获取卖家保存的自动评价策略
                        DataTable dtAutoConfig    = DBUtil.GetSellerAutoRateConfig(sellerNick);
                        int       isMiaoRate      = 0;
                        int       isWaitBuyerRate = 0;
                        int       isQiangRate     = 0;
                        if (dtAutoConfig == null || dtAutoConfig.Rows.Count == 0)
                        {
                            continue;
                        }

                        isMiaoRate      = Convert.ToInt32(dtAutoConfig.Rows[0]["isMiaoRate"]);
                        isWaitBuyerRate = Convert.ToInt32(dtAutoConfig.Rows[0]["isWaitBuyerRate"]);
                        isQiangRate     = Convert.ToInt32(dtAutoConfig.Rows[0]["isQiangRate"]);
                        //判断卖家是否开通秒评
                        if (isMiaoRate == 1)
                        {
                            #region 秒评

                            //评价开始
                            string sessionKey = DBUtil.GetSellerSessionKey(sellerNick);
                            if (!string.IsNullOrEmpty(sessionKey))
                            {
                                // 获取卖家保存的评价策略
                                DataTable tbSellerRateConfig = DBUtil.GetSellerRateConfig(sellerNick);
                                //检查商家设置:秒评:只检查该用户是否在黑名单
                                if (!DBUtil.CheckIsBlacklst(sellerNick, buyerNick))
                                {
                                    Trade objTrade = TBTrade.GetBuyerTrade(tid, sessionKey);
                                    if (objTrade != null && objTrade.Orders.Count > 0)
                                    {
                                        foreach (Order o in objTrade.Orders)
                                        {
                                            if (!o.SellerRate)
                                            {
                                                RateConfig objRate = new RateConfig();
                                                objRate.Tid        = Convert.ToInt64(tid);
                                                objRate.Oid        = o.Oid;
                                                objRate.Content1   = tbSellerRateConfig.Rows[0]["content1"].ToString();
                                                objRate.Content2   = tbSellerRateConfig.Rows[0]["content2"].ToString();
                                                objRate.Content3   = tbSellerRateConfig.Rows[0]["content3"].ToString();
                                                objRate.Result     = tbSellerRateConfig.Rows[0]["result"].ToString();
                                                objRate.SellerNick = sellerNick;
                                                string    strContent = "";
                                                TBRating  objRateDal = new TBRating();
                                                TradeRate obj        = null;
                                                //调用接口 新增单个评价
                                                obj = objRateDal.BuyerTradeRateOneByOne(objRate, ref strContent, sessionKey);
                                                if (obj == null)
                                                {
                                                    // 调用API进行批量评价
                                                    obj = objRateDal.BuyerTradeRate(objRate, ref strContent, sessionKey);
                                                }
                                                if (obj != null)
                                                {       //rating sucessfull
                                                    obj.Content = strContent;
                                                    obj.Nick    = objRate.SellerNick;
                                                    obj.Tid     = Convert.ToInt64(tid);
                                                    obj.Created = obj.Created;

                                                    // 添加卖家评价:秒评
                                                    //Console.WriteLine("评价卖家:" + obj.Nick + " 评价日期:" + obj.Created);
                                                    DBUtil.AddRateHisWithSeller(obj, "秒评");

                                                    Console.WriteLine("当前卖家:" + sellerNick + "评价时间:" + DateTime.Now.ToString());
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            #endregion
                        }

                        //判断卖家是否开通买家评价以后评价
                        if (isWaitBuyerRate == 1)
                        {
                            #region 方案二(买家评价以后评价)
                            string     sessionKey = DBUtil.GetSellerSessionKey(sellerNick);
                            RateConfig objRate    = new RateConfig();
                            TBRating   objRateDal = new TBRating();

                            objRate.Content1   = dtAutoConfig.Rows[0]["content1"].ToString();
                            objRate.Content2   = dtAutoConfig.Rows[0]["content2"].ToString();
                            objRate.Content3   = dtAutoConfig.Rows[0]["content3"].ToString();
                            objRate.SellerNick = sellerNick;
                            //默认好评
                            objRate.Result = dtAutoConfig.Rows[0]["result"].ToString();

                            //检查买家是否评论
                            List <TradeRate> sates   = objRateDal.GetTradeRate(sessionKey);
                            bool             isRated = false;
                            foreach (TradeRate trade in sates)
                            {
                                if (trade.Tid.ToString() == tid)
                                {
                                    isRated = true;
                                    break;
                                }
                            }
                            if (isRated) //买家已评价
                            {
                                //买家在黑名单
                                if (DBUtil.CheckIsBlacklst(sellerNick, buyerNick))
                                {
                                    int blackBuyerRatedIsRate = Convert.ToInt32(dtAutoConfig.Rows[0]["blackBuyerRatedIsRate"]);
                                    if (blackBuyerRatedIsRate == 1)
                                    {
                                        continue;
                                    }
                                    if (blackBuyerRatedIsRate == 3)
                                    {
                                        objRate.Result         = "neutral";
                                        objRate.BadRateContent = dtAutoConfig.Rows[0]["badRateContent"].ToString();
                                        objRate.Content1       = dtAutoConfig.Rows[0]["badRateContent"].ToString();
                                        objRate.Content2       = dtAutoConfig.Rows[0]["badRateContent"].ToString();
                                        objRate.Content3       = dtAutoConfig.Rows[0]["badRateContent"].ToString();
                                    }
                                    if (blackBuyerRatedIsRate == 4)
                                    {
                                        objRate.Result         = "bad";
                                        objRate.BadRateContent = dtAutoConfig.Rows[0]["badRateContent"].ToString();
                                        objRate.Content1       = dtAutoConfig.Rows[0]["badRateContent"].ToString();
                                        objRate.Content2       = dtAutoConfig.Rows[0]["badRateContent"].ToString();
                                        objRate.Content3       = dtAutoConfig.Rows[0]["badRateContent"].ToString();
                                    }
                                }
                            }
                            else //买家未评价
                            {
                                //买家在黑名单
                                if (DBUtil.CheckIsBlacklst(sellerNick, buyerNick))
                                {
                                    //检查是否到评论时间
                                    TimeSpan ts           = DateTime.Now - createDate;
                                    int      jiange       = (ts.Days * 24 * 60 * 60) + (ts.Hours * 60 * 60) + (ts.Minutes * 60) + (ts.Minutes);
                                    int      congigJiange = (Convert.ToInt32(dtAutoConfig.Rows[0]["blackBuyerNoRateQiangRateDay"]) * 24 * 60 * 60)
                                                            + (Convert.ToInt32(dtAutoConfig.Rows[0]["blackBuyerNoRateQiangRateHour"]) * 60 * 60) + (Convert.ToInt32(dtAutoConfig.Rows[0]["blackBuyerNoRateQiangRateFen"]) * 60);
                                    if (congigJiange < jiange)
                                    {
                                        continue;
                                    }
                                }
                                else //买家不在黑名单
                                {
                                    //检查是否到评论时间
                                    TimeSpan ts           = DateTime.Now - createDate;
                                    int      jiange       = (ts.Days * 24 * 60 * 60) + (ts.Hours * 60 * 60) + (ts.Minutes * 60) + (ts.Minutes);
                                    int      congigJiange = (Convert.ToInt32(dtAutoConfig.Rows[0]["waitBuyerTimeDay"]) * 24 * 60 * 60)
                                                            + (Convert.ToInt32(dtAutoConfig.Rows[0]["waitBuyerTimeHour"]) * 60 * 60) + (Convert.ToInt32(dtAutoConfig.Rows[0]["waitBuyerTimeFen"]) * 60);
                                    if (congigJiange < jiange)
                                    {
                                        continue;
                                    }
                                }
                            }

                            //评价开始
                            if (!string.IsNullOrEmpty(sessionKey))
                            {
                                // 获取卖家保存的评价策略
                                //DataTable tbSellerRateConfig = DBUtil.GetSellerRateConfig(sellerNick);

                                Trade objTrade = TBTrade.GetBuyerTrade(tid, sessionKey);
                                if (objTrade != null && objTrade.Orders.Count > 0)
                                {
                                    foreach (Order o in objTrade.Orders)
                                    {
                                        if (!o.SellerRate)
                                        {
                                            objRate.Tid = Convert.ToInt64(tid);
                                            objRate.Oid = o.Oid;
                                            string    strContent = "";
                                            TradeRate obj        = null;
                                            //调用接口 新增单个评价
                                            obj = objRateDal.BuyerTradeRateOneByOne(objRate, ref strContent, sessionKey);
                                            if (obj == null)
                                            {
                                                // 调用API进行批量评价
                                                obj = objRateDal.BuyerTradeRate(objRate, ref strContent, sessionKey);
                                            }
                                            if (obj != null)
                                            {       //rating sucessfull
                                                obj.Content = strContent;
                                                obj.Nick    = objRate.SellerNick;
                                                obj.Tid     = Convert.ToInt64(tid);
                                                obj.Created = obj.Created;

                                                // 添加卖家评价
                                                //Console.WriteLine("评价卖家:" + obj.Nick + " 评价日期:" + obj.Created);
                                                DBUtil.AddRateHisWithSeller(obj, "方案二");
                                                Console.WriteLine("当前卖家:" + sellerNick + "评价时间:" + DateTime.Now.ToString());
                                            }
                                        }
                                    }
                                }
                            }
                            #endregion
                        }

                        //判断卖家是否开通交易后多长时间评价
                        if (isQiangRate == 1)
                        {
                            #region 方案三(交易后多长时间评价)

                            //检查是否到评论时间
                            TimeSpan ts = DateTime.Now - createDate;
                            //当前时间到提单的时间间隔
                            int jiange = (ts.Days * 24 * 60 * 60) + (ts.Hours * 60 * 60) + (ts.Minutes * 60) + (ts.Minutes);
                            //评价配置的时间间隔
                            int congigJiange = (Convert.ToInt32(dtAutoConfig.Rows[0]["qiangRateTimeDay"]) * 24 * 60 * 60)
                                               + (Convert.ToInt32(dtAutoConfig.Rows[0]["qiangRateTimeHour"]) * 60 * 60) + (Convert.ToInt32(dtAutoConfig.Rows[0]["qiangRateTimeFen"]) * 60);
                            if (congigJiange < jiange)
                            {
                                continue;
                            }
                            //评价开始
                            string sessionKey = DBUtil.GetSellerSessionKey(sellerNick);
                            if (!string.IsNullOrEmpty(sessionKey))
                            {
                                //检查商家设置:秒评:只检查该用户是否在黑名单
                                if (!DBUtil.CheckIsBlacklst(sellerNick, buyerNick))
                                {
                                    Trade objTrade = TBTrade.GetBuyerTrade(tid, sessionKey);
                                    if (objTrade != null && objTrade.Orders.Count > 0)
                                    {
                                        foreach (Order o in objTrade.Orders)
                                        {
                                            if (!o.SellerRate)
                                            {
                                                RateConfig objRate = new RateConfig();
                                                objRate.Tid        = Convert.ToInt64(tid);
                                                objRate.Oid        = o.Oid;
                                                objRate.Content1   = dtAutoConfig.Rows[0]["content1"].ToString();
                                                objRate.Content2   = dtAutoConfig.Rows[0]["content2"].ToString();
                                                objRate.Content3   = dtAutoConfig.Rows[0]["content3"].ToString();
                                                objRate.Result     = dtAutoConfig.Rows[0]["result"].ToString();
                                                objRate.SellerNick = sellerNick;
                                                string    strContent = "";
                                                TBRating  objRateDal = new TBRating();
                                                TradeRate obj        = null;
                                                //调用接口 新增单个评价
                                                obj = objRateDal.BuyerTradeRateOneByOne(objRate, ref strContent, sessionKey);
                                                if (obj == null)
                                                {
                                                    // 调用API进行批量评价
                                                    obj = objRateDal.BuyerTradeRate(objRate, ref strContent, sessionKey);
                                                }
                                                if (obj != null)
                                                {   //rating sucessfull
                                                    obj.Content = strContent;
                                                    obj.Nick    = objRate.SellerNick;
                                                    obj.Tid     = Convert.ToInt64(tid);
                                                    obj.Created = obj.Created;

                                                    // 添加卖家评价:秒评
                                                    //Console.WriteLine("评价卖家:" + obj.Nick + " 评价日期:" + obj.Created);
                                                    DBUtil.AddRateHisWithSeller(obj, "方案三");

                                                    Console.WriteLine("当前卖家:" + sellerNick + "评价时间:" + DateTime.Now.ToString());
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            #endregion
                        }
                        //自动删除数据
                        DBUtil.DeleteValidTradeForMiaoRate(tid);
                    }
                    busySend = false;
                }
            }
            catch (Exception ex)
            {
                ExceptionReporter.WriteLog(ex, ExceptionPostion.TBApply_Data);
            }
            finally
            {
                sendMessageDoTimer.Enabled = true;
            }
        }
Exemplo n.º 16
0
        //保存评价配置
        protected void btnSaveRateConfig_Click(object sender, ImageClickEventArgs e)
        {
            //DataRow orderDate = SellersBLL.GetSelerOrderDate(Users.Nick);
            //if (orderDate != null)
            //{
            //    if (orderDate["OrderVersion"].Equals("体验版"))
            //    {
            //        versionControl.Visible = true;
            //        return;
            //    }
            //}
            RateConfig rateObj = new RateConfig();

            rateObj.SellerNick = Users.Nick;
            RatingBLL objBll = new RatingBLL();

            #region 自动评价设置
            //秒评
            if (rdoMiaoPing.Checked)
            {
                rateObj.IsMiaoRate = 1;
                //选择秒评,则自动开启主动通知授权
                ITopClient            client   = TBManager.GetClient();
                TmcUserPermitRequest  req      = new TmcUserPermitRequest();
                TmcUserPermitResponse response = client.Execute(req, Users.SessionKey);
                AppCustomer           appCus   = null;
                if (response.IsSuccess)
                {
                    appCus         = new AppCustomer();
                    appCus.Status  = "1";
                    appCus.Nick    = Users.Nick;
                    appCus.Created = DateTime.Now.ToShortDateString();

                    //检查卖家是否开启自动评价,如果已开启略过,未开启则开启
                    if (!objBll.CheckAppCusIsExit(Users.Nick))
                    {
                        objBll.AddAppCus(appCus);
                    }
                }
                else
                {
                    lberror2.Text = response.ErrMsg;
                    //Response.Write("<script>alert('" + response.ErrMsg + "');</script>");
                    //lberror2.ForeColor = Color.Red;
                }
            }
            else //其它情况则关闭主动通知消息,删除的前提是用户没有开通差评自动拦截
            {
                //检查卖家是否开启自动评价,如果已开启关闭,未开启则略过
                if (objBll.CheckAppCusIsExit(Users.Nick))
                {
                    //检查卖家差评自动拦截开关是否开启
                    if (!objBll.CheckIsAutoCloseOrder(Users.Nick))
                    {
                        ITopClient           client = TBManager.GetClient();
                        TmcUserCancelRequest req    = new TmcUserCancelRequest();
                        req.Nick = Users.Nick;
                        TmcUserCancelResponse response = client.Execute(req);
                        if (response.IsSuccess)
                        {
                            objBll.DeleteSellerNifty(Users.Nick);
                        }
                        else
                        {
                            lberror2.Text = response.ErrMsg;
                            Response.Write("<script>alert('" + response.ErrMsg + "');</script>");
                            //lberror2.ForeColor = Color.Red;
                        }
                    }
                    else
                    {
                        lberror2.Text = "请先关闭差评自动拦截开关!";
                        //lberror2.ForeColor = Color.Red;
                    }
                }
            }
            //买家评价以后评价
            if (rdoBuyerRated.Checked)
            {
                rateObj.IsWaitBuyerRate   = 1;
                rateObj.WaitBuyerTimeDay  = Convert.ToInt32(drpFangAn2Day.SelectedValue);
                rateObj.WaitBuyerTimeHour = Convert.ToInt32(drpFangAn2Hour.SelectedValue);
                rateObj.WaitBuyerTimeFen  = Convert.ToInt32(drpFangAn2Minute.SelectedValue);
                if (rdoFangAn2NotAtuo.Checked)
                {
                    rateObj.BlackBuyerRatedIsRate = 1;
                }
                if (rdoFangAn2AtuoGoodRate.Checked)
                {
                    rateObj.BlackBuyerRatedIsRate = 2;
                }
                if (rdoFangAn2AtuoNureRate.Checked)
                {
                    rateObj.BlackBuyerRatedIsRate = 3;
                }
                if (rdoFangAn2AtuoPoolRate.Checked)
                {
                    rateObj.BlackBuyerRatedIsRate = 4;
                }
                rateObj.BlackBuyerNoRateQiangRateDay  = Convert.ToInt32(drpFangAn2BacklstDay.SelectedValue);
                rateObj.BlackBuyerNoRateQiangRateHour = Convert.ToInt32(drpFangAn2BacklstHour.SelectedValue);
                rateObj.BlackBuyerNoRateQiangRateFen  = Convert.ToInt32(drpFangAn2BacklstMinute.SelectedValue);
                rateObj.BadRateContent = txtPoolRateContent.Text.Trim();
            }
            //在交易完成后多长时间评价
            if (rdoAutoRate.Checked)
            {
                rateObj.IsQiangRate       = 1;
                rateObj.QiangRateTimeDay  = Convert.ToInt32(drpFangAn3Day.SelectedValue);
                rateObj.QiangRateTimeHour = Convert.ToInt32(drpFangAn3Hour.SelectedValue);
                rateObj.QiangRateTimeFen  = Convert.ToInt32(drpFangAn3Minute.SelectedValue);
            }
            #endregion

            #region 中差评设置
            if (cbBlakList.Checked)
            {
                //自动把给我中差评的买家加入黑名单
                rateObj.AtuoAddBlackListBadRate = 1;
            }
            if (cbAddBlacklstTuikuan.Checked)
            {
                //把半年内有退款申请的买家加入黑名单
                rateObj.AtuoAddBlackListTuiKuan = 1;
            }
            #endregion

            //默认为好评
            rateObj.Result = "good";
            //rateObj.Result = "bad";
            if (!string.IsNullOrEmpty(txtRateTemp1.Text.Trim()))
            {
                rateObj.Content1 = txtRateTemp1.Text.Trim();
            }
            if (!string.IsNullOrEmpty(txtRateTemp2.Text.Trim()))
            {
                rateObj.Content2 = txtRateTemp2.Text.Trim();
            }
            if (!string.IsNullOrEmpty(txtRateTemp3.Text.Trim()))
            {
                rateObj.Content3 = txtRateTemp3.Text.Trim();
            }
            rateObj.ContentChoice = int.Parse(drpContentChoice.SelectedValue);

            //检查评价配置表是否存在卖家
            if (!objBll.CheckRateConfigIsExit(Users.Nick))
            {
                try
                {
                    objBll.AddRateConfig(rateObj);
                    if (string.IsNullOrEmpty(lberror2.Text))
                    {
                        lberror2.Text = "评价条件设置保存成功!";
                        //Response.Write("<script>alert('评价条件设置保存成功,请确保开启自动评价开关!');</script>");
                        //lberror2.ForeColor = Color.Blue;
                    }
                }
                catch (Exception ex)
                {
                    ExceptionReporter.WriteLog(ex, ExceptionPostion.TBApply_Web_UI);
                    Response.Write("<script>alert('评价条件修改失败!');</script>");
                }
            }
            else
            { //更新评价配置策略
                objBll.UpdateRateConfig(rateObj);
                if (string.IsNullOrEmpty(lberror2.Text))
                {
                    lberror2.Text = "评价条件修改成功!";
                    //Response.Write("<script>alert('评价条件修改成功!');</script>");
                    // lberror2.ForeColor = Color.Blue;
                }
            }
        }
Exemplo n.º 17
0
    public ExitCode Run(string[] arguments)
    {
      ExceptionReporter reporter = new ExceptionReporter(_console);

      Options options = new Options();
      if (!options.ParseArguments(arguments))
      {
        _console.WriteLine(Options.Usage());
        return ExitCode.Failure;
      }

      List<ISpecificationRunListener> listeners = new List<ISpecificationRunListener>();

      var timingListener = new TimingRunListener();
      listeners.Add(timingListener);
      listeners.Add(new AssemblyLocationAwareListener());

      ISpecificationRunListener mainListener;
      if (options.TeamCityIntegration)
      {
        mainListener = new TeamCityReporter(_console.WriteLine, timingListener);
      }
      else
      {
        mainListener = new RunListener(_console, options.Silent, timingListener);
      }

      try
      {

        if (!String.IsNullOrEmpty(options.HtmlPath))
        {
          if (IsHtmlPathValid(options.HtmlPath))
          {
            listeners.Add(GetHtmlReportListener(options));
          }
          else
          {
            _console.WriteLine("Invalid html path:" + options.HtmlPath);
            _console.WriteLine(Options.Usage());
            return ExitCode.Failure;
          }

        }

        if (!String.IsNullOrEmpty(options.XmlPath))
        {
          if (IsHtmlPathValid(options.XmlPath))
          {
            listeners.Add(GetXmlReportListener(options, timingListener));
          }
          else
          {
            _console.WriteLine("Invalid xml path:" + options.XmlPath);
            _console.WriteLine(Options.Usage());
            return ExitCode.Failure;
          }
        }

        listeners.Add(mainListener);

        if (options.AssemblyFiles.Count == 0)
        {
          _console.WriteLine(Options.Usage());
          return ExitCode.Failure;
        }

        var listener = new AggregateRunListener(listeners);

        ISpecificationRunner specificationRunner = new AppDomainRunner(listener, options.GetRunOptions());
        List<Assembly> assemblies = new List<Assembly>();
        foreach (string assemblyName in options.AssemblyFiles)
        {
          if (!File.Exists(assemblyName))
          {
            throw NewException.MissingAssembly(assemblyName);
          }

          Assembly assembly = Assembly.LoadFrom(assemblyName);
          assemblies.Add(assembly);
        }

        specificationRunner.RunAssemblies(assemblies);
      }
      catch (Exception ex)
      {
        reporter.ReportException(ex);
        return ExitCode.Error;
      }

      if (mainListener is ISpecificationResultProvider)
      {
        var errorProvider = (ISpecificationResultProvider)mainListener;
        if (errorProvider.FailureOccurred)
        {
          return ExitCode.Failure;
        }
      }
      return ExitCode.Success;
    }
Exemplo n.º 18
0
    public ExitCode Run(string[] arguments)
    {
      ExceptionReporter reporter = new ExceptionReporter(_console);

      Options options = new Options();
      if (!options.ParseArguments(arguments))
      {
        _console.WriteLine(Options.Usage());
        return ExitCode.Failure;
      }

      List<ISpecificationRunListener> listeners = new List<ISpecificationRunListener>();

      var timingListener = new TimingRunListener();
      listeners.Add(timingListener);
      listeners.Add(new AssemblyLocationAwareListener());

      ISpecificationRunListener mainListener;
      if (options.TeamCityIntegration || Environment.GetEnvironmentVariable("TEAMCITY_PROJECT_NAME") != null)
      {
        mainListener = new TeamCityReporter(_console.WriteLine, timingListener);
      }
      else if(options.TerseOutput)
      {
          mainListener = new TerseSpecFormatter(Console.Write, timingListener);
      }
      else
      {
        mainListener = new RunListener(_console, options.Silent, timingListener);
      }

      try
      {

        if (!String.IsNullOrEmpty(options.HtmlPath))
        {
          if (IsHtmlPathValid(options.HtmlPath))
          {
            listeners.Add(GetHtmlReportListener(options));
          }
          else
          {
            _console.WriteLine("Invalid html path:" + options.HtmlPath);
            _console.WriteLine(Options.Usage());
            return ExitCode.Failure;
          }

        }

        if (!String.IsNullOrEmpty(options.XmlPath))
        {
          if (IsHtmlPathValid(options.XmlPath))
          {
            listeners.Add(GetXmlReportListener(options, timingListener));
          }
          else
          {
            _console.WriteLine("Invalid xml path:" + options.XmlPath);
            _console.WriteLine(Options.Usage());
            return ExitCode.Failure;
          }
        }

        listeners.Add(mainListener);

        if (options.AssemblyFiles.Count == 0)
        {
          _console.WriteLine(Options.Usage());
          return ExitCode.Failure;
        }

        var listener = new AggregateRunListener(listeners);

        ISpecificationRunner specificationRunner = new AppDomainRunner(listener, options.GetRunOptions());
        List<Assembly> assemblies = new List<Assembly>();
        foreach (string assemblyName in options.AssemblyFiles)
        {
          if (!File.Exists(assemblyName))
          {
            throw NewException.MissingAssembly(assemblyName);
          }

          Assembly assembly = Assembly.LoadFrom(assemblyName);
          assemblies.Add(assembly);
        }

        if (options.WaitForDebugger)
        {
          WaitForDebugger();
          if (Debugger.IsAttached == false)
          {
            _console.WriteLine("Fatal error: Timeout while waiting for debugger to attach");
            return ExitCode.Failure;
          }
        }

        specificationRunner.RunAssemblies(assemblies);
      }
      catch (Exception ex)
      {
        reporter.ReportException(ex);
        return ExitCode.Error;
      }

      if (mainListener is ISpecificationResultProvider)
      {
        var errorProvider = (ISpecificationResultProvider)mainListener;
        if (errorProvider.FailureOccurred)
        {
          return ExitCode.Failure;
        }
      }
      return ExitCode.Success;
    }
Exemplo n.º 19
0
        private static void Main(string[] args)
        {
            if (Thread.CurrentThread.Name == null)
            {
                Thread.CurrentThread.Name             = "Main";
                Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
            }


            Logger.Info("Starting IA:GD..");
            ExceptionReporter.UrlStats = "https://webstats.evilsoft.net/report/iagd";


            Logger.Info("Starting exception monitor for bug reports..");
            Logger.Debug("Anonymous usage statistics can be seen at https://webstats.evilsoft.net/iagd");
            ExceptionReporter.EnableLogUnhandledOnThread();

            Uris.Initialize(Uris.EnvCloud);
            StartupService.Init();

#if DEBUG
            Test();
            Uris.Initialize(Uris.EnvLocalDev);
#endif

            // Prevent running in RELEASE mode by accident
            // And thus risking the live database
#if !DEBUG
            if (Debugger.IsAttached)
            {
                Logger.Fatal("Debugger attached, please run in DEBUG mode");
                return;
            }
#endif
            //ParsingUIBackgroundWorker tmp = new ParsingUIBackgroundWorker();

            ItemHtmlWriter.CopyMissingFiles();

            Guid guid = new Guid("{F3693953-C090-4F93-86A2-B98AB96A9368}");
            using (SingleInstance singleInstance = new SingleInstance(guid)) {
                if (singleInstance.IsFirstInstance)
                {
                    Logger.Info("Calling run..");
                    singleInstance.ArgumentsReceived += singleInstance_ArgumentsReceived;
                    singleInstance.ListenForArgumentsFromSuccessiveInstances();
                    using (ThreadExecuter threadExecuter = new ThreadExecuter()) {
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        Logger.Info("Visual styles enabled..");
                        Run(args, threadExecuter);
                    }
                }
                else
                {
                    if (args != null && args.Length > 0)
                    {
                        singleInstance.PassArgumentsToFirstInstance(args);
                    }
                    else
                    {
                        singleInstance.PassArgumentsToFirstInstance(new string[] { "--ignore" });
                    }

                    Logger.Info("Already has an instance of IA Running, exiting..");
                }
            }

            Logger.Info("IA Exited");
            LogManager.Shutdown();
        }
Exemplo n.º 20
0
        public static void Main(string[] args)
        {
            TmcClient client = new TmcClient(appKey, appSecret, "default");

            client.OnMessage += (s, e) =>
            {
                try
                {
                    string status = e.Message.Topic;
                    //将消息进行转换
                    IDictionary obj = TopUtils.ParseJson(e.Message.Content);

                    if (obj != null)
                    {
                        #region //物流信息的处理20160916 yao
                        try
                        {
                            if (obj.Contains("action"))
                            {
                                Console.WriteLine(DateTime.Now.ToString() + ":物流提醒:" + e.Message.Content);
                                LogsticDetailTrace logstic = new LogsticDetailTrace();

                                logstic.Tid  = obj["tid"].ToString();
                                logstic.Desc = obj["desc"].ToString();
                                if (obj.Contains("out_sid"))
                                {
                                    logstic.Out_side = obj["out_sid"].ToString();
                                }
                                logstic.Time = obj["time"].ToString();
                                if (obj.Contains("company_name"))
                                {
                                    logstic.Company_name = obj["company_name"].ToString();
                                }
                                logstic.Action = obj["action"].ToString();
                                if (LogisticsBLL.TidIsExist(logstic.Tid))
                                {
                                    LogisticsBLL.updateLogistics(logstic);
                                }
                                else
                                {
                                    LogisticsBLL.AddLogistics(logstic);
                                }
                            }
                            else
                            {
                                NotifyTrade trade = null;
                                Console.WriteLine(DateTime.Now.ToString() + ":店铺管家订单:" + e.Message.Content);
                                trade            = new NotifyTrade();
                                trade.Tid        = obj["tid"].ToString();
                                trade.BuyerNick  = obj["buyer_nick"].ToString();
                                trade.Status     = status;
                                trade.SellerNick = obj["seller_nick"].ToString();
                                trade.Oid        = obj["oid"].ToString();
                                trade.Payment    = obj["payment"].ToString();
                                if (!DBUtil.CheckNoteTradeIsExit(trade.Tid.ToString()))
                                {
                                    DBUtil.AddNoteTradeToDB(trade);                //物流提醒之用
                                    if (status.Equals("taobao_trade_TradeCreate")) //订单拦截之用
                                    {
                                        DBUtil.AddTradeOrderDenfense(trade);
                                    }
                                }
                                else
                                {
                                    DBUtil.UpdateNoteTradeToDB(trade);
                                }
                            }
                        }
                        catch (Exception e1)
                        {
                            Console.WriteLine(e1.ToString());
                        }
                        #endregion
                    }
                    // 默认不抛出异常则认为消息处理成功
                }
                catch (Exception exp)
                {
                    ExceptionReporter.WriteLog(exp, ExceptionPostion.TBApply_Data);
                    e.Fail(); // 消息处理失败回滚,服务端需要重发
                }
            };
            client.Connect("ws://mc.api.taobao.com/");
            Console.ReadLine();
        }
Exemplo n.º 21
0
        protected void btnSave_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                //检查输入项的值是否正确
                if (String.IsNullOrEmpty(txtAmount.Text.Trim()))
                {
                    lberror2.Text = "金额不能为空!"; return;
                }
                if (!Utility.IsINT(txtAmount.Text.Trim()))
                {
                    lberror2.Text = "金额必须为正整数!"; return;
                }
                MsgSendConfig o = new MsgSendConfig();
                o.SellerNick = Users.Nick;
                o.ShopName   = SellersBLL.GetSignName(Users.Nick);
                string strUnpayType  = "0";
                string payType       = "0";
                string shippingType  = "0";
                string arrivedType   = "0";
                string signType      = "0";
                string delayShipType = "0";
                string huiZJType     = "0";

                DataTable tb = MemberNotifyBLL.GetMsgConfigByBuyerSellerNick(o);
                if (tb != null && tb.Rows.Count > 0)
                {
                    strUnpayType  = tb.Rows[0]["unPayType"].ToString();
                    payType       = tb.Rows[0]["payType"].ToString();
                    shippingType  = tb.Rows[0]["shippingType"].ToString();
                    arrivedType   = tb.Rows[0]["arrivedType"].ToString();
                    signType      = tb.Rows[0]["signType"].ToString();
                    delayShipType = tb.Rows[0]["delayShippingType"].ToString();
                    huiZJType     = tb.Rows[0]["huiZJType"].ToString();
                }

                #region 催款

                string strUnpayMsg = "";

                string unpayMsgCus   = "";
                string isUnpayMsgCus = "0";

                if (rdounpayTemp1.Checked)
                {
                    strUnpayMsg = rdounpayTemp1.Text.Trim();
                }
                if (rdounpayTemp2.Checked)
                {
                    strUnpayMsg = rdounpayTemp2.Text.Trim();
                }
                if (rdounpayTemp3.Checked)
                {
                    strUnpayMsg = rdounpayTemp3.Text.Trim();
                }
                if (rdoUnpayCus.Checked)
                {
                    unpayMsgCus   = txtUnpayCusContent.Text.Trim();
                    isUnpayMsgCus = "1";
                }
                else
                {
                    unpayMsgCus   = "";
                    isUnpayMsgCus = "0";
                }
                o.UnpayMsg      = strUnpayMsg;
                o.UnPayType     = strUnpayType;
                o.UnpayMsgCus   = unpayMsgCus;
                o.IsUnpayMsgCus = isUnpayMsgCus;
                #endregion

                #region 付款

                string payMsg      = "";
                string payMsgCus   = "";
                string isPayMsgCus = "0";

                if (rdoPayType1.Checked)
                {
                    payMsg = rdoPayType1.Text.Trim();
                }
                if (rdoPayType2.Checked)
                {
                    payMsg = rdoPayType2.Text.Trim();
                }
                if (rdoPayType3.Checked)
                {
                    payMsg = rdoPayType3.Text.Trim();
                }
                if (rdoPayTypeCus.Checked)
                {
                    payMsgCus   = txtPayCus.Text.Trim();
                    isPayMsgCus = "1";
                }
                else
                {
                    payMsgCus   = "";
                    isPayMsgCus = "0";
                }
                o.PayMsg      = payMsg;
                o.PayType     = payType;
                o.PayMsgCus   = payMsgCus;
                o.IsPayMsgCus = isPayMsgCus;

                #endregion

                #region 发货

                string shippingNofityMsg    = "";
                string shippingNofityMsgCus = "";
                string isShippingMsgCus     = "0";

                if (rdoShippingCont1.Checked)
                {
                    shippingNofityMsg = rdoShippingCont1.Text.Trim();
                }
                if (rdoShippingCont2.Checked)
                {
                    shippingNofityMsg = rdoShippingCont2.Text.Trim();
                }
                if (rdoShippingCont3.Checked)
                {
                    shippingNofityMsg = rdoShippingCont3.Text.Trim();
                }
                if (rdoShiping.Checked)
                {
                    shippingNofityMsgCus = txtShippingContent.Text.Trim();
                    isShippingMsgCus     = "1";
                }
                else
                {
                    shippingNofityMsgCus = "";
                    isShippingMsgCus     = "0";
                }
                o.ShippingNofityMsg    = shippingNofityMsg;
                o.ShippingType         = shippingType;
                o.ShippingNofityMsgCus = shippingNofityMsgCus;
                o.IsShippingMsgCus     = isShippingMsgCus;
                #endregion

                #region 延时发货

                string delayShippingNofityMsg    = "";
                string delayShippingNofityMsgCus = "";
                string isDelayShippingMsgCus     = "0";

                if (rdoDelayShipping.Checked)
                {
                    delayShippingNofityMsg = rdoDelayShipping.Text.Trim();
                }
                if (rdoDelayShipCus.Checked)
                {
                    delayShippingNofityMsgCus = txtDelayShippingCus.Text.Trim();
                    isDelayShippingMsgCus     = "1";
                }
                else
                {
                    delayShippingNofityMsgCus = "";
                    isDelayShippingMsgCus     = "0";
                }
                o.DelayShippingNofityMsg    = delayShippingNofityMsg;
                o.DelayShippingType         = delayShipType;
                o.DelayShippingNofityMsgCus = delayShippingNofityMsgCus;
                o.IsDelayShippingMsgCus     = isDelayShippingMsgCus;
                #endregion

                #region 达到

                string arrivedNofityMsg    = "";
                string arrivedNofityMsgCus = "";
                string isArrivedMsgCus     = "0";

                if (RadioButton4.Checked)
                {
                    arrivedNofityMsg = RadioButton4.Text.Trim();
                }
                if (RadioButton5.Checked)
                {
                    arrivedNofityMsg = RadioButton5.Text.Trim();
                }
                if (RadioButton6.Checked)
                {
                    arrivedNofityMsg = RadioButton6.Text.Trim();
                }
                if (RadioButton7.Checked)
                {
                    arrivedNofityMsgCus = txtArrivedContent.Text.Trim();
                    isArrivedMsgCus     = "1";
                }
                else
                {
                    arrivedNofityMsgCus = "";
                    isArrivedMsgCus     = "0";
                }
                o.ArrivedNofityMsg    = arrivedNofityMsg;
                o.ArrivedType         = arrivedType;
                o.ArrivedNofityMsgCus = arrivedNofityMsgCus;
                o.IsArrivedMsgCus     = isArrivedMsgCus;
                #endregion

                #region 签收

                string signNofityMsg = "";

                string signNotifyMsgCus = "";
                string isSignMsgCus     = "0";
                if (rdoSign1.Checked)
                {
                    signNofityMsg = rdoSign1.Text.Trim();
                }
                if (rdoSign2.Checked)
                {
                    signNofityMsg = rdoSign2.Text.Trim();
                }
                if (rdoSign3.Checked)
                {
                    signNofityMsg = rdoSign3.Text.Trim();
                }
                if (rdoSignCus.Checked)
                {
                    signNotifyMsgCus = txtSignCus.Text.Trim();
                    isSignMsgCus     = "1";
                }
                else
                {
                    signNotifyMsgCus = "";
                    isSignMsgCus     = "0";
                }
                o.SignNofityMsg    = signNofityMsg;
                o.SignType         = signType;
                o.SignNotifyMsgCus = signNotifyMsgCus;
                o.IsSignMsgCus     = isSignMsgCus;
                #endregion

                #region 回款

                string huiZJNofityMsg = "";

                string huiZJNotifyMsgCus = "";
                string isHuiZJMsgCus     = "0";
                if (rdoHuiZJCont.Checked)
                {
                    huiZJNofityMsg = rdoHuiZJCont.Text.Trim();
                }

                if (rdoHuiZJCus.Checked)
                {
                    huiZJNotifyMsgCus = txtHuiZJContent.Text.Trim();
                    isHuiZJMsgCus     = "1";
                }
                else
                {
                    huiZJNotifyMsgCus = "";
                    isHuiZJMsgCus     = "0";
                }
                o.HuiZJNofityMsg    = huiZJNofityMsg;
                o.HuiZJType         = huiZJType;
                o.HuiZJNofityMsgCus = huiZJNotifyMsgCus;
                o.IsHuiZJMsgCus     = isHuiZJMsgCus;
                #endregion

                //if (tb != null && tb.Rows.Count > 0)
                //{
                o.Amount     = txtAmount.Text.Trim().ToString();
                o.BuyerLevel = 0;
                if (MemberNotifyBLL.UpdateMsgConfig(o))
                {
                    lbMsg.Text      = "条件保存成功!";
                    lbMsg.ForeColor = Color.Blue;
                }
                else
                {
                    lbMsg.Text = "条件保存失败,请联系客服";
                }
                //}
            }
            catch (Exception ex)
            {
                ExceptionReporter.WriteLog(ex, ExceptionPostion.TBApply_Web_UI);
                lbMsg.Text = "条件保存失败,请联系客服";
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// The get property values.
        /// </summary>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <param name="collection">
        /// The collection.
        /// </param>
        /// <returns>
        /// </returns>
        public override SettingsPropertyValueCollection GetPropertyValues(
            SettingsContext context, SettingsPropertyCollection collection)
        {
            var settingPropertyCollection = new SettingsPropertyValueCollection();

            if (collection.Count < 1)
            {
                return(settingPropertyCollection);
            }

            string username = context["UserName"].ToString();

            if (username.IsNotSet())
            {
                return(settingPropertyCollection);
            }

            // this provider doesn't support anonymous users
            if (!Convert.ToBoolean(context["IsAuthenticated"]))
            {
                ExceptionReporter.ThrowArgument("PROFILE", "NOANONYMOUS");
            }

            // load the property collection (sync profile class)
            this.LoadFromPropertyCollection(collection);

            // see if it's cached...
            if (this.UserProfileCache.ContainsKey(username.ToLower()))
            {
                // just use the cached version...
                return(this.UserProfileCache[username.ToLower()]);
            }
            // transfer properties regardless...
            foreach (SettingsProperty prop in collection)
            {
                settingPropertyCollection.Add(new SettingsPropertyValue(prop));
            }

            // get this profile from the DB
            DataSet   profileDS = DB.Current.GetProfiles(this.ApplicationName, 0, 1, username, null);
            DataTable profileDT = profileDS.Tables[0];

            if (profileDT.Rows.Count > 0)
            {
                DataRow row = profileDT.Rows[0];

                // load the data into the collection...
                foreach (SettingsPropertyValue prop in settingPropertyCollection)
                {
                    object val = row[prop.Name];

                    // Only initialize a SettingsPropertyValue for non-null values
                    if (val is DBNull || val == null)
                    {
                        continue;
                    }

                    prop.PropertyValue = val;
                    prop.IsDirty       = false;
                    prop.Deserialized  = true;
                }
            }

            // save this collection to the cache
            this.UserProfileCache.AddOrUpdate(username.ToLower(), (k) => settingPropertyCollection, (k, v) => settingPropertyCollection);

            return(settingPropertyCollection);
        }
Exemplo n.º 23
0
            public void ApplicationThreadException(object sender, ThreadExceptionEventArgs e)
            {
                ExceptionReporter reporter = new ExceptionReporter();

                reporter.Show(e.Exception);
            }
Exemplo n.º 24
0
        private void MainWindow_Load(object sender, EventArgs e)
        {
            if (Thread.CurrentThread.Name == null)
            {
                Thread.CurrentThread.Name = "UI";
            }


            ExceptionReporter.EnableLogUnhandledOnThread();
            SizeChanged += OnMinimizeWindow;

            buttonDevTools.Visible = Debugger.IsAttached || _requestedDevtools;

            _stashManager = new StashManager(_playerItemDao, _databaseItemStatDao, SetFeedback, ListviewUpdateTrigger);
            _stashFileMonitor.OnStashModified += (_, __) => {
                StashEventArg args = __ as StashEventArg;
                if (_stashManager.TryLootStashFile(args?.Filename))
                {
                    // STOP TIMER
                    _stashFileMonitor.CancelQueuedNotify();
                }
            };
            if (!_stashFileMonitor.StartMonitorStashfile(GlobalPaths.SavePath))
            {
                MessageBox.Show("Ooops!\nIt seems you are synchronizing your saves to steam cloud..\nThis tool is unfortunately not compatible.\n");
                Process.Start("http://www.grimdawn.com/forums/showthread.php?t=20752");

                if (!Debugger.IsAttached)
                {
                    Close();
                }
            }

            //ItemHtmlWriter.Write(new List<PlayerHeldItem>());

            // Chicken and the egg..
            SearchController searchController = new SearchController(
                _databaseItemDao,
                _playerItemDao,
                _databaseItemStatDao,
                _itemSkillDao,
                _buddyItemDao,
                _stashManager
                );

            _cefBrowserHandler.InitializeChromium(searchController.JsBind, Browser_IsBrowserInitializedChanged);
            searchController.Browser             = _cefBrowserHandler;
            searchController.JsBind.OnTransfer  += TransferItem;
            searchController.JsBind.OnClipboard += SetItemsClipboard;

            // Load the grim database
            string gdPath = GrimDawnDetector.GetGrimLocation();

            if (!string.IsNullOrEmpty(gdPath))
            {
            }
            else
            {
                Logger.Warn("Could not find the Grim Dawn install location");
                statusLabel.Text = "Could not find the Grim Dawn install location";

                var timer = new System.Windows.Forms.Timer();
                timer.Tick    += TimerTickLookForGrimDawn;
                timer.Interval = 10000;
                timer.Start();
            }

            // Load recipes
            foreach (string file in GlobalPaths.FormulasFiles)
            {
                if (!string.IsNullOrEmpty(file))
                {
                    bool isHardcore = file.EndsWith("gsh");
                    Logger.InfoFormat("Reading recipes at \"{0}\", IsHardcore={1}", file, isHardcore);
                    _recipeParser.UpdateFormulas(file, isHardcore);
                }
            }

            var addAndShow = UIHelper.AddAndShow;


            // Create the tab contents
            _buddySettingsWindow = new BuddySettings(delegate(bool b) { BuddySyncEnabled = b; },
                                                     _buddyItemDao,
                                                     _buddySubscriptionDao
                                                     );

            addAndShow(_buddySettingsWindow, buddyPanel);

            var backupSettings = new BackupSettings(EnableOnlineBackups, _playerItemDao);

            tabControl1.Selected += ((s, ev) => {
                if (ev.TabPage == tabPageBackups)
                {
                    backupSettings?.BackupSettings_GotFocus();
                }
            });
            addAndShow(backupSettings, backupPanel);
            addAndShow(new ModsDatabaseConfig(DatabaseLoadedTrigger, _databaseSettingDao, _arzParser, _playerItemDao, _parsingService), modsPanel);
            addAndShow(new HelpTab(), panelHelp);
            addAndShow(new LoggingWindow(), panelLogging);


            _searchWindow = new SearchWindow(_cefBrowserHandler.BrowserControl, SetFeedback, _playerItemDao, searchController, _itemTagDao);
            addAndShow(_searchWindow, searchPanel);


            addAndShow(
                new SettingsWindow(
                    _itemTagDao,
                    _tooltipHelper,
                    ListviewUpdateTrigger,
                    _databaseSettingDao,
                    _databaseItemDao,
                    _playerItemDao,
                    _arzParser,
                    _searchWindow.ModSelectionHandler.GetAvailableModSelection(),
                    _stashManager,
                    _parsingService
                    ),
                settingsPanel);


            new StashTabPicker(_stashManager.NumStashTabs).SaveStashSettingsToRegistry();

#if !DEBUG
            ThreadPool.QueueUserWorkItem(m => ExceptionReporter.ReportUsage());
            CheckForUpdates();
#endif

            int min  = 1000 * 60;
            int hour = 60 * min;
            _timerReportUsage = new Timer();
            _timerReportUsage.Start();
            _timerReportUsage.Elapsed += (a1, a2) => {
                if (Thread.CurrentThread.Name == null)
                {
                    Thread.CurrentThread.Name = "ReportUsageThread";
                }
                ReportUsage();
            };
            _timerReportUsage.Interval  = 12 * hour;
            _timerReportUsage.AutoReset = true;
            _timerReportUsage.Start();


            Shown += (_, __) => { StartInjector(); };

            //settingsController.Data.budd
            BuddySyncEnabled = (bool)Settings.Default.BuddySyncEnabled;

            // Start the backup task
            _backupBackgroundTask = new BackgroundTask(new CloudBackup(_playerItemDao));



            LocalizationLoader.ApplyLanguage(Controls, GlobalSettings.Language);
            EasterEgg.Activate(this);


            // Initialize the "stash packer" used to find item positions for transferring items ingame while the stash is open
            {
                _dynamicPacker.Initialize(8, 16);

                var transferFiles = GlobalPaths.TransferFiles;
                if (transferFiles.Count > 0)
                {
                    var file  = transferFiles.MaxBy(m => m.LastAccess);
                    var stash = StashManager.GetStash(file.Filename);
                    if (stash != null)
                    {
                        _dynamicPacker.Initialize(stash.Width, stash.Height);
                        if (stash.Tabs.Count >= 3)
                        {
                            foreach (var item in stash.Tabs[2].Items)
                            {
                                byte[] bx = BitConverter.GetBytes(item.XOffset);
                                uint   x  = (uint)BitConverter.ToSingle(bx, 0);

                                byte[] by = BitConverter.GetBytes(item.YOffset);
                                uint   y  = (uint)BitConverter.ToSingle(by, 0);

                                _dynamicPacker.Insert(item.BaseRecord, item.Seed, x, y);
                            }
                        }
                    }
                }
            }

            _messageProcessors.Add(new ItemPositionFinder(_dynamicPacker));
            _messageProcessors.Add(new PlayerPositionTracker());
            _messageProcessors.Add(new StashStatusHandler());
            _messageProcessors.Add(new ItemReceivedProcessor(_searchWindow, _stashFileMonitor, _playerItemDao));
            _messageProcessors.Add(new ItemInjectCallbackProcessor(_searchWindow.UpdateListviewDelayed, _playerItemDao));
            _messageProcessors.Add(new ItemSpawnedProcessor());
            _messageProcessors.Add(new CloudDetectorProcessor(SetFeedback));
            _messageProcessors.Add(new GenericErrorHandler());
            //messageProcessors.Add(new LogMessageProcessor());
#if DEBUG
            //messageProcessors.Add(new DebugMessageProcessor());
#endif

            GlobalSettings.StashStatusChanged += GlobalSettings_StashStatusChanged;

            _transferController = new ItemTransferController(
                _cefBrowserHandler,
                SetFeedback,
                SetTooltipAtmouse,
                _settingsController,
                _searchWindow,
                _dynamicPacker,
                _playerItemDao,
                _stashManager,
                new ItemStatService(_databaseItemStatDao, _itemSkillDao)
                );
            Application.AddMessageFilter(new MousewheelMessageFilter());


            {
                var b = !string.IsNullOrEmpty(Settings.Default.OnlineBackupToken) && Settings.Default.OnlineBackupVerified;
                EnableOnlineBackups(b);
            }



            if (BackupNagScreen.ShouldNag)
            {
                var b = new BackupNagScreen();
                b.ShowDialog();
                if (b.UserWantsBackups)
                {
                    tabControl1.SelectedTab = tabPageBackups;
                }
            }

            var titleTag = GlobalSettings.Language.GetTag("iatag_ui_itemassistant");
            if (!string.IsNullOrEmpty(titleTag))
            {
                this.Text += $" - {titleTag}";
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// 获取所有会员信息
        /// </summary>
        /// <returns></returns>
        public static DataTable GetBuyerInfo(string buyerNick, string status, string area, string grade, string group, string tradeAmount1,
                                             string tradeAmount2, string sellerNick2, string buyCount)
        {
            try
            {
                string query             = @"select buyer_id,buyer_nick,ISNULL(buyer_reallName,'unknown') AS buyer_reallName,cellPhone,status,grade,province,trade_amount,trade_count,group_id,item_num, CONVERT(varchar(100),last_trade_time, 23) as last_trade_time from Buyer 
                                where SELLER_ID = @SELLER_ID  ";
                List <SqlParameter> list = new List <SqlParameter>();
                if (!string.IsNullOrEmpty(buyerNick))
                {
                    query += " AND buyer_nick = @buyerNick ";
                    SqlParameter p1 = new SqlParameter("@buyerNick", buyerNick);
                    list.Add(p1);
                }
                if (!status.Equals("all"))
                {
                    query += " AND status = @status ";
                    SqlParameter P2 = new SqlParameter("@status", status);
                    list.Add(P2);
                }
                if (!area.Equals("all"))
                {
                    query += " AND province like @area ";
                    SqlParameter P3 = new SqlParameter("@area", "%" + area + "%");
                    list.Add(P3);
                }
                if (!grade.Equals("all"))
                {
                    query += " AND grade = @grade ";
                    SqlParameter P4 = new SqlParameter("@grade", grade);
                    list.Add(P4);
                }
                if (!string.IsNullOrEmpty(tradeAmount1))
                {
                    query += " AND trade_amount >= @tradeAmount1 ";
                    SqlParameter P5 = new SqlParameter("@tradeAmount1", tradeAmount1);
                    list.Add(P5);
                }
                if (!string.IsNullOrEmpty(tradeAmount2))
                {
                    query += " AND trade_amount <= @tradeAmount2 ";
                    SqlParameter P6 = new SqlParameter("@tradeAmount2", tradeAmount2);
                    list.Add(P6);
                }
                if (!string.IsNullOrEmpty(buyCount))
                {
                    query += " AND trade_count = @buyCount ";
                    SqlParameter P66 = new SqlParameter("@buyCount", buyCount);
                    list.Add(P66);
                }
                if (!group.Equals("全部") && !String.IsNullOrEmpty(group))
                {
                    if (group.Equals("新客户"))
                    {
                        query += "AND buyer_nick in(select T.buyer_nick from (select  count(buyer_nick) as buyerCount,buyer_nick from Trade where status = 'TRADE_FINISHED' group by buyer_nick,seller_nick having count(buyer_nick) = 1 and seller_nick = @seller_nick1) as T inner join Buyer B on B.buyer_nick = T.buyer_nick where B.trade_amount > 0 group by T.buyer_nick)";
                        SqlParameter P7 = new SqlParameter("@seller_nick1", sellerNick2);
                        list.Add(P7);
                    }
                    if (group.Equals("老客户"))
                    {
                        query += "AND buyer_nick in(select T.buyer_nick from (select  count(buyer_nick) as buyerCount,buyer_nick from Trade where status = 'TRADE_FINISHED' group by buyer_nick,seller_nick having count(buyer_nick) > 1 and seller_nick = @seller_nick1) as T inner join Buyer B on B.buyer_nick = T.buyer_nick where B.trade_amount > 0 group by T.buyer_nick)";
                        SqlParameter P8 = new SqlParameter("@seller_nick1", sellerNick2);
                        list.Add(P8);
                    }
                    if (group.Equals("休眠3个月"))
                    {
                        query += "AND buyer_nick in(select buyer_nick from Buyer where trade_amount > 0 and DATEDIFF(day,last_trade_time,getdate()) >= 90 and SELLER_ID = @seller_nick1 group by buyer_nick) ";
                        SqlParameter P9 = new SqlParameter("@seller_nick1", sellerNick2);
                        list.Add(P9);
                    }
                    if (group.Equals("潜在客户"))
                    {
                        query += "AND buyer_nick in(select buyer_nick from Buyer where trade_amount = 0 and SELLER_ID = @seller_nick1) ";
                        SqlParameter P10 = new SqlParameter("@seller_nick1", sellerNick2);
                        list.Add(P10);
                    }
                }

                SqlParameter P11 = new SqlParameter("@SELLER_ID", sellerNick2);
                list.Add(P11);

                query += " order by last_trade_time desc ";
                SqlParameter[] strParam = list.ToArray();
                DataTable      ds       = DataBase.ExecuteDt(query, strParam, CommandType.Text);
                return(ds);
            }
            catch (Exception ex)
            {
                ExceptionReporter.WriteLog(ex, ExceptionPostion.TBApply_Data);
                return(null);
            }
        }
Exemplo n.º 26
0
        private void MsgDataBind()
        {
            int hours1 = 0;
            int min1   = 0;
            int sec1   = 0;
            int hours2 = 0;
            int min2   = 0;
            int sec2   = 0;

            try
            {
                hours1 = string.IsNullOrEmpty(tbHours1.Text.Trim()) ? 0 : Convert.ToInt32(tbHours1.Text.Trim());
                min1   = string.IsNullOrEmpty(tbMin1.Text.Trim()) ? 0 : Convert.ToInt32(tbMin1.Text.Trim());
                sec1   = string.IsNullOrEmpty(tbSecond1.Text.Trim()) ? 0 : Convert.ToInt32(tbSecond1.Text.Trim());
                hours2 = string.IsNullOrEmpty(tbHours2.Text.Trim()) ? 0 : Convert.ToInt32(tbHours2.Text.Trim());
                min2   = string.IsNullOrEmpty(tbMin2.Text.Trim()) ? 0 : Convert.ToInt32(tbMin2.Text.Trim());
                sec2   = string.IsNullOrEmpty(tbSecond2.Text.Trim()) ? 0 : Convert.ToInt32(tbSecond2.Text.Trim());
                if (hours1 > 23 || min1 > 59 || sec1 > 59 || min2 > 59 || sec2 > 59 || hours2 > 23)
                {
                    Response.Write("<script language='javascript'>alert('请正确填写时分秒');</script>");
                    return;
                }
            }
            catch (Exception e)
            {
                Response.Write("<script language='javascript'>alert('请正确填写时分秒');</script>");
                return;
            }
            string startTime;

            if (string.IsNullOrEmpty(txt_StartTime.Value))
            {
                startTime = txt_StartTime.Value;
            }
            else
            {
                startTime = txt_StartTime.Value + " " + hours1 + ":" + min1 + ":" + sec1;
            }
            string endTime;

            if (string.IsNullOrEmpty(txt_EndTime.Value))
            {
                endTime = txt_EndTime.Value;
            }
            else
            {
                endTime = txt_EndTime.Value + " " + hours2 + ":" + min2 + ":" + sec2;
            }

            try
            {
                if (IsAll.Value == "1")
                {
                    DataTable tb = MsgBLL.GetSellerMsgSendHisForReminder(txtTitle.Text.Trim(), startTime, endTime, drpSendType.SelectedValue, "", "");
                    grdCus.DataSource = tb;
                    grdCus.DataBind();
                }
                else
                {
                    DataTable tb = MsgBLL.GetSellerMsgSendHisForReminder(Buyer.Value, "",
                                                                         "", "---全部---", "", "");
                    grdCus.DataSource = tb;
                    grdCus.DataBind();
                }
            }
            catch (Exception ex)
            {
                ExceptionReporter.WriteLog(ex, ExceptionPostion.TBApply_Data);
            }
        }
Exemplo n.º 27
0
        protected void imgbtnFinish_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                if (!rdoMsgTemp1.Checked && !rdoMsgTemp2.Checked && !rdoMsgTemp3.Checked)
                {
                    lbMsg.Text = "请选择短信模版!";
                    return;
                }
                tdLast.Visible             = false;
                tdFinish.Visible           = false;
                tdNext.Visible             = false;
                Menu1.Items[0].ImageUrl    = "~/Images/next3.jpg";
                MultiView1.ActiveViewIndex = 2;
                //确认按钮触发短信提醒
                if (Session["DataSource"] != null)
                {
                    DataTable tb = Session["DataSource"] as DataTable;
                    if (tb != null && tb.Rows.Count > 0)
                    {
                        var cellpone = "";
                        for (int i = 0; i < tb.Rows.Count; i++)
                        {
                            cellpone = tb.Rows[i]["cellPhone"].ToString();
                            if (string.IsNullOrEmpty(cellpone))
                            {
                                continue;
                            }
                            if (Utility.IsCellPhone(cellpone))
                            {
                                if (MsgBLL.CheckSellerMsgStatus())
                                {
                                    //Mobile obj = new Mobile();
                                    //发送消息
                                    string msgContent = "";
                                    if (rdoMsgTemp1.Checked)
                                    {
                                        msgContent = rdoMsgTemp1.Text;
                                    }
                                    if (rdoMsgTemp2.Checked)
                                    {
                                        msgContent = rdoMsgTemp2.Text;
                                    }
                                    if (rdoMsgTemp3.Checked)
                                    {
                                        msgContent = rdoMsgTemp3.Text;
                                    }
                                    if (rdoMsgTemp4.Checked)
                                    {
                                        msgContent = rdoMsgTemp4.Text;
                                    }
                                    msgContent = msgContent.Replace("**店铺名称**", Session["ShopName"] == null ? "" : Session["ShopName"].ToString()) + "【" + Users.Nick + "】";

                                    List <string> lstCellPhoneNo = new List <string>();
                                    lstCellPhoneNo.Add(cellpone);
                                    string sendStatus = Mobile.sendMsg(lstCellPhoneNo, msgContent);
                                    //if (sendStatus.Equals("0"))
                                    //{
                                    if (Convert.ToInt32(lbFontCount.Text.ToString()) <= 65)
                                    {
                                        MsgBLL.UpdateMsgTransUseCount(Users.Nick, 1);
                                    }
                                    else if (Convert.ToInt32(lbFontCount.Text.ToString()) > 65 && Convert.ToInt32(lbFontCount.Text.ToString()) <= 130)
                                    {
                                        MsgBLL.UpdateMsgTransUseCount(Users.Nick, 2);
                                    }
                                    else if (Convert.ToInt32(lbFontCount.Text.ToString()) > 130 && Convert.ToInt32(lbFontCount.Text.ToString()) <= 195)
                                    {
                                        MsgBLL.UpdateMsgTransUseCount(Users.Nick, 3);
                                    }
                                    //}
                                    else if (sendStatus.Equals("-4"))
                                    {
                                        lbOrderMsg.Text = "短信账户余额不足,请充值!";
                                        break;
                                    }
                                    else if (sendStatus.Equals("-5"))
                                    {
                                        lbOrderMsg.Text = "短信内容含有禁止关键字,请修改!";
                                        break;
                                    }
                                }
                                else
                                {
                                    //更新短信账户状态
                                    MsgBLL.UpdateMsgTransServiceStatus(Users.Nick, false);
                                    lbOrderMsg.Text            = "短信账户余额不足,现在去充值?";
                                    imgbtnFinish.Enabled       = false;
                                    Menu1.Items[0].ImageUrl    = "~/Images/next2.jpg";
                                    MultiView1.ActiveViewIndex = 1;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionReporter.WriteLog(ex, ExceptionPostion.TBApply_Web_UI);
            }
        }
Exemplo n.º 28
0
        private void MainWindow_Load(object sender, EventArgs e)
        {
            if (Thread.CurrentThread.Name == null)
            {
                Thread.CurrentThread.Name = "UI";
            }

            Logger.Debug("Starting UI initialization");


            // Set version number
            var      version   = Assembly.GetExecutingAssembly().GetName().Version;
            DateTime buildDate = new DateTime(2000, 1, 1)
                                 .AddDays(version.Build)
                                 .AddSeconds(version.Revision * 2);

            statusLabel.Text = statusLabel.Text + $" - {version.Major}.{version.Minor}.{version.Build}.{version.Revision} from {buildDate.ToString("dd/MM/yyyy")}";


            var settingsService = _serviceProvider.Get <SettingsService>();

            ExceptionReporter.EnableLogUnhandledOnThread();
            SizeChanged += OnMinimizeWindow;


            // Chicken and the egg.. search controller needs browser, browser needs search controllers var.
            var databaseItemDao  = _serviceProvider.Get <IDatabaseItemDao>();
            var searchController = _serviceProvider.Get <SearchController>();

            searchController.JsIntegration.OnRequestSetItemAssociations += (s, evvv) => { (evvv as GetSetItemAssociationsEventArgs).Elements = databaseItemDao.GetItemSetAssociations(); };

            _cefBrowserHandler.InitializeChromium(searchController.JsIntegration, Browser_IsBrowserInitializedChanged, tabControl1);
            searchController.Browser = _cefBrowserHandler;
            searchController.JsIntegration.OnClipboard += SetItemsClipboard;
            searchController.JsIntegration.OnRequestFeatureRecommendation += (o, args) => {
                var features = settingsService.GetPersistent().FeaturesNotShown;
                (args as FeatureSuggestionArgs).Feature    = features.FirstOrDefault();
                (args as FeatureSuggestionArgs).HasFeature = features.Count > 0;
            };
            searchController.JsIntegration.OnSeenFeatureRecommendation += (o, args) => settingsService.GetPersistent().AddShownFeature((args as FeatureSuggestionArgs).Feature);

            var playerItemDao = _serviceProvider.Get <IPlayerItemDao>();
            var cacher        = _serviceProvider.Get <TransferStashServiceCache>();

            _parsingService.OnParseComplete += (o, args) => cacher.Refresh();


            var stashWriter           = new SafeTransferStashWriter(settingsService, _cefBrowserHandler);
            var transferStashService  = new TransferStashService(_serviceProvider.Get <IDatabaseItemStatDao>(), settingsService, stashWriter);
            var transferStashService2 = new TransferStashService2(playerItemDao, cacher, transferStashService, stashWriter, settingsService, _cefBrowserHandler);

            _serviceProvider.Add(transferStashService2);

            _transferStashWorker = new TransferStashWorker(transferStashService2, _userFeedbackService);

            _stashFileMonitor.OnStashModified += (_, __) => {
                StashEventArg args = __ as StashEventArg;
                _transferStashWorker.Queue(args?.Filename);

                // May not minimize, but
                _usageStatisticsReporter.ResetLastMinimized();
                _automaticUpdateChecker.ResetLastMinimized();
            };

            if (!_stashFileMonitor.StartMonitorStashfile(GlobalPaths.SavePath))
            {
                MessageBox.Show("Ooops!\nIt seems you are synchronizing your saves to steam cloud..\nThis tool is unfortunately not compatible.\n");
                _cefBrowserHandler.ShowHelp(HelpService.HelpType.CloudSavesEnabled);

                Logger.Warn("Shutting down IA, unable to monitor stash files.");

                if (!Debugger.IsAttached)
                {
                    Close();
                }
            }

            // Load the grim database
            var    grimDawnDetector = _serviceProvider.Get <GrimDawnDetector>();
            string gdPath           = grimDawnDetector.GetGrimLocation();

            if (!string.IsNullOrEmpty(gdPath))
            {
            }
            else
            {
                Logger.Warn("Could not find the Grim Dawn install location");
                statusLabel.Text = "Could not find the Grim Dawn install location";

                var timer = new System.Windows.Forms.Timer();
                timer.Tick    += TimerTickLookForGrimDawn;
                timer.Interval = 10000;
                timer.Start();
            }

            // Load recipes
            foreach (string file in GlobalPaths.FormulasFiles)
            {
                if (!string.IsNullOrEmpty(file))
                {
                    bool isHardcore = file.EndsWith("gsh");
                    Logger.InfoFormat("Reading recipes at \"{0}\", IsHardcore={1}", file, isHardcore);
                    _recipeParser.UpdateFormulas(file, isHardcore);
                }
            }


            var buddyItemDao         = _serviceProvider.Get <IBuddyItemDao>();
            var buddySubscriptionDao = _serviceProvider.Get <IBuddySubscriptionDao>();



            var databaseSettingDao = _serviceProvider.Get <IDatabaseSettingDao>();

            _authService = new AuthService(_cefBrowserHandler, new AuthenticationProvider(settingsService), playerItemDao);
            var backupSettings = new BackupSettings(playerItemDao, settingsService, _cefBrowserHandler);

            UIHelper.AddAndShow(backupSettings, backupPanel);

            // TODO: buttonLogin.Visible = !BlockedLogsDetection.DreamcrashBlocked();
            var onlineSettings = new OnlineSettings(playerItemDao, _authService, settingsService, _cefBrowserHandler, buddyItemDao, buddySubscriptionDao);

            UIHelper.AddAndShow(onlineSettings, onlinePanel);
            _cefBrowserHandler.OnAuthSuccess += (_, __) => onlineSettings.UpdateUi();


            UIHelper.AddAndShow(new ModsDatabaseConfig(DatabaseLoadedTrigger, playerItemDao, _parsingService, databaseSettingDao, grimDawnDetector, settingsService, _cefBrowserHandler), modsPanel);

            if (!BlockedLogsDetection.DreamcrashBlocked())
            {
                UIHelper.AddAndShow(new LoggingWindow(), panelLogging);
            }

            var itemTagDao    = _serviceProvider.Get <IItemTagDao>();
            var backupService = new BackupService(_authService, playerItemDao, settingsService);

            _charBackupService   = new CharacterBackupService(settingsService, _authService);
            _backupServiceWorker = new BackupServiceWorker(backupService, _charBackupService);
            searchController.JsIntegration.OnRequestBackedUpCharacterList += (_, args) => {
                RequestCharacterListEventArg a = args as RequestCharacterListEventArg;
                a.Characters = _charBackupService.ListBackedUpCharacters();
            };
            searchController.JsIntegration.OnRequestCharacterDownloadUrl += (_, args) => {
                RequestCharacterDownloadUrlEventArg a = args as RequestCharacterDownloadUrlEventArg;
                a.Url = _charBackupService.GetDownloadUrl(a.Character);
            };

            backupService.OnUploadComplete += (o, args) => _searchWindow.UpdateListView();
            searchController.OnSearch      += (o, args) => backupService.OnSearch();

            _searchWindow = new SplitSearchWindow(_cefBrowserHandler.BrowserControl, SetFeedback, playerItemDao, searchController, itemTagDao, settingsService);
            UIHelper.AddAndShow(_searchWindow, searchPanel);

            searchPanel.Height = searchPanel.Parent.Height;
            searchPanel.Width  = searchPanel.Parent.Width;

            transferStashService2.OnUpdate += (_, __) => { _searchWindow.UpdateListView(); };

            var languagePackPicker = new LanguagePackPicker(itemTagDao, playerItemDao, _parsingService, settingsService);


            var dm = new DarkMode(this);

            UIHelper.AddAndShow(
                new SettingsWindow(
                    _cefBrowserHandler,
                    _tooltipHelper,
                    ListviewUpdateTrigger,
                    playerItemDao,
                    _searchWindow.ModSelectionHandler.GetAvailableModSelection(),
                    transferStashService,
                    transferStashService2,
                    languagePackPicker,
                    settingsService,
                    grimDawnDetector,
                    dm
                    ),
                settingsPanel);

#if !DEBUG
            if (!BlockedLogsDetection.DreamcrashBlocked())   // Uses dreamcrash server
            {
                ThreadPool.QueueUserWorkItem(m => ExceptionReporter.ReportUsage());
                _automaticUpdateChecker.CheckForUpdates();
            }
#endif

            Shown += (_, __) => { StartInjector(); };
            _buddyItemsService = new BuddyItemsService(
                buddyItemDao,
                3 * 60 * 1000,
                settingsService,
                _authService,
                buddySubscriptionDao
                );

            // Start the backup task
            _backupBackgroundTask = new BackgroundTask(new FileBackup(playerItemDao, settingsService));

            LocalizationLoader.ApplyLanguage(Controls, RuntimeSettings.Language);
            new EasterEgg(settingsService).Activate(this);

            // Initialize the "stash packer" used to find item positions for transferring items ingame while the stash is open
            {
                _dynamicPacker.Initialize(8, 16);

                var transferFiles = GlobalPaths.TransferFiles;
                if (transferFiles.Count > 0)
                {
                    var file  = transferFiles.MaxBy(m => m.LastAccess);
                    var stash = TransferStashService.GetStash(file.Filename);
                    if (stash != null)
                    {
                        _dynamicPacker.Initialize(stash.Width, stash.Height);
                        if (stash.Tabs.Count >= 3)
                        {
                            foreach (var item in stash.Tabs[2].Items)
                            {
                                byte[] bx = BitConverter.GetBytes(item.XOffset);
                                uint   x  = (uint)BitConverter.ToSingle(bx, 0);

                                byte[] by = BitConverter.GetBytes(item.YOffset);
                                uint   y  = (uint)BitConverter.ToSingle(by, 0);

                                _dynamicPacker.Insert(item.BaseRecord, item.Seed, x, y);
                            }
                        }
                    }
                }
            }

            _messageProcessors.Add(new ItemPositionFinder(_dynamicPacker));
            _messageProcessors.Add(new PlayerPositionTracker(Debugger.IsAttached && false));
            _messageProcessors.Add(new StashStatusHandler());
            _messageProcessors.Add(new CloudDetectorProcessor(SetFeedback));
            _messageProcessors.Add(new GenericErrorHandler());


            RuntimeSettings.StashStatusChanged += GlobalSettings_StashStatusChanged;

            _transferController = new ItemTransferController(
                _cefBrowserHandler,
                SetFeedback,
                SetTooltipAtmouse,
                _searchWindow,
                playerItemDao,
                transferStashService,
                _serviceProvider.Get <ItemStatService>(),
                settingsService
                );
            Application.AddMessageFilter(new MousewheelMessageFilter());


            var titleTag = RuntimeSettings.Language.GetTag("iatag_ui_itemassistant");
            if (!string.IsNullOrEmpty(titleTag))
            {
                this.Text += $" - {titleTag}";
            }


            // Popup login diag
            if (_authService.CheckAuthentication() == AuthService.AccessStatus.Unauthorized && !settingsService.GetLocal().OptOutOfBackups)
            {
                if (!BlockedLogsDetection.DreamcrashBlocked())
                {
                    // Backup login wont work
                    var t = new System.Windows.Forms.Timer {
                        Interval = 100
                    };
                    t.Tick += (o, args) => {
                        if (_cefBrowserHandler.BrowserControl.CanExecuteJavascriptInMainFrame)
                        {
                            _authService.Authenticate();
                            t.Stop();
                        }
                    };
                    t.Start();
                }
            }


            searchController.JsIntegration.ItemTransferEvent += TransferItem;
            new WindowSizeManager(this, settingsService);


            // Suggest translation packs if available
            if (string.IsNullOrEmpty(settingsService.GetLocal().LocalizationFile) && !settingsService.GetLocal().HasSuggestedLanguageChange)
            {
                if (LocalizationLoader.HasSupportedTranslations(grimDawnDetector.GetGrimLocations()))
                {
                    Logger.Debug("A new language pack has been detected, informing end user..");
                    new LanguagePackPicker(itemTagDao, playerItemDao, _parsingService, settingsService).Show(grimDawnDetector.GetGrimLocations());

                    settingsService.GetLocal().HasSuggestedLanguageChange = true;
                }
            }


            if (settingsService.GetPersistent().DarkMode)
            {
                dm.Activate(); // Needs a lot more work before its ready, for example custom components uses Draw and does not respect coloring.
                _cefBrowserHandler.SetDarkMode(settingsService.GetPersistent().DarkMode);
            }

            Logger.Debug("UI initialization complete");
        }
Exemplo n.º 29
0
        /// <summary>
        /// Initialie Membership Provider
        /// </summary>
        /// <param name="name">Membership Provider Name</param>
        /// <param name="config">NameValueCollection of configuration items</param>
        public override void Initialize(string name, NameValueCollection config)
        {
            // Verify that the configuration section was properly passed
            if (config == null)
            {
                ExceptionReporter.ThrowArgument("ROLES", "CONFIGNOTFOUND");
            }

            // Retrieve information for provider from web config
            // config ints

            // Minimum Required Password Length from Provider configuration
            _minimumRequiredPasswordLength = int.Parse(config ["minRequiredPasswordLength"] ?? "6");

            // Minimum Required Non Alpha-numeric Characters from Provider configuration
            _minRequiredNonAlphanumericCharacters = int.Parse(config ["minRequiredNonalphanumericCharacters"] ?? "1");

            // Maximum number of allowed password attempts
            _maxInvalidPasswordAttempts = int.Parse(config ["maxInvalidPasswordAttempts"] ?? "5");

            // Password Attempt Window when maximum attempts have been reached
            _passwordAttemptWindow = int.Parse(config ["passwordAttemptWindow"] ?? "10");

            // Check whething Hashing methods should use Salt
            _useSalt = Utils.Transform.ToBool(config ["useSalt"] ?? "false");

            // Application Name
            _appName = Utils.Transform.ToString(config ["applicationName"], "YetAnotherForum");

            _passwordStrengthRegularExpression = Utils.Transform.ToString(config ["passwordStrengthRegularExpression"]);

            // Password reset enabled from Provider Configuration
            _enablePasswordReset       = Utils.Transform.ToBool(config ["enablePasswordReset"] ?? "true");
            _enablePasswordRetrieval   = Utils.Transform.ToBool(config ["enablePasswordRetrieval"] ?? "false");
            _requiresQuestionAndAnswer = Utils.Transform.ToBool(config ["requiresQuestionAndAnswer"] ?? "true");

            _requiresUniqueEmail = Utils.Transform.ToBool(config ["requiresUniqueEmail"] ?? "true");

            string strPasswordFormat = Utils.Transform.ToString(config ["passwordFormat"], "Hashed");

            switch (strPasswordFormat)
            {
            case "Clear":
                _passwordFormat = MembershipPasswordFormat.Clear;
                break;

            case "Encrypted":
                _passwordFormat = MembershipPasswordFormat.Encrypted;
                break;

            case "Hashed":
                _passwordFormat = MembershipPasswordFormat.Hashed;
                break;

            default:
                ExceptionReporter.Throw("MEMBERSHIP", "BADPASSWORDFORMAT");
                break;
            }

            base.Initialize(name, config);
        }
 public unsafe static void Release(AtomicSafetyHandle handle)
 {
     AtomicSafetyHandle_Release(&handle);
     ExceptionReporter.Check();
 }
Exemplo n.º 31
0
        private void process(BackgroundWorker worker, RunArguments arguments)
        {
            System.Threading.Thread.Sleep(1200);

            HashSet <uint> pids = FindProcesses(arguments);


            if (pids.Count == 0 && _previouslyInjected.Count == 0)
            {
                worker.ReportProgress(NO_PROCESS_FOUND_ON_STARTUP, null);
            }
            else if (pids.Count == 0)
            {
                worker.ReportProgress(NO_PROCESS_FOUND, null);
            }

            string dll = Path.Combine(Directory.GetCurrentDirectory(), arguments.DllName);

            if (!File.Exists(dll))
            {
                Logger.FatalFormat("Could not find {1} at \"{0}\"", dll, arguments.DllName);
            }
            else
            {
                foreach (uint pid in pids)
                {
                    if (!_previouslyInjected.Contains(pid))
                    {
                        //DllInjector.adjustDebugPriv(pid);
                        IntPtr remoteModuleHandle = DllInjector.NewInject(pid, dll);
                        if (remoteModuleHandle == IntPtr.Zero)
                        {
                            if (!_dontLog.Contains(pid))
                            {
                                Logger.WarnFormat("Could not inject dll into process {0}, if this is a recurring issue, try running as administrator.", pid);
                                worker.ReportProgress(INJECTION_ERROR, "Could not inject dll into process " + pid);
                            }
                        }
                        else
                        {
                            if (!_dontLog.Contains(pid))
                            {
                                Logger.Info("Injected dll into process " + pid);
                            }

                            if (!InjectionVerifier.VerifyInjection(pid, arguments.DllName))
                            {
                                if (!_dontLog.Contains(pid))
                                {
                                    Logger.Warn("InjectionVerifier reports injection failed.");
                                    ExceptionReporter.ReportIssue("InjectionVerifier reports injection failed into PID " + pid);
                                    worker.ReportProgress(INJECTION_ERROR, string.Format("InjectionVerifier reports injection failed into PID {0}, try running as administrator.", pid));
                                }


                                _dontLog.Add(pid);
                            }
                            else
                            {
                                Logger.Info("InjectionVerifier reports injection succeeded.");
                                _previouslyInjected.Add(pid);
                                _pidModuleHandleMap[pid] = remoteModuleHandle;
                            }
                        }
                    }
                }
            }
        }
 public unsafe static void CheckDisposeAndThrow(AtomicSafetyHandle handle)
 {
     AtomicSafetyHandle_CheckDisposeAndThrow(&handle);
     ExceptionReporter.Check();
 }
Exemplo n.º 33
0
    public ExitCode Run(string[] arguments)
    {
      ExceptionReporter reporter = new ExceptionReporter(_console);

      Options options = new Options();
      if (!options.ParseArguments(arguments))
      {
        _console.WriteLine(Options.Usage());
        return ExitCode.Failure;
      }

      var timer = new TimingRunListener();
      var listeners = new List<ISpecificationRunListener>
                      {
                        timer
                      };

      ISpecificationRunListener mainListener;
      if (options.TeamCityIntegration ||
          (!options.DisableTeamCityAutodetection &&
           Environment.GetEnvironmentVariable("TEAMCITY_PROJECT_NAME") != null))
      {
        mainListener = new TeamCityReporter(_console.WriteLine, timer);
      }
      else
      {
        mainListener = new RunListener(_console, DetermineOutput(options, _console), timer);
      }

      try
      {

        if (!String.IsNullOrEmpty(options.HtmlPath))
        {
          if (IsHtmlPathValid(options.HtmlPath))
          {
            listeners.Add(GetHtmlReportListener(options));
          }
          else
          {
            _console.WriteLine("Invalid html path: {0}", options.HtmlPath);
            _console.WriteLine(Options.Usage());
            return ExitCode.Failure;
          }

        }

        if (!String.IsNullOrEmpty(options.XmlPath))
        {
          if (IsHtmlPathValid(options.XmlPath))
          {
            listeners.Add(GetXmlReportListener(options, timer));
          }
          else
          {
            _console.WriteLine("Invalid xml path: {0}", options.XmlPath);
            _console.WriteLine(Options.Usage());
            return ExitCode.Failure;
          }
        }

        listeners.Add(mainListener);

        if (options.AssemblyFiles.Count == 0)
        {
          _console.WriteLine(Options.Usage());
          return ExitCode.Failure;
        }

        var listener = new AggregateRunListener(listeners);

        ISpecificationRunner specificationRunner = new AppDomainRunner(listener, options.GetRunOptions());
        List<Assembly> assemblies = new List<Assembly>();
        foreach (string assemblyName in options.AssemblyFiles)
        {
          if (!File.Exists(assemblyName))
          {
            throw NewException.MissingAssembly(assemblyName);
          }

          var excludedAssemblies = new[] { "Machine.Specifications.dll", "Machine.Specifications.Clr4.dll" };
          if (excludedAssemblies.Any(x => Path.GetFileName(assemblyName) == x))
          {
            _console.WriteLine("Warning: Excluded {0} from the test run because the file name matches either of these: {1}", assemblyName, String.Join(", ", excludedAssemblies));
            continue;
          }

          Assembly assembly = Assembly.LoadFrom(assemblyName);
          assemblies.Add(assembly);
        }

        if (options.WaitForDebugger)
        {
          WaitForDebugger();
          if (Debugger.IsAttached == false)
          {
            _console.WriteLine("Fatal error: Timeout while waiting for debugger to attach");
            return ExitCode.Failure;
          }
        }

        specificationRunner.RunAssemblies(assemblies);
      }
      catch (Exception ex)
      {
        reporter.ReportException(ex);
        return ExitCode.Error;
      }

      if (mainListener is ISpecificationResultProvider)
      {
        var errorProvider = (ISpecificationResultProvider)mainListener;
        if (errorProvider.FailureOccurred)
        {
          return ExitCode.Failure;
        }
      }
      return ExitCode.Success;
    }
 public unsafe static void CheckGetSecondaryDataPointerAndThrow(AtomicSafetyHandle handle)
 {
     AtomicSafetyHandle_CheckGetSecondaryDataPointerAndThrow(&handle);
     ExceptionReporter.Check();
 }
Exemplo n.º 35
0
        public ExitCode Run(string[] arguments)
        {
            ExceptionReporter reporter = new ExceptionReporter(_console);

              Options options = new Options();
              if (!options.ParseArguments(arguments))
              {
            _console.WriteLine(Resources.UsageStatement);
            return ExitCode.Failure;
              }

              List<ISpecificationRunListener> listeners = new List<ISpecificationRunListener>();

              var runListener = new RunListener(_console, options.Silent);

              try
              {

            if (!String.IsNullOrEmpty(options.HtmlPath))
            {
              if (IsHtmlPathValid(options.HtmlPath))
              {
            listeners.Add(GetHtmlReportListener(options));
              }
              else
              {
            _console.WriteLine("Invalid html path:" + options.HtmlPath);
            _console.WriteLine(Resources.UsageStatement);
            return ExitCode.Failure;
              }

            }

            listeners.Add(runListener);

            if (options.AssemblyFiles.Count == 0)
            {
              _console.WriteLine(Resources.UsageStatement);
              return ExitCode.Failure;
            }

            var listener = new AggregateRunListener(listeners);

            ISpecificationRunner specificationRunner = new AppDomainRunner(listener, options.GetRunOptions());
            List<Assembly> assemblies = new List<Assembly>();
            foreach (string assemblyName in options.AssemblyFiles)
            {
              if (!File.Exists(assemblyName))
              {
            throw NewException.MissingAssembly(assemblyName);
              }

              Assembly assembly = Assembly.LoadFrom(assemblyName);
              assemblies.Add(assembly);
            }

            specificationRunner.RunAssemblies(assemblies);
              }
              catch(Exception ex)
              {
            reporter.ReportException(ex);
            return ExitCode.Error;
              }

              if (runListener.FailureOccured)
              {
            return ExitCode.Failure;
              }

              return ExitCode.Success;
        }
Exemplo n.º 36
0
    public ExitCode Run(string[] arguments)
    {
      ExceptionReporter reporter = new ExceptionReporter(_console);

      Options options = new Options();
      if (!options.ParseArguments(arguments))
      {
        _console.WriteLine(Resources.UsageStatement);
        return ExitCode.Failure;
      }

          ISpecificationRunListener mainListener = null;
      do
      {
          List<ISpecificationRunListener> listeners = new List<ISpecificationRunListener>();

          var timingListener = new TimingRunListener();
          listeners.Add(timingListener);

          if (options.TeamCityIntegration)
          {
              mainListener = new TeamCityReporter(_console.WriteLine, timingListener);
          }
          else
          {
              mainListener = new RunListener(_console, options.Silent, timingListener);
          }

          try
          {

              if (!String.IsNullOrEmpty(options.HtmlPath))
              {
                  if (IsHtmlPathValid(options.HtmlPath))
                  {
                      listeners.Add(GetHtmlReportListener(options));
                  }
                  else
                  {
                      _console.WriteLine("Invalid html path:" + options.HtmlPath);
                      _console.WriteLine(Resources.UsageStatement);
                      return ExitCode.Failure;
                  }

              }

              if (!String.IsNullOrEmpty(options.XmlPath))
              {
                  if (IsHtmlPathValid(options.XmlPath))
                  {
                      listeners.Add(GetXmlReportListener(options));
                  }
                  else
                  {
                      _console.WriteLine("Invalid xml path:" + options.XmlPath);
                      _console.WriteLine(Resources.UsageStatement);
                      return ExitCode.Failure;
                  }
              }

              listeners.Add(mainListener);

              if (options.AssemblyFiles.Count == 0)
              {
                  _console.WriteLine(Resources.UsageStatement);
                  return ExitCode.Failure;
              }

              _console.WriteLine("Files Count: {0} Name: {1}", options.AssemblyFiles.Count, options.AssemblyFiles.Count > 0?options.AssemblyFiles[options.AssemblyFiles.Count-1]:"none");
              bool runXap = options.AssemblyFiles.Count > 0 && options.AssemblyFiles[options.AssemblyFiles.Count-1].EndsWith(".xap", StringComparison.OrdinalIgnoreCase);

              if (!options.WcfListen && !runXap)
              {
                  listeners.Add(new AssemblyLocationAwareListener());
                  var listener = new AggregateRunListener(listeners);

                  ISpecificationRunner specificationRunner = new AppDomainRunner(listener, options.GetRunOptions());
                  List<Assembly> assemblies = new List<Assembly>();
                  foreach (string assemblyName in options.AssemblyFiles)
                  {
                      if (!File.Exists(assemblyName))
                      {
                          throw NewException.MissingAssembly(assemblyName);
                      }

                      Assembly assembly = Assembly.LoadFrom(assemblyName);
                      assemblies.Add(assembly);
                  }

                  specificationRunner.RunAssemblies(assemblies);
              }
              else
              {
                  var completionListener = new CompletionListener();
                  listeners.Add(completionListener);

                  var listener = new AggregateRunListener(listeners);

                  var proxy = new WcfRunnerProxy(listener);
                  ServiceHost host = null;
                  try
                  {
                      host = new ServiceHost(proxy);

                      host.AddServiceEndpoint(typeof(ISpecificationRunListener), new BasicHttpBinding(), new Uri("http://localhost:5931/MSpecListener"));

                      ((System.ServiceModel.Description.ServiceDebugBehavior)host.Description.Behaviors[typeof(System.ServiceModel.Description.ServiceDebugBehavior)]).IncludeExceptionDetailInFaults = true;

                      var smb = new System.ServiceModel.Description.ServiceMetadataBehavior();
                      smb.MetadataExporter.PolicyVersion = System.ServiceModel.Description.PolicyVersion.Policy15;
                      host.Description.Behaviors.Add(smb);

                      host.AddServiceEndpoint(typeof(System.ServiceModel.Description.IMetadataExchange),
                          System.ServiceModel.Description.MetadataExchangeBindings.CreateMexHttpBinding(), "http://localhost:5931/MSpecListener/MEX");

                      host.Open();

                      _console.WriteLine("=========================================================================");
                      _console.WriteLine("Waiting for test results via WCF at http://localhost:5931/MSpecListener");

                      if (runXap)
                      {
                          var xap = options.AssemblyFiles[options.AssemblyFiles.Count-1];
                          if (!File.Exists(xap))
                          {
                              throw NewException.MissingAssembly(xap);
                          }

                          var runner = new Wp7DeviceRunner(true);
                          runner.RunXap(xap);
                      }

                      completionListener.WaitForRunCompletion();
                      System.Threading.Thread.Sleep(1000);
                  }
                  finally
                  {
                      if (host != null && host.State != CommunicationState.Faulted)
                          host.Close();
                  }
              }
          }
          catch (Exception ex)
          {
              if (System.Diagnostics.Debugger.IsAttached)
                  System.Diagnostics.Debugger.Break();

              reporter.ReportException(ex);
              return ExitCode.Error;
          }
      } while (options.Loop);

      if (mainListener != null && mainListener is ISpecificationResultProvider)
      {
        var errorProvider = (ISpecificationResultProvider)mainListener;
        if (errorProvider.FailureOccured)
        {
          Console.WriteLine("Generic failure occurred, no idea what this is");
          return ExitCode.Failure;
        }
      }
      return ExitCode.Success;
    }