Пример #1
0
        static void Main(string[] args)
        {
            ILogger logger = new NLogger();

            // Create the threads.
            ServerThread server = new ServerThread(logger);
            ListenThread listen = new ListenThread(logger, server, 4530);
            DatabaseThread database = new DatabaseThread(logger);

            // Create the login handler.
            Login login = new Login(logger, server, database);

            // Start things up.
            server.Run();
            listen.Run();
            database.Run();

            // We could potentially make this a service so there's no infinite
            // looping.
            while (true) {
                if (server.Fatal || listen.Fatal) {
                    // TODO: Potentially attempt to restart?
                    break;
                }

                Thread.Sleep(100);
            }
        }
Пример #2
0
        private static SignaloBotHub<ObjectId> InitSenderHub()
        {
            ICommonLogger logger = new NLogger();
            MongoDbConnectionSettings connection = SignaloBotTestParameters.MongoDbConnection;

            var queueQueries = new MongoDbSignalDispatchQueries(logger, connection);
            var eventQueries = new MongoDbSignalEventQueries(logger, connection);
            var deliveryTypeSettingsQueries = new MongoDbUserDeliveryTypeSettingsQueries(logger, connection);
            var categoryQueries = new MongoDbUserCategorySettingsQueries(logger, connection);
            var topicQueries = new MongoDbUserTopicSettingsQueries(logger, connection);
            var receivePeriodQueries = new MongoDbUserReceivePeriodQueries(logger, connection);

            var hub = new SignaloBotHub<ObjectId>();
            hub.Logger = logger;
            hub.StatisticsCollector = new ConsoleStatisticsCollector<ObjectId>();

            hub.EventQueues.Add(new EventQueue<ObjectId>(eventQueries)
            {
                ItemsQueryCount = 200,
                QueryPeriod = TimeSpan.FromSeconds(30),
                MaxFailedAttempts = 2
            });

            hub.Composer = new KeyValueComposer<ObjectId>()
            {
                ComposerQueries = new LocalComposerQueries<ObjectId>(GetComposerSettings()),
                SubscriberQueries = new MongoDbSubscriberQueries(logger, connection),
                Logger = logger
            };

            hub.DispatchQueues.Add(new DispatchQueue<ObjectId>(queueQueries)
            {
                ItemsQueryCount = 200,
                QueryPeriod = TimeSpan.FromSeconds(30),
                MaxFailedAttempts = 2,
                FailedAttemptRetryPeriod = TimeSpan.FromMinutes(5)
            });

            hub.Senders.Add(new DispatchChannel<ObjectId>()
            {
                Sender = new ConsoleMessageSender<ObjectId>(),
                DeliveryType = (int)DeliveryType.Console
            });

            var instanceProvider = new SignalServiceInstanceProvider<ObjectId>(
                hub.EventQueues.First(), hub.StatisticsCollector
                , deliveryTypeSettingsQueries, categoryQueries, topicQueries, receivePeriodQueries);
            hub.ServiceHost = new SignalServiceSelfHost<ObjectId>(logger, instanceProvider);

            return hub;
        }
        public void HostTest()
        {
            var manualResetEvent = new ManualResetEventSlim();

            var uri = new Uri("ws://localhost");

            var logger = new NLogger();

            var host = new StyxHost(uri, logger: logger);

            host.Start();

            manualResetEvent.Wait();
        }
Пример #4
0
 public void CheckRecoveryFileExist()
 {
     if (!_isEnable)
     {
         return;
     }
     this.LoadRecoveryFiles();
     if (RecoveryInfo != null && RecoveryInfo.RecoveryFiles != null)
     {
         try
         {
             NLogger.Info("Check files in recovery setting exist.");
             var recoveryfiles = RecoveryInfo.RecoveryFiles.Where(x => File.Exists(x.GetFullPath())).ToList();
             RecoveryInfo.RecoveryFiles = recoveryfiles;
             this.SaveRecoveryFiles();
         }
         catch (Exception ex)
         {
             NLogger.Warn("CheckRecoveryFileExist failed.{0}", ex.ToString());
         }
     }
 }
