public object CheckRecoveryCode(dynamic data)
        {
            var encryptedId = data.data;

            try
            {
                if (encryptedId != null)
                {
                    var sId = Utilities.Unprotect(encryptedId.ToString());
                    int id;
                    if (int.TryParse(sId, out id))
                    {
                        var user = uow.UserRepository.GetByID(id);
                        if (user != null)
                        {
                            return new { user.id, user.username }
                        }
                        ;
                    }
                }
            }
            catch (CryptographicException ex)
            {
                Nlog.Log(LogLevel.Error, ex, $"CheckRecoveryCode {data}");
            }
            Nlog.Log(LogLevel.Error, $"CheckRecoveryCode: recovery code error: {data}");
            return(new HttpResponseMessage {
                StatusCode = HttpStatusCode.BadRequest, Content = new StringContent("Greška u kodu za oporavak.")
            });
        }
Example #2
0
        /// <summary>
        /// Nlog 寫入
        /// </summary>
        /// <param name="message">訊息</param>
        /// <param name="nlog">類型 預設為訊息</param>
        public static void NlogSet(string message, Nlog nlog = Nlog.Info)
        {
            switch (nlog)
            {
            // 用於追蹤,可以在程式裡需要追蹤的地方將訊息以Trace傳出。
            case Nlog.Trace:
                logger.Trace(message);
                break;

            // 用於開發,於開發時將一些需要特別關注的訊息以Debug傳出。
            case Nlog.Debug:
                logger.Debug(message);
                break;

            // 訊息,記錄不影響系統執行的訊息,通常會記錄登入登出或是資料的建立刪除、傳輸等。
            case Nlog.Info:
                logger.Info(message);
                break;

            // 警告,用於需要提示的訊息,例如庫存不足、貨物超賣、餘額即將不足等。
            case Nlog.Warn:
                logger.Warn(message);
                break;

            // 錯誤,記錄系統實行所發生的錯誤,例如資料庫錯誤、遠端連線錯誤、發生例外等。
            case Nlog.Error:
                logger.Error(message);
                break;

            // 致命,用來記錄會讓系統無法執行的錯誤,例如資料庫無法連線、重要資料損毀等。
            case Nlog.Fatal:
                logger.Fatal(message);
                break;
            }
        }
        public object Login(string username, string password)
        {
            var user = uow.UserRepository.Get(u => u.username == username && u.password == password, includeProperties: "Groups,AdministeredCourses,EnrolledCourses").FirstOrDefault();

            if (user != null)
            {
                var token = Guid.NewGuid();
                user.Token    = Utilities.Protect(token.ToString(), "auth");
                user.Sessions = new List <UserSession>();
                user.Sessions.Add(new UserSession {
                    DateCreated = DateTime.Now, Token = token
                });
                uow.Save();
                user.AvailableCourses = GetUserAvailableCourses(user);
                var u = UsersController.GetUserUIObject(user);
                Nlog.Log(LogLevel.Info, $"User {username} successfully logged in.");

                var userString = JsonConvert.SerializeObject(u);
                //HttpContext.Current.Response.Cookies.Add(new HttpCookie("pprojects_user_token", Utilities.Protect(token.ToString(), "cookie")));
                //HttpContext.Current.Response.Cookies.Add(new HttpCookie("pprojects_user", Utilities.Protect(userString, "cookie")));
                return(u);
            }
            Nlog.Log(LogLevel.Info, $"Wrong username or password. User {username}, Pass: {password} Ip: {GetClientIp()}");
            return(new HttpResponseMessage {
                StatusCode = HttpStatusCode.BadRequest, Content = new StringContent("Neispravno korisničko ime ili lozinka")
            });
        }
Example #4
0
 public bool Download(string sourcePath, string targetPath)
 {
     if (sourcePath.Length == 0)
     {
         Nlog.Info(NLogName, $"{Path.GetFileName(sourcePath) } is null"); return(false);
     }
     if (targetPath.Length == 0)
     {
         Nlog.Info(NLogName, $"{Path.GetFileName(targetPath) } is null"); return(false);
     }
     if (!File.Exists(sourcePath))
     {
         Nlog.Info(NLogName, $"未在磁盘上发现文件:{sourcePath}"); return(false);
     }
     try
     {
         File.Copy(sourcePath, targetPath, true);
     }
     catch (Exception ex)
     {
         Nlog.Info(NLogName, $"{Path.GetFileName(targetPath) } {ex.Message}");
         return(false);
     }
     Nlog.Info(NLogName, $"{Path.GetFileName(targetPath) }\tdown √");
     return(true);
 }
