public void Test_Image_ByteArray() { using (Image img = Image.FromFile(Files.Coders.PageTIF)) { byte[] bytes = null; using (MemoryStream memStream = new MemoryStream()) { img.Save(memStream, ImageFormat.Tiff); bytes = memStream.GetBuffer(); } using (MagickImage image = new MagickImage(bytes)) { image.CompressionMethod = CompressionMethod.Group4; using (MemoryStream memStream = new MemoryStream()) { image.Write(memStream); memStream.Position = 0; using (MagickImage before = new MagickImage(Files.Coders.PageTIF)) { using (MagickImage after = new MagickImage(memStream)) { Assert.AreEqual(0.0, before.Compare(after, ErrorMetric.RootMeanSquared)); } } } } } }
public override byte[] Build() { MemoryStream temp = new MemoryStream(128); Writer writer = new Writer(temp); writer.Seek(0x62, SeekOrigin.Begin); writer.WriteString(Login, Encoding.ASCII); writer.Seek(0x70, SeekOrigin.Begin); writer.WriteString(Password, Encoding.ASCII); MemoryStream ms = new MemoryStream(168); writer = new Writer(ms); writer.Write(Id); writer.Write(Encrypt(temp.GetBuffer())); writer.Write(SessionId); writer.Write(GameGuard); ulong chk = Utils.CheckSum(ms.GetBuffer(), 160); writer.Write((byte)(chk & 0xff)); writer.Write((byte)(chk >> 0x08 & 0xff)); writer.Write((byte)(chk >> 0x10 & 0xff)); writer.Write((byte)(chk >> 0x18 & 0xff)); writer.Write((Int32)0); return ms.GetBuffer(); }
protected void Button1_Click(object sender, EventArgs e) { Page.Title = "Contact List"; MemoryStream PDFData = new MemoryStream(); // step 1: creation of a document-object Document document = new Document(); // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter.GetInstance(document, PDFData); // step 3: we open the document document.Open(); // step 4: we add a paragraph to the document document.Add(new Paragraph(DateTime.Now.ToString())); Contact oContact = new Contact(); DataTable dtContact = oContact.LoadAll(); int numRow = dtContact.Rows.Count; int numCol = 5; iTextSharp.text.Table aTable = new iTextSharp.text.Table(numCol, numRow); aTable.AutoFillEmptyCells = true; aTable.Padding = 1; aTable.Spacing = 1; Cell cell = new Cell(new Phrase("Contact List", FontFactory.GetFont(FontFactory.TIMES, 14, Font.BOLD))); cell.Header = true; cell.Colspan = numCol; cell.BackgroundColor = Color.LIGHT_GRAY; cell.HorizontalAlignment = Element.ALIGN_CENTER; aTable.AddCell(cell); for (int i = 0; i < dtContact.Rows.Count; i++) { for (int n = 1; n <= numCol; n++) aTable.AddCell(dtContact.Rows[i][n].ToString()); } document.Add(aTable); // step 5: we close the document document.Close(); Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.ContentType = "application/pdf"; Response.Charset = string.Empty; Response.Cache.SetCacheability(System.Web.HttpCacheability.Public); Response.AddHeader("Content-Disposition", "attachment; filename=" + Title.Replace(" ", "").Replace(":", "-") + ".pdf"); Response.OutputStream.Write(PDFData.GetBuffer(), 0, PDFData.GetBuffer().Length); Response.OutputStream.Flush(); Response.OutputStream.Close(); Response.End(); }
public void EntryMetadataUrlRoundTrip() { var stream = new MemoryStream(); var writerRequestMemoryMessage = new InMemoryMessage(); writerRequestMemoryMessage.Stream = stream; writerRequestMemoryMessage.SetHeader("Content-Type", "application/json"); var writerSettings = new ODataMessageWriterSettings() {Version = ODataVersion.V4, DisableMessageStreamDisposal = true}; writerSettings.ODataUri = new ODataUri() {ServiceRoot = new Uri("http://christro.svc/")}; var messageWriter = new ODataMessageWriter((IODataResponseMessage)writerRequestMemoryMessage, writerSettings, this.model); var organizationSetWriter = messageWriter.CreateODataEntryWriter(this.organizationsSet); var odataEntry = new ODataEntry(){ TypeName = ModelNamespace + ".Corporation" }; odataEntry.Property("Id", 1); odataEntry.Property("Name", ""); odataEntry.Property("TickerSymbol", "MSFT"); organizationSetWriter.WriteStart(odataEntry); organizationSetWriter.WriteEnd(); var readerPayloadInput = Encoding.UTF8.GetString(stream.GetBuffer()); Console.WriteLine(readerPayloadInput); var readerResponseMemoryMessage = new InMemoryMessage(); readerResponseMemoryMessage.Stream = new MemoryStream(stream.GetBuffer()); readerResponseMemoryMessage.SetHeader("Content-Type", "application/json"); var messageReader = new ODataMessageReader((IODataResponseMessage)readerResponseMemoryMessage, new ODataMessageReaderSettings() {MaxProtocolVersion = ODataVersion.V4, DisableMessageStreamDisposal = true}, this.model); var organizationReader = messageReader.CreateODataEntryReader(this.organizationsSet, this.organizationsSet.EntityType()); organizationReader.Read().Should().Be(true); organizationReader.Item.As<ODataEntry>(); }
protected string ReceiveMessage() { var buffer = new MemoryStream(); int @byte; bool possibleDelimiterIsComing; var possibleDelimiterCount = 0; while ((@byte = stream.ReadByte()) != -1) { buffer.WriteByte((byte)@byte); if (@byte == this.delimiterBytes[possibleDelimiterCount]) { possibleDelimiterIsComing = true; possibleDelimiterCount++; } else { possibleDelimiterIsComing = false; possibleDelimiterCount = 0; } if (possibleDelimiterIsComing && this.delimiterBytes.Length == possibleDelimiterCount) { // complete message received, return removing the delimiters return StreamEncoding.GetString( buffer.GetBuffer(), 0, (int)(buffer.Length - this.delimiterBytes.Length)); } } // return incomplete message return StreamEncoding.GetString(buffer.GetBuffer()); }
public Image(MemoryStream imageStream) : this() { // Added new property to hold the stream ImageStream = new MemoryStream(); ImageStream.Write(imageStream.GetBuffer(), 0, imageStream.GetBuffer().Length); Name = String.Empty; // When no filename, we'll look for the stream. }
public static ActionResult UpgradeLayoutFile(Session session) { string appData = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "TraceLab"); var path = System.IO.Path.Combine(appData, "layout.xml"); bool resetLayout = false; try { if (System.IO.File.Exists(path)) { session.Log("Upgrading layout file."); using (MemoryStream memStream = new MemoryStream()) { using (var fileStream = File.OpenRead(path)) { memStream.SetLength(fileStream.Length); fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length); memStream.Flush(); fileStream.Close(); } UpgradeLayoutToCurrentVersion(memStream); // The memory stream has been transformed in place, it is now time to copy it back to the file. using (var fileStream = File.OpenWrite(path)) { fileStream.Write(memStream.GetBuffer(), 0, (int)memStream.Length); fileStream.SetLength(memStream.Length); fileStream.Close(); } } session.Log("Done upgrading layout file."); } } catch (Exception e) { session.Log("Exception occurred: {0}\n{1}", e.Message, e.StackTrace); resetLayout = true; } if (resetLayout) { try { session.Log("Resetting layout"); System.IO.File.Delete(path); } catch (Exception) { return ActionResult.Failure; } } return ActionResult.Success; }
public void CopyTo_MultiWithFirstLast() { using (MemoryStream src = new MemoryStream(new byte[] {0, 1, 2, 3, 5}), dst = new MemoryStream()) { StreamHelpers.CopyTo(src, dst, 1, 3); Assert.AreEqual(3, dst.Length); Assert.AreEqual(1, dst.GetBuffer()[0]); Assert.AreEqual(2, dst.GetBuffer()[1]); Assert.AreEqual(3, dst.GetBuffer()[2]); } }
public static byte[] ReadFully(Stream input) { using (MemoryStream tempStream = new MemoryStream()) { Copy(input, tempStream); if (tempStream.Length == tempStream.GetBuffer().Length) { return tempStream.GetBuffer(); } return tempStream.ToArray(); } }
public static Stream ConvertOgg(string inputFile) { if (needsConversion(inputFile)) { var platform = getPlatform(inputFile); EndianBitConverter bitConverter = platform.GetBitConverter(); using (var outputFileStream = new MemoryStream()) using (var inputFileStream = File.Open(inputFile, FileMode.Open)) using (var writer = new EndianBinaryWriter(bitConverter, outputFileStream)) using (var reader = new EndianBinaryReader(bitConverter, inputFileStream)) { writer.Write(reader.ReadBytes(4)); UInt32 fileSize = reader.ReadUInt32(); fileSize -= 8; // We're removing data, so update the size in the header writer.Write(fileSize); writer.Write(reader.ReadBytes(8)); writer.Write(66); reader.ReadUInt32(); // New fmt size is 66 writer.Write(reader.ReadBytes(16)); writer.Write((ushort)48); reader.ReadUInt16(); // New cbSize is 48 writer.Write(reader.ReadBytes(6)); reader.BaseStream.Seek(8, SeekOrigin.Current); // Skip ahead 8 bytes, we don't want the vorb chunk writer.Write(reader.ReadBytes((int)reader.BaseStream.Length - (int)reader.BaseStream.Position)); return new MemoryStream(outputFileStream.GetBuffer(), 0, (int)outputFileStream.Length); } } return File.OpenRead(inputFile); }
private void button2_Click(object sender, EventArgs e) { BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false); iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 12, iTextSharp.text.Font.ITALIC, BaseColor.DARK_GRAY); Document doc = new Document(iTextSharp.text.PageSize.LETTER,10,10,42,42); PdfWriter pdw = PdfWriter.GetInstance(doc, new FileStream(naziv + ".pdf", FileMode.Create)); doc.Open(); Paragraph p = new Paragraph("Word Count for : "+naziv,times); doc.Add(p); p.Alignment = 1; PdfPTable pdt = new PdfPTable(2); pdt.HorizontalAlignment = 1; pdt.SpacingBefore = 20f; pdt.SpacingAfter = 20f; pdt.AddCell("Word"); pdt.AddCell("No of repetitions"); foreach (Rijec r in lista_rijeci) { pdt.AddCell(r.Tekst); pdt.AddCell(Convert.ToString(r.Ponavljanje)); } using (MemoryStream stream = new MemoryStream()) { chart1.SaveImage(stream, ChartImageFormat.Png); iTextSharp.text.Image chartImage = iTextSharp.text.Image.GetInstance(stream.GetBuffer()); chartImage.ScalePercent(75f); chartImage.Alignment = 1; doc.Add(chartImage); } doc.Add(pdt); doc.Close(); MessageBox.Show("PDF created!"); }
private BufferSlice EncodeMessage(Message msg) { if (msg.Body.Length != 0) msg.Headers["Content-Length"] = msg.Body.Length.ToString(); var buffer = new byte[65535]; long length = 0; using (var stream = new MemoryStream(buffer)) { stream.SetLength(0); using (var writer = new StreamWriter(stream)) { foreach (string key in msg.Headers) { writer.Write(string.Format("{0}: {1}\n", key, msg.Headers[key])); } writer.Write("\n"); writer.Flush(); stream.Write(stream.GetBuffer(), 0, (int) stream.Length); length = stream.Length; } } var tmp = Encoding.ASCII.GetString(buffer, 0, (int) length); return new BufferSlice(buffer, 0, (int) length, (int) length); }
public object GetData() { var td = new TaskSchedulerData(); td.Name = UserName.Text; td.Surname = UserSurname.Text; td.Patronimyc = UserPatronymic.Text; if (MaleButton.Checked) { td.Gender = Gender.Male; } if (FemaleButton.Checked) { td.Gender = Gender.Female; } foreach (TaskData ed in ListBox1.Items) { td.Tasks.Add(ed); } var ms = new MemoryStream(); PhotoBox.Image.Save(ms, ImageFormat.Png); td.Photo = ms.GetBuffer(); return td; }
public ActionResult CreateProfile([Bind(Include = "Id, FirstName, LastName")] Profile profile, HttpPostedFileBase ImageFile) { if (ModelState.IsValid) { if (ImageFile != null) { using (MemoryStream ms = new MemoryStream()) { ImageFile.InputStream.CopyTo(ms); profile.Picture = ms.GetBuffer(); } } profile.Id = Guid.NewGuid(); db.UserProfiles.Add(profile); db.SaveChanges(); var currentUser = UserDB.Users.Find(User.Identity.GetUserId()); currentUser.MadeProfileYet = true; UserDB.SaveChanges(); db.UserProfiles.Find(profile.Id).AspNetUser_Id = new Guid(currentUser.Id); db.UserProfiles.Find(profile.Id).FavoriteSaying = UserDB.Users.Find(currentUser.Id).FavoritePhrase; db.SaveChanges(); return RedirectToAction("Index"); } return View(profile); }
public static byte[] Serialize(object data) { BinaryFormatter formatter = new BinaryFormatter(); MemoryStream rems = new MemoryStream(); formatter.Serialize(rems, data); return rems.GetBuffer(); }
public byte[] DoCapture() { FrameworkElement toSnap = null; if (!AutomationIdIsEmpty) toSnap = GetFrameworkElement(false); if (toSnap == null) toSnap = AutomationElementFinder.GetRootVisual(); if (toSnap == null) return null; // Save to bitmap var bmp = new WriteableBitmap((int)toSnap.ActualWidth, (int)toSnap.ActualHeight); bmp.Render(toSnap, null); bmp.Invalidate(); // Get memoryStream from bitmap using (var memoryStream = new MemoryStream()) { bmp.SaveJpeg(memoryStream, bmp.PixelWidth, bmp.PixelHeight, 0, 95); memoryStream.Seek(0, SeekOrigin.Begin); return memoryStream.GetBuffer(); } }
static void Main(string[] args) { MemoryStream m = new MemoryStream(64); Console.WriteLine("Lenth: {0}\tPosition: {1}\tCapacity: {2}", m.Length, m.Position, m.Capacity); for (int i = 0; i < 64; i++) { m.WriteByte((byte)i); } string s = "Foo"; for (int i = 0; i < 3; i++) { m.WriteByte((byte)s[i]); } Console.WriteLine("Length: {0}\tPosition: {1}\tCapacity: {2}", m.Length, m.Position, m.Capacity); Console.WriteLine("\nContents:"); byte[] ba = m.GetBuffer(); foreach (byte b in ba) { Console.Write("{0,-3}", b); } FileStream fs = new FileStream("Goo.txt", FileMode.Create, FileAccess.Write); m.WriteTo(fs); fs.Close(); m.Close(); Console.ReadLine(); }
/// <summary> /// Creates an action result containing the file contents of a png/image with the captcha chars /// </summary> public static ActionResult CaptchaResult(SessionWrapper session) { var randomText = GenerateRandomText(6); var hash = Utils.GetMd5Hash(randomText + GetSalt(), Encoding.ASCII); session.CaptchaHash = hash; var rnd = new Random(); var fonts = new[] { "Verdana", "Times New Roman" }; float orientationAngle = rnd.Next(0, 359); const int height = 30; const int width = 120; var index0 = rnd.Next(0, fonts.Length); var familyName = fonts[index0]; using (var bmpOut = new Bitmap(width, height)) { var g = Graphics.FromImage(bmpOut); var gradientBrush = new LinearGradientBrush(new Rectangle(0, 0, width, height), Color.White, Color.DarkGray, orientationAngle); g.FillRectangle(gradientBrush, 0, 0, width, height); DrawRandomLines(ref g, width, height); g.DrawString(randomText, new Font(familyName, 18), new SolidBrush(Color.Gray), 0, 2); var ms = new MemoryStream(); bmpOut.Save(ms, ImageFormat.Png); var bmpBytes = ms.GetBuffer(); bmpOut.Dispose(); ms.Close(); return new FileContentResult(bmpBytes, "image/png"); } }
public override byte[] CreateImage(out string validataCode) { Bitmap bitmap; string formatString = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z"; GetRandom(formatString, this.ValidataCodeLength, out validataCode); MemoryStream stream = new MemoryStream(); AnimatedGifEncoder encoder = new AnimatedGifEncoder(); encoder.Start(); encoder.SetDelay(1); encoder.SetRepeat(0); for (int i = 0; i < 3; i++) { this.SplitCode(validataCode); this.ImageBmp(out bitmap, validataCode); bitmap.Save(stream, ImageFormat.Png); encoder.AddFrame(Image.FromStream(stream)); stream = new MemoryStream(); bitmap.Dispose(); } encoder.OutPut(ref stream); bitmap = null; stream.Close(); stream.Dispose(); return stream.GetBuffer(); }
public async Task WriteRequestAsync(SwitchboardRequest request, CancellationToken ct) { var writeStream = this.GetWriteStream(); var ms = new MemoryStream(); var sw = new StreamWriter(ms, headerEncoding); sw.NewLine = "\r\n"; sw.WriteLine("{0} {1} HTTP/1.{2}", request.Method, request.RequestUri, request.ProtocolVersion.Minor); for (int i = 0; i < request.Headers.Count; i++) sw.WriteLine("{0}: {1}", request.Headers.GetKey(i), request.Headers.Get(i)); sw.WriteLine(); sw.Flush(); await writeStream.WriteAsync(ms.GetBuffer(), 0, (int)ms.Length) .ConfigureAwait(continueOnCapturedContext: false); if (request.RequestBody != null) { await request.RequestBody.CopyToAsync(writeStream) .ConfigureAwait(continueOnCapturedContext: false); } await writeStream.FlushAsync() .ConfigureAwait(continueOnCapturedContext: false); }
static void Main(string[] args) { string quit = "n"; while (quit == "n") { ITransport transport = TcpTransport.CreateTransport(45459); if (transport != null) { IEvent e = new TcpEvent((int)EventId.Media, null); BinaryFormatter bf = new BinaryFormatter(); MemoryStream mem = new MemoryStream(); bf.Serialize(mem, e); transport.Send(mem.GetBuffer()); Console.WriteLine("Quit?(y/n)"); quit = Console.ReadLine(); transport.Close(); //if (quit != "n") //{ // Console.WriteLine("send disconned event to Server to close the server"); // IEvent d = new TcpEvent((int)EventId.Disconnect, null); // BinaryFormatter bfd = new BinaryFormatter(); // MemoryStream memd = new MemoryStream(); // bfd.Serialize(memd, d); // transport.Send(memd.GetBuffer()); // transport.Close(); //} } } }
public void Run() { var location = typeof(AgePrinter).Assembly.Location; var assemblyDefinition = AssemblyDefinition.ReadAssembly(location); var module = assemblyDefinition.MainModule; var agePrinterType = (from t in module.Types where t.Name == "AgePrinter" select t).First(); var printAgeMethod = (from m in agePrinterType.Methods where m.Name == "PrintAge" select m).First(); RewriteMethod(printAgeMethod); assemblyDefinition.Write("output.dll"); var memoryStream = new MemoryStream(); assemblyDefinition.Write(memoryStream); // Convert the modified assembly into // an assembly that will be loaded by System.Reflection var bytes = memoryStream.GetBuffer(); var assembly = Assembly.Load(bytes); var modifiedType = (from t in assembly.GetTypes() where t.Name == "AgePrinter" select t).First(); var printer = (IAgePrinter)Activator.CreateInstance(modifiedType); printer.PrintAge(new Person(18)); }
public override string Serialize(MemberInfo storageType, object value, ISerializationOperator serializationOperator) { if (value == null) return "null"; if (_serializer == null) { throw new InvalidOperationException("No protobuf-net serializer is loaded"); } UnityObjectReferenceHack.ActiveOperator = serializationOperator; using (var stream = new MemoryStream()) { _serializer.Serialize(stream, value, new SerializationContext() { Context = serializationOperator }); UnityObjectReferenceHack.ActiveOperator = null; #if !UNITY_EDITOR && UNITY_WINRT return Convert.ToBase64String(stream.ToArray(), 0, (int)stream.Length); #else return Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length); #endif } }
private bool SetValue(object currentValue, out object newValue) { DTE dte = this.GetService<DTE>(true); IDictionaryService dictionaryService = (IDictionaryService)ServiceHelper.GetService(this, typeof(IDictionaryService)); try { if (!string.IsNullOrEmpty(RecipeArgument)) { string argumentvalue = dictionaryService.GetValue(RecipeArgument).ToString(); Version v = new Version(argumentvalue); if (v != null) { byte[] bytes; long length = 0; MemoryStream ws = new MemoryStream(); BinaryFormatter sf = new BinaryFormatter(); sf.Serialize(ws, v); length = ws.Length; bytes = ws.GetBuffer(); newValue = Convert.ToBase64String(bytes, 0, bytes.Length, Base64FormattingOptions.None); return true; } } } catch { } //string projectId = currentProject. newValue = ""; return false; }
public override void Write(Stream stream) { MemoryStream ms = new MemoryStream(); Icon.ToBitmap().Save(ms, ImageFormat.Png); byte[] buffer = ms.GetBuffer(); stream.Write(buffer, 0, (int) ms.Length); }
/// <summary> /// Expands (de-compresses) a string. /// </summary> /// <param name="value">The string to expanded.</param> /// <returns>The expanded string.</returns> public string ExpandString(string value) { // The input value must be non-null if (value == null) { throw new ArgumentNullException("value"); } var outputData = string.Empty; var inputData = Convert.FromBase64String(value); using (var inputStream = new MemoryStream(inputData)) { using (var outputStream = new MemoryStream()) { // Zip the string using (var zipStream = new InflaterInputStream(inputStream)) { zipStream.IsStreamOwner = false; StreamUtils.Copy(zipStream, outputStream, new byte[4096]); } // Convert to a string outputData = UTF8Encoding.UTF8.GetString(outputStream.GetBuffer(), 0, Convert.ToInt32(outputStream.Length)); } } // Return the compressed string return outputData; }
public int InsertBLOBImage(Bitmap image) { MemoryStream stream = new MemoryStream(); image.Save(stream, ImageFormat.Png); return insertBLOB(stream.GetBuffer()); }
public void UseBsonSerializer() { var message = GetMyJsonTestMessage(); var serializer = new JsonSerializer(); byte[] serializedMessage; using (var stream = new MemoryStream()) using (var writer = new BsonWriter(stream)) { serializer.Serialize(writer, message); serializedMessage = stream.GetBuffer(); } MyJsonTestMessage deserializedMessage; using (var stream = new MemoryStream(serializedMessage)) using (var reader = new BsonReader(stream)) { deserializedMessage = serializer.Deserialize<MyJsonTestMessage>(reader); } Console.Out.WriteLine(deserializedMessage.GetHashCode() == message.GetHashCode()); }
public StoreDataCommand(Key key, object objectToBeStored, DateTime expiry) : base(key) { this.expiry = expiry; if (objectToBeStored is int) { this.objType = StoredObjectType.IntCounter; dataToBeStored = Encoding.UTF8.GetBytes(objectToBeStored.ToString()); } else if (objectToBeStored is uint) { this.objType = StoredObjectType.UIntCounter; dataToBeStored = Encoding.UTF8.GetBytes(objectToBeStored.ToString()); } else if (objectToBeStored is long) { this.objType = StoredObjectType.LongCounter; dataToBeStored = Encoding.UTF8.GetBytes(objectToBeStored.ToString()); } else { this.objType = StoredObjectType.SerializableObject; using (MemoryStream ms = new MemoryStream()) { new BinaryFormatter().Serialize(ms, objectToBeStored); dataToBeStored = new byte[ms.Length]; Array.Copy(ms.GetBuffer(), dataToBeStored, dataToBeStored.Length); } } }
private void Form1_Load(object sender, EventArgs e) { //Create a DataSet from the XML file string filePath = "..\\..\\Employees.xml"; DataSet ds = new DataSet(); ds.ReadXml(filePath); //Create and add barcode column DataColumn dc = new DataColumn("BarcodeImage", typeof(byte[])); ds.Tables[0].Columns.Add(dc); //We'll use Code 128 Barcode Symbology BaseBarcode b = BarcodeFactory.GetBarcode(Symbology.Code128); b.Height = 50; b.FontHeight = 0.3F; //Now, generate and fill barcode images foreach (DataRow dr in ds.Tables[0].Rows) { //We'll encode the ID column b.Number = (string)dr["ID"]; //Create bitmap and save it to BarcodeImage column MemoryStream ms = new MemoryStream(); b.Save(ms, ImageType.Png); dr["BarcodeImage"] = ms.GetBuffer(); } CrystalReport1 report = new CrystalReport1(); report.SetDataSource(ds); crystalReportViewer1.ReportSource = report; }
public int MessageObj2Bytes <T>(T message_obj, int message_command) { System.IO.MemoryStream stream = new System.IO.MemoryStream(); ProtoBuf.Serializer.Serialize(stream, message_obj); int messageSize = HEAD_LENGTH + (int)stream.Length; MessageHeader.Header header = new MessageHeader.Header(messageSize, message_command); Debug.Log("header : " + header.ToString()); byte[] headerBytes = ObjectBytesTrans.StructToBytes(header); int headerBytesLength = headerBytes.Length; System.Array.Copy(headerBytes, 0, m_buffer, 0, headerBytesLength); byte[] bodyBytes = stream.GetBuffer(); long streamLength = stream.Length; System.Array.Copy(bodyBytes, 0, m_buffer, headerBytesLength, streamLength); int bytesLength = (int)(headerBytesLength + streamLength); return(bytesLength); }
//输出图片 参数:内容;是否扭曲(T为扭曲);扭曲程度(越高越厉害),波形(0-2PI),IFRAME支持与否 public void CreateImageOnPage(string code, bool bXDir, double dMultValue, double dPhase, HttpContext context, bool iframe, Page thePage) { if (iframe == true) { thePage.Response.AddHeader("P3P", "CP=CAO PSA OUR"); } System.IO.MemoryStream ms = new System.IO.MemoryStream(); Bitmap image = this.CreateImageCode(code, bXDir, dMultValue, dPhase); image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); context.Response.ClearContent(); context.Response.ContentType = "image/Jpeg"; context.Response.BinaryWrite(ms.GetBuffer()); ms.Close(); ms = null; image.Dispose(); image = null; }
protected void GridWeb1_SaveCommand(object sender, System.EventArgs e) { // Generates a memory stream. System.IO.MemoryStream ms = new System.IO.MemoryStream(); // Saves to the stream. this.GridWeb1.SaveToExcelFile(ms); // Sents the file to browser. Response.ContentType = "application/vnd.ms-excel"; //Adds header. Response.AddHeader("content-disposition", "attachment; filename=book1.xls"); // Writes file content to the response stream. Response.OutputStream.Write(ms.GetBuffer(), 0, (int)ms.Length); // OK. Response.End(); }
protected void Page_Load(object sender, EventArgs e) { if (!string.IsNullOrEmpty(Request["KeyID"])) { KeyID = Request["KeyID"] + ""; } //DataTable lo = new Hi.BLL.DIS_OrderOut().GetList("", " isnull(o.dr,0)=0 and o.IsAudit<>3 and o.ID=" + KeyID); Code39 _Code39 = new Code39(); _Code39.Height = 60; _Code39.Magnify = 0.5; //_Code39.ViewFont = new Font("微软雅黑", 11); System.Drawing.Image _CodeImage = _Code39.GetCodeImage(KeyID, Code39.Code39Model.Code39Normal, true, true); System.IO.MemoryStream _Stream = new System.IO.MemoryStream(); _CodeImage.Save(_Stream, System.Drawing.Imaging.ImageFormat.Jpeg); Response.ContentType = "image/jpeg"; Response.Clear(); Response.BufferOutput = true; Response.BinaryWrite(_Stream.GetBuffer()); Response.Flush(); }
protected void Page_Load(object sender, EventArgs e) { string codeType = Request["code"]; if (string.IsNullOrEmpty(codeType as string)) { codeType = "123"; } ValidateCodeImg vCodeImg = new ValidateCodeImg(); string verifyCode = vCodeImg.CreateVerifyCode(codeType, 6, 0); Session["ImgCode"] = verifyCode; System.Drawing.Bitmap bitmap = vCodeImg.CreateImage(verifyCode, false); System.IO.MemoryStream ms = new System.IO.MemoryStream(); bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png); Response.Clear(); Response.ContentType = "image/Png"; Response.BinaryWrite(ms.GetBuffer()); bitmap.Dispose(); ms.Dispose(); ms.Close(); Response.End(); }
public string Encrypting(string Source, string Key) { byte[] bytIn = System.Text.ASCIIEncoding.ASCII.GetBytes(Source); // create a MemoryStream so that the process can be done without I/O files System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] bytKey = GetLegalKey(Key); // set the private key mobjCryptoService.Key = bytKey; mobjCryptoService.IV = bytKey; // create an Encryptor from the Provider Service instance ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor(); // create Crypto Stream that transforms a stream using the encryption CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write); // write out encrypted content into MemoryStream cs.Write(bytIn, 0, bytIn.Length); cs.FlushFinalBlock(); // get the output and trim the '\0' bytes byte[] bytOut = ms.GetBuffer(); int i = 0; for (i = 0; i < bytOut.Length; i++) { if (bytOut[i] == 0) { break; } } // convert into Base64 so that the result can be used in xml return(System.Convert.ToBase64String(bytOut, 0, i)); }
private void toolStripMenuItem3_Click(object sender, EventArgs e) { if (txtNombres.Text != "" || txtApellidos.Text != "" || txtContrasenia.Text != "" || txtCorreo.Text != "" || txtUsuario.Text != "" || cbxRol.SelectedIndex != 0 || lblAnuncioIcono.Visible == false) { if (validar_Correo(txtCorreo.Text) == false) { MessageBox.Show("Dirección de correo electronico inválido.\nEl correo debe tener el formato: [email protected], " + "\nPor favor ingrese un correo válido", "Validación de correo electronico", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); txtCorreo.Focus(); txtCorreo.SelectAll(); } else { if (txtContrasenia.Text.Length >= 8) { if (txtUsuario.Text.Length >= 4) { try { SqlConnection con = new SqlConnection(); con.ConnectionString = CONEXION.Conexion_Maestra.conexion; con.Open(); SqlCommand cmd = new SqlCommand(); cmd = new SqlCommand("insertar_usuario", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@nombres", txtNombres.Text); cmd.Parameters.AddWithValue("@apellidos", txtApellidos.Text); cmd.Parameters.AddWithValue("@Login", txtUsuario.Text); cmd.Parameters.AddWithValue("@Password", (txtContrasenia.Text)); cmd.Parameters.AddWithValue("@Correo", txtCorreo.Text); cmd.Parameters.AddWithValue("@Rol", cbxRol.Text); System.IO.MemoryStream ms = new System.IO.MemoryStream(); //Proceso para imagenes pbIcono.Image.Save(ms, pbIcono.Image.RawFormat); //Transformar a tipo de datos de SQL cmd.Parameters.AddWithValue("@Icono", ms.GetBuffer()); //Transformar a binario- Referencias ruta cmd.Parameters.AddWithValue("@Nombre_de_icono", lblNumIcono.Text); cmd.Parameters.AddWithValue("@Estado", "ACTIVO"); cmd.ExecuteNonQuery(); con.Close(); mostrar(); panelRegistro.Visible = false; } catch (Exception ex) { MessageBox.Show(ex.Message); } } else { MessageBox.Show("El nombre de usuario debe tener un mínimo de 4 caracteres" + "\nPor favor ingresa una nuevo nombre de usuario", "Usuario inválido", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else { MessageBox.Show("La contraseña debe tener un mínimo de 8 caracteres" + "\nPor favor ingresa una nueva contraseña", "Seguridad de contraseña", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } else { MessageBox.Show("Faltan datos por ingresar" + "\nPor favor rellena los campos faltantes", "Datos faltantes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
private void BotonAceptar_Click(object sender, EventArgs e) { try { string respuesta = ""; if (CodigoDelLibroText.Text == string.Empty || ComboAutor.Text == string.Empty || ComboEditorial.Text == string.Empty || ComboGenero.Text == string.Empty || archivoPdf.src == null) { MensajeError("Falta ingresar algunos datos, serán remarcados"); mensajeErrorProvider.SetError(CodigoDelLibroText, "Ingrese un Valor"); mensajeErrorProvider.SetError(ComboAutor, "Ingrese un Valor"); mensajeErrorProvider.SetError(ComboEditorial, "Ingrese un Valor"); mensajeErrorProvider.SetError(ComboGenero, "Ingrese un Valor"); mensajeErrorProvider.SetError(archivoPdf, "Ingrese un Valor"); } else { if (!(libroService.BuscarLibro(CodigoDelLibroText.Text) == null)) { MensajeError("el codigo del libro: " + CodigoDelLibroText.Text + " ya se encuentra registrado en el sistema "); } else { libro = new Libro(); libro.codigo = CodigoDelLibroText.Text; libro.nombre = NombreDelLibroText.Text; libro.descripcion = DescripcionText.Text; libro.idautor = (int)ComboAutor.SelectedValue; libro.ideditorial = (int)ComboEditorial.SelectedValue; libro.idgenero = (int)ComboGenero.SelectedValue; ///guargdar imagen de portada System.IO.MemoryStream ms = new System.IO.MemoryStream(); this.pxFotoPortada.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png); byte[] imagen = ms.GetBuffer(); libro.imagen_portada = imagen; ///guardar archivo en pdf byte[] archivo = null; Stream myStream = file.OpenFile(); using (MemoryStream mStream = new MemoryStream()) { myStream.CopyTo(mStream); archivo = mStream.ToArray(); } libro.archivo_pdf = archivo; libro.nombre_archivo = file.SafeFileName; respuesta = libroService.GuardarLibro(libro); if (respuesta.Equals("OK")) { this.MensajeOk("Se Insertó de forma correcta el registro"); } else { this.MensajeError(respuesta); } } LimpiarCampos(); } } catch (Exception) { throw; } }
// 応答実行 public void Run() { try { // 要求受信 byte[] buffer = new byte[4096]; int recvLen = 0; System.Threading.Thread.Sleep(10); //タイミング対策 try { while (mClient.Available > 0) { recvLen += mClient.Receive(buffer); } } catch (SocketException e) { Console.WriteLine("{0} Error code: {1}.", e.Message, e.ErrorCode); throw e; } String message = Encoding.ASCII.GetString(buffer, 0, recvLen); Console.Write("httprequest:" + message); // httpmessageを展開する。 String req_method; String req_path; String req_httpversion; var req_dict = new Dictionary <string, string>(); // 改行で分解 String[] ms = message.Split(new String[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); var rm1 = new System.Text.RegularExpressions.Regex(@"^([A-Z]{3,4}) +(/.*) +HTTP/([0-9]+.[0-9]+)"); //リクエスト行 var mm = rm1.Match(ms[0]); if (!mm.Success) { throw new Exception(); } //リクエスト不正 // メソッド、ターゲット、HTTPバージョンなど取得 req_method = mm.Groups[1].Value; req_path = mm.Groups[2].Value; req_httpversion = mm.Groups[3].Value; // 他の要素取得 - ハッシュでいいかー var rm2 = new System.Text.RegularExpressions.Regex(@"^([^:]+) *: +(.+)"); for (int i = 1; i < ms.Length; i++) { var mmm = rm2.Match(ms[i]); if (mmm.Success) { req_dict.Add(mmm.Groups[1].Value, mmm.Groups[2].Value); } } Encoding sjisEnc = Encoding.GetEncoding("Shift_JIS"); String httpHeader = null; byte[] httpHeaderBuffer = new byte[4096]; String body = null; byte[] bodyBuffer = new byte[65536]; string basedir = System.IO.Path.GetDirectoryName(mForm.textBox_bbsmenu.Text); // reg var r = new System.Text.RegularExpressions.Regex(@"([^/]+)/subject\.txt"); var r1 = new System.Text.RegularExpressions.Regex(@"([^/]+)/setting\.txt"); var r2 = new System.Text.RegularExpressions.Regex(@"([^/]+)/dat/([0-9]+)\.dat"); var r4 = new System.Text.RegularExpressions.Regex(@"([0-9]+\.dat)(<>.+\t )\([0-9]+\)"); var r5 = new System.Text.RegularExpressions.Regex(@"^(/test/read.cgi)?/([^/]+)/"); var md = r5.Match(req_path); try { // 要求されてから作り込む if (req_path.Contains("bbsmenu.dat")) // menuは全部返す { StreamReader sr = new StreamReader( mForm.textBox_bbsmenu.Text, Encoding.GetEncoding("Shift_JIS")); body = convertLocalURI(sr.ReadToEnd(), req_dict["Host"]); sr.Close(); bodyBuffer = sjisEnc.GetBytes(body); } //subjectは要求された板のフォルダ下存在datをまとめて返す(subjectに存在するもののみ) //→subject.txtを上からさらって件数修正する。datの件数だけ読めればベター //書き込み中の場合、待つ else if (req_path.Contains("subject.txt")) { var m = r.Match(message); if (m.Success) { var t = basedir + "\\" + mForm.dict[m.Groups[1].Value] + "\\subject.txt"; // ファイル一覧を取得 string[] files = System.IO.Directory.GetFiles( basedir + "\\" + mForm.dict[m.Groups[1].Value], "*", SearchOption.TopDirectoryOnly); StreamReader sr = new StreamReader( basedir + "\\" + mForm.dict[m.Groups[1].Value] + "\\subject.txt", Encoding.GetEncoding("Shift_JIS")); var filesArr = new List <string>(files); var sb = new StringBuilder(); while (sr.Peek() >= 0) { // ファイルを 1 行ずつ読み込む var stBuffer = sr.ReadLine(); var m2 = r4.Match(stBuffer); if (m2.Success) //宣伝は対象外 { if (filesArr.Contains(basedir + "\\" + mForm.dict[m.Groups[1].Value] + "\\" + m2.Groups[1].Value)) { // ファイルを読む var fsr = new StreamReader( basedir + "\\" + mForm.dict[m.Groups[1].Value] + "\\" + m2.Groups[1].Value, Encoding.GetEncoding("Shift_JIS")); // 件数取得 書き込み中かもしれないが、どうせ追加していくだけなので行数を見ればだいたいあってる int c = 0; while (fsr.Peek() >= 0) { fsr.ReadLine(); c++; } fsr.Close(); sb.Append(m2.Groups[1].Value + m2.Groups[2].Value + "(" + c + ")\n"); // 現時点での読み込んだdatを反映 } } } sr.Close(); bodyBuffer = sjisEnc.GetBytes(sb.ToString()); } } // settingは特に変わらないのでそのまま送る else if (req_path.Contains("setting.txt")) { var m = r1.Match(message); if (m.Success) { StreamReader sr = new StreamReader( basedir + "\\" + mForm.dict[m.Groups[1].Value] + "\\setting.txt", Encoding.GetEncoding("Shift_JIS")); body = sr.ReadToEnd(); sr.Close(); bodyBuffer = sjisEnc.GetBytes(body); } } // datは直返しで問題ない。 else if (req_path.Contains("/dat/")) { var m = r2.Match(message); if (m.Success) { StreamReader sr = new StreamReader( basedir + "\\" + mForm.dict[m.Groups[1].Value] + "\\" + m.Groups[2].Value + ".dat", Encoding.GetEncoding("Shift_JIS")); body = convertLocalURI(sr.ReadToEnd(), req_dict["Host"]); sr.Close(); if (req_dict.ContainsKey("Range")) { string[] strRange = req_dict["Range"].Split('='); int range = 0; try { range = int.Parse(strRange[1].Replace("-", ""));//開始バイト位置 } catch (Exception) { } var bodyBufferTmp = sjisEnc.GetBytes(body); var bodyBufferTmp2 = new byte[bodyBufferTmp.Length - range]; Array.Copy(bodyBufferTmp, range, bodyBufferTmp2, 0, bodyBufferTmp.Length - range); bodyBuffer = bodyBufferTmp2; } else { bodyBuffer = sjisEnc.GetBytes(body); } } } //* 作ったけど使われなさそうな部分 ここから *// else if (req_path.Contains("/test/bbs.cgi")) { var sb = new StringBuilder(); sb.Append(@"<html> <head><title>■ 書き込み確認 ■</title><meta http-equiv=""Content-Type"" content=""text/html; charset=Shift_JIS"">"); sb.Append(@"<meta name=""viewport"" content=""width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.6,user-scalable=yes""/>"); sb.Append(@"</head><body bgcolor=#EEEEEE><font size=+1 color=#FF0000><b>書きこみ&クッキー確認</b></font><ul><br><br><b> </b><br>名前: "); sb.Append(@"<br>E-mail: <br>内容:<br>a<br><br></ul><form method=POST action=""../test/bbs.cgi?guid=ON""><input type=hidden name=subject value="""">"); sb.Append(@"<input TYPE=hidden NAME=FROM value=""""><input TYPE=hidden NAME=mail value=""""><input type=hidden name=MESSAGE value="""">"); sb.Append(@"<input type=hidden name=bbs value=namazuplus><input type=hidden name=sid value=><input type=hidden name=time value=1424749403>"); sb.Append(@"<input type=hidden name=key value=1422604082><br><input type=submit value=""確認して書き込む"" name=""submit""><br></form>"); sb.Append(@"変更する場合は戻るボタンで戻って書き直して下さい。<br><br>現在、荒らし対策でクッキーを設定していないと書きこみできないようにしています。<br>"); sb.Append(@"<font size=-1>(cookieを設定するとこの画面はでなくなります。)</font><br></body></html>"); bodyBuffer = sjisEnc.GetBytes(sb.ToString()); } // /livevenus/* 型 または /test/read.cgi/livevenus/* else if (md.Success && !string.IsNullOrEmpty(md.Groups[2].Value) && mForm.dict2.ContainsKey(md.Groups[2].Value)) { // 元データを取得して返す(リダイレクトしたいけどたぶんサポートしてないやろ) string server = mForm.dict2[md.Groups[2].Value]; //リクエストメッセージを作成する StringBuilder sb = new StringBuilder(); sb.Append(req_method + " " + req_path + " HTTP/" + req_httpversion + "\r\n"); // リクエスト行 sb.Append("Host: " + server + "\r\n"); foreach (string s in req_dict.Keys) { if (!s.Equals("Host")) { sb.Append(s + ": " + req_dict[s] + "\r\n"); } } sb.Append("\r\n\r\n"); var reqMsg = sb.ToString(); //文字列をbyte配列に変換 byte[] reqBytes = Encoding.UTF8.GetBytes(reqMsg); //ホスト名からIPアドレスを取得 System.Net.IPAddress hostadd = System.Net.Dns.GetHostEntry(server).AddressList[0]; //IPEndPointを取得 System.Net.IPEndPoint ephost = new System.Net.IPEndPoint(hostadd, 80); //Socketの作成 System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket( System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); //接続 sock.Connect(ephost); //リクエストメッセージを送信 sock.Send(reqBytes, reqBytes.Length, System.Net.Sockets.SocketFlags.None); //受信する byte[] resBytes = new byte[4096]; System.IO.MemoryStream mem = new System.IO.MemoryStream(); while (true) { int resSize = sock.Receive(resBytes, resBytes.Length, System.Net.Sockets.SocketFlags.None); if (resSize == 0) { break; } mem.Write(resBytes, 0, resSize); } //string resMsg = sjisEnc.GetString(mem.GetBuffer(), 0, (int)mem.Length); mClient.Send(mem.GetBuffer(), (int)mem.Length, SocketFlags.None); //クライアントに返す mem.Close(); //閉じる sock.Shutdown(System.Net.Sockets.SocketShutdown.Both); sock.Close(); return; } //* ここまで *// else { httpHeader = String.Format( "HTTP/" + req_httpversion + " 404 Not Found\r\n" + "Cache-Control: no-cache\r\n" + "\r\n" ); httpHeaderBuffer = Encoding.UTF8.GetBytes(httpHeader); mForm.BeginInvoke(new Action <String>(delegate(String str) { mForm.logoutput("リクエストが不正です。"); }), new object[] { "" }); //mClient.Close(); return; } // HTTPヘッダー生成 gzipの対応はしない。 httpHeader = String.Format( "HTTP/" + req_httpversion + " 200 OK\r\n" + "Cache-Control: no-cache\r\n" + "Content-Type: text/html\r\n" + "Content-Length: " + bodyBuffer.Length + "\r\n" + "\r\n" ); httpHeaderBuffer = Encoding.UTF8.GetBytes(httpHeader); mClient.Send(httpHeaderBuffer); mClient.Send(bodyBuffer, bodyBuffer.Length, SocketFlags.None); } catch (System.IO.IOException) // ファイルかフォルダが見つからない場合⇒まだ作られていない { // HTTPヘッダー生成 0byteを返す httpHeader = String.Format( "HTTP/" + req_httpversion + " 200 OK\r\n" + "Cache-Control: no-cache\r\n" + "Content-Type: text/plain\r\n" + "Content-Length: 0\r\n" + "\r\n" ); httpHeaderBuffer = Encoding.UTF8.GetBytes(httpHeader); mClient.Send(httpHeaderBuffer); } catch (Exception) { httpHeader = String.Format( "HTTP/" + req_httpversion + " 404 Not Found\r\n" + "Cache-Control: no-cache\r\n" + "\r\n" ); httpHeaderBuffer = Encoding.UTF8.GetBytes(httpHeader); mForm.BeginInvoke(new Action <String>(delegate(String str) { mForm.logoutput("例外が発生しました。"); }), new object[] { "" }); } } catch (System.Net.Sockets.SocketException e) { Console.Write(e.Message); } catch (System.ObjectDisposedException e) { Console.Write(e.Message); } catch (Exception e) { Console.Write(e.Message); } finally { mClient.Close(); } }
IEnumerator SaveGame() { // Failsafe if (player && playerCamera && redCube && greenCube && blueCube) { // Prepare a memory stream & a binary writer System.IO.MemoryStream dataStream = new System.IO.MemoryStream(); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(dataStream); // Write player state SerializeTransformToWriter(player.transform, writer); SerializeRigidbodyToWriter(player.rigidbody, writer); // Write player camera state SerializeTransformToWriter(playerCamera.transform, writer); // Write red, green & blue cubes state SerializeTransformToWriter(redCube.transform, writer); SerializeRigidbodyToWriter(redCube.rigidbody, writer); SerializeTransformToWriter(greenCube.transform, writer); SerializeRigidbodyToWriter(greenCube.rigidbody, writer); SerializeTransformToWriter(blueCube.transform, writer); SerializeRigidbodyToWriter(blueCube.rigidbody, writer); // Save game -- make sure directory exists JCloudDocumentOperation operation; operation = JCloudDocument.DirectoryExists("Savegames"); while (!operation.finished) { yield return(null); } // Look for error -- if any, handle & stop coroutine here if (operation.error.HasValue) { HandleDocumentError(operation.error.Value); yield break; } if (!(bool)operation.result) { operation = JCloudDocument.DirectoryCreate("Savegames"); while (!operation.finished) { yield return(null); } // Look for error -- if any, handle & stop coroutine here if (operation.error.HasValue) { HandleDocumentError(operation.error.Value); yield break; } } // Write file operation = JCloudDocument.FileWriteAllBytes("Savegames/My saved game.sav", dataStream.GetBuffer()); while (!operation.finished) { yield return(null); } // Look for error -- if any, handle & stop coroutine here if (operation.error.HasValue) { HandleDocumentError(operation.error.Value); yield break; } } }
public static void Main() { Console.WriteLine("入力してください"); string sendMsg = Console.ReadLine(); if (sendMsg == null || sendMsg.Length == 0) { return; } string ipOrHost = "127.0.0.1"; int port = 2001; System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient(ipOrHost, port); Console.WriteLine("サーバー({0}:{1})と接続しました({2}:{3})。", ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Address, ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Port, ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Address, ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Port); System.Net.Sockets.NetworkStream ns = tcp.GetStream(); ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; System.Text.Encoding enc = System.Text.Encoding.UTF8; byte[] sendBytes = enc.GetBytes(sendMsg + '\n'); ns.Write(sendBytes, 0, sendBytes.Length); Console.WriteLine(sendMsg); System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] resBytes = new byte[256]; int resSize = 0; do { resSize = ns.Read(resBytes, 0, resBytes.Length); if (resSize == 0) { Console.WriteLine("サーバーが切断しました。"); break; } ms.Write(resBytes, 0, resSize); } while (ns.DataAvailable || resBytes[resSize - 1] != '\n'); string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length); ms.Close(); resMsg = resMsg.TrimEnd('\n'); Console.WriteLine(resMsg); ns.Close(); tcp.Close(); Console.WriteLine("切断しました。"); Console.ReadLine(); }
public static void Main() { // サーバに送信するデータを入力してもらう Console.WriteLine("文字列を入力し,Enterキーを押して下さい."); string sendMsg = Console.ReadLine(); // 何も入力されなかった時は終了 if (sendMsg == null || sendMsg.Length == 0) { return; } // サーバのIPアドレスとポート番号 string ipOrHost = "127.0.0.1"; // strinb ipOrHost = "localhost"; int port = 50000; // TcpClientを作成し,サーバと接続する System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient(ipOrHost, port); Console.WriteLine("サーバ({0}:{1})と接続しました({2}:{3}.)", ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Address, ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Port, ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Address, ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Port); // NetworkStreamを取得する System.Net.Sockets.NetworkStream ns = tcp.GetStream(); // サーバにデータを送信する // 文字列をByte型配列に変換 System.Text.Encoding enc = System.Text.Encoding.UTF8; byte[] sendBytes = enc.GetBytes(sendMsg + "\n"); // データを送信する ns.Write(sendBytes, 0, sendBytes.Length); Console.WriteLine(sendMsg); // サーバから送られたデータを受信する System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] resBytes = new byte[256]; int resSize = 0; do { // データの一部を受信する resSize = ns.Read(resBytes, 0, resBytes.Length); // Readが0を返した時はサーバが切断したと判断 if (resSize == 0) { Console.WriteLine("サーバが切断しました"); break; } // 受信したデータを蓄積する ms.Write(resBytes, 0, resSize); } while (ns.DataAvailable || resBytes[resSize - 1] != '\n'); // 受信したデータを文字列に変換 string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length); ms.Close(); // 末尾の\nを削除 resMsg = resMsg.TrimEnd('\n'); Console.WriteLine(resMsg); // 閉じる ns.Close(); tcp.Close(); Console.WriteLine("切断しました."); Console.ReadLine(); }
public static void DumpBuffer(System.IO.MemoryStream ms, string path) => System.IO.File.WriteAllBytes(path, ms.GetBuffer());
public LuaByteBuffer(System.IO.MemoryStream stream) : this() { buffer = stream.GetBuffer(); Length = (int)stream.Length; }
public static void DumpBuffer(System.IO.MemoryStream ms) => System.IO.File.WriteAllBytes(GetUnixFullPath(System.IO.Path.Combine(Memory.FF8DIR, "debugUnpack.debug")), ms.GetBuffer());
private CatalogoWeb ObtenerDatos() { try { CatalogoWeb DatosAux = new CatalogoWeb(); DatosAux.NuevoRegistro = NuevoRegistro; DatosAux.IDImagen = NuevoRegistro ? string.Empty : this._DatosCatWeb.IDImagen; DatosAux.Tag = this.txtTagImagen.Text.Trim(); DatosAux.Alt = this.txtAlt.Text.Trim(); DatosAux.Title = this.txtTitle.Text.Trim(); DatosAux.NombreArchivo = Comun.RemoverAcentos(this.txtNombreImagen.Text.Trim()); DatosAux.Descripcion = this.txtImagenDesc.Text.Trim(); DatosAux.NombrePagina = Comun.RemoverSignosAcentos(this.txtTagImagen.Text.Trim()); if (ModificarImagen) { string Extension = Path.GetExtension(this.FileName); ImageFormat Formato; switch (Extension) { case ".jpg": case ".jpeg": Formato = ImageFormat.Jpeg; break; case ".gif": Formato = ImageFormat.Gif; break; case ".png": Formato = ImageFormat.Png; break; default: Formato = ImageFormat.Jpeg; break; } Image ImagenNormal = Image.FromFile(this.FileUrl); Image ImagenMin = ClasesAux.ComprimirImagen.ResizeImage(ImagenNormal, 200, 150, Formato); Image ImagenDGV = ClasesAux.ComprimirImagen.ResizeImage(ImagenNormal, 40, 40); System.IO.MemoryStream MSNormal = new System.IO.MemoryStream(); System.IO.MemoryStream MSMin = new System.IO.MemoryStream(); ImagenNormal.Save(MSNormal, Formato); ImagenMin.Save(MSMin, Formato); DatosAux.Imagen = ImagenNormal; DatosAux.ImagenMin = ImagenMin; DatosAux.BufferImagen = MSNormal.GetBuffer(); DatosAux.BufferImagenMin = MSMin.GetBuffer(); DatosAux.TipoArchivo = Convert.ToString(Formato); } if (NuevoRegistro == false) { DatosAux.TipoArchivo = this._DatosCatWeb.TipoArchivo; } DatosAux.ModificarImagen = this.ModificarImagen; DatosAux.IDProducto = this.CatalogoActual.IDProducto; DatosAux.IDSucursal = Comun.IDSucursalCaja; DatosAux.Conexion = Comun.Conexion; DatosAux.IDUsuario = Comun.IDUsuario; return(DatosAux); } catch (Exception ex) { throw ex; } }
/// <summary> /// 生成 验证码图片 /// </summary> /// <param name="code">验证码 字符串</param> /// <param name="context">Http Context</param> private void CreateImage(string code, HttpContext context) { _DL_FORMAT.Alignment = StringAlignment.Center; _DL_FORMAT.LineAlignment = StringAlignment.Center; long tick = DateTime.Now.Ticks; Random Rnd = new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32)); using (Bitmap _img = new Bitmap(_WIDTH, _HEIGHT)) { using (Graphics g = Graphics.FromImage(_img)) { g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; Point dot = new Point(20, 20); //// 定义一个无干扰线区间和一个起始位置 int nor = Rnd.Next(53), rsta = Rnd.Next(130); //// 绘制干扰正弦曲线 M:曲线平折度, D:Y轴常量 V:X轴焦距 int M = Rnd.Next(15) + 5, D = Rnd.Next(20) + 15, V = Rnd.Next(5) + 1; int ColorIndex = Rnd.Next(4); float Px_x = 0.0F; float Px_y = Convert.ToSingle((M * Math.Sin(((V * Px_x) * Math.PI) / 180)) + D); float Py_x, Py_y; ////填充背景 g.Clear(_COLOR_BACKGROUND[Rnd.Next(4)]); ////前景刷子 //背景刷子 using (Brush _BrushFace = new SolidBrush(_COLOR_FACE[ColorIndex])) { #region 绘制正弦线 for (int i = 0; i < 131; i++) { ////初始化y点 Py_x = Px_x + 1; Py_y = Convert.ToSingle((M * Math.Sin(((V * Py_x) * Math.PI) / 180)) + D); ////确定线条颜色 if (rsta >= i || i > (rsta + nor)) { ////初始化画笔 using (Pen _pen = new Pen(_BrushFace, Rnd.Next(2, 4) + 1.5F)) { ////绘制线条 g.DrawLine(_pen, Px_x, Px_y, Py_x, Py_y); } } ////交替x,y坐标点 Px_x = Py_x; Px_y = Py_y; } #endregion ////初始化光标的开始位置 g.TranslateTransform(14, 10); #region 绘制校验码字符串 for (int i = 0; i < code.Length; i++) { ////随机旋转 角度 int angle = Rnd.Next(-_ANGLE, _ANGLE); ////移动光标到指定位置 g.TranslateTransform(dot.X, dot.Y); ////旋转 g.RotateTransform(angle); ////初始化字体 ////using (Font _font = new Font(_FONT_FAMIly[Rnd.Next(0, 8)], _FONT_SIZE[Rnd.Next(0, 3)])) using (Font _font = new Font(_FONT_FAMIly[0], _FONT_SIZE[0])) { ////绘制 g.DrawString(code[i].ToString(), _font, _BrushFace, 1, 1, _DL_FORMAT); } ////反转 g.RotateTransform(-angle); ////重新定位光标位置 g.TranslateTransform(2, -dot.Y); } #endregion } } using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { context.Response.ContentType = "Image/PNG"; context.Response.Clear(); context.Response.BufferOutput = true; _img.Save(ms, ImageFormat.Png); ms.Flush(); context.Response.BinaryWrite(ms.GetBuffer()); context.Response.End(); } } }
public static void Main() { //サーバーに送信するデータを入力してもらう Console.WriteLine("文字列を入力し、Enterキーを押してください。"); string sendMsg = Console.ReadLine(); //何も入力されなかった時は終了 if (sendMsg == null || sendMsg.Length == 0) { return; } //サーバーのIPアドレス(または、ホスト名)とポート番号 string ipOrHost = "127.0.0.1"; //string ipOrHost = "localhost"; int port = 2001; //TcpClientを作成し、サーバーと接続する System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient(ipOrHost, port); Console.WriteLine("サーバー({0}:{1})と接続しました({2}:{3})。", ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Address, ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Port, ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Address, ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Port); //NetworkStreamを取得する System.Net.Sockets.NetworkStream ns = tcp.GetStream(); //読み取り、書き込みのタイムアウトを10秒にする //デフォルトはInfiniteで、タイムアウトしない //(.NET Framework 2.0以上が必要) ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; //サーバーにデータを送信する //文字列をByte型配列に変換 System.Text.Encoding enc = System.Text.Encoding.UTF8; byte[] sendBytes = enc.GetBytes(sendMsg + '\n'); //データを送信する ns.Write(sendBytes, 0, sendBytes.Length); Console.WriteLine(sendMsg); //サーバーから送られたデータを受信する System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] resBytes = new byte[256]; int resSize = 0; do { //データの一部を受信する resSize = ns.Read(resBytes, 0, resBytes.Length); //Readが0を返した時はサーバーが切断したと判断 if (resSize == 0) { Console.WriteLine("サーバーが切断しました。"); break; } //受信したデータを蓄積する ms.Write(resBytes, 0, resSize); //まだ読み取れるデータがあるか、データの最後が\nでない時は、 // 受信を続ける } while (ns.DataAvailable || resBytes[resSize - 1] != '\n'); //受信したデータを文字列に変換 string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length); ms.Close(); //末尾の\nを削除 resMsg = resMsg.TrimEnd('\n'); Console.WriteLine(resMsg); //閉じる ns.Close(); tcp.Close(); Console.WriteLine("切断しました。"); Console.ReadLine(); }
public static void Main() { // ListenするIPアドレス string ipString = "127.0.0.1"; System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(ipString); // Listenするポート番号 int port = 2001; // TcpListenerオブジェクトの作成 System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(ipAdd, port); // Listenを開始 listener.Start(); Console.WriteLine("Listenを開始しました({0}:{1}).", ((System.Net.IPEndPoint)listener.LocalEndpoint).Address, ((System.Net.IPEndPoint)listener.LocalEndpoint).Port); // 接続要求があったら受け入れる System.Net.Sockets.TcpClient client = listener.AcceptTcpClient(); Console.WriteLine("クライアント({0}:{1})と接続しました.", ((System.Net.IPEndPoint)listener.LocalEndpoint).Address, ((System.Net.IPEndPoint)listener.LocalEndpoint).Port); // NetworkStreamを取得 System.Net.Sockets.NetworkStream ns = client.GetStream(); // 読取り,書き込みのタイムアウトを10秒にする // デフォルトはInfiniteでタイムアウトしない // (.NET Framework 2.0以上が必要 ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; // クライアントから送られたデータを受信する System.Text.Encoding enc = System.Text.Encoding.UTF8; bool disconnected = false; System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] resBytes = new byte[256]; int resSize = 0; do { // データの一部を受信する resSize = ns.Read(resBytes, 0, resBytes.Length); // Readが0を返した時はクライアントが切断したと判断 if (resSize == 0) { disconnected = true; Console.WriteLine("クライアントが切断しました."); break; } // 受信したデータを蓄積する ms.Write(resBytes, 0, resSize); // まだ読み取れるデータがあるか,データの最後が\n出ない時は,受信を続ける } while (ns.DataAvailable || resBytes[resSize - 1] != '\n'); // 受信したデータを文字列に変換 string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length); ms.Close(); // 末尾の\nを削除 resMsg = resMsg.TrimEnd('\n'); Console.WriteLine(resMsg); if (!disconnected) { // クライアントにデータを送信する // クライアントに送信する文字列を作成 string sendMsg = resMsg.Length.ToString(); // 文字列をByte型配列に変換 byte[] sendBytes = enc.GetBytes(sendMsg + "\n"); // データを送信する ns.Write(sendBytes, 0, sendBytes.Length); Console.WriteLine(sendMsg); } // 閉じる ns.Close(); client.Close(); Console.WriteLine("クライアントとの接続を閉じました."); // リスナを閉じる listener.Stop(); Console.WriteLine("Listenerを閉じました."); Console.ReadLine(); }
//导出PDF public ActionResult ImportFile() { try { string typeData = "日"; string typeData2 = "月"; DateTime dateTT; //try //{ // dateTT = Convert.ToDateTime(date); //} //catch (Exception) //{ // return Content("<script>alert('日期格式不正确');</script>"); //} //导出日报 //string date1 = dateTT.ToString("yyyyMM") + "01"; //string date2 = Convert.ToDateTime(date).ToString("yyyyMMdd"); //list = new IncomingHeatDao().GetReportData(date1, date2); //字体读取的是windows系统宋体 BaseFont baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); iTextSharp.text.Font font = new Font(baseFont, 10); //设置字体为宋体和大小 iTextSharp.text.Font font2 = new Font(baseFont, 9); //设置字体为宋体和大小 //font.Color = BaseColor.BLUE;//字体颜色 iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.A4.Rotate(), 15, 15, 15, 15); System.IO.MemoryStream stream = new System.IO.MemoryStream(); PdfWriter.GetInstance(document, stream); document.Open(); document.AddTitle("入厂入炉热值差" + typeData + "报表"); Paragraph element = new Paragraph("入厂入炉热值差" + typeData + "报表", font); element.SpacingAfter = 10; //设置离后面内容的间距 element.Alignment = Element.ALIGN_CENTER; document.Add(element); //打印时间 Paragraph element2 = new Paragraph("打印时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm"), font); element2.SpacingAfter = 5; //设置离后面内容的间距 document.Add(element2); PdfPTable table = new PdfPTable(15); table.WidthPercentage = 100; //设置表格宽度占用百分比 //table.SetTotalWidth(new float[] { 90f, 90f, 150f, 90f, 150f, 90f, 150f, 90f, 150f, 90f, 150f, 90f, 150f, 150f, 150f }); #region 表头 //第一行表头 PdfPCell cell = new PdfPCell(new Paragraph("时间", font)); cell.Rowspan = 3; cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; //水平居中 table.AddCell(cell); cell = new PdfPCell(new Paragraph("入厂煤", font)); cell.Colspan = 4; //定义一个表格单元的跨度 cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; //水平居中 table.AddCell(cell); cell = new PdfPCell(new Paragraph("入炉煤", font)); cell.Colspan = 8; //定义一个表格单元的跨度 cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; //水平居中 table.AddCell(cell); cell = new PdfPCell(new Paragraph("入厂入炉热值差", font)); cell.Colspan = 2; //定义一个表格单元的跨度 cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; //水平居中 //cell.FixedHeight = 130f;//设置高度 table.AddCell(cell); //第二行 cell = new PdfPCell(new Paragraph("全厂当" + typeData, font)); cell.Colspan = 2; //定义一个表格单元的跨度 cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; //水平居中 table.AddCell(cell); //cell = new PdfPCell(new Paragraph("全厂" + typeData2 + "累计", font)); //cell.Colspan = 2;//定义一个表格单元的跨度 //cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 //cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;//水平居中 //table.AddCell(cell); cell = new PdfPCell(new Paragraph("一二期入炉", font)); cell.Colspan = 2; //定义一个表格单元的跨度 cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; //水平居中 table.AddCell(cell); cell = new PdfPCell(new Paragraph("三期入炉", font)); cell.Colspan = 2; //定义一个表格单元的跨度 cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; //水平居中 table.AddCell(cell); cell = new PdfPCell(new Paragraph("全厂当" + typeData, font)); cell.Colspan = 2; //定义一个表格单元的跨度 cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; //水平居中 table.AddCell(cell); //cell = new PdfPCell(new Paragraph("全厂" + typeData2 + "累计", font)); //cell.Colspan = 2;//定义一个表格单元的跨度 //cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 //cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;//水平居中 //table.AddCell(cell); cell = new PdfPCell(new Paragraph("全厂当" + typeData, font)); cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; //水平居中 table.AddCell(cell); //cell = new PdfPCell(new Paragraph("全厂" + typeData2 + "累计", font)); //cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 //cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;//水平居中 //table.AddCell(cell); string[] titleArr = { "吨量(t)", "热值(kj/kg)", "吨量(t)", "热值(kj/kg)", "吨量(t)", "热值(kj/kg)", "吨量(t)", "热值(kj/kg)", "吨量(t)", "热值(kj/kg)", "吨量(t)", "热值(kj/kg)", "热值(kj/kg)", "热值(kj/kg)" }; foreach (var item in titleArr) { cell = new PdfPCell(new Paragraph(item, font)); cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; //水平居中 table.AddCell(cell); } #endregion var list = new List <pdfData> { new pdfData { date = "1", qcdd_wt = "66" }, new pdfData { date = "2", qcdd_wt = "77" } }; #region 数据载入 foreach (var item in list) { PdfPCell cell_data = new PdfPCell(new Paragraph(item.date, font)); //时间 cell_data.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 cell_data.HorizontalAlignment = PdfPCell.ALIGN_CENTER; //水平居中 table.AddCell(cell_data); cell_data = new PdfPCell(new Paragraph(item.qcdd_wt.ToString(), font)); //全厂当日吨量 cell_data.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 cell_data.HorizontalAlignment = PdfPCell.ALIGN_CENTER; //水平居中 table.AddCell(cell_data); //cell_data = new PdfPCell(new Paragraph(item.qcdd_qr.ToString(), font));//全厂当日热值 //cell_data.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 //cell_data.HorizontalAlignment = PdfPCell.ALIGN_CENTER;//水平居中 //table.AddCell(cell_data); //cell_data = new PdfPCell(new Paragraph(item.qcmmsum_wt.ToString(), font));//全厂当月累计吨量 //cell_data.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 //cell_data.HorizontalAlignment = PdfPCell.ALIGN_CENTER;//水平居中 //table.AddCell(cell_data); //cell_data = new PdfPCell(new Paragraph(item.qcmmsum_qr.ToString(), font));//全厂当月累计热值 //cell_data.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 //cell_data.HorizontalAlignment = PdfPCell.ALIGN_CENTER;//水平居中 //table.AddCell(cell_data); //cell_data = new PdfPCell(new Paragraph(item.rulu12_wt.ToString(), font));//一二期入炉吨量 //cell_data.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 //cell_data.HorizontalAlignment = PdfPCell.ALIGN_CENTER;//水平居中 //table.AddCell(cell_data); //cell_data = new PdfPCell(new Paragraph(item.rulu12_qr.ToString(), font));//一二期入炉热值 //cell_data.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 //cell_data.HorizontalAlignment = PdfPCell.ALIGN_CENTER;//水平居中 //table.AddCell(cell_data); //cell_data = new PdfPCell(new Paragraph(item.rulu3_wt.ToString(), font));//三期入炉吨量 //cell_data.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 //cell_data.HorizontalAlignment = PdfPCell.ALIGN_CENTER;//水平居中 //table.AddCell(cell_data); //cell_data = new PdfPCell(new Paragraph(item.rulu3_qr.ToString(), font));//三期入炉热值 //cell_data.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 //cell_data.HorizontalAlignment = PdfPCell.ALIGN_CENTER;//水平居中 //table.AddCell(cell_data); //cell_data = new PdfPCell(new Paragraph(item.ruluqcddsum_wt.ToString(), font));//全厂当日入炉吨量 //cell_data.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 //cell_data.HorizontalAlignment = PdfPCell.ALIGN_CENTER;//水平居中 //table.AddCell(cell_data); //cell_data = new PdfPCell(new Paragraph(item.ruluqcddsum_qr.ToString(), font));//全厂当日入炉热值 //cell_data.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 //cell_data.HorizontalAlignment = PdfPCell.ALIGN_CENTER;//水平居中 //table.AddCell(cell_data); //cell_data = new PdfPCell(new Paragraph(item.ruluqcmmsum_wt.ToString(), font));//全厂月累计入炉吨量 //cell_data.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 //cell_data.HorizontalAlignment = PdfPCell.ALIGN_CENTER;//水平居中 //table.AddCell(cell_data); //cell_data = new PdfPCell(new Paragraph(item.ruluqcmmsum_qr.ToString(), font));//全厂月累计入炉热值 //cell_data.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 //cell_data.HorizontalAlignment = PdfPCell.ALIGN_CENTER;//水平居中 //table.AddCell(cell_data); //cell_data = new PdfPCell(new Paragraph(item.qccha_qr1.ToString(), font));//入厂入炉热值差,全厂当日 //cell_data.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 //cell_data.HorizontalAlignment = PdfPCell.ALIGN_CENTER;//水平居中 //table.AddCell(cell_data); //cell_data = new PdfPCell(new Paragraph(item.qccha_qr2.ToString(), font));//入厂入炉热值差,全厂月累计 //cell_data.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; //垂直居中 //cell_data.HorizontalAlignment = PdfPCell.ALIGN_CENTER;//水平居中 //table.AddCell(cell_data); } #endregion document.Add(table); document.Close(); byte[] fileBytes = stream.GetBuffer(); stream.Close(); stream.Dispose(); return(File(fileBytes, "application/pdf", DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf")); } catch (Exception ex) { string msg = string.Empty; if (ex.InnerException != null) { msg = ex.InnerException.Message; } else { msg = ex.Message; } return(Content("<script>alert(\"异常:" + msg + "\");</script>")); } }
public static void Main() { string ipString = "127.0.0.1"; System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(ipString); int port = 2001; System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(ipAdd, port); listener.Start(); Console.WriteLine("Listenを開始しました({0}:{1})。", ((System.Net.IPEndPoint)listener.LocalEndpoint).Address, ((System.Net.IPEndPoint)listener.LocalEndpoint).Port); // 接続要求があったら受け入れる System.Net.Sockets.TcpClient client = listener.AcceptTcpClient(); Console.WriteLine("クライアント({0}:{1})と接続しました。", ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Address, ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Port); // NetworkStreamを取得データの流れ System.Net.Sockets.NetworkStream ns = client.GetStream(); ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; System.Text.Encoding enc = System.Text.Encoding.UTF8; bool disconnected = false; System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] resBytes = new byte[256]; int resSize = 0; do { //データの一部を受信する resSize = ns.Read(resBytes, 0, resBytes.Length); //Readが0を返した時はクライアントが切断したと判断 if (resSize == 0) { disconnected = true; Console.WriteLine("クライアントが切断しました。"); break; } //受信したデータを蓄積する ms.Write(resBytes, 0, resSize); //まだ読み取れるデータがあるか、データの最後が\nでない時は、 // 受信を続ける } while (ns.DataAvailable || resBytes[resSize - 1] != '\n'); //受信したデータを文字列に変換 string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length); ms.Close(); resMsg = resMsg.TrimEnd('\n'); Console.WriteLine(resMsg); if (!disconnected) { //クライアントにデータを送信する //クライアントに送信する文字列を作成 string sendMsg = resMsg.Length.ToString(); //文字列をByte型配列に変換 byte[] sendBytes = enc.GetBytes(sendMsg + '\n'); //データを送信する ns.Write(sendBytes, 0, sendBytes.Length); Console.WriteLine(sendMsg); } ns.Close(); client.Close(); Console.WriteLine("クライアントとの接続を閉じました。"); listener.Stop(); Console.WriteLine("Listenerを閉じました。"); Console.ReadLine(); }
private void WriteXmlItem(Mvc5RQ.Models.RQItem rqItem, Stream writeStream) { if (rqItem != null) { var dSer = new DataContractSerializer(typeof(Mvc5RQ.Models.RQItem)); try { System.IO.MemoryStream ms = new System.IO.MemoryStream(); var xTrf = new System.Xml.Xsl.XslCompiledTransform(); var xSet = new System.Xml.Xsl.XsltSettings(enableDocumentFunction: true, enableScript: true); dSer.WriteObject(ms, rqItem); System.IO.TextReader tr = new System.IO.StringReader(System.Text.Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Position)); xTrf.Load(rqItem.FormatPreprocessor.XmlTransformPath, xSet, new System.Xml.XmlUrlResolver()); xTrf.Transform(new System.Xml.XPath.XPathDocument(tr), rqItem.FormatPreprocessor.XslTransformArg, writeStream); } catch { throw new NotImplementedException("Could not find a RiQuest item with requested document number."); } } }
private void toolStripMenuItem4_Click(object sender, EventArgs e) { if (validar_mail(txtCorreo.Text) == false) { MessageBox.Show("Direccion de correo electrónico no validada, el correo debe tener el formato: [email protected], " + "por favor seleccione un correo valido", "Validación de correo electrónico", MessageBoxButtons.OK, MessageBoxIcon.Question); txtCorreo.Focus(); txtCorreo.SelectAll(); } else { if (txtNombre.Text != "") { if (txtrol.Text != "") { if (lblAnuncioIcono.Visible == false) { try { SqlConnection con = new SqlConnection(); con.ConnectionString = CONEXION.CONEXIONMAESTRA.conexion; con.Open(); SqlCommand cmd = new SqlCommand(); cmd = new SqlCommand("insertar_usuario", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@nombres", txtNombre.Text); cmd.Parameters.AddWithValue("@Login", txtLogin.Text); cmd.Parameters.AddWithValue("@Password", txtPassword.Text); cmd.Parameters.AddWithValue("@Correo", txtCorreo.Text); cmd.Parameters.AddWithValue("@Rol", txtrol.Text); System.IO.MemoryStream ms = new System.IO.MemoryStream(); ICONO.Image.Save(ms, ICONO.Image.RawFormat); cmd.Parameters.AddWithValue("@Icono", ms.GetBuffer()); cmd.Parameters.AddWithValue("@Nombre_de_icono", lblnumeroIcono.Text); cmd.Parameters.AddWithValue("@Estado", "ACTIVO"); cmd.ExecuteNonQuery(); con.Close(); mostrar(); panel4.Visible = false; } catch (Exception ex) { MessageBox.Show(ex.Message); } } else { MessageBox.Show("Elija un icono", "Registro", MessageBoxButtons.OK); } } else { MessageBox.Show("Elija un rol", "Registro", MessageBoxButtons.OK); } } else { MessageBox.Show("Introduzca su nombre", "Registro", MessageBoxButtons.OK); } } }
public async Task ClientConnect() { //サーバーに送信するデータを入力してもらう //System.Console.WriteLine("文字列を入力し、Enterキーを押してください。"); string sendMsg = "heliiw";//System.Console.ReadLine(); //何も入力されなかった時は終了 //if (sendMsg == null || sendMsg.Length == 0) //{ // return ""; //} //try //{ //TcpClientを作成し、サーバーと接続する System.Net.Sockets.TcpClient tcp = await Task.Run(() => new System.Net.Sockets.TcpClient(ipOrHost, port)); System.Console.WriteLine("サーバー({0}:{1})と接続しました({2}:{3})。", ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Address, ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Port, ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Address, ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Port); //} //catch (IOException e) //{ // System.Console.WriteLine("文字列を入力し、Enterキーを押してください。" + e); //} //catch (IOException e) //{ // System.Console.WriteLine("文字列を入力し、Enterキーを押してください。"+e); //} //NetworkStreamを取得する System.Net.Sockets.NetworkStream ns = tcp.GetStream(); //読み取り、書き込みのタイムアウトを10秒にする //デフォルトはInfiniteで、タイムアウトしない //(.NET Framework 2.0以上が必要) ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; //サーバーにデータを送信する //文字列をByte型配列に変換 System.Text.Encoding enc = System.Text.Encoding.UTF8; byte[] sendBytes = enc.GetBytes(sendMsg + '\n'); //データを送信する ns.Write(sendBytes, 0, sendBytes.Length); System.Console.WriteLine(sendMsg); //サーバーから送られたデータを受信する System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] resBytes = new byte[256]; int resSize = 0; do { //データの一部を受信する resSize = ns.Read(resBytes, 0, resBytes.Length); //Readが0を返した時はサーバーが切断したと判断 if (resSize == 0) { System.Console.WriteLine("サーバーが切断しました。"); break; } //受信したデータを蓄積する ms.Write(resBytes, 0, resSize); //まだ読み取れるデータがあるか、データの最後が\nでない時は、 // 受信を続ける } while (ns.DataAvailable || resBytes[resSize - 1] != '\n'); //受信したデータを文字列に変換 string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length); ms.Close(); //末尾の\nを削除 resMsg = resMsg.TrimEnd('\n'); System.Console.WriteLine(resMsg); //閉じる ns.Close(); tcp.Close(); System.Console.WriteLine("切断しました。"); System.Console.ReadLine(); //return "message1"; }
//Fonction: Envoie de l'image public bool Envoi_image(System.Drawing.Image image) { Program.LogFich.Info("[Topaz_Manager] Envoi_image() - Envoie des données"); bool b = true; MemoryStream mstImage = new MemoryStream(); image.Save(mstImage, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] data = mstImage.GetBuffer(); mstImage.Dispose(); //StringBuilder dataSB = new StringBuilder(); //IntPtr dataPtr = Marshal.AllocHGlobal(data.Length); /* * for (int i = 0; i < data.Length; ++i) * { * data[i] = Marshal.ReadByte(dataPtr, i); * dataSB.Append(data[i]); * } */ try { Uri url = new Uri(urlapp.ToString() + "devices/TOPAZ_SIGPLUS.asp"); //StringBuilder sb = new StringBuilder(); //sb.Append("type_peripherique=").Append(HttpUtility.UrlEncode("TOPAZ_SIGPLUS", Encoding.ASCII)); //sb.Append("&machine=").Append(HttpUtility.UrlEncode(Functions.getHost(), Encoding.ASCII)); //sb.Append("data=").Append(HttpUtility.UrlEncode(data.ToString(), Encoding.ASCII)); //sb.Append("&datalen=").Append(HttpUtility.UrlEncode(data.Length.ToString(), Encoding.ASCII)); string boundary = DateTime.Now.Ticks.ToString("x"); MemoryStream memStream = new System.IO.MemoryStream(); byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); string headerTemplate = "Content-Disposition: form-data; name=\"signature\"; filename=\"signature.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n"; byte[] headerbytes = System.Text.Encoding.ASCII.GetBytes(headerTemplate); memStream.Write(boundarybytes, 0, boundarybytes.Length); memStream.Write(headerbytes, 0, headerbytes.Length); memStream.Write(data, 0, data.Length); memStream.Write(boundarybytes, 0, boundarybytes.Length); memStream.Position = 0; byte[] postBytes = memStream.GetBuffer(); memStream.Dispose(); string s = System.Text.Encoding.ASCII.GetString(postBytes); StringBuilder adr = new StringBuilder(); adr.Append(url.ToString()); adr.Append(this.WebBrowser.Url.Query); Uri adresse = new Uri(adr.ToString()); WebBrowser.Navigate(adresse, "", postBytes, "Content-Type: multipart/form-data; boundary=" + boundary + "\r\n" + "Content-Length: " + postBytes.Length + "\r\n" + "\r\n"); Program.LogFich.Info("[Topaz_Manager] Envoi_image() - Envoie termine - Trame envoyee = " + postBytes.ToString()); } catch (Exception e) { b = false; Program.LogFich.Error("[Topaz_Manager] Envoi_image() - Erreur d'envoie = " + e.ToString()); } return(b); }
public static float[] FloatArrayFromStream(System.IO.MemoryStream stream) { return(FloatArrayFromByteArray(stream.GetBuffer())); }
public async Task ServerConnect() { //int port = 3333; //ListenするIPアドレス string ipString = "127.0.0.1"; System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(ipString); //ホスト名からIPアドレスを取得する時は、次のようにする //string host = "localhost"; //System.Net.IPAddress ipAdd = // System.Net.Dns.GetHostEntry(host).AddressList[0]; //.NET Framework 1.1以前では、以下のようにする //System.Net.IPAddress ipAdd = // System.Net.Dns.Resolve(host).AddressList[0]; //Listenするポート番号 //int port = 2001; //TcpListenerオブジェクトを作成する System.Net.Sockets.TcpListener listener = await Task.Run(() => new System.Net.Sockets.TcpListener(ipAdd, port)); //Listenを開始する listener.Start(); System.Console.WriteLine("Listenを開始しました({0}:{1})。", ((System.Net.IPEndPoint)listener.LocalEndpoint).Address, ((System.Net.IPEndPoint)listener.LocalEndpoint).Port); //接続要求があったら受け入れる System.Net.Sockets.TcpClient client = listener.AcceptTcpClient(); System.Console.WriteLine("クライアント({0}:{1})と接続しました。", ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Address, ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Port); //NetworkStreamを取得 System.Net.Sockets.NetworkStream ns = client.GetStream(); //読み取り、書き込みのタイムアウトを10秒にする //デフォルトはInfiniteで、タイムアウトしない //(.NET Framework 2.0以上が必要) ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; //クライアントから送られたデータを受信する System.Text.Encoding enc = System.Text.Encoding.UTF8; bool disconnected = false; System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] resBytes = new byte[256]; int resSize = 0; do { //データの一部を受信する resSize = ns.Read(resBytes, 0, resBytes.Length); //Readが0を返した時はクライアントが切断したと判断 if (resSize == 0) { disconnected = true; System.Console.WriteLine("クライアントが切断しました。"); break; } //受信したデータを蓄積する ms.Write(resBytes, 0, resSize); //まだ読み取れるデータがあるか、データの最後が\nでない時は、 // 受信を続ける } while (ns.DataAvailable || resBytes[resSize - 1] != '\n'); //受信したデータを文字列に変換 string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length); ms.Close(); //末尾の\nを削除 resMsg = resMsg.TrimEnd('\n'); System.Console.WriteLine(resMsg); if (!disconnected) { //クライアントにデータを送信する //クライアントに送信する文字列を作成 string sendMsg = resMsg.Length.ToString(); //文字列をByte型配列に変換 byte[] sendBytes = enc.GetBytes(sendMsg + '\n'); //データを送信する ns.Write(sendBytes, 0, sendBytes.Length); System.Console.WriteLine(sendMsg); } //閉じる ns.Close(); client.Close(); System.Console.WriteLine("クライアントとの接続を閉じました。"); //リスナを閉じる listener.Stop(); System.Console.WriteLine("Listenerを閉じました。"); System.Console.ReadLine(); }
/// <summary> /// 获取Code图片二进制 /// </summary> /// <returns></returns> private byte[] GetImageBuffer() { string FontFamily = "Arial"; Brush Foreground = Brushes.Navy; Color Background = Color.Silver; if (m_CodeValue != "") { using (Bitmap bmp = new Bitmap(m_ImageWidth, m_ImageHeight)) using (Graphics g = Graphics.FromImage(bmp)) using (Font font = new Font(FontFamily, 1f)) { g.Clear(Background); // Perform trial rendering to determine best font size SizeF finalSize; SizeF testSize = g.MeasureString(m_CodeValue, font); float bestFontSize = Math.Min(m_ImageWidth / testSize.Width, m_ImageHeight / testSize.Height);// *0.95f; using (Font finalFont = new Font(FontFamily, bestFontSize)) { finalSize = g.MeasureString(m_CodeValue, finalFont); } // Get a path representing the text centered on the canvas g.PageUnit = GraphicsUnit.Point; PointF textTopLeft = new PointF((m_ImageWidth - finalSize.Width) / 2, (m_ImageHeight - finalSize.Height) / 2); using (GraphicsPath path = new GraphicsPath()) { path.AddString(m_CodeValue, new FontFamily(FontFamily), 0, bestFontSize, textTopLeft, StringFormat.GenericDefault); //生成随机生成器 Random random = new Random(); //清空图片背景色 g.Clear(Color.White); //画图片的背景噪音线 for (int i = 0; i < m_NoiseLine; i++) { int x1 = random.Next(bmp.Width); int x2 = random.Next(bmp.Width); int y1 = random.Next(bmp.Height); int y2 = random.Next(bmp.Height); g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); } // Render the path to the bitmap g.SmoothingMode = SmoothingMode.HighQuality; //未处理正常字体 g.FillPath(Foreground, path); g.FillPath(Foreground, DeformPath(path)); //画图片的前景噪音点 for (int i = 0; i < m_NoisePoint; i++) { int x = random.Next(bmp.Width); int y = random.Next(bmp.Height); bmp.SetPixel(x, y, Color.FromArgb(random.Next())); } //画图片的边框线 if (m_DrawBorder) { g.DrawRectangle(new Pen(Color.Silver), 0, 0, bmp.Width - 1, bmp.Height - 1); } g.Flush(); //将图像保存到指定的流 System.IO.MemoryStream ms = new System.IO.MemoryStream(); bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); return(ms.GetBuffer()); } } } return(new byte[0]); }
private ImageData load_image(Image img) { int width = img.Width; int height = img.Height; int targetWidth = 480, targetHeight = 640; int wRatio = 1, hRatio = 1; if (width > targetWidth) { wRatio = width / targetWidth; } if (height > targetHeight) { hRatio = height / targetHeight; } if (wRatio > 1 || hRatio > 1) { if (wRatio > hRatio) { width = targetWidth; height = ((height / wRatio) >> 2) << 2; img = resizeImage(img, new Size(width, height)); } else { width = ((width / hRatio) >> 2) << 2; height = targetHeight; img = resizeImage(img, new Size(width, height)); } } ImageData imageData = new ImageData(); imageData.Width = width; imageData.Height = height; byte[] result; using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { img.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp); // convert png to bmp result = stream.GetBuffer(); } byte[] image = new byte[width * height * 4]; int offset = 54; int iIndex = 0; int iRowIndex = 0; int iPixelBytes = 4; if (img.PixelFormat == System.Drawing.Imaging.PixelFormat.Format24bppRgb) { iPixelBytes = 3; } int iWidth = width * iPixelBytes; for (int i = height - 1; i >= 0; --i) { iRowIndex = i * iWidth; for (int j = 0; j < iWidth; j += iPixelBytes) { if (iPixelBytes == 3) { image[iIndex++] = result[iRowIndex + j + 2 + offset]; // B image[iIndex++] = result[iRowIndex + j + 1 + offset]; // G image[iIndex++] = result[iRowIndex + j + offset]; // R image[iIndex++] = 255; // A } else { image[iIndex++] = result[iRowIndex + j + 2 + offset]; // B image[iIndex++] = result[iRowIndex + j + 1 + offset]; // G image[iIndex++] = result[iRowIndex + j + offset]; // R image[iIndex++] = result[iRowIndex + j + 3 + offset]; // A } } } imageData.Data = image; return(imageData); }