Пример #5
0
        public static async Task PushByInspurIDAsync(List <string> inspurids, string message, string url = "")
        {
            StringBuilder sb = new StringBuilder(360);

            foreach (var item in inspurids)
            {
                sb.AppendFormat("contact={0}&", item);
            }

            string contacts = sb.ToString().TrimEnd('&');
            string pushUrl  = "https://ecm.inspur.com/bot/ecc_community/api/v0/bot/enterprise/10000/message?" + contacts;

            Dictionary <string, string> data = new Dictionary <string, string>();

            data.Add("type", "txt_rich");
            data.Add("creationDate", Convert.ToString(DateTime.Now.Ticks));
            data.Add("source", message);

            string jsonStr = JsonConvert.SerializeObject(data);

            HttpContent content = new StringContent(jsonStr, Encoding.UTF8, "application/json");

            HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Post, pushUrl);

            msg.Content = content;

            msg.Headers.Add("Authorization", Token);
            msg.Headers.Add("User-Agent", "Inspur travel cloud 1.0.0");

            var httpClient = new HttpClient();
            var rm         = await httpClient.SendAsync(msg);

            string json = await rm.Content.ReadAsStringAsync();

            if (rm.IsSuccessStatusCode == false)
            {
                NLogger.Error(json);
            }
        }
Пример #6
0
        public void Clear(string elementName, By byObject)
        {
            IWebElement element = null;

            try
            {
                element = WaitForElementToBeVisible(elementName, byObject);
                element.Clear();

                string info = string.Format("Clear element content [{0}]", elementName);
                NLogger.Info(info);
                HtmlReporter.Pass(info);
            }
            catch (WebDriverException ex)
            {
                string message = string.Format("An error happens when trying to clear element content [{0}].", elementName);
                ScreenShotCapturing.HighlightElement(driver, element);
                string screenshot = ScreenShotCapturing.TakeScreenShoot(driver, message);
                HtmlReporter.Fail(message, ex, screenshot);
                throw new ErrorHandler(message, ex);
            }
        }
Пример #7
0
        public void SelectValueInDropBoxByElement(string elementName, By byObject, By item)
        {
            try
            {
                IWebElement comboBox = WaitForElementToBeClickable(elementName, byObject);
                comboBox.Click();

                IWebElement selectedItem = WaitForElementToBeClickable("", item);
                selectedItem.Click();

                string info = string.Format("SelectValueInDropBoxByElement from element [{0}].", elementName);
                NLogger.Info(info);
                HtmlReporter.Pass(info);
            }
            catch (WebDriverException ex)
            {
                string message    = string.Format("An error happens when trying to SelectValueInDropBoxByElement from element [{0}].", elementName);
                string screenshot = ScreenShotCapturing.TakeScreenShoot(driver, message);
                HtmlReporter.Fail(message, ex, screenshot);
                throw new ErrorHandler(message, ex);
            }
        }
Пример #8
0
        public void SwitchToFrame(string elementName, By byObject)
        {
            IWebElement element = null;

            try
            {
                element = WaitForElementToBeVisible(elementName, byObject);
                driver.SwitchTo().Frame(element);

                string info = string.Format(string.Format("Switch to frame. Frame information: {0}", elementName));
                NLogger.Info(info);
                HtmlReporter.Pass(info);
            }
            catch (WebDriverException ex)
            {
                string message = string.Format("An error happens when switching to frame [{0}]", elementName);
                ScreenShotCapturing.HighlightElement(driver, element);
                string screenshot = ScreenShotCapturing.TakeScreenShoot(driver, message);
                HtmlReporter.Fail(message, ex, screenshot);
                throw new ErrorHandler(message, ex);
            }
        }
Пример #9
0
        public void UploadFile(string elementName, By byObject, string filename)
        {
            IWebElement element = null;

            try
            {
                element = WaitForElementToBeVisible(elementName, byObject);
                element.SendKeys(filename);

                string info = string.Format("Uploading file. File name: [{0}]; Element Name [{1}]", filename, elementName);
                NLogger.Info(info);
                HtmlReporter.Pass(info);
            }
            catch (WebDriverException ex)
            {
                string message = string.Format("An error happens when trying to send text [{0}] to element [{1}].", filename, elementName);
                ScreenShotCapturing.HighlightElement(driver, element);
                string screenshot = ScreenShotCapturing.TakeScreenShoot(driver, message);
                HtmlReporter.Fail(message, ex, screenshot);
                throw new ErrorHandler(message, ex);
            }
        }
