Search Results

Search found 355 results on 15 pages for 'memorystream'.

Page 13/15 | < Previous Page | 9 10 11 12 13 14 15  | Next Page >

  • Serialization of Queue type- Serialization not working; C#

    - by Soham
    Hi All, Consider this piece of code: private Queue Date=new Queue(); //other declarations public DateTime _Date { get { return (DateTime)Date.Peek();} set { Date.Enqueue(value); } } //other properties and stuff.... public void UpdatePosition(...) { //other code IFormatter formatter = new BinaryFormatter(); Stream Datestream = new MemoryStream(); formatter.Serialize(Datestream, Date); byte[] Datebin = new byte[2048]; Datestream.Read(Datebin,0,2048); //Debug-Bug Console.WriteLine(Convert.ToString(this._Date)); Console.WriteLine(BitConverter.ToString(Datebin, 0, 3)); //other code } The output of the first writeline is perfect. I.e to check if really the Queue is initialised or not. It is. The right variables are stored and et. all [I inserted a value in that Q, that part of the code is not shown] But the second writeline is not giving the right expected answer: It serializes the entire Queue to 00-00-00. Want some serious help! Soham

    Read the article

  • The file is damaged and could not be repaired

    - by acadia
    Hello Experts, I am trying to display a PDF file in my ASP.net page based on the binary data received from the ASP.net Web service. Below is the code. though I am getting the data from the Web Service for some reason, if I run the below mentioned code on page load I am getting the above mentioned error. Please help Response.Buffer = True Response.ContentType = "application/pdf" Response.AddHeader("Content-Disposition", "Inline") Dim ws As New imageGenService.Service1 Dim imagebyte As Byte() = Nothing imagebyte = ws.generateSamplePDF() If imagebyte IsNot Nothing Then '"attachment; filename=Whatever.pdf" Dim MemStream As New System.IO.MemoryStream Dim doc As New iTextSharp.text.Document Dim reader As iTextSharp.text.pdf.PdfReader Dim numberOfPages As Integer Dim currentPageNumber As Integer Dim writer As iTextSharp.text.pdf.PdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, MemStream) doc.Open() Dim cb As iTextSharp.text.pdf.PdfContentByte = writer.DirectContent Dim page As iTextSharp.text.pdf.PdfImportedPage Dim rotation As Integer reader = New iTextSharp.text.pdf.PdfReader(imagebyte) numberOfPages = reader.NumberOfPages currentPageNumber = 0 Do While (currentPageNumber < numberOfPages) currentPageNumber += 1 doc.SetPageSize(PageSize.LETTER) doc.NewPage() page = writer.GetImportedPage(reader, currentPageNumber) rotation = reader.GetPageRotation(currentPageNumber) If (rotation = 90) Or (rotation = 270) Then cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(currentPageNumber).Height) Else cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0) End If Loop If MemStream Is Nothing Then Response.Write("No Data is available for output") Else Response.BinaryWrite(MemStream.GetBuffer()) End If End If

    Read the article

  • Creating a shim Stream

    - by spender
    A decompression API that I am using has the following API: Decode(Stream inStream,Stream outStream) I'd like to create a wrapper around this API, such that I can create my own Stream class which offers up the decoded data. Stream decodedStream=new BlaDecodeStream(inStream); So that I can than use this stream as a parameter to the XmlReader constructor in the same way one might use the System.IO.Compression.GZipStream. As far as I can tell, the only other option is set outStream stream to a MemoryStream or to a FileStream and go in two hops. The files I am dealing with are enormous, so neither of these options are particularly attractive. Before I go reinventing the wheel, is there any prior art that I might be able to draw from, or something in the BCL I might have missed? The CircularStream implementation here would go some of the way to helping, but I'm really looking for something similar that would block (as opposed to over/underrun) when the Stream's internal buffer is 'empty' when reading from it and block when the internal buffer is full when writing to it. In this way it could serve as parameter outStream and simultaneously (i.e. from another thread) could be read from by the XmlReader.

    Read the article

  • GZIP Java vs .NET

    - by Jim Jones
    Using the following Java code to compress/decompress bytes[] to/from GZIP. First text bytes to gzip bytes: public static byte[] fromByteToGByte(byte[] bytes) { ByteArrayOutputStream baos = null; try { ByteArrayInputStream bais = new ByteArrayInputStream(bytes); baos = new ByteArrayOutputStream(); GZIPOutputStream gzos = new GZIPOutputStream(baos); byte[] buffer = new byte[1024]; int len; while((len = bais.read(buffer)) >= 0) { gzos.write(buffer, 0, len); } gzos.close(); baos.close(); } catch (IOException e) { e.printStackTrace(); } return(baos.toByteArray()); } Then the method that goes the other way compressed bytes to uncompressed bytes: public static byte[] fromGByteToByte(byte[] gbytes) { ByteArrayOutputStream baos = null; ByteArrayInputStream bais = new ByteArrayInputStream(gbytes); try { baos = new ByteArrayOutputStream(); GZIPInputStream gzis = new GZIPInputStream(bais); byte[] bytes = new byte[1024]; int len; while((len = gzis.read(bytes)) > 0) { baos.write(bytes, 0, len); } } catch (IOException e) { e.printStackTrace(); } return(baos.toByteArray()); } Think there is any effect since I'm not writing out to a gzip file? Also I noticed that in the standard C# function that BitConverter reads the first four bytes and then the MemoryStream Write function is called with a start point of 4 and a length of input buffer length - 4. So is that effect the validity of the header? Jim

    Read the article

  • VB.net Saving an MetaFile / EMF as a bitmap ( .tiff)

    - by pehaada
    Currently I have a third party control that generates a Metafile. I can save the .wmf file to disk with out issue. The problem is how do I render the Metafile as a Tiff file. Currently I have the following code to get my metafile and save it. Dim mf As Metafile = page.GetImage(TXTextControl.Page.PageContent.All) Dim enhMetafileHandle As IntPtr = mf.GetHenhmetafile() Dim h As IntPtr Dim bufferSize As UInteger = GetEnhMetaFileBits(enhMetafileHandle, 0, h) Dim buffer(CInt(bufferSize)) As Byte GetEnhMetaFileBits(enhMetafileHandle, bufferSize, buffer) Dim msMetafileStream As New MemoryStream msMetafileStream.Write(buffer, 0, CInt(bufferSize)) Dim baMetafileData() As Byte baMetafileData = msMetafileStream.ToArray Dim g As Graphics = Graphics.FromImage(mf) mf.Dispose() File.WriteAllBytes("c:\a.wmf", baMetafileData) end sub _ Public Shared Function GetEnhMetaFileBits( ByVal hEMF As System.IntPtr, ByVal nSize As UInteger, ByVal lpData As IntPtr) As UInteger End Function <System.Runtime.InteropServices.DllImportAttribute("gdi32.dll", EntryPoint:="GetEnhMetaFileBits")> _ Public Shared Function GetEnhMetaFileBits(<System.Runtime.InteropServices.InAttribute()> ByVal hEMF As System.IntPtr, ByVal nSize As UInteger, ByVal lpData() As Byte) As UInteger End Function I've tried all sort of IMAGE and Graphic calls and just can't save the meta file as a .tiff. Any suggestions would be great. I even tried to create a new bitmap and draw the metafile onto it. I always end up with a GDI exception being thrown.

    Read the article

  • How to Display a Bmp in a RTF control in VB.net

    - by Gerolkae
    I Started with this C# Question I'm trying to Display a bmp image inside a rtf Box for a Bot program I'm making. This function is supposed to convert a bitmap to rtf code whis is inserted to another rtf formatter srtring with additional text. Kind of like Smilies being used in a chat program. For some reason the output of this function gets rejected by the RTF Box and Vanishes completly. I'm not sure if it the way I'm converting the bmp to a Binary string or if its tied in with the header tags 'returns the RTF string representation of our picture Public Shared Function PictureToRTF(ByVal Bmp As Bitmap) As String Dim stream As New MemoryStream() Bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp) Dim bytes As Byte() = stream.ToArray() Dim str As String = BitConverter.ToString(bytes, 0).Replace("-", String.Empty) 'header to string we want to insert Using g As Graphics = Main.CreateGraphics() xDpi = g.DpiX yDpi = g.DpiY End Using Dim _rtf As New StringBuilder() ' Calculate the current width of the image in (0.01)mm Dim picw As Integer = CInt(Math.Round((Bmp.Width / xDpi) * HMM_PER_INCH)) ' Calculate the current height of the image in (0.01)mm Dim pich As Integer = CInt(Math.Round((Bmp.Height / yDpi) * HMM_PER_INCH)) ' Calculate the target width of the image in twips Dim picwgoal As Integer = CInt(Math.Round((Bmp.Width / xDpi) * TWIPS_PER_INCH)) ' Calculate the target height of the image in twips Dim pichgoal As Integer = CInt(Math.Round((Bmp.Height / yDpi) * TWIPS_PER_INCH)) ' Append values to RTF string _rtf.Append("{\pict\wbitmap0") _rtf.Append("\picw") _rtf.Append(Bmp.Width.ToString) ' _rtf.Append(picw.ToString) _rtf.Append("\pich") _rtf.Append(Bmp.Height.ToString) ' _rtf.Append(pich.ToString) _rtf.Append("\wbmbitspixel24\wbmplanes1") _rtf.Append("\wbmwidthbytes40") _rtf.Append("\picwgoal") _rtf.Append(picwgoal.ToString) _rtf.Append("\pichgoal") _rtf.Append(pichgoal.ToString) _rtf.Append("\bin ") _rtf.Append(str.ToLower & "}") Return _rtf.ToString End Function

    Read the article

  • My First F# program

    - by sudaly
    Hi I just finish writing my first F# program. Functionality wise the code works the way I wanted, but not sure if the code is efficient. I would much appreciate if someone could review the code for me and point out the areas where the code can be improved. Thanks Sudaly open System open System.IO open System.IO.Pipes open System.Text open System.Collections.Generic open System.Runtime.Serialization [<DataContract>] type Quote = { [<field: DataMember(Name="securityIdentifier") >] RicCode:string [<field: DataMember(Name="madeOn") >] MadeOn:DateTime [<field: DataMember(Name="closePrice") >] Price:float } let m_cache = new Dictionary<string, Quote>() let ParseQuoteString (quoteString:string) = let data = Encoding.Unicode.GetBytes(quoteString) let stream = new MemoryStream() stream.Write(data, 0, data.Length); stream.Position <- 0L let ser = Json.DataContractJsonSerializer(typeof<Quote array>) let results:Quote array = ser.ReadObject(stream) :?> Quote array results let RefreshCache quoteList = m_cache.Clear() quoteList |> Array.iter(fun result->m_cache.Add(result.RicCode, result)) let EstablishConnection() = let pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, 4) let mutable sr = null printfn "[F#] NamedPipeServerStream thread created, Wait for a client to connect" pipeServer.WaitForConnection() printfn "[F#] Client connected." try // Stream for the request. sr <- new StreamReader(pipeServer) with | _ as e -> printfn "[F#]ERROR: %s" e.Message sr while true do let sr = EstablishConnection() // Read request from the stream. printfn "[F#] Ready to Receive data" sr.ReadLine() |> ParseQuoteString |> RefreshCache printfn "[F#]Quot Size, %d" m_cache.Count let quot = m_cache.["MSFT.OQ"] printfn "[F#]RIC: %s" quot.RicCode printfn "[F#]MadeOn: %s" (String.Format("{0:T}",quot.MadeOn)) printfn "[F#]Price: %f" quot.Price

    Read the article

  • How to create an XML document from a .NET object?

    - by JL
    I have the following variable that accepts a file name: var xtr = new XmlTextReader(xmlFileName) { WhitespaceHandling = WhitespaceHandling.None }; var xd = new XmlDocument(); xd.Load(xtr); I would like to change it so that I can pass in an object. I don't want to have to serialize the object to file first. Is this possible? Update: My original intentions were to take an xml document, merge some xslt (stored in a file), then output and return html... like this: public string TransformXml(string xmlFileName, string xslFileName) { var xtr = new XmlTextReader(xmlFileName) { WhitespaceHandling = WhitespaceHandling.None }; var xd = new XmlDocument(); xd.Load(xtr); var xslt = new System.Xml.Xsl.XslCompiledTransform(); xslt.Load(xslFileName); var stm = new MemoryStream(); xslt.Transform(xd, null, stm); stm.Position = 1; var sr = new StreamReader(stm); xtr.Close(); return sr.ReadToEnd(); } In the above code I am reading in the xml from a file. Now what I would like to do is just work with the object, before it was serialized to the file. So let me illustrate my problem using code public string TransformXMLFromObject(myObjType myobj , string xsltFileName) { // Notice the xslt stays the same. // Its in these next few lines that I can't figure out how to load the xml document (xd) from an object, and not from a file.... var xtr = new XmlTextReader(xmlFileName) { WhitespaceHandling = WhitespaceHandling.None }; var xd = new XmlDocument(); xd.Load(xtr); }

    Read the article

  • DotNetOpenAuth occasionally throws a NotImplementedException

    - by Chris Moschini
    I have DotNetOpenAuth running on a background thread making calls to Google authorized with OAuth on a regular basis. About once a day, which is about one in 10,000 calls, I get the following Exception: An unhandled exception occurred and the process was terminated. Application ID: DefaultDomain Process ID: 3316 Exception: System.NotImplementedException Message: The method or operation is not implemented. StackTrace: at DotNetOpenAuth.Messaging.ProtocolException.GetObjectData(SerializationInfo info, StreamingContext context) in c:\Users\andarno\git\dotnetopenid\src\DotNetOpenAuth\Messaging\ProtocolException.cs:line 90 at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder) at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder) at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck) at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck) at System.Runtime.Remoting.Channels.CrossAppDomainSerializer.SerializeObject(Object obj, MemoryStream stm) at System.AppDomain.Serialize(Object o) at System.AppDomain.MarshalObject(Object o) If it was thrown and caught once a day I'd be fine, but this is a big one - I'm getting this in the Application Error log on the server, and it's crashing the process entirely - the site goes down and restarts. Has anyone else run into this? Something I'm clearly doing wrong?

    Read the article

  • C# How to perform a live xslt transformation on an in memory object?

    - by JL
    I have a function that takes 2 parameters : 1 = XML file, 2 = XSLT file, then performs a transformation and returns the resulting HTML. Here is the function: /// <summary> /// Will apply an XSLT style to any XML file and return the rendered HTML. /// </summary> /// <param name="xmlFileName"> /// The file name of the XML document. /// </param> /// <param name="xslFileName"> /// The file name of the XSL document. /// </param> /// <returns> /// The rendered HTML. /// </returns> public string TransformXml(string xmlFileName, string xslFileName) { var xtr = new XmlTextReader(xmlFileName) { WhitespaceHandling = WhitespaceHandling.None }; var xd = new XmlDocument(); xd.Load(xtr); var xslt = new System.Xml.Xsl.XslCompiledTransform(); xslt.Load(xslFileName); var stm = new MemoryStream(); xslt.Transform(xd, null, stm); stm.Position = 1; var sr = new StreamReader(stm); xtr.Close(); return sr.ReadToEnd(); } I want to change the function not to accept a file for the XML, but instead just an object. The object is exactly compatible with the xslt, if it was serialized to file. But I don't want to have to serialize it to a file first. So to recap : keep the xslt coming from a file, but the xml input should an object I pass and would like to generate the xml from without any file system interaction.

    Read the article

  • Serializing a DataType="time" field using XmlSerializer

    - by CraftyFella
    Hi, I'm getting an odd result when serializing a DateTime field using XmlSerializer. I have the following class: public class RecordExample { [XmlElement("TheTime", DataType = "time")] public DateTime TheTime { get; set; } [XmlElement("TheDate", DataType = "date")] public DateTime TheDate { get; set; } public static bool Serialize(Stream stream, object obj, Type objType, Encoding encoding) { try { using (var writer = XmlWriter.Create(stream, new XmlWriterSettings { Encoding = encoding })) { var xmlSerializer = new XmlSerializer(objType); if (writer != null) xmlSerializer.Serialize(writer, obj); } return true; } catch (Exception) { return false; } } } When i call the use the XmlSerializer with the following testing code: var obj = new RecordExample {TheDate = DateTime.Now.Date, TheTime = new DateTime(0001, 1, 1, 12, 00, 00)}; var ms = new MemoryStream(); RecordExample.Serialize(ms, obj, typeof (RecordExample), Encoding.UTF8); txtSource2.Text = Encoding.UTF8.GetString(ms.ToArray()); I get some strange results, here's the xml that is produced: <?xml version="1.0" encoding="utf-8"?> <RecordExample xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <TheTime>12:00:00.0000000+00:00</TheTime> <TheDate>2010-03-08</TheDate> </RecordExample> Any idea's how i can get the "TheTime" element to contain a time which looks more like this: <TheTime>12:00:00.0Z</TheTime> ...as that's what i was expecting? Thanks Dave

    Read the article

  • Copy Small Bitmaps on to Large Bitmap with Transparency Blend: What is faster than graphics.DrawImag

    - by Glenn
    I have identified this call as a bottleneck in a high pressure function. graphics.DrawImage(smallBitmap, x , y); Is there a faster way to blend small semi transparent bitmaps into a larger semi transparent one? Example Usage: XY[] locations = GetLocs(); Bitmap[] bitmaps = GetBmps(); //small images sizes vary approx 30px x 30px using (Bitmap large = new Bitmap(500, 500, PixelFormat.Format32bppPArgb)) using (Graphics largeGraphics = Graphics.FromImage(large)) { for(var i=0; i < largeNumber; i++) { //this is the bottleneck largeGraphics.DrawImage(bitmaps[i], locations[i].x , locations[i].y); } } var done = new MemoryStream(); large.Save(done, ImageFormat.Png); done.Position = 0; return (done); The DrawImage calls take a small 32bppPArgb bitmaps and copies them into a larger bitmap at locations that vary and the small bitmaps might only partially overlap the larger bitmaps visible area. Both images have semi transparent contents that get blended by DrawImage in a way that is important to the output. I've done some testing with BitBlt but not seen significant speed improvement and the alpha blending didn't come out the same in my tests. I'm open to just about any method including a better call to bitblt or unsafe c# code.

    Read the article

  • How to detect the error raised on a particular codeline?

    - by infant programmer
    [Please edit the title if you find its not good enough] I have code which triggers XSL-transformation: objMemoryStream = new MemoryStream(); xslTransform = new XslCompiledTransform(); xpathXmlOrig = new XPathDocument("E:\\xslt error\\Simulation_of_error\\input.xml"); xslSettings = new XsltSettings(); xslSettings.EnableScript = true; xslTransform.Load(strXmlQueryTransformPath, xslSettings, new XmlUrlResolver()); xslTransform.Transform(xpathXmlOrig, null, objMemoryStream); objMemoryStream.Position = 0; StreamReader objStreamReader = new StreamReader(objMemoryStream); The method xslTransform.Load(strXmlQueryTransformPath, xslSettings, new XmlUrlResolver()); is a victim, which fails some times due to some time-out issue. I want to detect the failure of this codeline and execute again until it successfully executes! I tried using "TRY CATCH and WHILE methods": bool flag = true; do { try { xslTransform.Load(strXmlQueryTransformPath, xslSettings, new XmlUrlResolver()); flag = false; } catch { flag = true; } } while (flag); but the problem is "error is getting logged in the log file", Well. The whole code is under one more try statement, which I suspect is writing to log. Which is what I don't want... I don't want end user to know about the failure of this codeline. Is there anyway to get it done?

    Read the article

  • How to call a service operation at a REST style WCF endpoint uri?

    - by Dieter Domanski
    Hi, is it possible to call a service operation at a wcf endpoint uri with a self hosted service? I want to call some default service operation when the client enters the endpoint uri of the service. In the following sample these uris correctly call the declared operations (SayHello, SayHi): - http://localhost:4711/clerk/hello - http://localhost:4711/clerk/hi But the uri - http://localhost:4711/clerk does not call the declared SayWelcome operation. Instead it leads to the well known 'Metadata publishing disabled' page. Enabling mex does not help, in this case the mex page is shown at the endpoint uri. private void StartSampleServiceHost() { ServiceHost serviceHost = new ServiceHost(typeof(Clerk), new Uri( "http://localhost:4711/clerk/")); ServiceEndpoint endpoint = serviceHost.AddServiceEndpoint(typeof(IClerk), new WebHttpBinding(), ""); endpoint.Behaviors.Add(new WebHttpBehavior()); serviceHost.Open(); } [ServiceContract] public interface IClerk { [OperationContract, WebGet(UriTemplate = "")] Stream SayWelcome(); [OperationContract, WebGet(UriTemplate = "/hello/")] Stream SayHello(); [OperationContract, WebGet(UriTemplate = "/hi/")] Stream SayHi(); } public class Clerk : IClerk { public Stream SayWelcome() { return Say("welcome"); } public Stream SayHello() { return Say("hello"); } public Stream SayHi() { return Say("hi"); } private Stream Say(string what) { string page = @"<html><body>" + what + "</body></html>"; return new MemoryStream(Encoding.UTF8.GetBytes(page)); } } Is there any way to disable the mex handling and to enable a declared operation instead? Thanks in advance, Dieter

    Read the article

  • Serialize Forms into memory

    - by serhio
    Background: In a desktop MDI application we have a lot of forms. Task: Save the controls contents of closed forms(textbox texts, checkbox checks etc). Limitations: A saved form for (DB/Windows) user? For (DB/Windows) group of users? Both variants may be possible. Question: a) What is the best way? b) if I want do not use files, how to serialize the form into a MemoryStream and then recuperate it if the opening form was been once opened and serialized? StartingPoint: Implemented a form that implements ISerializable. Deserialize the form on opening, serialize onclosing: Public Sub GetObjectData(ByVal info As System.Runtime.Serialization.SerializationInfo, ByVal context As System.Runtime.Serialization.StreamingContext) Implements System.Runtime.Serialization.ISerializable.GetObjectData info.AddValue("tbxExportFolder", tbxExportFolder.Text, GetType(String)) info.AddValue("cbxCheckAliasUnicity", cbxCheckAliasUnicity.Checked, GetType(Boolean)) End Sub Public Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext) Me.New() Me.tbxExportFolder.Text = info.GetString("tbxExportFolder") Me.cbxCheckAliasUnicity.Checked = info.GetBoolean("cbxCheckAliasUnicity") End Sub Private Sub SerializeMe() Dim binFormatter As New Formatters.Binary.BinaryFormatter Dim fileStream As New FileStream(SerializedFilename, FileMode.Create) Try binFormatter.Serialize(fileStream, Me) Catch Throw Finally fileStream.Close() End Try End Sub Protected Overrides Sub OnClosing(ByVal e As System.ComponentModel.CancelEventArgs) SerializeMe() MyBase.OnClosing(e) End Sub

    Read the article

  • Png image processing in .NET.

    - by Oybek
    I have the following task. Take a base image and overlay on it another one. The base image is 8b png as well as overlay. Here are the base (left) and overlay (right) images. Here is a result and how it must look. The picture in the left is a screenshot when one picture is on top of another (html and positioning) and the second is the result of programmatic merging. As you can see in the screenshot the borders of the text is darker. Also here are the sizes of the images Base image 14.9 KB Overlay image 6.87 KB Result image 34.8 KB The size of the resulting image is also huge Here is my code that I use to merge those pictures /*...*/ public Stream Concatinate(Stream baseStream, params Stream[] overlayStreams) { var @base = Image.FromStream(baseStream); var canvas = new Bitmap(@base.Width, @base.Height); using (var g = canvas.ToGraphics()) { g.DrawImage(@base, 0, 0); foreach (var item in overlayStreams) { using (var overlayImage = Image.FromStream(item)) { try { Overlay(@base, overlayImage, g); } catch { } } } } var ms = new MemoryStream(); canvas.Save(ms, ImageFormat.Png); canvas.Dispose(); @base.Dispose(); return ms; } /*...*/ /*Tograpics extension*/ public static Graphics ToGraphics(this Image image, CompositingQuality compositingQuality = CompositingQuality.HighQuality, SmoothingMode smoothingMode = SmoothingMode.HighQuality, InterpolationMode interpolationMode = InterpolationMode.HighQualityBicubic) { var g = Graphics.FromImage(image); g.CompositingQuality = compositingQuality; g.SmoothingMode = smoothingMode; g.InterpolationMode = interpolationMode; return g; } My questions are What should I do in order to merge images to achieve the result as in the screenshot? How can I lower the size of the result image? Is the System.Drawing a suitable tool for this or is there any better tool for working with png for .NET?

    Read the article

  • XSLT question, how to transform xml when I have xslt file stored, but object in mem?

    - by JL
    I have a function that takes 2 parameters : 1 = XML file, 2 = XSLT file, then performs a transformation and returns the resulting HTML. Here is the function: /// <summary> /// Will apply an XSLT style to any XML file and return the rendered HTML. /// </summary> /// <param name="xmlFileName"> /// The file name of the XML document. /// </param> /// <param name="xslFileName"> /// The file name of the XSL document. /// </param> /// <returns> /// The rendered HTML. /// </returns> public string TransformXml(string xmlFileName, string xslFileName) { var xtr = new XmlTextReader(xmlFileName) { WhitespaceHandling = WhitespaceHandling.None }; var xd = new XmlDocument(); xd.Load(xtr); var xslt = new System.Xml.Xsl.XslCompiledTransform(); xslt.Load(xslFileName); var stm = new MemoryStream(); xslt.Transform(xd, null, stm); stm.Position = 1; var sr = new StreamReader(stm); xtr.Close(); return sr.ReadToEnd(); } I want to change the function not to accept a file name, but rather a strongly typed object de-serialized (now in the form of a variable). Is this possible? So keep the xslt coming from a file, but the xml input should be a the serialized xml of the object I pass, and I want to do this without file system IO.

    Read the article

  • How to create a "Shell IDList Array" to support drag-and-drop of virtual files from C# to Windows Ex

    - by JustABill
    I started trying to implement drag-and-drop of virtual files (from a C# 4/WPF app) with this codeplex tutorial. After spending some time trying to figure out a DV_E_FORMATETC error, I figured out I need to support the "Shell IDList Array" data format. But there seems to be next to zero documentation on what this format actually does. After some searching, I found this page on advanced data transfer which said that a Shell IDList Array was a pointer to a CIDA structure. This CIDA structure then contains the number of PIDLs, and a list of offsets to them. So what the hell is a PIDL? After some more searching, this page sort of implies it's a pointer to an ITEMIDLIST, which itself contains a single member that is a list of SHITEMIDs. My next idea was to try dragging a file from another application with virtual files. I just got a MemoryStream back for this format. At least I know what class to provide for the thing, but that doesn't help at all for explaining what to put in it. So now that that's explained, I still have no idea how to create one of these things so that it's valid. There's two real questions here: What is a valid "abID" member for a SHITEMID? These virtual files only exist with my program; will the thing they are dragged to pass the "abID" back later when it executes GetData? Do they have to be system-unique? Why are there two levels of lists; a list of PIDLs and each PIDL has a list of SHITEMIDs? I'm assuming one of them is one for each file, but what's the other one for? Multiple IDs for the same file? Any help or even links that explain what I should be doing would be greatly appreciated.

    Read the article

  • C# async callback on disposed form

    - by Rodney Burton
    Quick question: One of my forms in my winform app (c#) makes an async call to a WCF service to get some data. If the form happens to close before the callback happens, it crashes with an error about accessing a disposed object. What's the correct way to check/handle this situation? The error happens on the Invoke call to the method to update my form, but I can't drill down to the inner exception because it says the code has been optimized. The Code: public void RequestUserPhoto(int userID) { WCF.Service.BeginGetUserPhoto(userID, new AsyncCallback(GetUserPhotoCB), userID); } public void GetUserPhotoCB(IAsyncResult result) { var photo = WCF.Service.EndGetUserPhoto(result); int userID = (int)result.AsyncState; UpdateUserPhoto(userID, photo); } public delegate void UpdateUserPhotoDelegate(int userID, Binary photo); public void UpdateUserPhoto(int userID, Binary photo) { if (InvokeRequired) { var d = new UpdateUserPhotoDelegate(UpdateUserPhoto); Invoke(d, new object[] { userID, photo }); } else { if (photo != null) { var ms = new MemoryStream(photo.ToArray()); var bmp = new System.Drawing.Bitmap(ms); if (userID == theForm.AuthUserID) { pbMyPhoto.BackgroundImage = bmp; } else { pbPhoto.BackgroundImage = bmp; } } } }

    Read the article

  • DRYing out implementation of ICloneable in several classes

    - by Sarah Vessels
    I have several different classes that I want to be cloneable: GenericRow, GenericRows, ParticularRow, and ParticularRows. There is the following class hierarchy: GenericRow is the parent of ParticularRow, and GenericRows is the parent of ParticularRows. Each class implements ICloneable because I want to be able to create deep copies of instances of each. I find myself writing the exact same code for Clone() in each class: object ICloneable.Clone() { object clone; using (var stream = new MemoryStream()) { var formatter = new BinaryFormatter(); // Serialize this object formatter.Serialize(stream, this); stream.Position = 0; // Deserialize to another object clone = formatter.Deserialize(stream); } return clone; } I then provide a convenience wrapper method, for example in GenericRows: public GenericRows Clone() { return (GenericRows)((ICloneable)this).Clone(); } I am fine with the convenience wrapper methods looking about the same in each class because it's very little code and it does differ from class to class by return type, cast, etc. However, ICloneable.Clone() is identical in all four classes. Can I abstract this somehow so it is only defined in one place? My concern was that if I made some utility class/object extension method, it would not correctly make a deep copy of the particular instance I want copied. Is this a good idea anyway?

    Read the article

  • How to efficiently convert String, integer, double, datetime to binary and vica versa?

    - by Ben
    Hi, I'm quite new to C# (I'm using .NET 4.0) so please bear with me. I need to save some object properties (their properties are int, double, String, boolean, datetime) to a file. But I want to encrypt the files using my own encryption, so I can't use FileStream to convert to binary. Also I don't want to use object serialization, because of performance issues. The idea is simple, first I need to somehow convert objects (their properties) to binary (array), then encrypt (some sort of xor) the array and append it to the end of the file. When reading first decrypt the array and then somehow convert the binary array back to object properties (from which I'll generate objects). I know (roughly =) ) how to convert these things by hand and I could code it, but it would be useless (too slow). I think the best way would be just to get properties' representation in memory and save that. But I don't know how to do it using C# (maybe using pointers?). Also I though about using MemoryStream but again I think it would be inefficient. I am thinking about class Converter, but it does not support toByte(datetime) (documentation says it always throws exception). For converting back I think the only options is class Converter. Note: I know the structure of objects and they will not change, also the maximum String length is also known. Thank you for all your ideas and time. EDIT: I will be storing only parts of objects, in some cases also parts of different objects (a couple of properties from one object type and a couple from another), thus I think that serialization is not an option for me.

    Read the article

  • Managed C++ or C# .NET, Downloading from rapidshare?

    - by cruisx
    I am trying to download a file from rapidshare via C++ .NET but I'm having a bit of trouble. The address used to be "https://ssl.rapidshare.com/cgi-bin/premiumzone.cgi" but that no longer works, does anyone know what the new one is? The code works but the file size is always 1KB, I don't think its connecting to the right server. private: void downloadFileAsync(String^ fileUrl) { String^ uriString; //fileUrl = "http://rapidshare.com/files/356458319/Keeping.Up.with.the.Kardashians.S04E10.Delivering.Baby.Mason.HDTV.XviD-MOMENTUM.rar"; uriString = "https://ssl.rapidshare.com/premzone.html";//"https://ssl.rapidshare.com"; NameValueCollection^ postvals = gcnew NameValueCollection(); postvals->Add("login", "bob"); postvals->Add("password", "12345"); // postvals->Add("uselandingpage", "1"); WebClient^ myWebClient = gcnew WebClient(); array<unsigned char>^ responseArray = gcnew array<unsigned char>(10024); responseArray = myWebClient->UploadValues(uriString, "POST", postvals); StreamReader^ strRdr = gcnew StreamReader(gcnew MemoryStream(responseArray)); String^ cookiestr = myWebClient->ResponseHeaders->Get("Set-Cookie"); myWebClient->Headers->Add("Cookie", cookiestr); //myWebClient->DownloadFileCompleted += gcnew AsyncCompletedEventHandler(myWebClient->DownloadFileCompleted); myWebClient-DownloadFileAsync(gcnew Uri(fileUrl),"C:\rapid\"+Path::GetFileName(fileUrl)); }

    Read the article

  • What is the fastest way for reading huge files in Delphi?

    - by dummzeuch
    My program needs to read chunks from a huge binary file with random access. I have got a list of offsets and lengths which may have several thousand entries. The user selects an entry and the program seeks to the offset and reads length bytes. The program internally uses a TMemoryStream to store and process the chunks read from the file. Reading the data is done via a TFileStream like this: FileStream.Position := Offset; MemoryStream.CopyFrom(FileStream, Size); This works fine but unfortunately it becomes increasingly slower as the files get larger. The file size starts at a few megabytes but frequently reaches several tens of gigabytes. The chunks read are around 100 kbytes in size. The file's content is only read by my program. It is the only program accessing the file at the time. Also the files are stored locally so this is not a network issue. I am using Delphi 2007 on a Windows XP box. What can I do to speed up this file access?

    Read the article

  • public class ImageHandler : IHttpHandler

    - by Ken
    cmd.Parameters.AddWithValue("@id", new system.Guid (imageid)); What using System reference would this require? Here is the handler: using System; using System.Collections.Specialized; using System.Web; using System.Web.Configuration; using System.Web.Security; using System.Globalization; using System.Configuration; using System.Data.SqlClient; using System.Data; using System.IO; using System.Web.Profile; using System.Drawing; public class ImageHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { string imageid; if (context.Request.QueryString["id"] != null) imageid = (context.Request.QueryString["id"]); else throw new ArgumentException("No parameter specified"); context.Response.ContentType = "image/jpeg"; Stream strm = ShowProfileImage(imageid.ToString()); byte[] buffer = new byte[8192]; int byteSeq = strm.Read(buffer, 0, 8192); while (byteSeq > 0) { context.Response.OutputStream.Write(buffer, 0, byteSeq); byteSeq = strm.Read(buffer, 0, 8192); } //context.Response.BinaryWrite(buffer); } public Stream ShowProfileImage(String imageid) { string conn = ConfigurationManager.ConnectionStrings["MyConnectionString1"].ConnectionString; SqlConnection connection = new SqlConnection(conn); string sql = "SELECT image FROM Profile WHERE UserId = @id"; SqlCommand cmd = new SqlCommand(sql, connection); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@id", new system.Guid (imageid));//Failing Here!!!! connection.Open(); object img = cmd.ExecuteScalar(); try { return new MemoryStream((byte[])img); } catch { return null; } finally { connection.Close(); } } public bool IsReusable { get { return false; } } }

    Read the article

  • Serialization of Queue type not working

    - by Soham
    Consider this piece of code: private Queue Date=new Queue(); //other declarations public DateTime _Date { get { return (DateTime)Date.Peek();} set { Date.Enqueue(value); } } //other properties and stuff.... public void UpdatePosition(...) { //other code IFormatter formatter = new BinaryFormatter(); Stream Datestream = new MemoryStream(); formatter.Serialize(Datestream, Date); byte[] Datebin = new byte[2048]; Datestream.Read(Datebin,0,2048); //Debug-Bug Console.WriteLine(Convert.ToString(this._Date)); Console.WriteLine(BitConverter.ToString(Datebin, 0, 3)); //other code } The output of the first WriteLine is perfect. I.e to check if really the Queue is initialised or not. It is. The right variables are stored etc. (I inserted a value in that Queue, that part of the code is not shown.) But the second WriteLine is not giving the right expected answer: It serializes the entire Queue to 00-00-00.

    Read the article

< Previous Page | 9 10 11 12 13 14 15  | Next Page >