Exemplo n.º 1
0
    //public Transform prefab;

    void Start()
    {
        //levelManager = GetComponent<LevelManager>();
        // Déplacement au microphone

        /*
         * foreach (var device in Microphone.devices)
         * {
         *  Debug.Log("Name: " + device);
         *  //Debug.Log("Microphone.GetDeviceCaps : "+device.GetDeviceCaps);
         * }
         */

        //Debug.Log(Microphone.GetDeviceCaps);
        rb          = GetComponent <Rigidbody2D>();
        _audio      = GetComponent <AudioSource>();
        _audio.clip = Microphone.Start(null, true, 10, 44100);
        //_audio.clip = Microphone.Start("Microphone Array (Realtek High Definition Audio)", true, 10, 44100);
        _audio.loop = true;
        _audio.mute = false;
        while (!(Microphone.GetPosition(null) > 0))
        {
        }

        _audio.Play();
        Calibration calibration = GameObject.Find("Thresholds").GetComponent <Calibration>();

        runLoudnessThreshold  = calibration.moveThresh;
        jumpLoudnessThreshold = calibration.jumpThresh;
        LogWritter lw = gameObject.GetComponent <LogWritter>();

        lw.writeThreshOnFile(runLoudnessThreshold, jumpLoudnessThreshold);
    }
Exemplo n.º 2
0
        public static void InsertEcologDopplerNotMM(InsertDatum datum, MainWindowViewModel.UpdateTextDelegate updateTextDelegate, InsertConfig.GpsCorrection correction)
        {
            var tripsTable = TripsDopplerNotMMDao.Get(datum);

            //int i = 1;

            //foreach (DataRow row in tripsTable.Rows)
            //{
            //    updateTextDelegate($"Insetring ECOLOG ... , {i} / {tripsTable.Rows.Count}");
            //    LogWritter.WriteLog(LogWritter.LogMode.Ecolog, $"Insetring ECOLOG... , { i} / { tripsTable.Rows.Count}, Datum: {datum}");
            //    var ecologTable = HagimotoEcologCalculator.CalcEcolog(row, datum, correction);
            //    EcologDao.Insert(ecologTable);

            //    i++;
            //}
            Parallel.For(0, tripsTable.Rows.Count, i =>
            {
                if (tripsTable.Rows[i][(TripsDopplerNotMMDao.ColumnConsumedEnergy)] == DBNull.Value)
                {
                    updateTextDelegate($"Insetring ECOLOGDopplerNotMM ... , {i + 1} / {tripsTable.Rows.Count}");
                    LogWritter.WriteLog(LogWritter.LogMode.Ecolog, $"Insetring ECOLOGDopplerNotMM... , { i} / { tripsTable.Rows.Count}, Datum: {datum}");
                    var ecologTable = HagimotoEcologCalculator.CalcEcologDoppler(tripsTable.Rows[i], datum, correction);
                    EcologDopplerNotMMDao.Insert(ecologTable);
                }
            });

            TripsDopplerNotMMDao.UpdateConsumedEnergy();
        }
Exemplo n.º 3
0
        public static DataTable GetResult(string query)
        {
            var dataTable = new DataTable();

            using (SqlConnection sqlConnection = new SqlConnection(DatabaseAccesser.ConnectionString))
            {
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(query, DatabaseAccesser.ConnectionString);

                try
                {
                    sqlConnection.Open();
                    SqlCommand command = new SqlCommand(query, sqlConnection);
                    command.CommandTimeout       = 600;
                    sqlDataAdapter.SelectCommand = command;
                    sqlDataAdapter.Fill(dataTable);
                }
                catch (SqlException sqlException)
                {
                    // Console.WriteLine($"ERROR: {sqlException.Message}, {sqlException.StackTrace}");
                    LogWritter.WriteLog(LogWritter.LogMode.Error, $"ERROR: {sqlException.Message}, {sqlException.StackTrace}");
                }
                finally
                {
                    sqlConnection.Close();
                }
            }

            return(dataTable);
        }
Exemplo n.º 4
0
 public static void Insert(string query)
 {
     using (SqlConnection sqlConnection = new SqlConnection(DatabaseAccesser.ConnectionString))
     {
         try
         {
             sqlConnection.Open();
             SqlCommand command = new SqlCommand(query, sqlConnection);
             command.CommandTimeout = 600;
             command.ExecuteNonQuery();
         }
         catch (SqlException sqlException)
         {
             if (sqlException.Number != NumberOfViolationOfPrimaryKey)
             {
                 Console.WriteLine($"ERROR: {sqlException.Message}, {sqlException.StackTrace}");
                 LogWritter.WriteLog(LogWritter.LogMode.Error, $"ERROR: {sqlException.Message}, {sqlException.StackTrace}");
             }
         }
         finally
         {
             sqlConnection.Close();
         }
     }
 }