Example #5
0
        /// <summary>
        /// 删除目录(包括下面所有子目录和子文件)
        /// </summary>
        /// <param name="remoteDirectory">要删除的带路径目录名</param>
        /// <returns></returns>
        private bool DeleteDirectory(string remoteDirectory)
        {
            bool result = true;
            List <FileStruct> allList = FindAllFilesAndDirectories(remoteDirectory).FileList;

            allList.Add(new FileStruct {
                FullName = remoteDirectory, IsDirectory = true
            });
            foreach (var f in allList.Where(x => !x.IsDirectory))
            {
                DeleteFile(f.FullName);
            }
            foreach (var f in allList.Where(x => x.IsDirectory).OrderByDescending(x => x.FullName.Count(c => c == '/')))
            {
                try
                {
                    using (OpenResponse(new Uri($"{_ftpUri}/{f.FullName}"), WebRequestMethods.Ftp.RemoveDirectory, out FtpWebRequest request))
                    {
                        request.Abort();
                        Nlog.Info(_nlogName, $"{f.FullName} \t delete √");
                    }
                }
                catch (Exception ex)
                {
                    result = false;
                    Nlog.Info(_nlogName, $"{f.FullName} \t delete failed {ex.Message}");
                }
            }
            return(result);
        }
        private void DeleteFtpFiles(FtpConfig ftpConfig)
        {
            Nlog.Info(ftpConfig.FileType, $"{ftpConfig.FileType}\t开始删除...");

            var ftp = Containers.Resolve <IFtp>(
                new NamedParameter("nLogName", ftpConfig.FileType),
                new NamedParameter("ftpServerIp", ftpConfig.Ip),
                new NamedParameter("ftpProt", ftpConfig.Port),
                new NamedParameter("privateKeyFile", Path.Combine(Environment.CurrentDirectory, @"SFTP_KEY\tmp.cap")),
                new NamedParameter("ftpRemotePath", ftpConfig.RemoteFolder),
                new NamedParameter("ftpUserId", ftpConfig.Uid),
                new NamedParameter("ftpPassword", ftpConfig.Pwd),
                new NamedParameter("isdirectory", ftpConfig.IsDirectory));

            ftp.InitializeFileListStyle();
            //Thread.Sleep(5000);

            var list1 = ftp.FindFiles().Where(x => ftpConfig.NameContains.Length <= 0 || x.Name.ToLower().Contains(ftpConfig.NameContains.ToLower()));

            Thread.Sleep(3000);
            var list2 = ftp.FindFiles();

            var list = list1.Join(list2, x => new { x.Name, x.Size }, y => new { y.Name, y.Size },
                                  (x, y) => new FileStruct {
                IsDirectory = x.IsDirectory, Name = x.Name, CreateTime = x.CreateTime, FullName = x.FullName, Size = x.Size, IsSuccess = false
            })
                       .Where(x => x.IsDirectory == ftpConfig.IsDirectory).ToList();

            foreach (var file in list)
            {
                ftp.Delete(file.FullName);
            }
        }
        public object UpdateUser(User user)
        {
            HttpResponseMessage message = new HttpResponseMessage {
                StatusCode = HttpStatusCode.Unauthorized
            };

            if (CurrentUser.IsAdmin || CurrentUser.id == user.id)
            {
                if (ValidateUser(user, out message))
                {
                    var u = uow.UserRepository.GetByID(user.id);
                    if (u != null)
                    {
                        var text = $"User data for {user.username} successfully changed. Changed by: {CurrentUser.username} -  name={u.name}=>{user.name} surname={u.surname}=>{user.surname} email={u.email}=>{user.email} username={u.username}=>{user.username}";
                        u.name             = user.name;
                        u.surname          = user.surname;
                        u.email            = user.email;
                        u.registrationCode = user.registrationCode;
                        u.username         = user.username;
                        uow.Save();
                        Nlog.Log(LogLevel.Info, text);
                    }

                    return(user);
                }
            }
            return(message);
        }