Пример #10
0
        public string CaptureScreenshot(string fileDir, string filename, By byObject)
        {
            try
            {
                ScrolltillElement(filename, byObject);
                IWebElement element = WaitForElementToBeVisible(filename, byObject);

                string     fileLocation = fileDir + Utils.separator + filename + ".png";
                Screenshot ss           = ((ITakesScreenshot)driver).GetScreenshot();
                var        img          = Image.FromStream(new MemoryStream(ss.AsByteArray)) as Bitmap;
                var        e            = img.Clone(new Rectangle(element.Location, element.Size), img.PixelFormat);
                e.Save(fileLocation, System.Drawing.Imaging.ImageFormat.Png);

                NLogger.Info(string.Format("Screenshot captured. File location: {0}", fileLocation));

                return(fileLocation);
            }
            catch (Exception)
            {
                return("");
            }
        }
Пример #11
0
        public IWebElement WaitForElementToBeVisible(string elementName, By byObject)
        {
            try
            {
                WebDriverWait wait    = new WebDriverWait(driver, TimeSpan.FromSeconds(GetWaitTimeoutSeconds()));
                IWebElement   element = wait.Until(ExpectedConditions.ElementIsVisible(byObject));

                string info = string.Format("Wait for element [{0}] to be visible", elementName);
                HtmlReporter.Pass(info);
                NLogger.Info(info);

                return(element);
            }
            catch (WebDriverTimeoutException ex)
            {
                var message = string.Format("Element [{0}] is not visible as expected.", elementName);

                string screenshot = ScreenShotCapturing.TakeScreenShoot(driver, message);
                HtmlReporter.Fail(message, ex, screenshot);
                throw new ErrorHandler(message, ex);
            }
        }
Пример #12
0
        /// <summary>
        /// Remove annotations in document
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="outPath"></param>
        private static void RemoveAnnotations(DocumentInfo doc, string outPath)
        {
            try
            {
                var(filename, folder) = PrepareFolder(doc, outPath);
                // doc.Workbook.Save($"{folder}/{filename}");

                var wb = doc.Workbook;

                var sb = new StringBuilder();

                foreach (var ws in wb.Worksheets)
                {
                    foreach (var cm in ws.Comments)
                    {
                        var cellName = CellsHelper.CellIndexToName(cm.Row, cm.Column);

                        var str = $"Sheet Name: \"{ws.Name}\", Cell Name: {cellName}, Comment Note: \r\n\"{cm.Note}\"";

                        sb.AppendLine(str);
                        sb.AppendLine();
                    }
                }

                File.WriteAllText($"{folder}/comments.txt", sb.ToString());

                foreach (var ws in wb.Worksheets)
                {
                    ws.Comments.Clear();
                }

                // wb.Save(outPath);
                wb.Save($"{folder}/{filename}");
            }
            catch (Exception e)
            {
                NLogger.LogError(App, "RemoveAnnotations", e.Message, outPath);
            }
        }
Пример #13
0
        /// <summary>
        /// 获取缓存集合
        /// </summary>
        /// <param name="keys">缓存Key集合</param>
        /// <returns></returns>
        public async Task <IDictionary <string, object> > GetAllAsync(IEnumerable <string> keys, string prefix = "")
        {
            try
            {
                if (keys == null)
                {
                    throw new ArgumentNullException(nameof(keys));
                }
                var dict = new Dictionary <string, object>();

                foreach (string key in keys)
                {
                    dict.Add(key, await GetAsync(MergeKey(key, prefix)));
                }
                return(dict);
            }
            catch (Exception ex)
            {
                NLogger.Error("获取缓存集合:" + ex.ToString());
                return(null);
            }
        }