Exemplo n.º 5
0
        public static Task InsertGps(List <string> insertFileList, InsertConfig config, int correctionIndex, List <InsertDatum> insertDatumList)
        {
            var tasks = new List <Task>();

            foreach (string filePath in insertFileList)
            {
                Console.WriteLine("GPSinserting:" + filePath);
                string[] word = filePath.Split('\\');

                // GPSファイルでない場合はcontinue
                if (!System.Text.RegularExpressions.Regex.IsMatch(word[word.Length - 1], @"\d{14}UnsentGPS.csv"))
                {
                    continue;
                }

                var datum = new InsertDatum()
                {
                    DriverId          = DriverNames.GetDriverId(word[DriverIndex]),
                    CarId             = CarNames.GetCarId(word[CarIndex]),
                    SensorId          = SensorNames.GetSensorId(word[SensorIndex]),
                    StartTime         = config.StartDate,
                    EndTime           = config.EndDate,
                    EstimatedCarModel = EstimatedCarModel.GetModel(config.CarModel)
                };

                InsertDatum.AddDatumToList(insertDatumList, datum);

                LogWritter.WriteLog(LogWritter.LogMode.Gps, $"インサートデータ, FilePath: {filePath}, DriverId: {datum.DriverId}, CarId: {datum.CarId}, SensorId: {datum.SensorId}");

                // ファイルごとの処理なので主キー違反があっても挿入されないだけ
                var gpsRawTable = InsertGpsRaw(filePath, datum, config.Correction[correctionIndex]);
                if (config.Correction[correctionIndex] == InsertConfig.GpsCorrection.SpeedLPFMapMatching ||
                    config.Correction[correctionIndex] == InsertConfig.GpsCorrection.MapMatching)
                {
                    gpsRawTable = MapMatching.getResultMapMatching(gpsRawTable, datum);
                }
                else if (config.Correction[correctionIndex] == InsertConfig.GpsCorrection.DopplerSpeed)
                {
                    gpsRawTable = MapMatching.getResultMapMatchingDoppler(gpsRawTable, datum);
                }
                if (gpsRawTable.Rows.Count != 0)
                {
                    var task = Task.Run(() =>
                    {
                        InsertCorrectedGps(gpsRawTable, config.Correction[correctionIndex]);
                    });

                    tasks.Add(task);

                    TripInserter.InsertTripRaw(gpsRawTable, config.Correction[correctionIndex]);
                    //TripInserter.InsertTrip(datum, config.Correction[correctionIndex]);
                }
                else
                {
                    LogWritter.WriteLog(LogWritter.LogMode.Gps, $"ファイルの行数が0行のためインサートを行いませんでした: {filePath}");
                }
            }
            return(Task.WhenAll(tasks));
        }
Exemplo n.º 6
0
        public void init()
        {
            LogWritter.Add(Environment.NewLine + Environment.NewLine + "******************************************************************************************");
            LogWritter.Add(DateTime.Now + ": run test begin" + Environment.NewLine);
            var sw = new StreamWriter("Launches\\" + "run_" + DateTime.Now.ToShortDateString() + ".txt", false, Encoding.Default);

            sw.Close();
        }
Exemplo n.º 7
0
        public void end()
        {
            LogWritter.Add(DateTime.Now + ": run test end" + Environment.NewLine);
            LogWritter.Add("******************************************************************************************" + Environment.NewLine + Environment.NewLine);

            Classes.Utilites.Notifier.FormNotif();
            Classes.Utilites.Notifier.SendNotif();
        }
Exemplo n.º 8
0
        private void Application_DispatcherUnhandledException(
            object sender,
            DispatcherUnhandledExceptionEventArgs e)
        {
            LogWritter.WriteLog(LogWritter.LogMode.Error, e.Exception.Message + ", " + e.Exception.StackTrace);

            e.Handled = true;
        }
Exemplo n.º 9
0
        public override async Task <AppMetadata> ScrapeAsync(string appId)
        {
            var url = string.Format(StoreUrlTemplate, appId);
            var msg = new HttpRequestMessage(HttpMethod.Get, url);

            msg.Headers.Add("MS-Contract-Version", "4");
            var response = await _client.SendAsync(msg);

            response.EnsureSuccessStatusCode();
            var content = await response.Content.ReadAsStringAsync();

            var result = GetAppPayload(content, appId);

            if (result == null && content.IndexOf("The thing you're looking for isn't here", StringComparison.OrdinalIgnoreCase) > 0)
            {
                LogWritter?.Invoke(TraceLevel.Warning, $"Windows store url [{url}] returned not found result", null);
                return(null);
            }
            var meta = new AppMetadata()
            {
                Id = result.ProductId, ScraperType = this.GetType()
            };

            meta.AppUrl = string.Format(StoreUrlUserTemplate, meta.Id);
            meta.Name   = result.Title;
            var icon = GetIcon(result.Images);

            meta.IconUrl        = icon?.Url;
            meta.PublisherEmail = GetFirst <string>(result.SupportUris, "Uri", "mailto:", "Uri")?.Replace("mailto:", string.Empty);
            meta.Publisher      = result.PublisherName;
            meta.Website        = result.AppWebsiteUrl;
            meta.Categories     = ArrayToList(result.Categories);
            meta.Rating         = result.AverageRating;
            meta.RatingCount    = result.RatingCount;
            meta.Description    = result.Description;
            meta.Version        = result.Version;
            meta.Paid           = result.Price > 0;
            meta.AddValue("Price", result.DisplayPrice);
            meta.AddValue("IsUniversal", result.IsUniversal);
            meta.AddValue("BgColor", icon?.BackgroundColor ?? result.BGColor);
            meta.AddValue("HasFreeTrial", result.HasFreeTrial);
            meta.AddValue("ProductType", result.ProductType);
            meta.AddValue("PackageFamilyName", result.PackageFamilyName);
            meta.AddValue("CategoryId", result.CategoryId);
            meta.AddValue("ApproximateSizeInBytes", result.ApproximateSizeInBytes);
            meta.AddValue("SubcategoryId", result.SubcategoryId);
            meta.AddValue("Language", result.Language);
            meta.AddValue("ImageType", icon.ImageType);
            DateTime date = DateTime.Now;

            if (DateTime.TryParse((result.LastUpdateDateUtc ?? string.Empty).ToString(), out date))
            {
                meta.Updated = date;
            }
            return(meta);
        }
