public static void extract(string dirName) { FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog(); DialogResult result = folderBrowserDialog1.ShowDialog(); if (result != DialogResult.OK) { return; } string outPath = folderBrowserDialog1.SelectedPath; if (CommandFindRomsInGame == null) { CommandFindRomsInGame = new SQLiteCommand( @"SELECT ROM.RomId, ROM.name, FILES.size, FILES.compressedsize, FILES.crc, FILES.sha1 FROM ROM,FILES WHERE ROM.FileId=FILES.FileId AND ROM.GameId=@GameId AND ROM.PutInZip ORDER BY ROM.RomId", Program.db.Connection); } CommandFindRomsInGame.Parameters.Add(new SQLiteParameter("GameId")); byte[] buff = new byte[1024]; Debug.WriteLine(dirName); SQLiteCommand getfiles = new SQLiteCommand(@"SELECT dir.FullName,GameId,game.Name FROM dir,dat,game where dat.dirid=dir.dirid and game.datid=dat.datid and dir.fullname like '" + dirName + "%'", Program.db.Connection); DbDataReader reader = getfiles.ExecuteReader(); while (reader.Read()) { string outputFile = reader["fullname"].ToString() + reader["Name"].ToString() + ".zip"; outputFile = outputFile.Substring(dirName.Length); outputFile = Path.Combine(outPath, outputFile).Replace(@"/", @"\"); Debug.WriteLine(outputFile); int GameId = Convert.ToInt32(reader["GameId"]); string GameName = reader["name"].ToString(); Debug.WriteLine("Game " + GameId + " Name: " + GameName); ZipFile memZip = new ZipFile(); memZip.ZipCreateFake(); ulong fileOffset = 0; Stream _zipFs = null; int romCount = 0; using (DbDataReader drRom = ZipSetGetRomsInGame(GameId)) { while (drRom.Read()) { int RomId = Convert.ToInt32(drRom["RomId"]); string RomName = drRom["name"].ToString(); ulong size = Convert.ToUInt64(drRom["size"]); ulong compressedSize = Convert.ToUInt64(drRom["compressedsize"]); byte[] CRC = VarFix.CleanMD5SHA1(drRom["crc"].ToString(), 8); byte[] sha1 = VarFix.CleanMD5SHA1(drRom["sha1"].ToString(), 32); Debug.WriteLine(" Rom " + RomId + " Name: " + RomName + " Size: " + size + " Compressed: " + compressedSize + " CRC: " + VarFix.ToString(CRC)); byte[] localHeader; memZip.ZipFileAddFake(RomName, fileOffset, size, compressedSize, CRC, out localHeader); //ZipSetLocalFileHeader(RomId, localHeader, fileOffset); if (romCount == 0) { ZipFile.CreateDirForFile(outputFile); int errorCode = FileStream.OpenFileWrite(outputFile, out _zipFs); } _zipFs.Write(localHeader, 0, localHeader.Length); GZip GZip = new GZip(); string strFilename = RomRootDir.GetFilename(sha1, true); GZip.ReadGZip(strFilename, false); Stream oStr; GZip.GetRawStream(out oStr); ulong sizetogo = compressedSize; while (sizetogo > 0) { ulong sizenow = sizetogo > 1024 ? 1024 : sizetogo; oStr.Read(buff, 0, (int)sizenow); _zipFs.Write(buff, 0, (int)sizenow); sizetogo -= sizenow; } oStr.Dispose(); GZip.Close(); fileOffset += (ulong)localHeader.Length + compressedSize; _zipFs.Position = (long)fileOffset; romCount += 1; } } byte[] centeralDir; memZip.ZipFileCloseFake(fileOffset, out centeralDir); if (romCount > 0) { _zipFs.Write(centeralDir, 0, centeralDir.Length); _zipFs.Flush(); _zipFs.Close(); _zipFs.Dispose(); } } }
public void Do(ConnectClient client) { Client = client; Loger.Log("Server ReceiveBytes1"); ///установка условно защищенного соединения //Строго первый пакет: Передаем серверу КОткр var rc = Client.ReceiveBytes(); var crypto = new CryptoProvider(); if (SessionClient.UseCryptoKeys) { crypto.OpenKey = Encoding.UTF8.GetString(rc); } //Строго первый ответ: Передаем клиенту КОткр(Сессия) SetKey(); Loger.Log("Server SendMessage1"); if (SessionClient.UseCryptoKeys) { Client.SendMessage(crypto.Encrypt(Key)); } else { Client.SendMessage(Key); } //if (LogMessage != null) LogMessage("session Connected"); Worker = new Service(); ///рабочий цикл while (true) { //Loger.Log("Server Loop1"); var rec = Client.ReceiveBytes(); if (Worker.Player != null) { Worker.Player.Public.LastOnlineTime = DateTime.UtcNow; } //отдельно обрабатываем пинг if (rec.Length == 1) { if (rec[0] == 0x00) { Client.SendMessage(new byte[1] { 0x00 }); } //отдельно обрабатываем запрос на обновление (ответ 0 - нет ничего, 1 - что-то есть) else if (rec[0] == 0x01) { var exists = ServiceCheck(); Client.SendMessage(new byte[1] { exists ? (byte)0x01 : (byte)0x00 }); } continue; } //Loger.Log("Server Loop2"); var rec2 = CryptoProvider.SymmetricDecrypt(rec, Key); //Loger.Log("Server " + Loger.Bytes(rec2)); //Loger.Log("Server Loop3"); var recObj = (ModelContainer)GZip.UnzipObjByte(rec2); //Deserialize //Loger.Log("Server Loop4"); var sendObj = Service(recObj); //Loger.Log("Server Loop5"); var ob = GZip.ZipObjByte(sendObj); //Serialize //Loger.Log("Server Loop6"); var send = CryptoProvider.SymmetricEncrypt(ob, Key); //Loger.Log("Server Loop7"); Client.SendMessage(send); } }
public void PrepareSend() { HeadStream = (Stream) new MemoryStream(); StreamWriter headWriter = new StreamWriter(HeadStream, Encoding.ASCII); string codeReason = HttpConst.CodeReasons[Code]; headWriter.WriteLine("{0} {1} {2}", HttpConst.HttpVersion, (int)Code, codeReason); if (Location != null) { headWriter.WriteLine("Location: {0}", Location); } headWriter.WriteLine("Server: {0}", WebConfig.ServerVersion); headWriter.WriteLine("Connection: {0}", Connection); headWriter.WriteLine("Date: {0}", HttpTime.HtmlNow()); if (Body != null && Body.HasContent) { if (Body.ContentEncoding != ContentEncodings.NORMAL) { string cenc = ""; switch (Body.ContentEncoding) { case ContentEncodings.GZIP: cenc = "gzip"; break; case ContentEncodings.DEFLATE: cenc = "deflate"; break; } headWriter.WriteLine("Content-Encoding: {0}", cenc); } if (Body.ContentEncoding == ContentEncodings.GZIP) { MemoryStream body = new MemoryStream(); GZip.Compress(Body.ContentStream, body); Body.ContentStream = body; } if (LastModified != null) { headWriter.WriteLine("Last-Modified: {0}", HttpTime.Date2TimeHtml(LastModified)); } headWriter.Write("Content-Type: {0}", Body.ContentType); if (Body.ContentType.StartsWith("text") && Body.CharSet.Length > 0) { headWriter.Write("; charset={0}", Body.CharSet); } headWriter.WriteLine(); if (Body.ContentDisposition != null && Body.ContentDisposition.Length > 0) { headWriter.WriteLine("Content-Disposition: {0}", Body.ContentDisposition); } headWriter.WriteLine("Content-Length: {0}", Body.Length); // BUG para MSIE para imagenes en CSS if (Body.ContentType.StartsWith("image") && Request.IsMSIEBrowser) { headWriter.WriteLine("Expires: {0}", HttpTime.Date2TimeHtml(DateTime.Now.AddHours(2))); } headWriter.WriteLine("Cache-Control: {0}", "public, must-revalidate, max-age = 1"); } else { headWriter.WriteLine("Content-Length: {0}", 0); } foreach (object item in Head.Fields.Values) { var field = (HttpField)item; switch (field.Name) { default: headWriter.WriteLine("{0}: {1}", field.Name, field.Value); break; } } headWriter.WriteLine(); headWriter.Flush(); }
private static void ScanAFile(FileInfo f) { Debug.WriteLine(f.FullName); Stream fStream; int errorCode = IO.FileStream.OpenFileRead(f.FullName, out fStream); if (errorCode != 0) { return; } int offset; FileType foundFileType = FileHeaderReader.GetType(fStream, out offset); RvFile tFile = UnCompFiles.CheckSumRead(fStream, offset); tFile.AltType = foundFileType; if (foundFileType == FileType.CHD) { // need to validate check the CHD file } // test if needed. FindStatus res = fileneededTest(tFile); if (res == FindStatus.FileNeededInArchive) { Debug.WriteLine("Reading file as " + tFile.SHA1); GZip gz = new GZip(); gz.crc = tFile.CRC; gz.md5Hash = tFile.MD5; gz.sha1Hash = tFile.SHA1; gz.uncompressedSize = tFile.Size; Stream ds; IO.FileStream.OpenFileRead(f.FullName, out ds); string outfile = Getfilename(tFile.SHA1); gz.WriteGZip(outfile, ds, false); ds.Close(); ds.Dispose(); tFile.DBWrite(); } if (foundFileType == FileType.ZIP) { ZipFile fz = new ZipFile(); fz.ZipFileOpen(f.FullName, f.LastWriteTime, true); { for (int i = 0; i < fz.LocalFilesCount(); i++) { // this needs to go back into the Zip library. int Buffersize = 1024 * 1024; byte[] _buffer = new byte[Buffersize]; Stream stream; ulong streamSize; ushort compressionMethod; fz.ZipFileOpenReadStream(i, false, out stream, out streamSize, out compressionMethod); string file = @"C:\RomVaultX\" + Guid.NewGuid(); Stream Fs; IO.FileStream.OpenFileWrite(file, out Fs); ulong sizetogo = streamSize; while (sizetogo > 0) { int sizenow = sizetogo > (ulong)Buffersize ? Buffersize : (int)sizetogo; stream.Read(_buffer, 0, sizenow); Fs.Write(_buffer, 0, sizenow); sizetogo -= (ulong)sizenow; } Fs.Close(); stream.Close(); FileInfo fi = new FileInfo(file); ScanAFile(fi); File.Delete(file); } } } if (foundFileType == FileType.GZ) { } }
protected void btnLogin_Click(object sender, EventArgs e) { string filename = string.Empty; string appVersion = "1.1.1"; string dbfileName = string.Empty; string mac = string.Empty; // GetMACAddress(); // mac = macAddress.Value; mac = fingerPrint; // Session["macAddress"] = mac; mac1 = Session["macAddress"].ToString(); // BusinessLogic bl1 = new BusinessLogic(); // bl1.macaddressretrive(mac); try { if (Session["CompanyList"] != null) { listComp = (Hashtable)Session["CompanyList"]; if (!listComp.Contains(txtCompany.Text.Trim().ToUpper())) { ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Invalid Company Code. Please try again.');", true); return; } } else { Response.Redirect("Login.aspx"); } //if (((HiddenField)this.Master.FindControl("hdIsInternetExplorer")).Value != "True") //{ // ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('For Security Reasons we strongly recommend TROYPLUS Software should be used with Internet Explorer. Request you to please close this browser and use Internet Explorer.');", true); // return; //} Response.Cookies.Clear(); foreach (HttpCookie ck in Response.Cookies) { ck.Expires = DateTime.Now.AddDays(-1); Response.AppendCookie(ck); } HttpCookie cookie = new HttpCookie("Company"); if (txtCompany.Text != "") { cookie.Value = txtCompany.Text; if (Response.Cookies["Company"] == null) { Response.Cookies.Add(cookie); } else { Response.SetCookie(cookie); } } else { return; } string sCustomer = string.Empty; BusinessLogic bl = new BusinessLogic(); DataSet ds1 = bl.GetBranch(txtCompany.Text, txtLogin.Text); DataSet dss = new DataSet(); drpBranch.Items.Clear(); drpBranch.Items.Add(new ListItem("Select Branch", "0")); dss = bl.ListBranchLogin(txtCompany.Text); drpBranch.DataSource = dss; drpBranch.DataBind(); drpBranch.DataTextField = "BranchName"; drpBranch.DataValueField = "Branchcode"; if (ds1.Tables[0].Rows.Count > 0) { sCustomer = Convert.ToString(ds1.Tables[0].Rows[0]["DefaultBranchCode"]); drpBranch.ClearSelection(); ListItem li = drpBranch.Items.FindByValue(System.Web.HttpUtility.HtmlDecode(sCustomer)); if (li != null) { li.Selected = true; } txtPassword.Focus(); HttpCookie cookie1 = new HttpCookie("Branch"); HttpCookie dash1 = new HttpCookie("dash"); dash1.Value = ds1.Tables[0].Rows[0]["dashboard"].ToString(); Response.Cookies.Add(dash1); if (ds1.Tables[0].Rows[0]["BranchCheck"].ToString() == "True") { drpBranch.Enabled = true; cookie1.Value = "All"; if (Response.Cookies["Branch"] == null) { Response.Cookies.Add(cookie1); } else { Response.SetCookie(cookie1); } } else { drpBranch.Enabled = false; cookie1.Value = drpBranch.SelectedValue; if (Response.Cookies["Branch"] == null) { Response.Cookies.Add(cookie1); } else { Response.SetCookie(cookie1); } } } //HttpCookie cookie1 = new HttpCookie("Branch"); //if (drpBranch.SelectedValue != "0") //{ // cookie1.Value = drpBranch.SelectedValue; // if (Response.Cookies["Branch"] == null) // Response.Cookies.Add(cookie1); // else // Response.SetCookie(cookie1); //} //else // return; string localpath = ConfigurationManager.AppSettings["LocalPath"].ToString(); string connStr = System.Configuration.ConfigurationManager.ConnectionStrings[Request.Cookies["Company"].Value].ConnectionString; dbfileName = connStr.Remove(0, connStr.LastIndexOf(@"App_Data\") + 9); dbfileName = dbfileName.Remove(dbfileName.LastIndexOf(";Persist Security Info")); filename = Server.MapPath(localpath + dbfileName); if (File.Exists(filename + ".zip")) { GZip objZip = new GZip(filename + ".zip", filename, Action.UnZip); File.Delete(filename + ".zip"); } // BusinessLogic bl = new BusinessLogic(); bool isAuthenticated = IsAuthenticated(txtLogin.Text, txtPassword.Text); if (isAuthenticated == true) { string[] roles = GetRoles(txtLogin.Text); string roleData = string.Join("|", roles); FormsAuthentication.SignOut(); HttpCookie authCookie = FormsAuthentication.GetAuthCookie(txtLogin.Text, chkRemember.Checked); FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value); FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, roleData); string encryptedTicket = FormsAuthentication.Encrypt(authTicket); authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); if (Response.Cookies[FormsAuthentication.FormsCookieName] == null) { Response.Cookies.Add(authCookie); } else { Response.SetCookie(authCookie); } LoadAppSettings(); if (Session["AppSettings"] != null) { DataSet ds = (DataSet)Session["AppSettings"]; for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { if (ds.Tables[0].Rows[i]["KEYNAME"].ToString() == "VERSION") { if (ds.Tables[0].Rows[i]["KEYNAME"].ToString() == "CURRENCY") { Session["CurrencyType"] = ds.Tables[0].Rows[i]["KEYVALUE"].ToString(); } if (ds.Tables[0].Rows[i]["KEYNAME"].ToString() == "OWNERMOB") { Session["OWNERMOB"] = ds.Tables[0].Rows[i]["KEYVALUE"].ToString(); } if (ds.Tables[0].Rows[i]["KEYVALUE"].ToString() != appVersion) { ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Application and Database Version should be same. Please Contact Administrator.');", true); } } } } string id = Helper.GetDecryptedKey("InstallationType"); //if ((Helper.GetDecryptedKey("InstallationType") == "ONLINE-OFFLINE-SERVER") || // (Helper.GetDecryptedKey("InstallationType") == "SERVER")) if ((System.Configuration.ConfigurationManager.AppSettings["InstallationType"].ToString() == "ONLINE-OFFLINE-SERVER") || (System.Configuration.ConfigurationManager.AppSettings["InstallationType"].ToString() == "SERVER")) { if (!IsValidIPRequest()) { ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('You are not a Valid User, Only Ristricted Users are allowed to Login. Please Contact Administrator.');", true); return; } } IsSMSRequired(); CheckDateLock(); if (!(CheckPasswordExpiry(txtLogin.Text))) { Response.Redirect("PasswordExpiry.aspx", false); ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('welcome' + '" + fingerPrint + "');", true); return; } int expdays = 10; if ((expdays == 0) || (expdays < 0)) { ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Your password is expired. Please Contact Administrator.');", true); return; } else if ((expdays < 7) && (expdays > 0)) { DialogResult dr = MessageBox.Show("Your password will expire within 7 days. Do you want to change the password now?", "Password Expiry Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (dr == DialogResult.Yes) { Response.Redirect("ChangePassword.aspx"); // ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('welcome' + '" + fingerPrint + "');", true); } else { if (!bl.GetSalesRole(Request.Cookies["Company"].Value, txtLogin.Text)) { Response.Redirect("Default.aspx"); // ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('welcome' + '" + fingerPrint + "');", true); } else { Response.Redirect(FormsAuthentication.DefaultUrl, true); } } } else { if (!bl.GetSalesRole(Request.Cookies["Company"].Value, txtLogin.Text)) { Response.Redirect("Default.aspx"); ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('welcome' + '" + fingerPrint + "');", true); } else { Response.Redirect(FormsAuthentication.DefaultUrl, true); } } } else { ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Invalid Login. Please check the username and password');", true); Response.Cookies.Clear(); return; } } catch (Exception ex) { TroyLiteExceptionManager.HandleException(ex); ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('welcome' + '" + fingerPrint + "');", true); return; } }
/// <summary> /// 组合简历 /// </summary> private static void PortfolioResume() { while (true) { try { ZhaopinResume resume; var stopwatch = new Stopwatch(); stopwatch.Restart(); if (!resumeQueue.TryDequeue(out resume)) { Thread.Sleep(100); continue; } var filePath = $"{uploadFilePath}{resume.Id}.json"; if (File.Exists(filePath)) { uploadQueue.Enqueue(filePath); continue; } string userId; string cellphone; string email; using (var db = new MangningXssDBEntities()) { var user = db.ZhaopinUser.AsNoTracking().FirstOrDefault(f => f.Id == resume.UserId); if (user == null) { continue; } userId = user.Id.ToString(); cellphone = user.Cellphone; email = user.Email; using (var stream = new MemoryStream()) { if (mangningOssClient.DoesObjectExist(mangningBucketName, $"Zhaopin/Resume/{resume.Id}")) { var bytes = new byte[1024]; int len; var streamContent = mangningOssClient.GetObject(mangningBucketName, $"Zhaopin/Resume/{resume.Id}").Content; while ((len = streamContent.Read(bytes, 0, bytes.Length)) > 0) { stream.Write(bytes, 0, len); } var resumeContent = Encoding.UTF8.GetString(GZip.Decompress(stream.ToArray())); var resumeObj = JsonConvert.DeserializeObject <dynamic>(resumeContent); var resumeDetail = JsonConvert.DeserializeObject(resumeObj.detialJSonStr.ToString()); resumeDetail.DateModified = user.ModifyTime.ToLocalTime(); resumeDetail.DateCreated = user.CreateTime?.ToLocalTime() ?? resumeDetail.DateCreated; resumeDetail.DateLastReleased = resume.RefreshTime.Value.ToLocalTime(); resumeDetail.DateLastViewed = resume.RefreshTime.Value.ToLocalTime(); resumeObj.detialJSonStr = resumeDetail; resumeContent = JsonConvert.SerializeObject(resumeObj); File.WriteAllText(filePath, resumeContent); uploadQueue.Enqueue(filePath); continue; } if (mangningOssClient.DoesObjectExist(mangningBucketName, $"WatchResume/{resume.Id}")) { var bytes = new byte[1024]; int len; var streamContent = mangningOssClient.GetObject(mangningBucketName, $"WatchResume/{resume.Id}").Content; while ((len = streamContent.Read(bytes, 0, bytes.Length)) > 0) { stream.Write(bytes, 0, len); } var resumeContent = Encoding.UTF8.GetString(GZip.Decompress(stream.ToArray())); var resumeObj = JsonConvert.DeserializeObject <dynamic>(resumeContent); resumeObj.userDetials.mobilePhone = user.Cellphone; resumeObj.userDetials.email = user.Email; var resumeDetail = JsonConvert.DeserializeObject(resumeObj.detialJSonStr.ToString()); resumeDetail.DateModified = user.ModifyTime.ToLocalTime(); resumeDetail.DateCreated = user.CreateTime.Value.ToLocalTime(); resumeDetail.DateLastReleased = resume.RefreshTime.Value.ToLocalTime(); resumeDetail.DateLastViewed = resume.RefreshTime.Value.ToLocalTime(); resumeObj.detialJSonStr = resumeDetail; resumeContent = JsonConvert.SerializeObject(resumeObj); using (var jsonStream = new MemoryStream(GZip.Compress(Encoding.UTF8.GetBytes(resumeContent)))) { mangningOssClient.PutObject(mangningBucketName, $"Zhaopin/Resume/{resume.Id}", jsonStream); } File.WriteAllText(filePath, resumeContent); uploadQueue.Enqueue(filePath); continue; } var zhaopinResume = db.ZhaopinResume.FirstOrDefault(f => f.Id == resume.Id); if (zhaopinResume != null) { zhaopinResume.Flag = 0x2; } } db.SaveChanges(); stopwatch.Stop(); } using (var bdcDb = new BadoucaiAliyunDBEntities()) { bdcDb.CoreResumeZhaopin.Add(new CoreResumeZhaopin { Cellphone = cellphone, Email = email, ResumeKey = userId, Type = "ResumeUserId", IsMatched = false }); bdcDb.SaveChanges(); } Console.WriteLine($"{DateTime.Now} > 简历未找到 Josn 源!ResumeId = {resume.Id}, UserId = {userId}, Elapsed = {stopwatch.ElapsedMilliseconds} ms."); } catch (Exception ex) { Trace.TraceError(ex.ToString()); } } }
public static void Compress(object sender, EventArgs e) { var tsi = sender as ToolStripMenuItem; if (!PrepareFiles("Open a decompressed " + tsi.Tag.ToString() + "file...", "Save your compressed file...", ".comp", out FileStream openFile, out FileStream saveFile)) { return; } try { using (openFile) using (var outFs = new BinaryWriterX(saveFile)) switch (tsi.Tag) { /*case Compression.L5LZSS: * outFs.Write(Level5.Compress(openFile, 1)); * break; * case Compression.L5Huff4: * outFs.Write(Level5.Compress(openFile, 2)); * break; * case Compression.L5Huff8: * outFs.Write(Level5.Compress(openFile, 3)); * break; * case Compression.L5RLE: * outFs.Write(Level5.Compress(openFile, 4)); * break;*/ case Compression.GZip: outFs.Write(GZip.Compress(openFile)); break; case Compression.Huff4: outFs.Write(Huffman.Compress(openFile, 4)); break; case Compression.Huff8: outFs.Write(Huffman.Compress(openFile, 8)); break; case Compression.LZ10: outFs.Write(LZ10.Compress(openFile)); break; case Compression.LZ11: outFs.Write(LZ11.Compress(openFile)); break; /*case Compression.LZSS: * outFs.Write(LZSS.Compress(openFile)); * break;*/ case Compression.RevLZ77: outFs.Write(RevLZ77.Compress(openFile)); break; case Compression.RLE: outFs.Write(RLE.Compress(openFile)); break; case Compression.ZLib: outFs.Write(ZLib.Compress(openFile)); break; } } catch (Exception ex) { MessageBox.Show(ex.ToString(), tsi?.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } MessageBox.Show($"Successfully compressed {Path.GetFileName(openFile.Name)}.", tsi?.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); }
internal static void Extract(Models.FileTransportInfo fileTransferInfo) { GZip.Decompress(System.IO.File.OpenRead(fileTransferInfo.SourceFullName), System.IO.File.OpenWrite(fileTransferInfo.DestinationFullName), true); }
/// <summary> /// Compresses data using gzip /// </summary> /// <param name="data">The data to compress</param> /// <returns>The compressed stream.</returns> public static Stream ZipAsStream(this byte[] data) { using (var stream = new MemoryStream(data)) return(GZip.Zip(stream)); }
/// <summary> /// 单个文件上传 /// </summary> /// <param name="newBucket"></param> /// <param name="path"></param> /// <param name="newOss"></param> private void SingleFileUpload(IOss newOss, string newBucket, string path) { var resume = JsonConvert.DeserializeObject <Resume>(File.ReadAllText(path)); dynamic response; string tag; var account = new ResumeRefrence { Id = resume.Reference.Id, Source = resume.Reference.Source }; #region 准备上传简历到数据库 try { response = HttpAPI.PrepareUploadResume(JsonConvert.SerializeObject(account)); if (response.Code.ToString() != "0") { this.AsyncSetLog(this.tbx_Log, $"准备上传简历API,响应信息:{JsonConvert.SerializeObject(response)}"); HttpAPI.FinishUploadResume(JsonConvert.SerializeObject(account)); pathQueue.Enqueue(path); return; } } catch (Exception ex) { pathQueue.Enqueue(path); this.AsyncSetLog(this.tbx_Log, $"{DateTime.Now} 准备上传简历到数据库异常,异常消息:{ex.Message}"); HttpAPI.FinishUploadResume(JsonConvert.SerializeObject(account)); return; } #endregion #region 简历到数据库 try { var times = 0; while (true) { response = HttpAPI.UploadResume(JsonConvert.SerializeObject(resume)); if (response.Code.ToString() != "0" && times++ == 0) { HttpAPI.FinishUploadResume(JsonConvert.SerializeObject(account)); continue; } break; } tag = response.Reference.Tag.ToString(); if (response.Code.ToString() != "0") { var failpath = ConfigurationManager.AppSettings["Zhaopin_UploadFailFiles_Path"] + companyName + Path.GetFileName(path); if (File.Exists(failpath)) { File.Delete(failpath); } File.Move(path, failpath); this.AsyncSetLog(this.tbx_Log, $"上传简历失败!响应信息:{JsonConvert.SerializeObject(response)}"); return; } else { if (tag == "C") { Interlocked.Increment(ref insertCount); } if (tag == "U") { Interlocked.Increment(ref updateCount); } this.AsyncSetLog(this.tbx_Log, $"上传简历成功!已上传:{Interlocked.Increment(ref successCount)} C=>{insertCount} U=>{updateCount} 还剩余:{pathQueue.Count} 份待上传!"); } } catch (Exception ex) { pathQueue.Enqueue(path); this.AsyncSetLog(this.tbx_Log, $"{DateTime.Now} 上传简历到数据库异常,异常消息:{ex.Message}"); return; } finally { HttpAPI.FinishUploadResume(JsonConvert.SerializeObject(account)); } #endregion #region 简历到 OSS var id = response.Reference.ResumeId.ToString(); if (tag == "C" || tag == "U") { using (var stream = new MemoryStream(GZip.Compress(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(resume))))) { try { newOss.PutObject(newBucket, $"{ConfigurationManager.AppSettings["Oss.New.ResumePath"]}{id}", stream); } catch (Exception ex) { this.AsyncSetLog(this.tbx_Log, "上传 OSS 失败!异常信息:" + ex.Message); retryResumeQueue.Enqueue(new Tuple <string, Resume, string>(id, resume, path)); return; } } } var uploadSuccessPath = ConfigurationManager.AppSettings["Zhaopin_UploadSuccessFiles_Path"] + companyName; if (!Directory.Exists(uploadSuccessPath)) { Directory.CreateDirectory(uploadSuccessPath); } uploadSuccessPath += Path.GetFileName(path); if (File.Exists(uploadSuccessPath)) { File.Delete(uploadSuccessPath); } File.Move(path, uploadSuccessPath); #endregion }
internal static void Create(Models.FileTransportInfo fileTransferInfo) { GZip.Compress(System.IO.File.OpenRead(fileTransferInfo.SourceFullNameWithBasePath), System.IO.File.Create(fileTransferInfo.DestinationFullName), true); }
private static async Task LogHttpResponseData(BotData data, HttpResponse response, HttpRequest request, RuriLib.Functions.Http.Options.HttpRequestOptions requestOptions) { // Try to read the raw source for Content-Length calculation try { data.RAWSOURCE = await response.Content.ReadAsByteArrayAsync(data.CancellationToken); } catch (NullReferenceException) { // Thrown when there is no content (204) or we decided to not read it data.RAWSOURCE = Array.Empty <byte>(); } // Address var uri = response.Request.Uri; if (!uri.IsAbsoluteUri) { uri = new Uri(request.Uri, uri); } data.ADDRESS = response.Request.Uri.AbsoluteUri; data.Logger.Log($"Address: {data.ADDRESS}", LogColors.DodgerBlue); // Response code data.RESPONSECODE = (int)response.StatusCode; data.Logger.Log($"Response code: {data.RESPONSECODE}", LogColors.Citrine); // Headers data.HEADERS = response.Headers; if (response.Content != null) { foreach (var header in response.Content.Headers) { data.HEADERS[header.Key] = header.Value.First(); } } if (!data.HEADERS.ContainsKey("Content-Length")) { data.HEADERS["Content-Length"] = data.RAWSOURCE.Length.ToString(); } data.Logger.Log("Received Headers:", LogColors.MediumPurple); data.Logger.Log(data.HEADERS.Select(h => $"{h.Key}: {h.Value}"), LogColors.Violet); // Cookies data.Logger.Log("Received Cookies:", LogColors.MikadoYellow); data.Logger.Log(data.COOKIES.Select(h => $"{h.Key}: {h.Value}"), LogColors.Khaki); // Unzip the GZipped content if still gzipped (after Content-Length calculation) if (data.RAWSOURCE.Length > 1 && data.RAWSOURCE[0] == 0x1F && data.RAWSOURCE[1] == 0x8B) { try { data.RAWSOURCE = GZip.Unzip(data.RAWSOURCE); } catch { data.Logger.Log("Tried to unzip but failed", LogColors.DarkOrange); } } // Source if (!string.IsNullOrWhiteSpace(requestOptions.CodePagesEncoding)) { data.SOURCE = CodePagesEncodingProvider.Instance .GetEncoding(requestOptions.CodePagesEncoding).GetString(data.RAWSOURCE); } else { data.SOURCE = Encoding.UTF8.GetString(data.RAWSOURCE); } data.Logger.Log("Received Payload:", LogColors.ForestGreen); data.Logger.Log(data.SOURCE, LogColors.GreenYellow, true); }
public bool ActualizarAplicacion() { bool actualizacionCorrecta = true; try { string misDocumentos = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); string dirApp = Path.Combine(Path.Combine(misDocumentos, "AppsCNDC"), _nombreModulo); string nombreLog = string.Format("logActualizacion_{0}.txt", System.DateTime.Now.ToString("ddMMyy_HHmm")); pathLog = Path.Combine(dirApp, nombreLog); System.IO.StreamWriter log = new StreamWriter(pathLog, true); log.AutoFlush = true; _pgbActualizacion.Maximum = _archivosParaActualizar.Count; _pgbActualizacion.Update(); Application.DoEvents(); ConexionBD conexion = new ConexionBD("USER ID=quantum;DATA SOURCE=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SID=xe)));PASSWORD=quantum;PERSIST SECURITY INFO=true;"); foreach (string archi in _archivosParaActualizar) { byte[] datos = _servActualizacion.GetArchivo(_nombreModulo, archi); datos = GZip.DesComprimir(datos); string pathBack = Path.Combine(dirApp, "BKFiles"); if (!Directory.Exists(pathBack)) { Directory.CreateDirectory(pathBack); } string destino = Path.Combine(dirApp, archi); string backup = destino + ".back"; if (File.Exists(destino)) { if (File.Exists(backup)) { File.Delete(backup); } File.Copy(destino, backup); } try { File.WriteAllBytes(destino, datos); } catch (Exception ex) { log.WriteLine(archi); log.WriteLine(string.Format("{0} - {1}", System.DateTime.Now.ToString("dd/MM/yyyy"), ex.ToString())); tbError.Text += ex.ToString(); actualizacionCorrecta = false; } _pgbActualizacion.Value++; _pgbActualizacion.Update(); if (archi.EndsWith(".sql")) { string sql = GetTexto(destino); string elog = conexion.EjecutarSql(sql); log.WriteLine(archi); log.WriteLine(string.Format("{0} - {1} {2} {3} {4} {5} {6} ", archi, System.DateTime.Now.ToString("dd/MM/yyyy"), Environment.NewLine, sql, Environment.NewLine, elog, Environment.NewLine, "-----------------------------------------")); tbError.Text += elog; actualizacionCorrecta = false; tbError.Visible = false; } Application.DoEvents(); } _pgbActualizacion.Value = _pgbActualizacion.Maximum; _pgbActualizacion.Update(); Application.DoEvents(); ActualizarVersion(); _pgbActualizacion.Value = _pgbActualizacion.Maximum; _pgbActualizacion.Update(); log.Flush(); log.Close(); if (actualizacionCorrecta) { string archivoNotas = Path.Combine(dirApp, "notasActualizacion.txt"); if (File.Exists(archivoNotas)) { FormNotas fNotas = new FormNotas(); fNotas.VisualizarNotas(archivoNotas); } } else { FrmEnvioCorreo frm = new FrmEnvioCorreo(); frm.EnviarEmail(tbError.Text, pathLog); frm.ShowDialog(); this.Close(); } } catch (Exception ex) { MessageBox.Show("Error al actualizar los archivos." + Environment.NewLine + ex.ToString()); } return(actualizacionCorrecta); }
/// <summary> /// 处理简历 /// </summary> /// <param name="item"></param> /// <param name="cellphone"></param> /// <param name="email"></param> /// <param name="cleaningProcedure"></param> /// <param name="businessId"></param> private static void HandleResume(Match item, string cellphone, string email, ZhaopinCleaningProcedure cleaningProcedure, int businessId) { var number = item.Result("$1").Substring(0, 10); DateTime updateDateTime; if (!DateTime.TryParse(item.Result("$4"), out updateDateTime)) { return; } using (var db = new MangningXssDBEntities()) { var resume = db.ZhaopinResume.FirstOrDefault(f => f.RandomNumber == number); if (resume != null) { if (resume.Flag == 15) { #region 刷新简历更新时间 //if (resume.RefreshTime != null && updateDateTime.Date == resume.RefreshTime.Value.Date) continue; resume.RefreshTime = updateDateTime; resume.Flag = 14; var filePath = $@"D:\Badoucai\Resume\LocationJson\{resume.Id}.json"; using (var stream = new MemoryStream()) { if (!mangningOssClient.DoesObjectExist(mangningBucketName, $"Zhaopin/Resume/{resume.Id}")) { return; } var bytes = new byte[1024]; int len; var streamContent = mangningOssClient.GetObject(mangningBucketName, $"Zhaopin/Resume/{resume.Id}").Content; while ((len = streamContent.Read(bytes, 0, bytes.Length)) > 0) { stream.Write(bytes, 0, len); } var resumeContent = Encoding.UTF8.GetString(GZip.Decompress(stream.ToArray())); var jsonObj = JsonConvert.DeserializeObject <dynamic>(resumeContent); dynamic detialJSonStr; try { detialJSonStr = jsonObj.detialJSonStr; if (!string.IsNullOrEmpty((string)jsonObj.detialJSonStr.DateModified)) { jsonObj.detialJSonStr = JsonConvert.SerializeObject(jsonObj.detialJSonStr); } } catch (Exception) { detialJSonStr = JsonConvert.DeserializeObject <dynamic>((string)jsonObj.detialJSonStr); } detialJSonStr.DateLastReleased = updateDateTime; detialJSonStr.DateModified = updateDateTime; jsonObj.detialJSonStr = detialJSonStr; var newResumeContent = JsonConvert.SerializeObject(jsonObj); using (var jsonStream = new MemoryStream(GZip.Compress(Encoding.UTF8.GetBytes(newResumeContent)))) { mangningOssClient.PutObject(mangningBucketName, $"Zhaopin/Resume/{resume.Id}", jsonStream); } File.WriteAllText(filePath, newResumeContent); } #endregion } if (resume.Flag == 2) { var user = db.ZhaopinUser.FirstOrDefault(f => f.Id == resume.UserId); if (user == null) { return; } if (!WatchResumeDetail(item, cookieContainer, user.Cellphone, user.Email, businessId)) { var procedure = db.ZhaopinCleaningProcedure.FirstOrDefault(f => f.Id == cleaningProcedure.Id); if (procedure != null) { procedure.Cookie = null; db.SaveChanges(); } businessIdQueue.Enqueue(businessId); } } } else { var incompleteResume = db.ZhaopinIncompleteResume.FirstOrDefault(f => f.ResumeNumber == number); if (incompleteResume != null) { incompleteResume.CompletionTime = DateTime.Now; } WatchResumeDetail(item, cookieContainer, cellphone, email, businessId); } db.SaveChanges(); } }
/// <summary> /// Uncompresses a file using gzip. /// </summary> /// <param name="file">The file to uncompress</param> /// <returns>The stream of uncompressed data.</returns> public static async Task <Stream> UnzipAsStreamAsync(this FileInfo file) { using (var stream = file.OpenRead()) return(await GZip.UnzipAsync(stream)); }
/// <summary> /// Compresses data using gzip /// </summary> /// <param name="data">The data to compress</param> /// <returns>The compressed stream.</returns> public static async Task <Stream> ZipAsStreamAsync(this byte[] data) { using (var stream = new MemoryStream(data)) return(await GZip.ZipAsync(stream)); }
/// <summary> /// 上传简历 /// </summary> private static void UploadResume() { var serializer = new Serialization.Template.Zhaopin.Json.v1.Serializer(); var stopwatch = new Stopwatch(); while (true) { string path; if (!uploadQueue.TryDequeue(out path)) { Thread.Sleep(100); continue; } Interlocked.Increment(ref totalUpload); try { stopwatch.Restart(); var resumeId = Convert.ToInt32(Path.GetFileNameWithoutExtension(path)); var content = File.ReadAllText(path); var jsonObj = JsonConvert.DeserializeObject <dynamic>(content); dynamic formatterResume; try { if (jsonObj.Flag != null && jsonObj.Flag < 0) { formatterResume = Format.Convert_V0(Format.ConvertTo_Dtl_V5(content)); } else { var serializationResume = serializer.Deserialize(content); formatterResume = Formatter.Template.Zhaopin.Json.v1.Formatter.Format(serializationResume); } } catch (Exception ex) { var filePath = $"{ConfigurationManager.AppSettings["File.FailPath"]}{Path.GetFileName(path)}"; if (File.Exists(filePath)) { File.Delete(filePath); } File.Move(path, filePath); Trace.TraceError(ex.ToString()); using (var db = new MangningXssDBEntities()) { var resume = db.ZhaopinResume.FirstOrDefault(f => f.Id == resumeId); if (resume != null) { resume.Flag = 0xA; } db.SaveChanges(); } continue; } string tag; while (true) { var data = JsonConvert.SerializeObject(new { formatterResume.Reference.Id, formatterResume.Reference.Source }); var response = PrepareUploadResume(data); if (response.Code.ToString() != "0") { FinishUploadResume(data); Trace.WriteLine($"{DateTime.Now} > PrepareUploadResume failed ! Data = {data}, Response = {JsonConvert.SerializeObject(response)}"); continue; } var badoucaiResumeJson = JsonConvert.SerializeObject(formatterResume); response = UploadResume(badoucaiResumeJson); var returnCode = (string)response.Code; using (var db = new MangningXssDBEntities()) { tag = response.Reference?.Tag.ToString(); db.ZhaopinResumeUploadLog.Add(new ZhaopinResumeUploadLog { ResumeId = resumeId, ReturnCode = returnCode, Tag = tag, UploadTime = DateTime.Now }); FinishUploadResume(data); var resume = db.ZhaopinResume.FirstOrDefault(f => f.Id == resumeId); if (resume != null) { resume.Flag = 0xF; } if (jsonObj.Flag != null && jsonObj.Flag < 0) { resume.Flag = 0xB; } if (returnCode != "0") { Trace.WriteLine($"{DateTime.Now} > UploadResume failed !ResumeId = {resumeId}, Response = {JsonConvert.SerializeObject(response)}."); tag = "NULL"; db.SaveChanges(); var filePath = $"{ConfigurationManager.AppSettings["File.UploadFailPath"]}{Path.GetFileName(path)}"; if (File.Exists(filePath)) { File.Delete(filePath); } File.Move(path, filePath); break; } if (tag == "C" || tag == "U" || tag == "N") { using (var stream = new MemoryStream(GZip.Compress(Encoding.UTF8.GetBytes(badoucaiResumeJson)))) { var id = response.Reference.ResumeId.ToString(); badoucaiOssClient.PutObject(badoucaiBucketName, $"Badoucai/{id}", stream); } ProgramTasksThread.HandleResume(content, resumeId); // 更新 Resume 表的信息 } File.Delete(path); db.SaveChanges(); Interlocked.Increment(ref successUpload); } break; } stopwatch.Stop(); Console.WriteLine($"{DateTime.Now} > ResumeId = {resumeId}, Tag = {tag}, {successUpload}/{totalUpload} = {Math.Round(successUpload / (double)totalUpload, 3) * 100}%, Elapsed = {stopwatch.ElapsedMilliseconds} ms."); } catch (Exception ex) { Trace.TraceError(ex.ToString()); } } }
/// <summary> /// Compresses a string using gzip /// </summary> /// <param name="value">The string to compress.</param> /// <param name="encoding">The encoding of the string.</param> /// <returns>The compressed stream.</returns> public static Stream ZipAsStream(this string value, Encoding encoding) { using (var source = new MemoryStream(encoding.GetBytes(value))) return(GZip.Zip(source)); }
/// <summary> /// 导入外部Josn /// </summary> private static void ImportResume() { var importCount = 0; while (true) { try { var filePaths = Directory.GetFiles(importFilePath); if (filePaths.Length == 0) { Thread.Sleep(10 * 1000); continue; } Console.WriteLine($"{DateTime.Now} > {filePaths.Length} Need Import ! "); foreach (var filePath in filePaths) { try { var jsonObj = JsonConvert.DeserializeObject <dynamic>(File.ReadAllText(filePath)); var resumeData = jsonObj.data == null ? jsonObj : jsonObj.data; var resumeDetail = JsonConvert.DeserializeObject(resumeData.detialJSonStr.ToString()); var resumeId = resumeData.resumeId != null ? (int)resumeData.resumeId : resumeDetail.ResumeId != null ? (int)resumeDetail.ResumeId : 0; var cellphone = resumeData.userDetials.mobilePhone.ToString(); if (string.IsNullOrEmpty(cellphone)) { var path = importFailPath + Path.GetFileName(filePath); if (File.Exists(path)) { File.Delete(path); } File.Move(filePath, path); continue; } var resumeNumber = ((string)resumeData.resumeNo).Substring(0, 10); var userId = (int)resumeData.userDetials.userMasterId; var refreshTime = BaseFanctory.GetTime((string)resumeDetail.DateLastReleased).ToUniversalTime(); using (var db = new MangningXssDBEntities()) { var resume = db.ZhaopinResume.FirstOrDefault(f => f.Id == resumeId); var isNeedUpload = true; var sourceFlag = -1; var isUpload = false; if (resume != null) { sourceFlag = resume.Flag; } if (!(resume?.RefreshTime != null && resume.RefreshTime.Value.Date >= refreshTime.Date) || resume?.Flag < 8) { if (resume != null) { resume.RandomNumber = resumeNumber; resume.RefreshTime = refreshTime; resume.UpdateTime = DateTime.UtcNow; if (string.IsNullOrEmpty(resume.UserExtId)) { resume.UserExtId = resumeDetail.UserMasterExtId?.ToString(); } if (resumeData.Flag != null && (int)resumeData.Flag < 0) { if (resume.Flag >= 8 || mangningOssClient.DoesObjectExist(mangningBucketName, $"Zhaopin/Resume/{resume.Id}") || mangningOssClient.DoesObjectExist(mangningBucketName, $"WatchResume/{resume.Id}")) { isNeedUpload = false; } } resume.Flag = 0xE; } else { resume = new ZhaopinResume { Id = resumeId, RandomNumber = resumeNumber, UserId = userId, RefreshTime = refreshTime, UpdateTime = DateTime.UtcNow, UserExtId = resumeDetail.UserMasterExtId.ToString(), DeliveryNumber = null, Source = "Import", Flag = 0xE }; db.ZhaopinResume.Add(resume); } var user = db.ZhaopinUser.FirstOrDefault(f => f.Id == userId); if (user != null) { if (!user.Source.Contains("MANUAL")) { user.ModifyTime = BaseFanctory.GetTime((string)resumeDetail.DateModified).ToUniversalTime(); user.CreateTime = resumeData.Flag != null && (int)resumeData.Flag < 0 ? user.CreateTime : BaseFanctory.GetTime((string)resumeDetail.DateCreated).ToUniversalTime(); user.Cellphone = resumeData.userDetials.mobilePhone.ToString(); user.Email = resumeData.userDetials.email.ToString(); user.Name = resumeData.userDetials.userName.ToString(); user.UpdateTime = DateTime.UtcNow; user.Username = resumeData.userDetials.email.ToString(); } } else { user = new ZhaopinUser { Id = userId, Source = "Import", ModifyTime = BaseFanctory.GetTime((string)resumeDetail.DateModified).ToUniversalTime(), CreateTime = BaseFanctory.GetTime((string)resumeDetail.DateCreated).ToUniversalTime(), Cellphone = resumeData.userDetials.mobilePhone.ToString(), Email = resumeData.userDetials.email.ToString(), Name = resumeData.userDetials.userName.ToString(), UpdateTime = DateTime.UtcNow, Username = resumeData.userDetials.email.ToString() }; db.ZhaopinUser.Add(user); } if (isNeedUpload) { isUpload = true; var resumeContent = JsonConvert.SerializeObject(resumeData); using (var jsonStream = new MemoryStream(GZip.Compress(Encoding.UTF8.GetBytes(resumeContent)))) { mangningOssClient.PutObject(mangningBucketName, $"Zhaopin/Resume/{resume.Id}", jsonStream); } } db.SaveChanges(); } File.Delete(filePath); Console.WriteLine($"{DateTime.Now} > Improt success ! ResumeId = {resumeId}, SourceFlag = {sourceFlag}, IsUpload = {isUpload}, Count = {++importCount}."); } } catch (Exception ex) { var path = importFailPath + Path.GetFileName(filePath); if (File.Exists(path)) { File.Delete(path); } File.Move(filePath, path); Trace.WriteLine($"{DateTime.Now} > Import Error Message = {ex.Message}, Path = {path}."); } } } catch (Exception ex) { Trace.TraceError(ex.ToString()); } } }
/// <summary> /// Uncompresses a stream using gzip /// </summary> /// <param name="stream">The stream to uncompress</param> /// <returns>The uncompressed stream.</returns> public static Stream UnzipAsStream(this Stream stream) { stream.Seek(0, SeekOrigin.Begin); return(GZip.Unzip(stream)); }
private static void ScanADir(string directory) { _bgw.ReportProgress(0, new bgwText("Scanning Dir : " + directory)); DirectoryInfo di = new DirectoryInfo(directory); FileInfo[] fi = di.GetFiles(); _bgw.ReportProgress(0, new bgwRange2Visible(true)); _bgw.ReportProgress(0, new bgwSetRange2(fi.Count())); for (int j = 0; j < fi.Count(); j++) { if (_bgw.CancellationPending) { return; } FileInfo f = fi[j]; _bgw.ReportProgress(0, new bgwValue2(j)); _bgw.ReportProgress(0, new bgwText2(f.Name)); string ext = Path.GetExtension(f.Name); if (ext.ToLower() == ".zip") { ZipFile fz = new ZipFile(); ZipReturn zr = fz.ZipFileOpen(f.FullName, f.LastWriteTime, true); if (zr != ZipReturn.ZipGood) { continue; } fz.DeepScan(); int FileUsedCount = 0; for (int i = 0; i < fz.LocalFilesCount(); i++) { Debug.WriteLine(fz.Filename(i)); RvFile tFile = new RvFile(); tFile.Size = fz.UncompressedSize(i); tFile.CRC = fz.CRC32(i); tFile.MD5 = fz.MD5(i); tFile.SHA1 = fz.SHA1(i); Debug.WriteLine("CRC " + VarFix.ToString(tFile.CRC)); Debug.WriteLine("MD5 " + VarFix.ToString(tFile.MD5)); Debug.WriteLine("SHA1 " + VarFix.ToString(tFile.SHA1)); FindStatus res = fileneededTest(tFile); if (res == FindStatus.FileUnknown) { continue; } FileUsedCount++; if (res != FindStatus.FoundFileInArchive) { GZip gz = new GZip(); gz.crc = tFile.CRC; gz.md5Hash = tFile.MD5; gz.sha1Hash = tFile.SHA1; gz.uncompressedSize = tFile.Size; bool isZipTrrntzip = (fz.ZipStatus == ZipStatus.TrrntZip); ulong compressedSize; ushort method; Stream zds; fz.ZipFileOpenReadStream(i, isZipTrrntzip, out zds, out compressedSize, out method); gz.compressedSize = compressedSize; string outfile = Getfilename(tFile.SHA1); gz.WriteGZip(outfile, zds, isZipTrrntzip); tFile.CompressedSize = gz.compressedSize; fz.ZipFileCloseReadStream(); tFile.DBWrite(); } } fz.ZipFileClose(); if (delFiles && FileUsedCount == fz.LocalFilesCount()) { File.SetAttributes(f.FullName, FileAttributes.Normal); File.Delete(f.FullName); } } else if (ext.ToLower() == ".gz") { GZip gZipTest = new GZip(); ZipReturn errorcode = gZipTest.ReadGZip(f.FullName, true); if (errorcode != ZipReturn.ZipGood) { continue; } RvFile tFile = new RvFile(); tFile.CRC = gZipTest.crc; tFile.MD5 = gZipTest.md5Hash; tFile.SHA1 = gZipTest.sha1Hash; tFile.Size = gZipTest.uncompressedSize; FindStatus res = fileneededTest(tFile); if (res == FindStatus.FileUnknown) { continue; } if (res != FindStatus.FoundFileInArchive) { GZip gz = new GZip(); gz.crc = tFile.CRC; gz.md5Hash = tFile.MD5; gz.sha1Hash = tFile.SHA1; gz.uncompressedSize = tFile.Size; Stream ds; gZipTest.GetStream(out ds); string outfile = Getfilename(tFile.SHA1); gz.WriteGZip(outfile, ds, false); ds.Close(); ds.Dispose(); gZipTest.Close(); tFile.CompressedSize = gz.compressedSize; tFile.DBWrite(); } if (delFiles) { File.SetAttributes(f.FullName, FileAttributes.Normal); File.Delete(f.FullName); } } else { RvFile tFile = new RvFile(); int errorcode = UnCompFiles.CheckSumRead(f.FullName, true, out tFile.CRC, out tFile.MD5, out tFile.SHA1, out tFile.Size); if (errorcode != 0) { continue; } // test if needed. FindStatus res = fileneededTest(tFile); if (res == FindStatus.FileUnknown) { continue; } if (res != FindStatus.FoundFileInArchive) { GZip gz = new GZip(); gz.crc = tFile.CRC; gz.md5Hash = tFile.MD5; gz.sha1Hash = tFile.SHA1; gz.uncompressedSize = tFile.Size; Stream ds; int errorCode = IO.FileStream.OpenFileRead(f.FullName, out ds); string outfile = Getfilename(tFile.SHA1); gz.WriteGZip(outfile, ds, false); ds.Close(); ds.Dispose(); tFile.CompressedSize = gz.compressedSize; tFile.DBWrite(); } if (delFiles) { File.SetAttributes(f.FullName, FileAttributes.Normal); File.Delete(f.FullName); } } } DirectoryInfo[] childdi = di.GetDirectories(); foreach (DirectoryInfo d in childdi) { if (_bgw.CancellationPending) { return; } ScanADir(d.FullName); } if (directory != rootDir && IsDirectoryEmpty(directory)) { Directory.Delete(directory); } }
/// <summary> /// Uncompresses a stream using gzip /// </summary> /// <param name="stream">The stream to uncompress</param> /// <returns>The uncompressed stream.</returns> public static async Task <Stream> UnzipAsStreamAsync(this Stream stream) { stream.Seek(0, SeekOrigin.Begin); return(await GZip.UnzipAsync(stream)); }
private static void ScanRomRoot(string directory) { _bgw.ReportProgress(0, new bgwText("Scanning Dir : " + directory)); DirectoryInfo di = new DirectoryInfo(directory); FileInfo[] fi = di.GetFiles(); _bgw.ReportProgress(0, new bgwRange2Visible(true)); _bgw.ReportProgress(0, new bgwSetRange2(fi.Count())); for (int j = 0; j < fi.Count(); j++) { if (_bgw.CancellationPending) { return; } FileInfo f = fi[j]; _bgw.ReportProgress(0, new bgwValue2(j)); _bgw.ReportProgress(0, new bgwText2(f.Name)); string ext = Path.GetExtension(f.Name); if (ext.ToLower() == ".gz") { GZip gZipTest = new GZip(); ZipReturn errorcode = gZipTest.ReadGZip(f.FullName, false); gZipTest.sha1Hash = VarFix.CleanMD5SHA1(Path.GetFileNameWithoutExtension(f.Name), 40); gZipTest.Close(); if (errorcode != ZipReturn.ZipGood) { _bgw.ReportProgress(0, new bgwShowError(f.FullName, "gz File corrupt")); if (!Directory.Exists("corrupt")) { Directory.CreateDirectory("corrupt"); } File.Move(f.FullName, Path.Combine("corrupt", f.Name)); continue; } RvFile tFile = new RvFile(); tFile.CRC = gZipTest.crc; tFile.MD5 = gZipTest.md5Hash; tFile.SHA1 = gZipTest.sha1Hash; tFile.Size = gZipTest.uncompressedSize; tFile.AltType = (HeaderFileType)gZipTest.altType; tFile.AltCRC = gZipTest.altcrc; tFile.AltMD5 = gZipTest.altmd5Hash; tFile.AltSHA1 = gZipTest.altsha1Hash; tFile.AltSize = gZipTest.uncompressedAltSize; tFile.CompressedSize = gZipTest.compressedSize; FindStatus res = fileneededTest(tFile); if (res != FindStatus.FoundFileInArchive) { if (deep) { gZipTest = new GZip(); try { errorcode = gZipTest.ReadGZip(f.FullName, true); gZipTest.sha1Hash = VarFix.CleanMD5SHA1(Path.GetFileNameWithoutExtension(f.Name), 40); gZipTest.Close(); } catch (Exception e) { gZipTest.Close(); _bgw.ReportProgress(0, new bgwShowError(f.FullName, "gz Crashed Compression")); if (!Directory.Exists("corrupt")) { Directory.CreateDirectory("corrupt"); } File.Move(f.FullName, Path.Combine("corrupt", f.Name)); continue; } if (errorcode != ZipReturn.ZipGood) { _bgw.ReportProgress(0, new bgwShowError(f.FullName, "gz File corrupt")); if (!Directory.Exists("corrupt")) { Directory.CreateDirectory("corrupt"); } File.Move(f.FullName, Path.Combine("corrupt", f.Name)); continue; } } tFile.DBWrite(); } } if (_bgw.CancellationPending) { return; } } DirectoryInfo[] childdi = di.GetDirectories(); foreach (DirectoryInfo d in childdi) { if (_bgw.CancellationPending) { return; } ScanRomRoot(d.FullName); } }
/// <summary> /// Uncompresses a stream using gzip. /// </summary> /// <param name="stream">The stream to uncompress</param> /// <param name="encoding">The encoding of the string.</param> /// <returns>The uncompresses string.</returns> public static string UnzipAsString(this Stream stream, Encoding encoding) { using (var output = GZip.Unzip(stream)) return(encoding.GetString(output.ToArray())); }
private void DemoLogin() { string filename = string.Empty; string appVersion = "1.1.1"; string dbfileName = string.Empty; HttpCookie cookie = new HttpCookie("Company"); cookie.HttpOnly = true; cookie.Secure = true; cookie.Value = "DEMO"; Response.Cookies.Add(cookie); string localpath = ConfigurationManager.AppSettings["LocalPath"].ToString(); string connStr = System.Configuration.ConfigurationManager.ConnectionStrings[Request.Cookies["Company"].Value].ConnectionString; dbfileName = connStr.Remove(0, connStr.LastIndexOf(@"App_Data\") + 9); dbfileName = dbfileName.Remove(dbfileName.LastIndexOf(";Persist Security Info")); filename = Server.MapPath(localpath + dbfileName); if (File.Exists(filename + ".zip")) { GZip objZip = new GZip(filename + ".zip", filename, Action.UnZip); File.Delete(filename + ".zip"); } bool isAuthenticated = IsAuthenticated("admin", "admin123"); if (isAuthenticated == true) { string[] roles = GetRoles("admin"); string roleData = string.Join("|", roles); FormsAuthentication.SignOut(); HttpCookie authCookie = FormsAuthentication.GetAuthCookie("admin", true); FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value); FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, roleData); string encryptedTicket = FormsAuthentication.Encrypt(authTicket); authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); Response.Cookies.Add(authCookie); LoadAppSettings(); //FormsAuthentication.RedirectFromLoginPage(txtLogin.Text, false); if (Session["AppSettings"] != null) { DataSet ds = (DataSet)Session["AppSettings"]; for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { if (ds.Tables[0].Rows[i]["KEY"].ToString() == "CURRENCY") { Session["CurrencyType"] = ds.Tables[0].Rows[i]["KEYVALUE"].ToString(); } if (ds.Tables[0].Rows[i]["KEY"].ToString() == "VERSION") { if (ds.Tables[0].Rows[i]["KEYVALUE"].ToString() != appVersion) { ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Application and Database Version should be same. Please Contact Administrator.');", true); } } } } if ((Helper.GetDecryptedKey("InstallationType") == "ONLINE-OFFLINE-SERVER") || (Helper.GetDecryptedKey("InstallationType") == "SERVER")) { if (!IsValidIPRequest()) { ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('You are not a Valid User, Only Ristricted Users are allowed to Login. Please Contact Administrator.');", true); return; } } IsSMSRequired(); //FormsAuthentication.RedirectFromLoginPage(txtLogin.Text, false); Response.Redirect(FormsAuthentication.DefaultUrl, true); } else { ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Invalid Login. Please check the username and password');", true); return; } }
/// <summary> /// Uncompresses a stream using gzip. /// </summary> /// <param name="stream">The stream to uncompress</param> /// <param name="encoding">The encoding of the string.</param> /// <returns>The uncompresses string.</returns> public static async Task <string> UnzipAsStringAsync(this Stream stream, Encoding encoding) { using (var output = await GZip.UnzipAsync(stream)) return(encoding.GetString(output.ToArray())); }
public void UnZipNullFile() { ICompressor compressor = new GZip(); _decompressedFile = compressor.Decompress(null, new DirectoryInfo(Path.Combine("IntegrationTests", "Compression", "Data"))).FirstOrDefault(); }
/// <summary> /// Uncompresses a file using gzip. /// </summary> /// <param name="file">The file to uncompress</param> /// <returns>The stream of uncompressed data.</returns> public static Stream UnzipAsStream(this FileInfo file) { using (var stream = file.OpenRead()) return(GZip.Unzip(stream)); }
public void Do(ConnectClient client) { Client = client; Loger.Log("Server ReceiveBytes1"); ///установка условно защищенного соединения //Строго первый пакет: Передаем серверу КОткр var rc = Client.ReceiveBytes(); var crypto = new CryptoProvider(); if (SessionClient.UseCryptoKeys) { crypto.OpenKey = Encoding.UTF8.GetString(rc); } //Строго первый ответ: Передаем клиенту КОткр(Сессия) SetKey(); Loger.Log("Server SendMessage1"); if (SessionClient.UseCryptoKeys) { Client.SendMessage(crypto.Encrypt(Key)); } else { Client.SendMessage(Key); } var context = new ServiceContext(); Worker = new Service(context); ///рабочий цикл while (true) { var rec = Client.ReceiveBytes(); if (context.Player != null) { lock (context.Player) { context.Player.Public.LastOnlineTime = DateTime.UtcNow; } } //отдельно обрабатываем пинг if (rec.Length == 1) { if (rec[0] == 0x00) { Client.SendMessage(new byte[1] { 0x00 }); } //отдельно обрабатываем запрос на обновление (ответ 0 - нет ничего, 1 - что-то есть) else if (rec[0] == 0x01) { var exists = ServiceCheck(); Client.SendMessage(new byte[1] { exists ? (byte)0x01 : (byte)0x00 }); } continue; } var time1 = DateTime.UtcNow; var rec2 = CryptoProvider.SymmetricDecrypt(rec, Key); var recObj = (ModelContainer)GZip.UnzipObjByte(rec2); //Deserialize if (rec.Length > 1024 * 512) { Loger.Log($"Server Network fromC {rec.Length} unzip {GZip.LastSizeObj} "); } var time2 = DateTime.UtcNow; ModelContainer sendObj; try { sendObj = Worker.GetPackage(recObj); } catch (Exception ext) { Loger.Log("Exception GetPackage: " + ext.ToString()); sendObj = new ModelContainer() { TypePacket = 0 }; } var time3 = DateTime.UtcNow; var ob = GZip.ZipObjByte(sendObj); //Serialize var send = CryptoProvider.SymmetricEncrypt(ob, Key); if (send.Length > 1024 * 512) { Loger.Log($"Server Network toC {send.Length} unzip {GZip.LastSizeObj} "); } var time4 = DateTime.UtcNow; Client.SendMessage(send); var time5 = DateTime.UtcNow; if ((time5 - time1).TotalMilliseconds > 900) { Loger.Log($"Server Network timeDeserialize {(time2 - time1).TotalMilliseconds}" + $" timeWorker {(time3 - time2).TotalMilliseconds}" + $" timeSerialize {(time4 - time3).TotalMilliseconds}" + $" timeSend {(time5 - time4).TotalMilliseconds}"); } if (context.Player != null) { lock (context.Player) { context.Player.Public.LastOnlineTime = DateTime.UtcNow; if (context.Player.ExitReason != OCUnion.Transfer.DisconnectReason.AllGood) { //context.Player.ExitReason = OCUnion.Transfer.DisconnectReason.AllGood; Loger.Log("Disconnect . . ." + context.Player.ExitReason.ToString()); break; } } } } }
public bool Subir(string token, byte[] dataSet, string modulo) { bool resultado = true; modulo = modulo.ToUpper(); if (modulo == "SISFALLA") { PistaMgr.Instance.Debug("WcfServicioSISFALLA.Subir()", "Iniciando..." + GetIPCliente()); AsegurarConexion(token); AsegurarMgrsLocal(); try { dataSet = GZip.DesComprimir(dataSet); DataSet ds = Serializador.DeSerializar <DataSet>(dataSet); foreach (var mgr in _managersLocal) { if (ds.Tables.Contains(mgr.NombreTabla)) { DataTable tabla = ds.Tables[mgr.NombreTabla]; PistaMgr.Instance.Debug("WcfServicioSISFALLA.Subir()", "mgr=" + mgr.NombreTabla + " Cant. Reg.:" + tabla.Rows.Count); List <DataRow> rowsNuevos = new List <DataRow>(); List <DataRow> rowsAntiguos = new List <DataRow>(); foreach (DataRow row in tabla.Rows) { bool esNuevo = !mgr.Existe(mgr.NombreTabla, row); if (esNuevo) { rowsNuevos.Add(row); } else { rowsAntiguos.Add(row); } } if (rowsNuevos.Count > 0) { PistaMgr.Instance.Debug("WcfServicioSISFALLA.Subir()", mgr.NombreTabla + " nuevos: " + rowsNuevos.Count); mgr.Insertar(rowsNuevos); } if (rowsAntiguos.Count > 0) { PistaMgr.Instance.Debug("WcfServicioSISFALLA.Subir()", mgr.NombreTabla + " antiguos: " + rowsAntiguos.Count); mgr.Actualizar(rowsAntiguos); } } else { PistaMgr.Instance.Debug("WcfServicioSISFALLA.Subir()", "DataSet NO contiene tabla" + mgr.NombreTabla); } } DataTable tablaInforme = ds.Tables[InformeFalla.NOMBRE_TABLA]; InformeFalla informe = new InformeFalla(tablaInforme.Rows[0]); DOMINIOS_OPERACION tipoOperacion = DOMINIOS_OPERACION.AGENTE_ENVIA_PRELIMINAR; if (informe.PkDCodTipoinforme == (long)PK_D_COD_TIPOINFORME.PRELIMINAR) { tipoOperacion = DOMINIOS_OPERACION.AGENTE_ENVIA_PRELIMINAR; } else if (informe.PkDCodTipoinforme == (long)PK_D_COD_TIPOINFORME.FINAL) { tipoOperacion = DOMINIOS_OPERACION.AGENTE_ENVIA_FINAL; } Operacion opn = new Operacion(); opn.RegistrarOperacion(tipoOperacion, informe.PkCodFalla, informe.PkOrigenInforme); } catch (Exception ex) { PistaMgr.Instance.Error("WcfServicioSISFALLA.Subir()", ex); } PistaMgr.Instance.Debug("WcfServicioSISFALLA.Subir()", "Finalizando..."); } return(resultado); }