Пример #14
0
        private void VerifyTask(HttpRequestBase ipnRequest)
        {
            var    verificationResponse = string.Empty;
            string informationRequets   = "";

            try
            {
                var verificationRequest = (HttpWebRequest)WebRequest.Create("https://www.sandbox.paypal.com/cgi-bin/webscr");

                //Set values for the verification request
                verificationRequest.Method      = "POST";
                verificationRequest.ContentType = "application/x-www-form-urlencoded";
                var param      = Request.BinaryRead(ipnRequest.ContentLength);
                var strRequest = Encoding.ASCII.GetString(param);

                //Add cmd=_notify-validate to the payload
                strRequest = "cmd=_notify-validate&" + strRequest;
                NLogger.Infor("strRequest: " + strRequest);
                informationRequets = strRequest;
                verificationRequest.ContentLength = strRequest.Length;

                //Attach payload to the verification request
                var streamOut = new StreamWriter(verificationRequest.GetRequestStream(), Encoding.ASCII);
                streamOut.Write(strRequest);
                streamOut.Close();

                //Send the request to PayPal and get the response
                var streamIn = new StreamReader(verificationRequest.GetResponse().GetResponseStream());
                verificationResponse = streamIn.ReadToEnd();
                streamIn.Close();
            }
            catch (Exception exception)
            {
                //Capture exception for manual investigation
            }

            ProcessVerificationResponse(informationRequets, verificationResponse);
        }
Пример #15
0
        public void CreateLibrary()
        {
            try
            {
                RenameWindow win = new RenameWindow();
                win.NewName = CommonDefine.Untitled;
                win.Owner   = Application.Current.MainWindow;
                win.ShowDialog();

                if (win.Result.HasValue && win.Result.Value)
                {
                    string libraryName = win.NewName;

                    string           objectName = CommonDefine.Untitled;
                    ISerializeWriter writer     = GetSerializeWriter(ref objectName);
                    if (writer == null)
                    {
                        return;
                    }

                    //Create a new Library. Thumbnail is empty now, and waiting for a improvement
                    IDocumentService DocService = ServiceLocator.Current.GetInstance <IDocumentService>();
                    ILibrary         newLibrary =
                        DocService.LibraryManager.CreateLibrary(writer, objectName, CreateIconImage(false), null);
                    if (newLibrary != null)
                    {
                        ICustomLibraryService customLibraryService = ServiceLocator.Current.GetInstance <ICustomLibraryService>();
                        customLibraryService.GetMyLibrary().CreateCustomLibrary(newLibrary.Guid, libraryName);
                    }
                }
            }
            catch (Exception ex)
            {
                NLogger.Warn("Add Library failed. ex:{0}", ex.ToString());

                MessageBox.Show(GlobalData.FindResource("Error_Create_Library") + ex.Message);
            }
        }
Пример #16
0
        private void OnFontSizeChange(object data)
        {
            TextRange rang     = GetOptionRange();
            double    fontsize = 0;

            try
            {
                fontsize = Convert.ToDouble(data);
            }
            catch (System.Exception ex)
            {
                NLogger.Error("Format of font size variable is not correct,will reset to 12.");
                fontsize = 12;
            }

            if (fontsize > 0)
            {
                rang.ApplyPropertyValue(TextElement.FontSizeProperty, fontsize);

                //////////////////////////////////////////////////////////////////////////
                foreach (Block block in Document.Blocks)
                {
                    if (block is Paragraph)
                    {
                        Paragraph para = block as Paragraph;

                        foreach (Inline line in para.Inlines)
                        {
                            line.FontSize = line.FontSize;
                        }
                    }
                }

                Document.FontSize = fontsize;

                //////////////////////////////////////////////////////////////////////////
            }
        }