Exemplo n.º 10
0
 void Start()
 {
     currentLevel = 0;
     pm           = gameObject.GetComponent <PlayerMovement>();
     pd           = gameObject.GetComponent <ProcessData>();
     logWritter   = gameObject.GetComponent <LogWritter>();
     playerStats  = gameObject.GetComponent <PlayerStats>();
     TMPro.TextMeshProUGUI text = GameObject.Find("Canvas").GetComponentInChildren <TMPro.TextMeshProUGUI>();
     timer = text.GetComponent <Timer>();
     mp    = gameObject.GetComponent <MenuPause>();
 }
Exemplo n.º 11
0
        public ActionResult Login(Login model)
        {
            if (ModelState.IsValid)
            {
                var user = db.Users.Where(u => String.Compare(u.UserName, model.UserName) == 0).FirstOrDefault();
                if (user != null)
                {
                    if (user.IsActive)
                    {
                        // Verify user password
                        var success = SaltedHash.Verify(user.Salt, user.Password, model.Password);
                        if (success)
                        {
                            // Save authentication info
                            ElectricalShopPrincipleModel principle = new ElectricalShopPrincipleModel();
                            principle.UserId   = user.UserId;
                            principle.FullName = user.FullName;
                            principle.Roles    = user.Roles.Select(r => r.RoleName).ToArray();

                            // Add authentication cookie
                            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, model.UserName,
                                                                                                 DateTime.Now, DateTime.Now.AddDays(7), model.RememberMe, JsonConvert.SerializeObject(principle));
                            String     authTicketEncrypted = FormsAuthentication.Encrypt(authTicket);
                            HttpCookie asCookie            = new HttpCookie(FormsAuthentication.FormsCookieName, authTicketEncrypted);
                            Response.Cookies.Add(asCookie);

                            // Write action log
                            Log log = new Log();
                            log.LogDate = DateTime.Now;
                            log.Action  = "Login";
                            log.Tags    = GetRequestedIP() + "," + model.UserName;
                            log.Message = "Đăng nhập hệ thống";
                            LogWritter.WriteLog(log);

                            return(RedirectToAction("Index", "Admin"));
                        }
                        else
                        {
                            ModelState.AddModelError("", "Sai mật khẩu!");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "Tài khoản đã bị khóa!");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Tài khoản không tồn tại trong hệ thống!");
                }
            }
            return(View(model));
        }
        public override async Task <AppMetadata> ScrapeAsync(string appId)
        {
            var url = string.Format(StoreUrlTemplate, appId);
            var msg = new HttpRequestMessage(HttpMethod.Get, url);

            msg.Headers.Add("Accept", "text/json");
            var response = await _client.SendAsync(msg);

            response.EnsureSuccessStatusCode();
            var content = await response.Content.ReadAsStringAsync();

            var json = JsonConvert.DeserializeObject <dynamic>(content);

            if (json?.resultCount == 0)
            {
                LogWritter?.Invoke(TraceLevel.Warning, $"Apple store (ITunes) url [{url}] returned zero results", null);
                return(null);
            }
            var result = json["results"][0];
            var meta   = new AppMetadata()
            {
                Id = result.trackId, ScraperType = this.GetType(), AppUrl = GetUrlFromId(appId)
            };

            meta.Name        = result.trackName;
            meta.IconUrl     = result.artworkUrl512 ?? result.artworkUrl100 ?? result.artworkUrl60;
            meta.Publisher   = result.sellerName ?? result.artistName;
            meta.Website     = result.sellerUrl;
            meta.Categories  = ArrayToList(result.genres);
            meta.Rating      = result.averageUserRating;
            meta.RatingCount = result.userRatingCount;
            meta.Description = result.description;
            meta.Version     = result.version;
            meta.Paid        = result.price > 0;
            meta.AddValue("Url", result.trackViewUrl.ToString());
            meta.AddValue("Price", result.formattedPrice.ToString());
            meta.AddValue("artistId", result.artistId);
            meta.AddValue("primaryGenreName", result.primaryGenreName);
            meta.AddValue("releaseNotes", result.releaseNotes);
            meta.AddValue("trackCensoredName", result.trackCensoredName);
            meta.AddValue("fileSizeBytes", result.fileSizeBytes);
            meta.AddValue("trackId", result.trackId);
            meta.AddValue("kind", result.formattedPrice);
            meta.AddValue("bundleId", result.bundleId);
            DateTime date;

            if (DateTime.TryParse((result.currentVersionReleaseDate ?? string.Empty).ToString(), out date))
            {
                meta.Updated = date;
            }
            return(meta);
        }
Exemplo n.º 13
0
 /// <summary>
 /// 情感倾向分析接口
 /// 对包含主观观点信息的文本进行情感极性类别
 /// </summary>
 public static NLPSentimentClassify SentimentClassify(string data)
 {
     try
     {
         var obj = nlp.SentimentClassify(data);
         LogWritter.Write(LogType.Debug, obj.ToString(), "SentimentClassify");
         return(obj.ToObject <NLPSentimentClassify>());
     }
     catch (Exception exp)
     {
     }
     return(null);
 }