Example #8
0
 /// <summary>
 /// 下载文件
 /// </summary>
 /// <param name="remotePath">下载后的保存路径</param>
 /// <param name="localPath">要下载的文件名</param>
 private bool DownloadFile(string remotePath, string localPath)
 {
     //var path = Path.GetDirectoryName(loaclPath);
     //if (path?.Length > 0 && !Directory.Exists(path)) Directory.CreateDirectory(path);
     byte[] buffer = new byte[2048];
     try
     {
         using (var response = OpenResponse(new Uri($"{_ftpUri}/{remotePath}"), WebRequestMethods.Ftp.DownloadFile, out FtpWebRequest request))
         {
             using (Stream reader = response.GetResponseStream())
                 using (FileStream fileStream = new FileStream(localPath, FileMode.Create))
                     while (true)
                     {
                         int bytesRead = reader.Read(buffer, 0, buffer.Length);
                         if (bytesRead == 0)
                         {
                             break;
                         }
                         fileStream.Write(buffer, 0, bytesRead);
                     }
             request.Abort();
         }
         var result = File.Exists(localPath) && new FileInfo(localPath).Length > 0;
         Nlog.Info(_nlogName, $"{remotePath} \t down {(result ? "√" : "failed")}");
         return(result);
     }
     catch (Exception ex)
     {
         Nlog.Info(_nlogName, $"{remotePath} \t down failed {ex.Message}");
         return(false);
     }
 }
Example #9
0
        private (bool code, List <string> FileList) FindFilesAndDirectories(string uri, string webRequestMethods)
        {
            List <string> listFiles = new List <string>();

            try
            {
                using (var response = OpenResponse(new Uri(uri), webRequestMethods, out FtpWebRequest request))
                {
                    using (var stream = response.GetResponseStream())
                        using (var sr = new StreamReader(stream, Encoding.Default))
                        {
                            string line;
                            while ((line = sr.ReadLine()) != null)
                            {
                                listFiles.Add(line);
                            }
                        }
                    request.Abort();
                }
                return(true, listFiles);
            }
            catch (Exception ex)
            {
                Nlog.Info(_nlogName, $"获取文件信息失败,{uri}.{ex.Message}");
            }
            return(false, listFiles);
        }
Example #10
0
 /// <summary>
 /// 上传文件
 /// </summary>
 /// <param name="loaclPath">本地文件路径</param>
 public bool Upload(string loaclPath)
 {
     try
     {
         FileInfo fileInf = new FileInfo(loaclPath);
         var      request = OpenRequest(new Uri(_ftpUri + fileInf.Name), WebRequestMethods.Ftp.UploadFile);
         request.ContentLength = fileInf.Length;
         int    buffLength = 2048;
         byte[] buff       = new byte[buffLength];
         using (var fs = fileInf.OpenRead())
             using (var strm = request.GetRequestStream())
             {
                 var contentLen = fs.Read(buff, 0, buffLength);
                 while (contentLen != 0)
                 {
                     strm.Write(buff, 0, contentLen);
                     contentLen = fs.Read(buff, 0, buffLength);
                 }
             }
         request.Abort();
         Nlog.Info(_nlogName, $"{fileInf.Name} \t upload √");
         return(true);
     }
     catch (Exception ex)
     {
         Nlog.Info(_nlogName, $"{Path.GetFileName(loaclPath)} \t upload failed {ex.Message}");
         return(false);
     }
 }
Example #11
0
        public bool GetResult(int imimKey, string json, DownloadConfig config, bool status)
        {
            if (!status)
            {
                var e = new SPEH_CLIM_CLM_IMIM_STTS_UPDATE_OCR
                {
                    ConnectionString  = ConnectionStringConfig <SPEH_CLIM_CLM_IMIM_STTS_UPDATE_OCR> .GetConnectionString(config.ConnectionStringDictionary),
                    pIMIM_STTS_UPDATE = new List <IMIM_STTS_UPDATE>
                    {
                        new IMIM_STTS_UPDATE {
                            IMIM_KY = imimKey
                        }
                    }

                    .ToDataTable(),
                    pSTS = ((int)ResultJsonStatus.Failed).ToString()
                };
                _commonBl.Execute(e);
                return(e.ReturnValue == 1);
            }
            var item = json.FromJson <ImageDefineJson>();

            //item.Type = "0M";
            Console.WriteLine(item.Name + "\t\t" + item.Type);

            var list = new List <IMIM_INFO_INSERT> {
                new IMIM_INFO_INSERT(imimKey, item.Type, float.Parse(item.Conf) * (float)100)
            };
            var entity = new SPEH_CLIM_CLM_IMIM_PRE_SECOND_DEFINE_OCR
            {
                ConnectionString  = ConnectionStringConfig <SPEH_CLIM_CLM_IMIM_PRE_SECOND_DEFINE_OCR> .GetConnectionString(config.ConnectionStringDictionary),
                pIMIM_INFO_INSERT = list.ToDataTable()
            };

            try
            {
                _commonBl.Execute(entity);
                return(entity.ReturnValue == 1);
            }
            catch (Exception ex)
            {
                Nlog.Info($"{config.NLogName}.json", $"getresult catch:{ex.Message}");
                var e = new SPEH_CLIM_CLM_IMIM_STTS_UPDATE_OCR
                {
                    ConnectionString  = ConnectionStringConfig <SPEH_CLIM_CLM_IMIM_STTS_UPDATE_OCR> .GetConnectionString(config.ConnectionStringDictionary),
                    pIMIM_STTS_UPDATE = new List <IMIM_STTS_UPDATE>
                    {
                        new IMIM_STTS_UPDATE {
                            IMIM_KY = imimKey
                        }
                    }

                    .ToDataTable(),
                    pSTS = ((int)ResultJsonStatus.Failed).ToString()
                };
                _commonBl.Execute(e);
                return(false);
            }
        }
        public void NLogLoggerTestWithConfig()
        {
            var config = new LoggingConfiguration();

            Nlog.Init(config);

            var logger      = LogManager.GetLogger(typeof(LoggingTests));
            var loggerScope = LogManager.GetLogger("TestScope");

            CallLogger(logger);
            CallLogger(loggerScope);
        }