Пример #17
0
        protected override void Seed(EfDbContext context)
        {
            try
            {
                //context.Set<CityArea>().AddRange(new List<CityArea> {
                //new CityArea { Name = "厦门", Pinyin = "xiamen", CityId = 0, IsEdit = false, Sort = 1, State = 1, CreateTime = DateTime.Now },
                //new CityArea { Name = "深圳", Pinyin = "shenzhen", CityId = 0, IsEdit = false, Sort = 1, State = 0, CreateTime = DateTime.Now },
                //new CityArea { Name = "福州", Pinyin = "fuzhou", CityId = 0, IsEdit = false, Sort = 1, State = 0, CreateTime = DateTime.Now },
                //new CityArea { Name = "泉州", Pinyin = "quanzhou", CityId = 0, IsEdit = false, Sort = 1, State = 0, CreateTime = DateTime.Now },
                //new CityArea { Name = "龙岩", Pinyin = "longyan", CityId = 0, IsEdit = false, Sort = 1, State = 0, CreateTime = DateTime.Now },
                //new CityArea { Name = "武汉", Pinyin = "wuhan", CityId = 0, IsEdit = false, Sort = 1, State = 0, CreateTime = DateTime.Now },
                //new CityArea { Name = "重庆", Pinyin = "chongqing", CityId = 0, IsEdit = false, Sort = 1, State = 0, CreateTime = DateTime.Now }});
                //context.SaveChanges();

                //ProductCategory productCategory = new ProductCategory { Name = "其他", CreateTime = DateTime.Now, State = DelStateEnum.正常 };
                //context.Set<ProductCategory>().Add(productCategory);
                //context.SaveChanges();
                //context.Set<Product>().Add(new Product { Name = "其他", ProductCategoryId = productCategory.Id, State = DelStateEnum.正常, CreateTime = DateTime.Now });
                //context.SaveChanges();

                var filePath = ZConfig.GetConfigString("InitSqlFile");
                if (string.IsNullOrEmpty(filePath))
                    throw new Exception("初始化数据文件不能为空!");
                if (filePath.StartsWith("~"))
                {
                    filePath = filePath.Substring(2);
                    filePath = $"{AppDomain.CurrentDomain.BaseDirectory}{filePath}";
                }
                var sql = File.ReadAllText(filePath);
                context.Database.ExecuteSqlCommand(sql);
                base.Seed(context);
            }
            catch (Exception ex)
            {
                NLogger.Error(ex);
            }

        }
        /// <summary>
        /// Search categories by name or description.
        /// </summary>
        /// <param name="searchName"></param>
        /// <param name="type">true = by CategoryName false = Description</param>
        /// <returns></returns>
        public List <Category> SearchCategory(string searchName, bool type)
        {
            NLogger         logging = new NLogger();
            List <Category> searchResult;


            if (type == true)
            {
                searchResult = this.Categories.Where(c => c.CategoryName.Contains(searchName)).ToList();

                if (searchResult.Count() == 0)
                {
                    logging.Log("WARN", "There were no categories found.");
                }
                else
                {
                    logging.Log("INFO", searchResult.Count() + " Categories Found.");
                }
            }

            else
            {
                searchResult = this.Categories.Where(c => c.Description.Contains(searchName)).ToList();

                if (searchResult.Count() == 0)
                {
                    logging.Log("WARN", "There were no categories found.");
                }
                else
                {
                    logging.Log("INFO", searchResult.Count() + " Categories Found.");
                }
            }



            return(searchResult);
        }
Пример #19
0
        private List <SongSheetModel> ConvertToModel(List <SongSheetDTO> songSheets)
        {
            try
            {
                List <SongSheetModel> resultLst = new List <SongSheetModel>();

                foreach (var songSheet in songSheets)
                {
                    resultLst.Add(new SongSheetModel
                    {
                        Name  = songSheet.Name,
                        Icon  = songSheet.Icon,
                        Songs = ConvertToSongs(songSheet.Songs)
                    });
                }
                return(resultLst);
            }
            catch (Exception ex)
            {
                NLogger.Error(ex.Message, ex);
                return(null);
            }
        }
Пример #20
0
 public void LogInstallServiceString(string logStr)
 {
     NLogger.LogDebugToHdd(logStr);
     if (this.InvokeRequired)
     {
         this.Invoke(new MethodInvoker(() =>
         {
             _rtbInstallServiceLog.AppendText($"{logStr}{Environment.NewLine}");
             if (_progressBar1.Value < _progressBar1.Maximum)
             {
                 _progressBar1.Value++;
             }
         }));
     }
     else
     {
         _rtbInstallServiceLog.AppendText($"{logStr}{Environment.NewLine}");
         if (_progressBar1.Value < _progressBar1.Maximum)
         {
             _progressBar1.Value++;
         }
     }
 }