Exemplo n.º 14
0
 /// <summary>
 /// 短文本相似度接口
 /// 短文本相似度接口用来判断两个文本的相似度得分
 /// </summary>
 public static NLPSimNet SimNet(string src, string target)
 {
     try
     {
         var obj = nlp.Simnet(src, target);
         LogWritter.Write(LogType.Debug, obj.ToString(), "SimNet");
         return(obj.ToObject <NLPSimNet>());
     }
     catch (Exception exp)
     {
     }
     return(null);
 }
Exemplo n.º 15
0
 /// <summary>
 ///  词法分析(定制版)接口
 ///  词法分析接口向用户提供分词、词性标注、专名识别三大功能;
 ///  能够识别出文本串中的基本词汇(分词),对这些词汇进行重组、标注组合后词汇的词性,并进一步识别出命名实体。
 /// </summary>
 public static NLPLexer Lexer(string data)
 {
     try
     {
         var obj = nlp.Lexer(data);
         LogWritter.Write(LogType.Debug, obj.ToString(), "Lexer");
         return(obj.ToObject <NLPLexer>());
     }
     catch (Exception exp)
     {
     }
     return(null);
 }
Exemplo n.º 16
0
        public ActionResult Index()
        {
            // Write action log
            Log log = new Log();

            log.LogDate = DateTime.Now;
            log.Action  = "View Roles";
            log.Tags    = GetRequestedIP() + "," + GetLogonUserName();
            log.Message = "Xem danh sách chức danh";
            LogWritter.WriteLog(log);

            return(View());
        }
Exemplo n.º 17
0
        public ActionResult Profiler(Profiler model)
        {
            if (ModelState.IsValid)
            {
                var user = db.Users.Where(u => u.UserId == model.UserId).FirstOrDefault();
                if (user != null)
                {
                    if (String.IsNullOrWhiteSpace(model.NewPassword))
                    {
                        user.FullName = model.FullName;
                        user.Phone    = model.Phone;
                        user.Email    = model.Email;
                        db.SaveChanges();
                        RedirectToAction("Index", "Admin");
                    }
                    else
                    {
                        /* User changed password */
                        if (SaltedHash.Verify(user.Salt, user.Password, model.Password))
                        {
                            SaltedHash sh = new SaltedHash(model.NewPassword);
                            user.Password = sh.Hash;
                            user.Salt     = sh.Salt;
                            user.FullName = model.FullName;
                            user.Phone    = model.Phone;
                            user.Email    = model.Email;
                            db.SaveChanges();

                            // Write action log
                            Log log = new Log();
                            log.LogDate = DateTime.Now;
                            log.Action  = "Update profile";
                            log.Tags    = GetRequestedIP() + "," + model.UserName;
                            log.Message = "Cập nhật thông tin cá nhân";
                            LogWritter.WriteLog(log);

                            RedirectToAction("Index", "Admin");
                        }
                        else
                        {
                            ModelState.AddModelError("", "Sai mật khẩu!");
                        }
                    }
                }
                else
                {
                    return(RedirectToAction("Login"));
                }
            }
            return(View(model));
        }
Exemplo n.º 18
0
 private LogWritter CreateLogWritter(string name)
 {
     lock (_loggerWritersDic)
     {
         LogWritter logWritter;
         if (!_loggerWritersDic.TryGetValue(name, out logWritter))
         {
             string filePath = GetLogFilePath(name);
             logWritter = new LogWritter(filePath);
             _loggerWritersDic.TryAdd(name, logWritter);
         }
         return(logWritter);
     }
 }
Exemplo n.º 19
0
        public ActionResult SignOut()
        {
            // Write action log
            Log log = new Log();

            log.LogDate = DateTime.Now;
            log.Action  = "SignOut";
            log.Tags    = GetRequestedIP() + "," + GetLogonUserName();
            log.Message = "Đăng xuất hệ thống";
            LogWritter.WriteLog(log);

            FormsAuthentication.SignOut();
            return(RedirectToAction("Login"));
        }
Exemplo n.º 20
0
 /// <summary>
 /// 依存句法分析接口
 /// 依存句法分析接口可自动分析文本中的依存句法结构信息,利用句子中词与词之间的依存关系来表示词语的句法结构信息(如“主谓”、“动宾”、“定中”等结构关系),并用树状结构来表示整句的结构(如“主谓宾”、“定状补”等)。
 /// </summary>
 public static NLPDepParser DepParser(string data)
 {
     try
     {
         var options = new Dictionary <string, object>
         {
             { "mode", 1 }
         };
         var obj = nlp.DepParser(data, options);
         LogWritter.Write(LogType.Debug, obj.ToString(), "SentimentClassify");
         return(obj.ToObject <NLPDepParser>());
     }
     catch (Exception exp)
     {
     }
     return(null);
 }
Exemplo n.º 21
0
        internal string DownTodayBg()
        {
            string date     = DateTime.Now.ToString("yyyyMMdd");
            string filename = AppDomain.CurrentDomain.BaseDirectory + "BINGBG\\" + date + "\\bg.jpg";

            if (!FileUtils.Exists(filename))
            {
                string result = APIRequest.RequestByGet(CommonConfig.CommonData.APIURL.BingImageURL + "?format=js&idx=0&n=1");
                try
                {
                    var IMAGEPATH = JsonConvertUtils.JsonToObject <BingImageObj>(result);
                    var URL       = BING_URL_HEAD + IMAGEPATH.images[0].url;
                    Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "BINGBG\\" + date);
                    SavePhotoFromUrl(filename, URL);
                    LogWritter.Write(LogType.Debug, "已下载图片", "BingIMGDownloader");
                }
                catch (Exception ex)
                { }
            }
            return("");
        }