Example #13
0
        static void BeginWork(IDownload down, DownloadConfig config, IRpcProxy proxy)
        {
            try
            {
                //调用sp 获取imimKy batchNo imimPath
                var callDataBase = Containers.Resolve <ICallDataBase>(config.CallDataBaseServiceName);
                var data         = callDataBase.FindData(config);
                //var data = Enumerable.Range(1, 16).Select(x => new ImageInfo { ImimKy = x.ToJson(), BatchNo = "5", ImimPath = $@"C:\Users\sh179\Desktop\testx\{x}.jpg" }).ToList();

                var batchNos = data.Select(x => x.BatchNo).Distinct().ToList();
                Nlog.Info(down.NLogName, $"{config.SourceServerIp}{down.NLogName} 批次 down star,count:{batchNos.Count}");
                foreach (var item in batchNos)
                {
                    var directoryName = $"{config.SourceServerIp}{item}";
                    var path          = $@"{config.TargetServerPath}\{directoryName}";
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    var list = data.Where(x => x.BatchNo == item).DefaultIfEmpty().ToList();

                    Nlog.Info(down.NLogName, $"{config.SourceServerIp}{down.NLogName} image down star,count:{list.Count}\tBatchNo:{item}");
                    Parallel.ForEach(list, new ParallelOptions {
                        MaxDegreeOfParallelism = int.Parse(config.MaxDegreeOfParallelism)
                    }, f => f.IsSuccess = down.Download(f.ImimPath, $@"{path}\{config.SourceServerIp}{f.ImimKy}{(Path.GetExtension(f.ImimPath)?.ToLower() == "" ? ".jpg" : Path.GetExtension(f.ImimPath)?.ToLower())}"));
                    Nlog.Info(down.NLogName, $"{config.SourceServerIp}{down.NLogName} image down end,count:{list.Count(x => x.IsSuccess)}");

                    string result = "未接收到";
                    try
                    {
                        callDataBase.SendJson(list.Where(x => x.IsSuccess).ToList(), config);
                        result = proxy.SendMessage(config.CallDataBaseServiceName, $"{directoryName}");
                        //todo:批次全部发送成功,跟新数据库
                        if (result.ToLower() == "ok")
                        {
                            callDataBase.SendImage(list.Where(x => x.IsSuccess).ToList(), config);
                        }
                        Nlog.Info(down.NLogName, $"{config.SourceServerIp}{down.NLogName} Ocr.Send:{item} Ocr.Result:{result}");
                    }
                    catch (Exception ex)
                    {
                        Nlog.Info(down.NLogName, $"{config.SourceServerIp}{down.NLogName} Ocr.Send:{item} Ocr.Result:{result}.Catch:{ex.Message}");
                    }
                    Thread.Sleep(1000);
                }
                if (batchNos.Count > 0)
                {
                    Nlog.Info(down.NLogName, $"{config.SourceServerIp}{down.NLogName} 批次 down end!\r\n\r\n");
                }
            }
            catch (Exception ex) { Nlog.Info($"{config.NLogName}", $"beginwork catch:{config.SourceServerIp}.{ex.Message}"); }
            Thread.Sleep(config.SendMillisecondsTimeout);
        }