Пример #21
0
 public void LogInstallServiceString(Exception ex)
 {
     NLogger.LogDebugToHdd(ex.ToString());
     if (this.InvokeRequired)
     {
         this.Invoke(new MethodInvoker(() =>
         {
             _rtbInstallServiceLog.AppendText($"{ex.Message}{Environment.NewLine}");
             if (_progressBar1.Value < _progressBar1.Maximum)
             {
                 _progressBar1.Value++;
             }
         }));
     }
     else
     {
         _rtbInstallServiceLog.AppendText($"{ex.Message}{Environment.NewLine}");
         if (_progressBar1.Value < _progressBar1.Maximum)
         {
             _progressBar1.Value++;
         }
     }
 }
Пример #22
0
        public List <string> WaitForVisibilityOfAllElementTextsLocatedBy(string elementName, By byObject, List <string> itemList)
        {
            try
            {
                WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(GetWaitTimeoutSeconds()));
                List <string> list = wait.Until(CustomExpectedConditions.VisibilityOfAllElementTextsLocatedBy(byObject, itemList));

                string info = string.Format("Wait for text list to be present in element. String list: [{0}]; Element information: {1}",
                                            string.Join(", ", itemList.ToArray()), elementName);
                HtmlReporter.Pass(info);
                NLogger.Info(info);

                return(list);
            }
            catch (WebDriverTimeoutException ex)
            {
                var message = string.Format("Text list is not present in element as expected. String list: [{0}]; Element information: {1}",
                                            string.Join(", ", itemList.ToArray()), elementName);
                string screenshot = ScreenShotCapturing.TakeScreenShoot(driver, message);
                HtmlReporter.Fail(message, ex, screenshot);
                throw new ErrorHandler(message, ex);
            }
        }
Пример #23
0
        public string GetValue(string elementName, By byObject)
        {
            IWebElement element = null;

            try
            {
                element = WaitForElementToBeVisible(elementName, byObject);

                string info = string.Format("Get the value of elemet [{0}]", elementName);
                NLogger.Info(info);
                HtmlReporter.Pass(info);

                return(element.GetAttribute("value"));
            }
            catch (WebDriverException ex)
            {
                string message = string.Format("An error happens when trying to get the value of element [{0}].", elementName);
                ScreenShotCapturing.HighlightElement(driver, element);
                string screenshot = ScreenShotCapturing.TakeScreenShoot(driver, message);
                HtmlReporter.Fail(message, ex, screenshot);
                throw new ErrorHandler(message, ex);
            }
        }
Пример #24
0
        public void HoverMouseOn(string elementName, By byObject)
        {
            IWebElement element = null;

            try
            {
                element = WaitForElementToBeClickable(elementName, byObject);
                Actions action = new Actions(driver);
                action.MoveToElement(element).Perform();

                string info = string.Format(string.Format("Hover mouse on element. Element information: {0}", elementName));
                NLogger.Info(info);
                HtmlReporter.Pass(info);
            }
            catch (WebDriverException ex)
            {
                string message = string.Format("An error happens when trying to hover mouse on element [{0}].", elementName);
                ScreenShotCapturing.HighlightElement(driver, element);
                string screenshot = ScreenShotCapturing.TakeScreenShoot(driver, message);
                HtmlReporter.Fail(message, ex, screenshot);
                throw new ErrorHandler(message, ex);
            }
        }
Пример #25
0
        public void Uninstall()
        {
            try
            {
                UninstallBase();

                if (Directory.Exists(MAGIC_UPDATER_PATH))
                {
                    FilesWorks.DeleteDirectoryFull(MAGIC_UPDATER_PATH);
                }

                if (Directory.Exists(MAGIC_UPDATER_NEW_VER_PATH))
                {
                    FilesWorks.DeleteDirectoryFull(MAGIC_UPDATER_NEW_VER_PATH);
                }
            }
            catch (Exception ex)
            {
                Program.MainForm?.LogInstallServiceString(ex);
                AddMessage(ex.Message);
                NLogger.LogErrorToHdd(ex.ToString());
            }
        }