Exemplo n.º 22
0
 private void AddMsg(string txt, Color color)
 {
     Thread.Sleep(0);
     if (base.InvokeRequired)
     {
         base.Invoke(new FrameDisplay.AddMsgDelegate(this.AddMsg), new object[]
         {
             txt,
             color
         });
     }
     else
     {
         try
         {
             if (Program.SaveLog == 1)
             {
                 LogWritter.WriteLine(txt);
             }
         }
         catch
         {
         }
         try
         {
             if (txt.Length > 0)
             {
                 this.textbox.Select(this.textbox.Text.Length, 0);
                 this.textbox.SelectionColor = color;
                 this.textbox.AppendText(txt);
                 this.textbox.Select(this.textbox.Text.Length, 0);
                 this.textbox.ScrollToCaret();
             }
         }
         catch
         {
         }
         Application.DoEvents();
     }
 }
Exemplo n.º 23
0
        public void WriteTest()
        {
            const string logData = "test message";

            using (ShimsContext.Create())
            {
                System.Fakes.ShimDateTime.UtcNowGet = () => new DateTime(2012, 6, 5);

                var fileWriter   = new MsFakesSample.Fakes.StubIFileWriter();
                var dataProvider = new MsFakesSample.Fakes.StubIDataProvider
                {
                    GetData = () => logData
                };

                var logWritter = new LogWritter(dataProvider, fileWriter);

                var expected = new Log(logData);
                var actual   = logWritter.AddLog();

                Assert.AreEqual(expected.Message, actual.Message);
                Assert.AreEqual(expected.CreatedDate, actual.CreatedDate);
            }
        }
Exemplo n.º 24
0
 public static void Insert(String tableName, DataTable dataTable)
 {
     using (SqlBulkCopy bulkCopy = new SqlBulkCopy(DatabaseAccesser.ConnectionString))
     {
         try
         {
             bulkCopy.BulkCopyTimeout      = 600;
             bulkCopy.DestinationTableName = tableName;
             bulkCopy.WriteToServer(dataTable);
         }
         catch (SqlException sqlException)
         {
             if (sqlException.Number != NumberOfViolationOfPrimaryKey)
             {
                 Console.WriteLine($"ERROR: {sqlException.Message}, {sqlException.StackTrace}");
                 LogWritter.WriteLog(LogWritter.LogMode.Error, $"ERROR: {sqlException.Message}, {sqlException.StackTrace}");
             }
         }
         finally
         {
             bulkCopy.Close();
         }
     }
 }
Exemplo n.º 25
0
 public static void Initialize(TestContext testContext)
 {
     LogWritter = new LogWritter(new FloatRounder());
 }