Example #14
0
        public bool DisconnectBT()
        {
            if (Mac != null)
            {
                Console.WriteLine("Trying to disconnect BT device " + Mac);
                IntPtr btHandle = IntPtr.Zero;
                int    IOCTL_BTH_DISCONNECT_DEVICE = 0x41000c;

                byte[]   btAddr = new byte[8];
                string[] sbytes = Mac.Split(':');
                for (int i = 0; i < 6; i++)
                {
                    //parse hex byte in reverse order
                    btAddr[5 - i] = Convert.ToByte(sbytes[i], 16);
                }
                long lbtAddr = BitConverter.ToInt64(btAddr, 0);

                NativeMethods.BLUETOOTH_FIND_RADIO_PARAMS p = new NativeMethods.BLUETOOTH_FIND_RADIO_PARAMS();
                p.dwSize = Marshal.SizeOf(typeof(NativeMethods.BLUETOOTH_FIND_RADIO_PARAMS));
                IntPtr searchHandle  = NativeMethods.BluetoothFindFirstRadio(ref p, ref btHandle);
                int    bytesReturned = 0;
                bool   success       = false;
                while (!success && btHandle != IntPtr.Zero)
                {
                    success = NativeMethods.DeviceIoControl(btHandle, IOCTL_BTH_DISCONNECT_DEVICE, ref lbtAddr, 8, IntPtr.Zero, 0, ref bytesReturned, IntPtr.Zero);
                    NativeMethods.CloseHandle(btHandle);
                    if (!success)
                    {
                        if (!NativeMethods.BluetoothFindNextRadio(searchHandle, ref btHandle))
                        {
                            btHandle = IntPtr.Zero;
                        }
                    }
                }
                NativeMethods.BluetoothFindRadioClose(searchHandle);
                Console.WriteLine("Disconnect successful: " + success);
                Nlog.Debug("Disconnect successful(DisconnectBT): " + success);
                Log.LogToTray("Disconnect successful(DisconnectBT): " + success);
                success = true; // XXX return value indicates failure, but it still works?
                if (success)
                {
                    IsDisconnecting = true;
                    StopOutputUpdate();
                    if (Removal != null)
                    {
                        Removal(this, EventArgs.Empty);
                    }
                }
                return(success);
            }
            return(false);
        }
Example #15
0
        static void BeginGetOcrResult(DownloadConfig config)
        {
            //try
            //{
            //    //删除空文件夹
            //    foreach (var item in Directory.GetDirectories(config.TargetServerPath))
            //    {
            //        var dir = new DirectoryInfo(item);
            //        if (dir.GetFiles().Length == 0) Directory.Delete(item);
            //    }
            //}
            //catch (Exception ex) { Nlog.Info($"{config.NLogName}.json", $"Directory.Delete catch:{config.SourceServerIp}.{ex.Message}"); }

            try
            {
                Stopwatch sw = new Stopwatch();
                sw.Start();
                var jsons = Directory.GetFiles(config.TargetServerPath, "*.json.ok", SearchOption.AllDirectories);
                sw.Stop();

                Nlog.Info($"{config.NLogName}.json", $"{config.SourceServerIp}{config.NLogName} 获取到json.Count:{jsons.Length} 耗时:{sw.Elapsed}");
                var database = Containers.Resolve <ICallDataBase>(config.CallDataBaseServiceName);
                foreach (var item in jsons)
                {
                    var fileName       = Path.GetFileName(item) ?? "";
                    var sourceServerIp = fileName.Substring(0, config.SourceServerIp.Length);
                    if (sourceServerIp != config.SourceServerIp)
                    {
                        continue;
                    }
                    try
                    {
                        string json   = File.ReadAllText(item).Replace("\r\n", "");
                        var    result = database.GetResult(int.Parse(fileName.Replace(config.SourceServerIp, "").Replace(".json.ok", "")), json, config, json.Length > 10);
                        Nlog.Info($"{config.NLogName}.json", $"{fileName} json result:{(json.Length > 10 ? "√" : "╳")},input database:{(result ? "√" : "╳")}");

                        //File.Delete(item);
                        var backupDirectory = $@"{OcrJsonBackupDirectory}\{config.SourceServerIp}\{config.CallDataBaseServiceName}\{DateTime.Now:yyyy-MM-dd}";
                        if (!Directory.Exists(backupDirectory))
                        {
                            Directory.CreateDirectory(backupDirectory);
                        }
                        File.Move(item, $@"{backupDirectory}\{DateTime.Now:yyyy.MM.dd HH.mm.ss.fff}.{fileName}");
                    }
                    catch (Exception ex) { Nlog.Info($"{config.NLogName}.json", $"move json catch:{config.SourceServerIp}{item}.{ex.Message}"); }
                    Thread.Sleep(0);
                }
            }
            catch (Exception ex) { Nlog.Info($"{config.NLogName}.json", $"getresult catch:{ex.Message}"); }
            Thread.Sleep(config.SendMillisecondsTimeout);
        }
        public void NLogLoggerTestWithConfigAllLogLevelsEnabled()
        {
            var config = new LoggingConfiguration();

            config.AddTarget("null", new NullTarget());
            config.AddRule(LogLevel.Trace, LogLevel.Fatal, "null");
            Nlog.Init(config);

            var logger      = LogManager.GetLogger(typeof(LoggingTests));
            var loggerScope = LogManager.GetLogger("TestScope");

            CallLogger(logger);
            CallLogger(loggerScope);
        }
        public void NLogLoggerTest()
        {
            Nlog.Init();
            var logger      = LogManager.GetLogger(typeof(LoggingTests));
            var loggerScope = LogManager.GetLogger("TestScope");

            Assert.True(logger.IsDebugEnabled);
            Assert.True(logger.IsErrorEnabled);
            Assert.True(logger.IsFatalEnabled);
            Assert.True(logger.IsInfoEnabled);
            Assert.True(logger.IsTraceEnabled);
            Assert.True(logger.IsWarnEnabled);

            CallLogger(logger);
            CallLogger(loggerScope);
        }