Пример #26
0
        public void VerifyDouble(string elementName, By byObject, double expectedDouble)
        {
            double actualDouble = 0;

            try
            {
                actualDouble = double.Parse(GetText(elementName, byObject));
                Assert.AreEqual(expectedDouble, actualDouble);

                string info = string.Format("Double of element [{0}] as expectation [{1}]", elementName, expectedDouble);
                NLogger.Info(info);
                HtmlReporter.Pass(info);
            }
            catch (AssertFailedException ex)
            {
                IWebElement element = WaitForElementToBeVisible(elementName, byObject);
                string      message = string.Format("Verify Double for element [{0}] failed. Expected [{1}] but actual [{2}]", elementName, expectedDouble, actualDouble);
                ScreenShotCapturing.HighlightElement(driver, element);
                string screenshot = ScreenShotCapturing.TakeScreenShoot(driver, message);
                HtmlReporter.Fail(message, ex, screenshot);
                throw new ErrorHandler(message, ex);
            }
        }
Пример #27
0
        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="key">缓存Key</param>
        /// <returns></returns>
        public async Task <object> GetAsync(string key, string prefix = "")
        {
            try
            {
                if (key == null)
                {
                    throw new ArgumentNullException(nameof(key));
                }

                var value = await Cache.StringGetAsync(MergeKey(key, prefix));

                if (!value.HasValue)
                {
                    return(null);
                }
                return(JsonConvert.DeserializeObject(value));
            }
            catch (Exception ex)
            {
                NLogger.Error("获取缓存:" + ex.ToString());
                return(null);
            }
        }
Пример #28
0
        public void SelectComboItemByText(string elementName, By byObject, string itemText)
        {
            IWebElement element = null;

            try
            {
                element = WaitForElementToBeVisible(elementName, byObject);
                SelectElement select = new SelectElement(element);
                select.SelectByText(itemText);

                string info = string.Format("Select [{0}] from element [{1}].", elementName, itemText);
                NLogger.Info(info);
                HtmlReporter.Pass(info);
            }
            catch (WebDriverException ex)
            {
                string message = string.Format("An error happens when trying to SelectComboItemByText [{0}] from element [{1}].", elementName, itemText);
                ScreenShotCapturing.HighlightElement(driver, element);
                string screenshot = ScreenShotCapturing.TakeScreenShoot(driver, message);
                HtmlReporter.Fail(message, ex, screenshot);
                throw new ErrorHandler(message, ex);
            }
        }
Пример #29
0
        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="key">缓存Key</param>
        /// <returns></returns>
        public T Get <T>(string key, string prefix = "") where T : class
        {
            try
            {
                if (key == null)
                {
                    throw new ArgumentNullException(nameof(key));
                }

                var value = Cache.StringGet(MergeKey(key, prefix));
                if (!value.HasValue)
                {
                    return(default(T));
                }

                return(JsonConvert.DeserializeObject <T>(value));
            }
            catch (Exception ex)
            {
                NLogger.Error("获取缓存:" + ex.ToString());
                return(null);
            }
        }
Пример #30
0
 /// <summary>
 /// 执行数据库操作
 /// </summary>
 /// <typeparam name="Result">返回值类型 泛型</typeparam>
 /// <param name="func">方法委托</param>
 /// <param name="commandTimeOut">超时时间, 单位为秒, 默认为30秒</param>
 /// <param name="dbType">数据库类型</param>
 /// <returns>泛型返回值</returns>
 public static Result Exec <Result>(Func <SqlSugarClient, Result> func, int commandTimeOut = 30, SqlSugarDbType dbType = SqlSugarDbType.MySql)
 {
     if (func == null)
     {
         throw new Exception("委托为null, 事务处理无意义");
     }
     using (var db = InitDB(commandTimeOut, dbType))
     {
         try
         {
             return(func(db));
         }
         catch (Exception ex)
         {
             NLogger.Error(ex);
             throw ex;
         }
         finally
         {
             db.Dispose();
         }
     }
 }