Exemplo n.º 26
0
        public override async Task <AppMetadata> ScrapeAsync(string appId)
        {
            var url  = string.Format(StoreUrlTemplate, appId);
            var url2 = string.Format(StoreUrlTemplate2, appId);
            var msg  = new HttpRequestMessage(HttpMethod.Get, url);

            msg.Headers.Add("Accept", "text/json");
            var response = await Client.SendAsync(msg);

            response.EnsureSuccessStatusCode();

            var content = await response.Content.ReadAsStringAsync();

            var json = JsonConvert.DeserializeObject <dynamic>(content);

            if (json == null || json[appId]["success"] != true)
            {
                LogWritter?.Invoke(TraceLevel.Warning, $"Steam url [{url}] returned unsuccessfull status (app not found)", null);
                return(null);
            }

            dynamic result = json[appId].data;
            var     meta   = new AppMetadata()
            {
                Id = result.steam_appid, ScraperType = this.GetType(), AppUrl = GetUrlFromId(appId)
            };

            var response2 = await Client.SendAsync(new HttpRequestMessage(HttpMethod.Get, url2));

            if (!response2.IsSuccessStatusCode)
            {
                LogWritter?.Invoke(TraceLevel.Warning, $"Steam url [{url2}] returned status code [{response2.StatusCode}]; This URL is only used for DescriptionShort;", null);
            }
            else
            {
                var content2 = await response2.Content.ReadAsStringAsync();

                meta.AddValue("DescriptionShort", DescriptionRegex.GetGroup(content2)?.Trim());
            }

            meta.Name           = result.name;
            meta.IconUrl        = result.header_image;
            meta.Publisher      = result.publishers[0]?.ToString();
            meta.Website        = result.website ?? result.support_info?.url;
            meta.PublisherEmail = result.support_info.email;
            meta.Categories     = ArrayToList(result.genres, "description");
            meta.Rating         = result.metacritic?.score;
            meta.Description    = Utils.StripHtml(result.about_the_game);
            meta.Paid           = result.is_free == false;

            meta.AddValue("DescriptionLong", Utils.StripHtml(result.detailed_description));
            meta.AddValue("DescriptionLongRaw", result.detailed_description?.ToString());
            meta.AddValue("Price", result.price_overview?.initial / 100m);
            meta.AddValue("PriceCurrency", result.price_overview?.currency?.ToString());
            meta.AddValue("SupportedLanguages", Utils.StripHtml(result.supported_languages));
            meta.AddValue("RequiredAge", result.required_age?.ToString());
            meta.AddValue("Type", result.type?.ToString());
            meta.AddValue("AboutGameRaw", result.about_the_game?.ToString());
            meta.AddValue("LegalNotice", result.legal_notice?.ToString());
            meta.AddValue("Developers", ArrayToList(result.developers));
            meta.AddValue("Publishers", ArrayToList(result.publishers));
            meta.AddValue("Categories", ArrayToList(result.categories, "description"));
            meta.AddValue("Screenshots", ArrayToList(result.screenshots, "path_full"));
            meta.AddValue("PlatformWindows", result.platforms?.windows);
            meta.AddValue("PlatformLinux", result.platforms?.linux);
            meta.AddValue("PlatformMac", result.platforms?.mac);
            meta.AddValue("ReleaseDate", result.release_date?.date);
            meta.AddValue("Background", result.background);

            return(meta);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Sending An Email with master mail template.
        /// </summary>
        /// <param name="mailFrom">Mail From.</param>
        /// <param name="mailTo">Mail To.</param>
        /// <param name="mailCC">Mail CC.</param>
        /// <param name="mailBCC">Mail BCC.</param>
        /// <param name="subject">Mail Subject.</param>
        /// <param name="body">Mail Body.</param>
        /// <param name="languageId">Mail Language.</param>
        /// <param name="emailType">Email Type.</param>
        /// <param name="attachment">Mail Attachment.</param>
        /// <param name="mailLogo">Mail Logo</param>
        /// <param name="LoginUrl">Login Url</param>
        /// <param name="attachmentByteList">Attachment byte list for the mail.</param>
        /// <param name="attachmentName">Attachment file name for the mail.</param>
        /// <param name="sender">Sender.</param>
        /// <returns>return send status.</returns>
        public static bool Send(string mailFrom, string mailTo, string mailCC, string mailBCC, string subject, string body, int languageId, EmailType emailType, string attachment, string mailLogo, string LoginUrl, List <byte[]> attachmentByteList = null, string attachmentName = null, string sender = null)
        {
            if (ProjectConfiguration.SkipEmail)
            {
                return(true);
            }

            if (ProjectConfiguration.IsEmailTest)
            {
                mailTo  = ProjectConfiguration.FromEmailAddress;
                mailCC  = string.Empty;
                mailBCC = string.Empty;
            }

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            if (!string.IsNullOrEmpty(mailFrom))
            {
                mailFrom = mailFrom.Trim(';').Trim(',');
            }

            if (!string.IsNullOrEmpty(mailTo))
            {
                mailTo = mailTo.Trim(';').Trim(',');
            }

            if (!string.IsNullOrEmpty(mailCC))
            {
                mailCC = mailCC.Trim(';').Trim(',');
            }

            if (!string.IsNullOrEmpty(mailBCC))
            {
                mailBCC = mailBCC.Trim(';').Trim(',');
            }

            if (ValidateEmail(mailFrom, mailTo) && (string.IsNullOrEmpty(mailCC) || ValidateEmail(mailCC)) && (string.IsNullOrEmpty(mailBCC) || ValidateEmail(mailBCC)))
            {
                System.Net.Mail.MailMessage mailMesg = new System.Net.Mail.MailMessage();
                mailMesg.From = new System.Net.Mail.MailAddress(mailFrom);
                if (!string.IsNullOrEmpty(mailTo))
                {
                    mailTo = mailTo.Replace(";", ",");
                    mailMesg.To.Add(mailTo);
                }

                if (!string.IsNullOrEmpty(mailCC))
                {
                    mailCC = mailCC.Replace(";", ",");
                    mailMesg.CC.Add(mailCC);
                }

                if (!string.IsNullOrEmpty(mailBCC))
                {
                    mailBCC = mailBCC.Replace(";", ",");
                    mailMesg.Bcc.Add(mailBCC);
                }

                if (!string.IsNullOrEmpty(attachment) && string.IsNullOrEmpty(attachmentName))
                {
                    string[] attachmentArray = attachment.Trim(';').Split(';');
                    foreach (string attachFile in attachmentArray)
                    {
                        try
                        {
                            System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(attachFile);
                            mailMesg.Attachments.Add(attach);
                        }
                        catch
                        {
                        }
                    }
                }
                else if (!string.IsNullOrEmpty(attachment) && !string.IsNullOrEmpty(attachmentName))
                {
                    string[] attachmentArray     = attachment.Trim(';').Split(';');
                    string[] attachmentNameArray = attachmentName.Trim(';').Split(';');

                    if (attachmentArray.Length == attachmentNameArray.Length)
                    {
                        for (int cnt = 0; cnt <= attachmentArray.Length - 1; cnt++)
                        {
                            if (System.IO.File.Exists(attachmentArray[cnt]))
                            {
                                try
                                {
                                    string fileName = ConvertTo.String(attachmentName[cnt]);
                                    if (!string.IsNullOrEmpty(fileName))
                                    {
                                        System.IO.FileStream       fs     = new System.IO.FileStream(attachmentArray[cnt], System.IO.FileMode.Open, System.IO.FileAccess.Read);
                                        System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(fs, fileName);
                                        mailMesg.Attachments.Add(attach);
                                    }
                                }
                                catch
                                {
                                }
                            }
                        }
                    }
                }

                if (attachmentByteList != null && attachmentName != null)
                {
                    string[] attachmentNameArray = attachmentName.Trim(';').Split(';');

                    if (attachmentByteList.Count == attachmentNameArray.Length)
                    {
                        for (int cnt = 0; cnt <= attachmentByteList.Count - 1; cnt++)
                        {
                            string fileName = attachmentNameArray[cnt];
                            if (!string.IsNullOrEmpty(fileName))
                            {
                                try
                                {
                                    MemoryStream ms = new MemoryStream(attachmentByteList[cnt]);
                                    System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, fileName);
                                    mailMesg.Attachments.Add(attach);
                                }
                                catch
                                {
                                }
                            }
                        }
                    }
                }

                mailMesg.Subject = subject;
                mailMesg.AlternateViews.Add(GetMasterBody(body, subject, emailType, languageId, sender, mailLogo, LoginUrl));
                mailMesg.IsBodyHtml = true;

                System.Net.Mail.SmtpClient objSMTP = new System.Net.Mail.SmtpClient();
                try
                {
                    objSMTP.Send(mailMesg);
                    return(true);
                }
                catch (Exception ex)
                {
                    LogWritter.WriteErrorFile(ex);
                }
                finally
                {
                    objSMTP.Dispose();
                    mailMesg.Dispose();
                    mailMesg = null;
                }
            }

            return(false);
        }