Example #18
0
 /// <summary>
 /// 删除文件
 /// </summary>
 /// <param name="remotePath">要删除的文件</param>
 private bool DeleteFile(string remotePath)
 {
     try
     {
         using (var response = OpenResponse(new Uri($"{_ftpUri}/{remotePath}"), WebRequestMethods.Ftp.DeleteFile, out FtpWebRequest request))
         {
             request.Abort();
             return(response.StatusCode == FtpStatusCode.FileActionOK);
         }
     }
     catch (Exception ex)
     {
         Nlog.Info(_nlogName, $"{remotePath} delete failed {ex.Message}");
     }
     return(false);
 }
Example #19
0
 /// <summary>
 /// 创建目录
 /// </summary>
 /// <param name="remoteDirectoryName">目录名</param>
 public bool CreateDirectory(string remoteDirectoryName)
 {
     try
     {
         using (var response = OpenResponse(new Uri(_ftpUri + remoteDirectoryName), WebRequestMethods.Ftp.MakeDirectory, out FtpWebRequest request))
         {
             request.Abort();
             return(response.StatusCode == FtpStatusCode.FileActionOK);
         }
     }
     catch (Exception ex)
     {
         Nlog.Info(_nlogName, $"makeDirectory failed,{ex.Message}");
     }
     return(false);
 }
        public object UpdatePassword(PasswordChange obj)
        {
            HttpResponseMessage message;

            try
            {
                if (ValidatePassword(obj, out message))
                {
                    /*int id = -1;
                     * if (obj.id != null)
                     * {
                     *  var sId = Utilities.Unprotect(obj.id);
                     *  int.TryParse(sId, out id);
                     *
                     * }*/
                    int id = CurrentUser?.id ?? 0;

                    if (id == 0 && obj.code == null)
                    {
                        if (obj.id != null)
                        {
                            var sId = Utilities.Unprotect(obj.id);
                            int.TryParse(sId, out id);
                        }
                    }

                    var user = id > 0 ? uow.UserRepository.GetByID(id) : uow.UserRepository.Get(u => u.registrationCode == obj.code).FirstOrDefault();

                    if (user != null)
                    {
                        user.password = obj.password;
                        uow.Save();
                        Nlog.Log(LogLevel.Info, $"User {user?.username} successfully updated password.");
                        return(obj);
                    }
                    return(new HttpResponseMessage(HttpStatusCode.BadRequest));
                }
                return(message);
            }
            catch (CryptographicException ex)
            {
                Nlog.Log(LogLevel.Error, ex, $"UpdatePassword. CurrentUser: {CurrentUser?.name} id: {obj.id}");
            }
            return(new HttpResponseMessage {
                StatusCode = HttpStatusCode.BadRequest, Content = new StringContent("Greška u postavljanju lozinke.")
            });
        }
Example #21
0
        public static void InitNlog(string logPath)
        {
            var configPath = FileSys.Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location) ?? Env.CurrentDirectory;

            if (string.IsNullOrWhiteSpace(configPath))
            {
                configPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
            }
            var nlogConfigFile = FileSys.Path.Combine(configPath, "NLog.config");

            if (!FileSys.File.Exists(nlogConfigFile))
            {
                throw new ApplicationException("NLog.config not found");
            }
            Nlog.Init(nlogConfigFile);
            NLog.LogManager.Configuration.Variables["LogPath"] = logPath;
        }