Пример #31
0
        private void comboBoxRevitFamilyTypes_SelectedIndexChanged(object sender, EventArgs e)
        {
            NLogger.LogText("Enter comboBoxRevitFamilies_SelectedIndexChanged");

            ComboBoxRevitFamilyTypesSourceData selectedFamilyType = (ComboBoxRevitFamilyTypesSourceData)comboBoxRevitFamilyTypes.SelectedItem;

            if (selectedFamilyType != null)
            {
                offsitePanelHandler.FillGrid(dgElements, null);
                offsitePanelHandler.FillGrid(dgParamsMapping, null);
                offsitePanelHandler.FillGrid(dgInvRevMapping, null);
                txtInventorTemplatesPath.Text = "";
                offsitePanelHandler.ResetRevitInventorMappingInternalStructure();
                ((System.Windows.Forms.Control)tabControl1.TabPages[tabName]).Enabled = false;

                //  Extract Revit family from revit document, based on selected xml configured element
                NLogger.LogText($"Revit family type selected: {selectedFamilyType.FamilyTypeName}");

                Type famType = Type.GetType(selectedFamilyType.FamilyTypeInstance); //Type.GetType("Autodesk.Revit.DB.FamilyInstance,RevitAPI");

                var filteredElements = offsitePanelHandler.FindInstancesOfType(famType, selectedFamilyType.IdType, selectedFamilyType.TargetCategory);

                var tempelStructureList = offsitePanelHandler.ProcessElements(filteredElements);
                elStructureList = offsitePanelHandler.FilterElements(tempelStructureList);

                NLogger.LogText($"Retrieved: {elStructureList.Count()} Revit elements");

                // Populate the Element datagrid
                var dataSources = offsitePanelHandler.GetElementsDataGridSource(elStructureList);

                elementList = dataSources["Elements"];

                offsitePanelHandler.FillGrid(dgElements, elementList);
            }

            NLogger.LogText("Exit comboBoxRevitFamilies_SelectedIndexChanged");
        }
Пример #32
0
        private void btn_login_Click(object sender, RoutedEventArgs e)
        {
            ExceptionCatcher.ExceptionFinder(() => {
                if (txtedit_username.Text.Length == 0 || txtbox_password.Text.Length == 0)
                {
                    MessageBox.Show("Lütfen Kullanıcı Adı ve Şifre Giriniz!");
                }
                else
                {
                    using (SDB sdb = new SDB())
                    {
                        var hashpassword  = HashingHelper.HashingPassword(txtbox_password.Text);
                        Personel personel = (from p in sdb.Personels where p.PersonelUsername == txtedit_username.Text && p.PersonelPassword == hashpassword select p).Single();

                        if (personel != null)
                        {
                            BL.AuthenticateHelperr.LoginUser.Add(personel);
                            AuthenticateHelperr.LoginUser.Add(new Personel
                            {
                                PersonelID     = personel.PersonelID,
                                PersonelAd     = personel.PersonelAd,
                                PersonelSoyad  = personel.PersonelSoyad,
                                PersonelRoleID = personel.PersonelRoleID
                            });
                            NLogger.GetLogItems(null, InfoLogTypes.LoginLogout, DateTime.UtcNow, UserAuthenticationStatus.Login, $"{personel.PersonelAd} {personel.PersonelSoyad}");
                            MainWindow mainWindow = new MainWindow();
                            this.Close();
                            mainWindow.Show();
                        }
                        else
                        {
                            MessageBox.Show("KullanıcıAdı veya Şifre Hatalı!");
                        }
                    }
                }
            });
        }
Пример #33
0
        public static TryGetLogPath1C GetLogPath1C()
        {
            if (string.IsNullOrEmpty(ExePath1C))
            {
                string msg = "Отсутствует путь к исполняемуом файлу 1С";
                NLogger.LogErrorToHdd(msg);
                return(new TryGetLogPath1C(false, msg));
            }

            string logs = Path.Combine(Path.GetTempPath(), "1CLogsForMagicUpdater");

            if (!Directory.Exists(logs))
            {
                try
                {
                    Directory.CreateDirectory(logs);
                }
                catch (Exception ex)
                {
                    NLogger.LogErrorToHdd(ex.Message.ToString());
                    return(new TryGetLogPath1C(false, ex.Message.ToString()));
                }
            }
            try
            {
                Extensions.AddDirectorySecurity(logs, System.Security.Principal.WindowsIdentity.GetCurrent().Name, System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow);
            }
            catch (Exception ex)
            {
                NLogger.LogErrorToHdd(ex.Message.ToString());
                return(new TryGetLogPath1C(false, ex.Message.ToString()));
            }

            LogPath1C = Path.Combine(logs, "OutLog.log");

            return(new TryGetLogPath1C());
        }