Exemplo n.º 28
0
        /// <summary>
        ///  Handles the Error event of the Application control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void Application_Error(object sender, EventArgs e)
        {
            Exception exception = this.Server.GetLastError();

            this.Response.Clear();

            if (this.IsExceptionIgnored(exception) || exception.Message.ToString().Contains("was not found or does not implement IController."))
            {
                return;
            }

            string controller = SmartLibrary.Admin.Pages.Controllers.Error;
            string action     = string.Empty;

            if (exception.InnerException?.Message == "The remote server returned an error: (404) Not Found.")
            {
                action = Actions.UnAuthorizePage;
                this.Session.Abandon();
                this.Session.Clear();
            }
            else if (exception.InnerException?.Message == "The remote server returned an error: (401) Unauthorized.")
            {
                action = Actions.UnAuthorizePage;

                this.Session.Abandon();
                this.Session.Clear();
            }
            else
            {
                action = Actions.ErrorPage;
                var httpException = exception as HttpException;
                if (httpException?.GetHttpCode() == 404)
                {
                    action = Actions.PageNotFound;
                }
            }

            bool throwError = System.Configuration.ConfigurationManager.AppSettings["ThrowError"].ToBoolean();

            if ((!throwError || action == Actions.UnAuthorizePage) && !string.IsNullOrEmpty(action))
            {
                var routeData = new RouteData();
                routeData.Values.Add("controller", controller);
                routeData.Values.Add("action", action);
                routeData.Values.Add("exception", exception);
                this.Server.ClearError();
                this.Response.TrySkipIisCustomErrors = true;
                this.Response.Headers.Add("Content-Type", "text/html");
                if (controller != SmartLibrary.Admin.Pages.Controllers.Home)
                {
                    IController errorController = new SmartLibrary.Admin.Controllers.ErrorController();
                    errorController.Execute(new RequestContext(new HttpContextWrapper(this.Context), routeData));
                }
                else
                {
                    IController loginController = new SmartLibrary.Admin.Controllers.ErrorController();
                    loginController.Execute(new RequestContext(new HttpContextWrapper(this.Context), routeData));
                }
            }

            LogWritter.WriteErrorFile(exception, ProjectSession.Email);
        }
Exemplo n.º 29
0
        private InsertConfig GenerateInsertConfig()
        {
            var insertConfig = InsertConfig.GetInstance();

            #region ドライバーの設定

            if (this.IsCheckedTommy)
            {
                insertConfig.CheckeDrivers.Add(DriverNames.Tommy);
            }
            if (this.IsCheckedMori)
            {
                insertConfig.CheckeDrivers.Add(DriverNames.Mori);
            }
            if (this.IsCheckedTamura)
            {
                insertConfig.CheckeDrivers.Add(DriverNames.Tamura);
            }
            if (this.IsCheckedLabMember)
            {
                insertConfig.CheckeDrivers.Add(DriverNames.Arisimu);
            }


            //if (this.IsCheckedLabMember)
            //insertConfig.CheckeDrivers.Add(DriverNames.Uemura);
            // TODO 研究室メンバー

            #endregion

            #region 期間の設定
            if (IsCheckedPeriod)
            {
                insertConfig.StartDate = this.StartDate;
                insertConfig.EndDate   = this.EndDate;
            }
            else
            {
                insertConfig.StartDate = DateTime.Now.AddDays(-7);
                insertConfig.EndDate   = DateTime.Now.AddDays(1);
            }
            #endregion

            #region 推定対象車両の設定
            if (this.IsCheckedLeafEarlyModel)
            {
                insertConfig.CarModel = InsertConfig.EstimatedCarModel.LeafEarlyModel;
            }

            #endregion

            #region 推定モデルの設定

            if (this.IsCheckedEvModel)
            {
                insertConfig.EstModel = InsertConfig.EstimationModel.EvEnergyConsumptionModel;
            }
            else if (this.IsCheckedMlModel)
            {
                insertConfig.EstModel = InsertConfig.EstimationModel.MachineLearningModel;
            }

            #endregion

            #region GPS補正の設定
            if (this.IsCheckedNormal)
            {
                insertConfig.Correction.Add(InsertConfig.GpsCorrection.Normal);
            }
            if (this.IsCheckedMapMatching)
            {
                insertConfig.Correction.Add(InsertConfig.GpsCorrection.MapMatching);
            }
            //else if (this.IsCheckedDeadReckoning)
            //    insertConfig.Correction = InsertConfig.GpsCorrection.DeadReckoning;
            if (this.IsCheckedSpeedLPFMapMatching)
            {
                insertConfig.Correction.Add(InsertConfig.GpsCorrection.SpeedLPFMapMatching);
            }

            #endregion

            LogWritter.WriteLog(LogWritter.LogMode.Search, insertConfig.ToString());

            return(insertConfig);
        }