Example #22
0
 /// <summary>
 /// 更改目录或文件名
 /// </summary>
 /// <param name="uri"></param>
 /// <param name="newName">修改后新名称</param>
 private bool ReName(string uri, string newName)
 {
     try
     {
         var request = OpenRequest(new Uri(uri), WebRequestMethods.Ftp.Rename);
         request.RenameTo = newName;
         using (var response = (FtpWebResponse)request.GetResponse())
         {
             request.Abort();
             return(response.StatusCode == FtpStatusCode.FileActionOK);
         }
     }
     catch (Exception ex)
     {
         Nlog.Info(_nlogName, $"rename failed,{ex.Message}");
     }
     return(false);
 }
 public void BeginWork()
 {
     while (true)
     {
         SPIN_FLFL_FILE_LOG_INFO_INSERT entity = null;
         var result = _msmq.ReceiveTranMessageQueue(x =>
         {
             entity = x.FromJson <SPIN_FLFL_FILE_LOG_INFO_INSERT>();
             _commonBl.Execute(entity);
             return(entity.ReturnValue == 0);
         });
         Nlog.Info(_nLogName, $"{entity?.pFILE_NAME}\t{result.msg}");
         if (result.code == 1)
         {
             break;
         }
     }
     Thread.Sleep(10000);
 }
        public object SendRecoveryLink(string email)
        {
            var user = uow.UserRepository.Get(u => u.email == email).FirstOrDefault();

            if (user == null)
            {
                return new HttpResponseMessage {
                           StatusCode = HttpStatusCode.BadRequest, Content = new StringContent("Email ne postoji u bazi korisnika.")
                }
            }
            ;

            var encryptedId = Utilities.Protect(user.id.ToString());
            var link        = Utilities.GetSiteUrl() + "/#/passrecovery/" + HttpUtility.UrlEncode(encryptedId);
            var body        = $"<a href=\"{link}\">Kliknite da biste otvorili stranicu za promjenu lozinke.</a>";

            Nlog.Log(LogLevel.Info, $"User {email} requested recovery link.");

            Utilities.SendMail(email, "Postavljanje nove lozinke za Portal za završne radove", body);
            return($"Email s linkom za oporavak je poslan na adresu {email}.");
        }