Exemplo n.º 30
0
        public async void Insert()
        {
            this.InsertDatumList       = new List <InsertDatum>();
            this.InsertFileList        = new List <string>();
            IsEnabledInsertButton      = false;
            IsEnabledStartUpLoopButton = false;
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();

            this.InsertConfig = this.GenerateInsertConfig();
            #region ファイル検索

            this.LogText += LogTexts.DuringCheckOfTheUpdateFile + "\n";
            LogWritter.WriteLog(LogWritter.LogMode.Search, LogTexts.DuringCheckOfTheUpdateFile + "\n");

            await Task.Run(() =>
            {
                this.InsertFileList = DirectorySearcher.DirectorySearch(this.InsertConfig);
            });

            this.LogText += $"{LogTexts.NumberOfTheInsertedFile}: {this.InsertFileList.Count}\n";
            LogWritter.WriteLog(LogWritter.LogMode.Search, $"{LogTexts.NumberOfTheInsertedFile}: {this.InsertFileList.Count}\n");

            #endregion

            #region GPS挿入

            this.LogText += LogTexts.TheSrartOfTheInsertingGps + "\n";
            LogWritter.WriteLog(LogWritter.LogMode.Gps, LogTexts.TheSrartOfTheInsertingGps + "\n");

            //await Task.Run(() =>
            //{
            //    for (int i = 0; i < this.InsertConfig.Correction.Count; i++)
            //    {
            //        GpsInserter.InsertGps(this.InsertFileList, this.InsertConfig, i, this.InsertDatumList);
            //    }
            //});

            Parallel.For(0, this.InsertConfig.Correction.Count, i =>
            {
                GpsInserter.InsertGps(this.InsertFileList, this.InsertConfig, i, this.InsertDatumList);
            });

            this.LogText += LogTexts.TheEndOfTheInsertingGps + "\n";
            LogWritter.WriteLog(LogWritter.LogMode.Gps, LogTexts.TheEndOfTheInsertingGps + "\n");

            #endregion

            #region 加速度挿入

            if (IsCheckedInsertAcc)
            {
                this.LogText += LogTexts.TheSrartOfTheInsertingAcc + "\n";
                LogWritter.WriteLog(LogWritter.LogMode.Acc, LogTexts.TheSrartOfTheInsertingAcc + "\n");

                await Task.Run(() =>
                {
                    AccInserter.InsertAcc(this.InsertFileList, this.InsertConfig, this.InsertDatumList);
                });

                this.LogText += LogTexts.TheEndOfTheInsertingAcc + "\n";
                LogWritter.WriteLog(LogWritter.LogMode.Acc, LogTexts.TheEndOfTheInsertingAcc + "\n");
            }

            #endregion

            foreach (var datum in InsertDatumList)
            {
                #region トリップ挿入

                //await Task.Run(() =>
                //{
                for (int i = 0; i < this.InsertConfig.Correction.Count; i++)
                {
                    TripInserter.InsertTrip(datum, InsertConfig.Correction[i]);
                }
                //});

                #endregion

                #region 補正加速度挿入

                //if (IsCheckedInsertCorrectedAcc)
                //{
                //    await Task.Run(() =>
                //    {
                //        AccInserter.InsertCorrectedAcc(datum, InsertConfig);
                //    });
                //}

                #endregion
            }
            int count = 0;
            Parallel.For(0, InsertDatumList.Count, i =>
            {
                #region ECOLOG挿入
                //     sw.Start();

                if (IsCheckedSpeedLPFMapMatching)
                {
                    EcologInserter.InsertEcologSpeedLPF005MM(InsertDatumList[i], this.UpdateText, InsertConfig.GpsCorrection.SpeedLPFMapMatching);
                }
                if (IsCheckedMapMatching)
                {
                    EcologInserter.InsertEcologMM(InsertDatumList[i], this.UpdateText, InsertConfig.GpsCorrection.MapMatching);
                }

                if (IsCheckedNormal)
                {
                    EcologInserter.InsertEcolog(InsertDatumList[i], this.UpdateText, InsertConfig.GpsCorrection.Normal, out count);
                }


                //       sw.Stop();
                //      LogWritter.WriteLog(LogWritter.LogMode.Elapsedtime, "Total Time:" + sw.Elapsed);
                #endregion
            });
            this.LogText += LogTexts.TheEndOfTheInsertingEcolog + "\n";

            /*if (count > 0)
             * {
             *  SlackUtil.commentToSlack(InsertConfig.StartDate, InsertConfig.EndDate, InsertConfig.Correction);
             * }
             * else {
             *  SlackUtil.commentToSlackNotInsert(InsertConfig.StartDate, InsertConfig.EndDate, InsertConfig.Correction);
             * }*/
            IsEnabledInsertButton      = true;
            IsEnabledStartUpLoopButton = true;
        }