Example #25
0
        /// <summary>
        /// 获取当前目录下指定目录下的文件和一级子目录信息
        /// </summary>
        /// <param name="directory">如未指定目录,则启用默认目录</param>
        /// <returns></returns>
        private (bool code, List <FileStruct> FileList) FindFilesByCurrentDirectories(string directory = "")
        {
            //必须保留最后的[/]符号,不然给出的列表会是带有directory/fileName这样的结果
            string uri  = directory.Length == 0 ? _ftpUri : $"{_ftpUri}/{directory}/";
            var    res1 = FindFilesAndDirectories(uri, WebRequestMethods.Ftp.ListDirectory);
            var    res2 = FindFilesAndDirectories(uri, WebRequestMethods.Ftp.ListDirectoryDetails);


            var fileList = new List <FileStruct>();

            foreach (var name in res1.FileList)
            {
                string line = res2.FileList.FirstOrDefault(x => x.Contains(name)) ?? "";
                if (line.Length > 0)
                {
                    if (_fileListStyle == FileListStyle.Unknown || line == "")
                    {
                        continue;
                    }
                    FileStruct f = new FileStruct
                    {
                        Name     = name,
                        FullName = directory.Length > 0 ? $"{directory}/{name}" : name
                    };
                    switch (_fileListStyle)
                    {
                    case FileListStyle.UnixStyle: ParseFileStructFromUnixStyleRecord(line, ref f); break;

                    case FileListStyle.WindowsStyle: ParseFileStructFromWindowsStyleRecord(line, ref f); break;
                    }
                    fileList.Add(f);
                }
            }
            if (res2.FileList.Count > 0)
            {
                res2.FileList = res2.FileList.Select(x => $"{directory}/{x}").ToList();
                Nlog.Info(_nlogName, $"\r\n{string.Join("\r\n", res2.FileList)}");
            }
            return(res1.code && res2.code, fileList);
        }
        /// <summary>
        /// 获取当前目录的文件和一级子目录信息
        /// </summary>
        /// <returns></returns>
        private (bool code, List <FileStruct> FileList) ListFilesAndDirectories(string ftpRemotePath)
        {
            ftpRemotePath = ftpRemotePath.Length > 0 ? $"/{_ftpRemotePath}/{ftpRemotePath}" : $"/{_ftpRemotePath}";
            try
            {
                List <SftpFile> sftpFileList;
                using (var sftp = new SftpClient(_connInfo))
                {
                    sftp.Connect();
                    sftpFileList = sftp.ListDirectory(ftpRemotePath)?.Where(x => x.Name != "." && x.Name != "..").ToList();
                    sftp.Disconnect();
                }

                if (sftpFileList?.Count > 0)
                {
                    Nlog.Info(_nlogName, $"\r\n{string.Join("\r\n", sftpFileList.Select(x => $"{x.LastWriteTime} {x.Length.ToString().PadRight(8, ' ')}\t{x.FullName.Replace($"/{_ftpRemotePath}/", "")}"))}");
                }

                //if (sftpFileList == null || sftpFileList.Any(x => x.Length == 0))
                //{
                //    Nlog.Info(_nlogName, $@"获取文件信息失败,{ftpRemotePath.Replace($"/{_ftpRemotePath}/", "")}/{sftpFileList?.FirstOrDefault(x => x.Length == 0)?.Name} size=0||size=null");
                //    return (false, new List<FileStruct>());
                //}

                return(true, sftpFileList?.Select(x => new FileStruct
                {
                    IsDirectory = x.IsDirectory,
                    CreateTime = x.LastWriteTime,
                    Name = x.Name,
                    FullName = x.FullName,
                    Size = x.Length.ToString()
                }).ToList());
            }
            catch (Exception ex)
            {
                Nlog.Info(_nlogName, $"获取文件信息失败,{ftpRemotePath.Replace($"/{_ftpRemotePath}/", "")}.{ex.Message}");
            }
            return(false, new List <FileStruct>());
        }
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="remoteName">要删除的文件名</param>
        private bool DeleteFile(string remoteName)
        {
            bool result;

            try
            {
                using (var sftp = new SftpClient(_connInfo))
                {
                    sftp.Connect();
                    sftp.DeleteFile($"/{remoteName}");
                    sftp.Disconnect();
                    result = true;
                }
                Nlog.Info(_nlogName, $"{remoteName.Replace($"/{_ftpRemotePath}/", "")} \t delete √");
            }
            catch (Exception ex)
            {
                result = false;
                Nlog.Info(_nlogName, $"{remoteName.Replace($"/{_ftpRemotePath}/", "")} \t delete failed {ex.Message}");
            }
            return(result);
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="remoteName">下载后的保存路径</param>
        /// <param name="localPath">要下载的文件名</param>
        private bool DownloadFile(string remoteName, string localPath)
        {
            try
            {
                using (var sftp = new SftpClient(_connInfo))
                {
                    sftp.Connect();
                    var byt = sftp.ReadAllBytes(remoteName);
                    sftp.Disconnect();
                    File.WriteAllBytes(localPath, byt);
                }
                //var result = File.Exists(localPath) && new FileInfo(localPath).Length > 0;

                var result = File.Exists(localPath);
                Nlog.Info(_nlogName, $"{remoteName.Replace($"/{_ftpRemotePath}/", "")} \t down {(result ? "√" : "failed")}");
                return(result);
            }
            catch (Exception ex)
            {
                Nlog.Info(_nlogName, $"{remoteName.Replace($"/{_ftpRemotePath}/", "")} \t down failed {ex.Message}");
                return(false);
            }
        }
        /// <summary>
        /// 删除目录
        /// </summary>
        /// <param name="directory">要删除的目录名</param>
        private bool DeleteDirectory(string directory)
        {
            bool result;

            try
            {
                using (SshClient ssh = new SshClient(_connInfo))
                {
                    ssh.Connect();
                    using (var scmd = ssh.RunCommand($"rm -rf {directory}"))
                        result = scmd.ExitStatus == 0;
                    ssh.Disconnect();
                }

                Nlog.Info(_nlogName, $"{directory.Replace($"/{_ftpRemotePath}/", "")} \t delete √");
            }
            catch (Exception ex)
            {
                result = false;
                Nlog.Info(_nlogName, $"{directory.Replace($"/{_ftpRemotePath}/", "")} \t delete failed {ex.Message}");
            }
            return(result);
        }
Example #30
0
        public bool Download(string sourcePath, string targetPath)
        {
            if (sourcePath.Length == 0)
            {
                Nlog.Info(NLogName, $"{Path.GetFileName(sourcePath) } is null"); return(false);
            }
            if (targetPath.Length == 0)
            {
                Nlog.Info(NLogName, $"{Path.GetFileName(targetPath) } is null"); return(false);
            }

            try
            {
                var result = api.GetAsync(sourcePath, targetPath);
                //var result = _api.Download(sourcePath, targetPath);
                Nlog.Info(NLogName, $"{Path.GetFileName(targetPath) }\tCloud down {(result ? "√" : "failed")}");
                return(result);
            }
            catch (Exception ex)
            {
                Nlog.Info(NLogName, $"{Path.GetFileName(targetPath) } {ex.Message}");
                return(false);
            }
        }