Search Results

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

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

  • Why is a .net generic dictionary so big

    - by thefroatgt
    I am serializing a generic dictionary in VB.net and I am very surprised that it is about 1.3kb with a single item. Am I doing something wrong, or is there something else I should be doing? I have a large number of dictionaries and it is killing me to send them all across the wire. The code I use for serialization is Dim dictionary As New Dictionary(Of Integer, Integer) Dim stream As New MemoryStream Dim bformatter As New BinaryFormatter() dictionary.Add(1, 1) bformatter.Serialize(stream, dictionary) Dim len As Long = stream.Length

    Read the article

  • using a connection string in web.config for crystal report

    - by zombiegx
    I`m having problems between two servers, wich use differente odbc dsn. My apps work great but crystal reports uses the original odbc connection, how can I fix this? I'm thinking of using the same connection string in the web.config, but I don't know how. found this but is too confusing for me this is an example of my code, its a aspx file that loads as a pdf protected void Page_Load(object sender, EventArgs e) { try { var par = Request.QueryString; int pidmun = 0; if (!string.IsNullOrEmpty(Request["id"])) { pidmun = int.Parse(Request["id"]); } string pFechaIni = Request["fi"]; string pFechaFin = Request["ff"]; string pTipo = Request["t"]; string pNombreMunicipio = Request["nm"]; var pos = Request.Form; if (string.IsNullOrEmpty(pFechaIni)) { pFechaIni = "01/01/2010"; } if (string.IsNullOrEmpty(pFechaFin)) { pFechaFin = "01/01/2010"; } if (string.IsNullOrEmpty(pTipo)) { pTipo = "FOLIO"; } if (string.IsNullOrEmpty(pNombreMunicipio)) { pNombreMunicipio = "NombreMunicipio"; } ReporteIngresos report = new ReporteIngresos(); TextObject nom; TextObject periodo; nom = (TextObject)report.ReportDefinition.ReportObjects["TxtNombreMunicipio"]; periodo = (TextObject)report.ReportDefinition.ReportObjects["TxtPeriodo"]; nom.Text = "Ingresos Municipio de " + pNombreMunicipio; periodo.Text = "Periodo del " + pFechaIni + " al " + pFechaFin; report.SetParameterValue("pidMun", pidmun); report.SetParameterValue("pFechaIni", pFechaIni); report.SetParameterValue("pFechaFin", pFechaFin); report.SetParameterValue("pTipo", pTipo); MemoryStream oStream; oStream = (MemoryStream)report.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat); Response.Clear(); Response.Buffer = true; Response.AddHeader("CustomHeader", "ReporteIngresos"); Response.CacheControl = "No-cache"; Response.ContentType = "application/pdf"; Response.BinaryWrite(oStream.ToArray()); Response.End(); } catch (Exception ex) { ExBi.log(ex); throw ex; } } thanks.

    Read the article

  • .NET AES returns wrong Test Vectors

    - by ralu
    I need to implement some crypto protocol on C# and want to say that this is my first project in C#. After spending some time to get used on C# I found out that I am unable to get compliant AES vectors. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; using System.IO; namespace ConsoleApplication1 { class Program { public static void Main() { try { //test vectors from "ecb_vk.txt" byte[] key = { 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; byte[] data = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; byte[] encTest = { 0x0e, 0xdd, 0x33, 0xd3, 0xc6, 0x21, 0xe5, 0x46, 0x45, 0x5b, 0xd8, 0xba, 0x14, 0x18, 0xbe, 0xc8 }; AesManaged aesAlg = new AesManaged(); aesAlg.BlockSize = 128; aesAlg.Key = key; aesAlg.Mode = CipherMode.ECB; ICryptoTransform encryptor = aesAlg.CreateEncryptor(); MemoryStream msEncrypt = new MemoryStream(); CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write); StreamWriter swEncrypt = new StreamWriter(csEncrypt); swEncrypt.Write(data); swEncrypt.Close(); csEncrypt.Close(); msEncrypt.Close(); aesAlg.Clear(); byte[] encr; encr = msEncrypt.ToArray(); string datastr = BitConverter.ToString(data); string encrstr = BitConverter.ToString(encr); string encTestStr = BitConverter.ToString(encTest); Console.WriteLine("data: {0}", datastr); Console.WriteLine("encr: {0}", encrstr); Console.WriteLine("should: {0}", encTestStr); Console.ReadKey(); } catch (Exception e) { Console.WriteLine("Error: {0}", e.Message); } } } } Output is wrong: data: 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 encr: A0-3C-C2-22-A4-32-F7-C9-BA-36-AE-73-66-BD-BB-A3 should: 0E-DD-33-D3-C6-21-E5-46-45-5B-D8-BA-14-18-BE-C8 I am sure that there is a correct AES implementation in .NET, so I need some advice from a .NET wizard to help with this.

    Read the article

  • XmlSerializer.Deserialize blocks over NetworkStream

    - by Luca
    I'm trying to sends XML serializable objects over a network stream. I've already used this on an UDP broadcast server, where it receive UDP messages from the local network. Here a snippet of the server side: while (mServiceStopFlag == false) { if (mSocket.Available > 0) { IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, DiscoveryPort); byte[] bData; // Receive discovery message bData = mSocket.Receive(ref ipEndPoint); // Handle discovery message HandleDiscoveryMessage(ipEndPoint.Address, bData); ... Instead this is the client side: IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Broadcast, DiscoveryPort); MemoryStream mStream = new MemoryStream(); byte[] bData; // Create broadcast UDP server mSocket = new UdpClient(); mSocket.EnableBroadcast = true; // Create datagram data foreach (NetService s in ctx.Services) XmlHelper.SerializeClass<NetService>(mStream, s); bData = mStream.GetBuffer(); // Notify the services while (mServiceStopFlag == false) { mSocket.Send(bData, (int)mStream.Length, ipEndPoint); Thread.Sleep(DefaultServiceLatency); } It works very fine. But now i'me trying to get the same result, but on a TcpClient socket, but the using directly an XMLSerializer instance: On server side: TcpClient sSocket = k.Key; ServiceContext sContext = k.Value; Message msg = new Message(); while (sSocket.Connected == true) { if (sSocket.Available > 0) { StreamReader tr = new StreamReader(sSocket.GetStream()); msg = (Message)mXmlSerialize.Deserialize(tr); // Handle message msg = sContext.Handler(msg); // Reply with another message if (msg != null) mXmlSerialize.Serialize(sSocket.GetStream(), msg); } else Thread.Sleep(40); } And on client side: NetworkStream mSocketStream; Message rMessage; // Network stream mSocketStream = mSocket.GetStream(); // Send the message mXmlSerialize.Serialize(mSocketStream, msg); // Receive the answer rMessage = (Message)mXmlSerialize.Deserialize(mSocketStream); return (rMessage); The data is sent (Available property is greater then 0), but the method XmlSerialize.Deserialize (which should deserialize the Message class) blocks. What am I missing?

    Read the article

  • Feedback on Optimizing C# NET Code Block

    - by Brett Powell
    I just spent quite a few hours reading up on TCP servers and my desired protocol I was trying to implement, and finally got everything working great. I noticed the code looks like absolute bollocks (is the the correct usage? Im not a brit) and would like some feedback on optimizing it, mostly for reuse and readability. The packet formats are always int, int, int, string, string. try { BinaryReader reader = new BinaryReader(clientStream); int packetsize = reader.ReadInt32(); int requestid = reader.ReadInt32(); int serverdata = reader.ReadInt32(); Console.WriteLine("Packet Size: {0} RequestID: {1} ServerData: {2}", packetsize, requestid, serverdata); List<byte> str = new List<byte>(); byte nextByte = reader.ReadByte(); while (nextByte != 0) { str.Add(nextByte); nextByte = reader.ReadByte(); } // Password Sent to be Authenticated string string1 = Encoding.UTF8.GetString(str.ToArray()); str.Clear(); nextByte = reader.ReadByte(); while (nextByte != 0) { str.Add(nextByte); nextByte = reader.ReadByte(); } // NULL string string string2 = Encoding.UTF8.GetString(str.ToArray()); Console.WriteLine("String1: {0} String2: {1}", string1, string2); // Reply to Authentication Request MemoryStream stream = new MemoryStream(); BinaryWriter writer = new BinaryWriter(stream); writer.Write((int)(1)); // Packet Size writer.Write((int)(requestid)); // Mirror RequestID if Authenticated, -1 if Failed byte[] buffer = stream.ToArray(); clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); } I am going to be dealing with other packet types as well that are formatted the same (int/int/int/str/str), but different values. I could probably create a packet class, but this is a bit outside my scope of knowledge for how to apply it to this scenario. If it makes any difference, this is the Protocol I am implementing. http://developer.valvesoftware.com/wiki/Source_RCON_Protocol

    Read the article

  • C# AES returns wrong Test Vectors

    - by ralu
    I need to implement some crypto protocol on C# and want to say that this is my first project in C#. After spending some time to get used on C# I found out that I am unable to get compliant AES vectors. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; using System.IO; namespace ConsoleApplication1 { class Program { public static void Main() { try { //test vectors from "ecb_vk.txt" byte[] key = { 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; byte[] data = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; byte[] encTest = { 0x0e, 0xdd, 0x33, 0xd3, 0xc6, 0x21, 0xe5, 0x46, 0x45, 0x5b, 0xd8, 0xba, 0x14, 0x18, 0xbe, 0xc8 }; AesManaged aesAlg = new AesManaged(); aesAlg.BlockSize = 128; aesAlg.Key = key; aesAlg.Mode = CipherMode.ECB; ICryptoTransform encryptor = aesAlg.CreateEncryptor(); MemoryStream msEncrypt = new MemoryStream(); CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write); StreamWriter swEncrypt = new StreamWriter(csEncrypt); swEncrypt.Write(data); swEncrypt.Close(); csEncrypt.Close(); msEncrypt.Close(); aesAlg.Clear(); byte[] encr; encr = msEncrypt.ToArray(); string datastr = BitConverter.ToString(data); string encrstr = BitConverter.ToString(encr); string encTestStr = BitConverter.ToString(encTest); Console.WriteLine("data: {0}", datastr); Console.WriteLine("encr: {0}", encrstr); Console.WriteLine("should: {0}", encTestStr); Console.ReadKey(); } catch (Exception e) { Console.WriteLine("Error: {0}", e.Message); } } } } Output is wrong: data: 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 encr: A0-3C-C2-22-A4-32-F7-C9-BA-36-AE-73-66-BD-BB-A3 should: 0E-DD-33-D3-C6-21-E5-46-45-5B-D8-BA-14-18-BE-C8 I am sure that there is correct AES implementation in C#, so I need some advice from C# wizard to help whit this. Thanks

    Read the article

  • Download pdf programatically...

    - by Perplexed
    Hi, How can I download a pdf and store to disk using vb.net or c#? The url (of the pdf) has some rediection going on before the final pdf is reached. I tried the below but the pdf seems corrupted when I attempt to open locally, Dim PdfFile As FileStream = File.OpenWrite(saveTo) Dim PdfStream As MemoryStream = GetFileStream(pdfURL) PdfStream.WriteTo(PdfFile) PdfStream.Flush() PdfStream.Close() PdfFile.Flush() PdfFile.Close() many thanks, KS

    Read the article

  • what is the best method of concatenating a series of binary files into one file?

    - by Andrew
    hello everyone i have a series of PDF byte arrays in a arraylist files that i wish to concatenate into one file, currently when the PDF application trys to open the file is it corrupted: foreach (byte[] array in files) { using (Stream s = new MemoryStream(downloadbytes)) { s.Write(array, 0, array.Length); } } downloadbytes is the resultant concatenated array of bytes below is another implementation which also failed foreach (byte[] array in files) { System.Buffer.BlockCopy(array, 0, downloadbytes, offset, array.Length); offset += array.Length; } any pointers?

    Read the article

  • What DirectShow Interface to use for capturing to Stream instead of creating actual file?

    - by jhorton
    I've got a DirectShow project where I want to capture and stream to a webserver. I have seen how to capture and create a file, but I'm looking for ideas on how to capture into something like a MemoryStream to transport through a NetworkStream. I'm also using the library DirectShowLib for the ability to write in C# if that makes any difference. Of if there is a sample that I overlooked in the SDK I would greatly appreciate the direction. Thanks in advance.

    Read the article

  • How can I write an extension method that converts a System.Drawing.Bitmap to a byte array?

    - by Patrick Szalapski
    How can I write an extension method that converts a System.Drawing.Bitmap to a byte array? Why not: <Extension()> _ Public Function ToByteArray(ByVal image As System.Drawing.Bitmap) As Byte() Using ms = New MemoryStream() image.Save(ms, image.RawFormat) Return ms.ToArray() End Using End Function Yet when I use that, I get "System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+." What am I doing wrong?

    Read the article

  • Using the HTML5 &lt;input type=&quot;file&quot; multiple=&quot;multiple&quot;&gt; Tag in ASP.NET

    - by Rick Strahl
    Per HTML5 spec the <input type="file" /> tag allows for multiple files to be picked from a single File upload button. This is actually a very subtle change that's very useful as it makes it much easier to send multiple files to the server without using complex uploader controls. Please understand though, that even though you can send multiple files using the <input type="file" /> tag, the process of how those files are sent hasn't really changed - there's still no progress information or other hooks that allow you to automatically make for a nicer upload experience without additional libraries or code. For that you will still need some sort of library (I'll post an example in my next blog post using plUpload). All the new features allow for is to make it easier to select multiple images from disk in one operation. Where you might have required many file upload controls before to upload several files, one File control can potentially do the job. How it works To create a file input box that allows with multiple file support you can simply do:<form method="post" enctype="multipart/form-data"> <label>Upload Images:</label> <input type="file" multiple="multiple" name="File1" id="File1" accept="image/*" /> <hr /> <input type="submit" id="btnUpload" value="Upload Images" /> </form> Now when the file open dialog pops up - depending on the browser and whether the browser supports it - you can pick multiple files. Here I'm using Firefox using the thumbnail preview I can easily pick images to upload on a form: Note that I can select multiple images in the dialog all of which get stored in the file textbox. The UI for this can be different in some browsers. For example Chrome displays 3 files selected as text next to the Browse… button when I choose three rather than showing any files in the textbox. Most other browsers display the standard file input box and display the multiple filenames as a comma delimited list in the textbox. Note that you can also specify the accept attribute in the <input> tag, which specifies a mime-type to specify what type of content to allow.Here I'm only allowing images (image/*) and the browser complies by just showing me image files to display. Likewise I could use text/* for all text formats registered on the machine or text/xml to only show XML files (which would include xml,xst,xsd etc.). Capturing Files on the Server with ASP.NET When you upload files to an ASP.NET server there are a couple of things to be aware of. When multiple files are uploaded from a single file control, they are assigned the same name. In other words if I select 3 files to upload on the File1 control shown above I get three file form variables named File1. This means I can't easily retrieve files by their name:HttpPostedFileBase file = Request.Files["File1"]; because there will be multiple files for a given name. The above only selects the first file. Instead you can only reliably retrieve files by their index. Below is an example I use in app to capture a number of images uploaded and store them into a database using a business object and EF 4.2.for (int i = 0; i < Request.Files.Count; i++) { HttpPostedFileBase file = Request.Files[i]; if (file.ContentLength == 0) continue; if (file.ContentLength > App.Configuration.MaxImageUploadSize) { ErrorDisplay.ShowError("File " + file.FileName + " is too large. Max upload size is: " + App.Configuration.MaxImageUploadSize); return View("UploadClassic",model); } var image = new ClassifiedsBusiness.Image(); var ms = new MemoryStream(16498); file.InputStream.CopyTo(ms); image.Entered = DateTime.Now; image.EntryId = model.Entry.Id; image.ContentType = "image/jpeg"; image.ImageData = ms.ToArray(); ms.Seek(0, SeekOrigin.Begin); // resize image if necessary and turn into jpeg Bitmap bmp = Imaging.ResizeImage(ms.ToArray(), App.Configuration.MaxImageWidth, App.Configuration.MaxImageHeight); ms.Close(); ms = new MemoryStream(); bmp.Save(ms,ImageFormat.Jpeg); image.ImageData = ms.ToArray(); bmp.Dispose(); ms.Close(); model.Entry.Images.Add(image); } This works great and also allows you to capture input from multiple input controls if you are dealing with browsers that don't support multiple file selections in the file upload control. The important thing here is that I iterate over the files by index, rather than using a foreach loop over the Request.Files collection. The files collection returns key name strings, rather than the actual files (who thought that was good idea at Microsoft?), and so that isn't going to work since you end up getting multiple keys with the same name. Instead a plain for loop has to be used to loop over all files. Another Option in ASP.NET MVC If you're using ASP.NET MVC you can use the code above as well, but you have yet another option to capture multiple uploaded files by using a parameter for your post action method.public ActionResult Save(HttpPostedFileBase[] file1) { foreach (var file in file1) { if (file.ContentLength < 0) continue; // do something with the file }} Note that in order for this to work you have to specify each posted file variable individually in the parameter list. This works great if you have a single file upload to deal with. You can also pass this in addition to your main model to separate out a ViewModel and a set of uploaded files:public ActionResult Edit(EntryViewModel model,HttpPostedFileBase[] uploadedFile) You can also make the uploaded files part of the ViewModel itself - just make sure you use the appropriate naming for the variable name in the HTML document (since there's Html.FileFor() extension). Browser Support You knew this was coming, right? The feature is really nice, but unfortunately not supported universally yet. Once again Internet Explorer is the problem: No shipping version of Internet Explorer supports multiple file uploads. IE10 supposedly will, but even IE9 does not. All other major browsers - Chrome, Firefox, Safari and Opera - support multi-file uploads in their latest versions. So how can you handle this? If you need to provide multiple file uploads you can simply add multiple file selection boxes and let people either select multiple files with a single upload file box or use multiples. Alternately you can do some browser detection and if IE is used simply show the extra file upload boxes. It's not ideal, but either one of these approaches makes life easier for folks that use a decent browser and leaves you with a functional interface for those that don't. Here's a UI I recently built as an alternate uploader with multiple file upload buttons: I say this is my 'alternate' uploader - for my primary uploader I continue to use an add-in solution. Specifically I use plUpload and I'll discuss how that's implemented in my next post. Although I think that plUpload (and many of the other packaged JavaScript upload solutions) are a better choice especially for large uploads, for simple one file uploads input boxes work well enough. The advantage of this solution is that it's very easy to handle on the server side. Any of the JavaScript controls require special handling for uploads which I'll also discuss in my next post.© Rick Strahl, West Wind Technologies, 2005-2012Posted in HTML5  ASP.NET  MVC   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • How do i route TCP connections via TOR? [on hold]

    - by acidzombie24
    I was reading about torchat which is essentially an anonymous chat program. It sounded cool so i wanted to experiment with making my own. First i wrote a test to grab a webpage using Http. Sicne .NET doesnt support SOCKS4A/SOCKS5 i used privoxy and my app worked. Then i switch to a TCP echo test and privoxy doesnt support TCP so i searched and installed 6+ proxy apps (freecap, socat, freeproxy, delegate are the ones i can remember from the top of my head, i also played with putty bc i know it supports tunnels and SOCK5) but i couldnt successfully get any of them to work let alone get it running with my http test that privoxy easily and painlessly did. What may i use to get TCP connections going through TOR? I spent more then 2 hours without success. I don't know if i am looking for a relay, tunnel, forwarder, proxy or a proxychain which all came up in my search. I use the config below for .NET. I need TCP working but i am first testing with http since i know i had it working using privoxy. What apps and configs do i use to get TCP going through tor? <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.net> <defaultProxy enabled="true"> <proxy bypassonlocal="True" proxyaddress="http://127.0.0.1:8118"/> </defaultProxy> <settings> <httpWebRequest useUnsafeHeaderParsing="true"/> </settings> </system.net> </configuration> -edit- Thanks to Bernd i have a solution. Here is the code i ended up writing. It isn't amazing but its fair. static NetworkStream ConnectSocksProxy(string proxyDomain, short proxyPort, string host, short hostPort, TcpClient tc) { tc.Connect(proxyDomain, proxyPort); if (System.Text.RegularExpressions.Regex.IsMatch(host, @"[\:/\\]")) throw new Exception("Invalid Host name. Use FQDN such as www.google.com. Do not have http, a port or / in it"); NetworkStream ns = tc.GetStream(); var HostNameBuf = new ASCIIEncoding().GetBytes(host); var HostPortBuf = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(hostPort)); if (true) //5 { var bufout = new byte[128]; var buflen = 0; ns.Write(new byte[] { 5, 1, 0 }, 0, 3); buflen = ns.Read(bufout, 0, bufout.Length); if (buflen != 2 || bufout[0] != 5 || bufout[1] != 0) throw new Exception(); var buf = new byte[] { 5, 1, 0, 3, (byte)HostNameBuf.Length }; var mem = new MemoryStream(); mem.Write(buf, 0, buf.Length); mem.Write(HostNameBuf, 0, HostNameBuf.Length); mem.Write(new byte[] { HostPortBuf[0], HostPortBuf[1] }, 0, 2); var memarr = mem.ToArray(); ns.Write(memarr, 0, memarr.Length); buflen = ns.Read(bufout, 0, bufout.Length); if (bufout[0] != 5 || bufout[1] != 0) throw new Exception(); } else //4a { var bufout = new byte[128]; var buflen = 0; var mem = new MemoryStream(); mem.WriteByte(4); mem.WriteByte(1); mem.Write(HostPortBuf, 0, 2); mem.Write(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(1)), 0, 4); mem.WriteByte(0); mem.Write(HostNameBuf, 0, HostNameBuf.Length); mem.WriteByte(0); var memarr = mem.ToArray(); ns.Write(memarr, 0, memarr.Length); buflen = ns.Read(bufout, 0, bufout.Length); if (buflen != 8 || bufout[0] != 0 || bufout[1] != 90) throw new Exception(); } return ns; } Usage using (TcpClient client = new TcpClient()) using (var ns = ConnectSocksProxy("127.0.0.1", 9050, "website.com", 80, client)) {...}

    Read the article

  • protobuf-net: Issues deserializing DataMember fields in lieu of read-only property

    - by Paul Smith
    I'm having issues deserializing certain properties of ORM-generated entities using protobuf-net. I suspect something in the way the ORM manages serialization attributes on read-only properties (uses public backing fields with DataMember attributes & [de]serializes) those instead of the corresponding read-only property, which has an IgnoreDataMember attribute). Guid properties might have issues of their own, but the field vs. property thing is my working theory now. Here's a simplified example of the code. Say I have a class, Account with an AccountID read-only guid, and an AccountName read-write string. I serialize & immediately deserialize a clone. In this scenario I get one of two results (depending on the entity, haven't isolated the specific commonality yet). The deserialized clone either: ...has a different AccountID from the original, or ...throws an Incorrect wire-type deserializing Guid exception while deserializing. Here's example usage... Account acct = new Account() { AccountName = "Bob's Checking" }; Debug.WriteLine(acct.AccountID.ToString()); using (MemoryStream ms = new MemoryStream()) { ProtoBuf.Serializer.Serialize<Account>(ms, acct); Debug.WriteLine(Encoding.UTF8.GetString(ms.GetBuffer())); ms.Position = 0; Account clone = ProtoBuf.Serializer.Deserialize<Account>(ms); Debug.WriteLine(clone.AccountID.ToString()); } And here's an example ORM'd class (simplified; hopefully haven't removed the cause of the issue in the process). Uses a shell game to deserialize read-only properties by exposing the backing field ("can't write" essentially becomes "shouldn't write," but we can scan code for instances of assigning to these fields, so the hack works for our purposes): [DataContract()] [Serializable()] public partial class Account { public Account() { _accountID = Guid.NewGuid(); } [XmlAttribute("AccountID")] [DataMember(Name = "AccountID", Order = 0)] public Guid _accountID; /// <summary> /// A read-only property; XML, JSON and DataContract serializers all seem /// to correctly recognize the public backing field when deserializing: /// </summary> [IgnoreDataMember] [XmlIgnore] public Guid AccountID { get { return this._accountID; } } [IgnoreDataMember] protected string _accountName; [DataMember(Name = "AccountName", Order = 1)] [XmlAttribute] public string AccountName { get { return this._accountName; } set { this._accountName = value; } } } XML, JSON and DataContract serializers all seem to serialize / deserialize matching object graphs here, so this attribute arrangement apparently causes those serializers to correctly assign to the public backing field when deserializing. I've tried protobuf-net with lists vs. single instances, different prefix styles, etc., but always either get the 'incorrect wire type ... Guid' exception, or the Guid property (field) not deserializing correctly. So the specific questions are, is there a quick workaround for this, and/or is there an explanation for both of outcomes 1 & 2 above, and/or can protobuf-net somehow be corralled into behaving like WCF in cases like this (i.e. follow the same DataMember/IgnoreDataMember semantics)? We hope not to have to create a protobuf dependency directly in the entity layer; if that's the case, we'll probably create proxy DTO entities with all public properties having protobuf attributes. (This is a subjective issue I have with all declarative serialization models; it's a ubiquitous pattern, but IMO, "normal" should be to have objects and serialization contracts decoupled.) Thanks!

    Read the article

  • protobuf-net: incorrect wire-type exception deserializing Guid properties

    - by Paul Smith
    I'm having issues deserializing certain Guid properties of ORM-generated entities using protobuf-net. Here's a simplified example of the code (reproduces most elements of the scenario, but doesn't reproduce the behavior; I can't expose our internal entities, so I'm looking for clues to account for the exception). Say I have a class, Account with an AccountID read-only guid, and an AccountName read-write string. I serialize & immediately deserialize a clone. Deserializing throws an Incorrect wire-type deserializing Guid exception while deserializing. Here's example usage... Account acct = new Account() { AccountName = "Bob's Checking" }; Debug.WriteLine(acct.AccountID.ToString()); using (MemoryStream ms = new MemoryStream()) { ProtoBuf.Serializer.Serialize<Account>(ms, acct); Debug.WriteLine(Encoding.UTF8.GetString(ms.GetBuffer())); ms.Position = 0; Account clone = ProtoBuf.Serializer.Deserialize<Account>(ms); Debug.WriteLine(clone.AccountID.ToString()); } And here's an example ORM'd class (simplified, but demonstrates the relevant semantics I can think of). Uses a shell game to deserialize read-only properties by exposing the backing field ("can't write" essentially becomes "shouldn't write," but we can scan code for instances of assigning to these fields, so the hack works for our purposes). Again, this does not reproduce the exception behavior; I'm looking for clues as to what could: [DataContract()] [Serializable()] public partial class Account { public Account() { _accountID = Guid.NewGuid(); } [XmlAttribute("AccountID")] [DataMember(Name = "AccountID", Order = 1)] public Guid _accountID; /// <summary> /// A read-only property; XML, JSON and DataContract serializers all seem /// to correctly recognize the public backing field when deserializing: /// </summary> [IgnoreDataMember] [XmlIgnore] public Guid AccountID { get { return this._accountID; } } [IgnoreDataMember] protected string _accountName; [DataMember(Name = "AccountName", Order = 2)] [XmlAttribute] public string AccountName { get { return this._accountName; } set { this._accountName = value; } } } XML, JSON and DataContract serializers all seem to serialize / deserialize these object graphs just fine, so the attribute arrangement basically works. I've tried protobuf-net with lists vs. single instances, different prefix styles, etc., but still always get the 'incorrect wire-type ... Guid' exception when deserializing. So the specific questions is, is there any known explanation / workaround for this? I'm at a loss trying to trace what circumstances (in the real code but not the example) could be causing it. We hope not to have to create a protobuf dependency directly in the entity layer; if that's the case, we'll probably create proxy DTO entities with all public properties having protobuf attributes. (This is a subjective issue I have with all declarative serialization models; it's a ubiquitous pattern & I understand why it arose, but IMO, if we can put a man on the moon, then "normal" should be to have objects and serialization contracts decoupled. ;-) ) Thanks!

    Read the article

  • Need Help Setting an Image with Transparent Background to Clipboard

    - by AMissico
    I need help setting a transparent image to the clipboard. I keep getting "handle is invalid". Basically, I need a "second set of eyes" to look over the following code. (The complete working project at ftp://missico.net/ImageVisualizer.zip.) This is an image Debug Visualizer class library, but I made the included project to run as an executable for testing. (Note that window is a toolbox window and show in taskbar is set to false.) I was tired of having to perform a screen capture on the toolbox window, open the screen capture with an image editor, and then deleting the background added because it was a screen capture. So I thought I would quickly put the transparent image onto the clipboard. Well, the problem is...no transparency support for Clipboard.SetImage. Google to the rescue...not quite. This is what I have so far. I pulled from a number of sources. See the code for the main reference. My problem is the "invalid handle" when using CF_DIBV5. Do I need to use BITMAPV5HEADER and CreateDIBitmap? Any help from you GDI/GDI+ Wizards would be greatly appreciated. public static void SetClipboardData(Bitmap bitmap, IntPtr hDC) { const uint SRCCOPY = 0x00CC0020; const int CF_DIBV5 = 17; const int CF_BITMAP = 2; //'reference //'http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/816a35f6-9530-442b-9647-e856602cc0e2 IntPtr memDC = CreateCompatibleDC(hDC); IntPtr memBM = CreateCompatibleBitmap(hDC, bitmap.Width, bitmap.Height); SelectObject(memDC, memBM); using (Graphics g = Graphics.FromImage(bitmap)) { IntPtr hBitmapDC = g.GetHdc(); IntPtr hBitmap = bitmap.GetHbitmap(); SelectObject(hBitmapDC, hBitmap); BitBlt(memDC, 0, 0, bitmap.Width, bitmap.Height, hBitmapDC, 0, 0, SRCCOPY); if (!OpenClipboard(IntPtr.Zero)) { throw new System.Runtime.InteropServices.ExternalException("Could not open Clipboard", new Win32Exception()); } if (!EmptyClipboard()) { throw new System.Runtime.InteropServices.ExternalException("Unable to empty Clipboard", new Win32Exception()); } //IntPtr hClipboard = SetClipboardData(CF_BITMAP, memBM); //works but image is not transparent //all my attempts result in SetClipboardData returning hClipboard = IntPtr.Zero IntPtr hClipboard = SetClipboardData(CF_DIBV5, memBM); //because if (hClipboard == IntPtr.Zero) { // InnerException: System.ComponentModel.Win32Exception // Message="The handle is invalid" // ErrorCode=-2147467259 // NativeErrorCode=6 // InnerException: throw new System.Runtime.InteropServices.ExternalException("Could not put data on Clipboard", new Win32Exception()); } if (!CloseClipboard()) { throw new System.Runtime.InteropServices.ExternalException("Could not close Clipboard", new Win32Exception()); } g.ReleaseHdc(hBitmapDC); } } private void __copyMenuItem_Click(object sender, EventArgs e) { using (Graphics g = __pictureBox.CreateGraphics()) { IntPtr hDC = g.GetHdc(); MemoryStream ms = new MemoryStream(); __pictureBox.Image.Save(ms, ImageFormat.Png); ms.Seek(0, SeekOrigin.Begin); Image imag = Image.FromStream(ms); // Derive BitMap object using Image instance, so that you can avoid the issue //"a graphics object cannot be created from an image that has an indexed pixel format" Bitmap img = new Bitmap(new Bitmap(imag)); SetClipboardData(img, hDC); g.ReleaseHdc(); } }

    Read the article

  • pdfptable format problem?

    - by raj
    Hi, I am using the code below to convert Html string to PDF.I notice that at times, it does print the tables in PDF but no styles(no border, color etc..).Below is the html string: Can anyone suggest me where am I missing something? Hi userThe Message ID 56456 has been assigned to you for Edition. AUTO VERIFY FOR CONGROUP cccccccc FAILEDSSID ssss message, RPTD BY rrrrSSID ssss RLD ll message, RPTD BY rrrrSSID ssss DEV ddd message, RPTD BY rrrr Table 12 EMC9998W message format <table style="border: medium solid #00FF00; width:100%; table-layout: auto; visibility: visible;" title="EMC9998W message format"> <tr> <td> <b>Exception code</b></td> <td> <b>Meaning</b></td> <td> <b>Message format</b></td> </tr> <tr> <td > 1460 </td> <td> DYNAMIC SPARING INVOKED</td> <td> 1</td> </tr> <tr> <td > 147D REMOTE </td> <td > LINK DIRECTOR PROBLEM/FAILURE</td> <td> 2</td> </tr> </table> Where MSG FORMAT 1 EMC9998W SSID ssss message, RPTD BY rrrr MSG FORMAT 2 EMC9998W SSID ssss message, RPTD BY rrrr MSG FORMAT 3 EMC9998W SSID ssss message, RPTD BY rrrr private void HtmltoPdf(string s, Paragraph p,Document doc) { string strLine = s; byte[] byteArray = Encoding.ASCII.GetBytes(strLine); MemoryStream stream = new MemoryStream(byteArray); StreamReader reader2 = new StreamReader(stream); StringReader sr2 = new StringReader(reader2.ReadToEnd()); iTextSharp.text.html.simpleparser.HTMLWorker worker = new HTMLWorker(doc); ArrayList elementlist = HTMLWorker.ParseToList(sr2, null); Phrase ph = new Phrase(); for (int k = 0; k < elementlist.Count; ++k) { IElement ielement = (IElement)elementlist[k]; ArrayList chunks = ielement.Chunks; if (ielement.Type == Element.PTABLE) { PdfPTable pt = (PdfPTable)ielement; pt.DefaultCell.Border = 2; PdfPTable t = new PdfPTable(1);//(new float[] {1f,1f,1f}); ph.Add(t); PdfPCell pcell = new PdfPCell(new Paragraph(ph)); t.AddCell(pcell); p.Add(t); foreach (PdfPRow row in t.Rows) { } } else if (ielement.Type == Element.LIST) { } else { ph.Clear(); ph.Add((IElement)elementlist[k]); p.Add(new Paragraph(ph)); } } sr2.Close(); reader2.Close(); stream.Close(); }

    Read the article

  • ASP.NET Send Image Attachment With Email Without Saving To Filesystem

    - by KGO
    I'm trying to create a form that will send an email with an attached image and am running into some problems. The form I am creating is rather large so I have created a small test form for the purpose of this question. The email will send and the attachment will exist on the email, but the image is corrupt or something as it is not viewable. Also.. I do not want to save the image to the filesystem. You may think it is convoluted to take the image file from the fileupload to a stream, but this is due to the fact that the real form I am working on will allow multiple files to be added through a single fileupload and will be saved in session, thus the images will not be coming from the fileupload control directly on submit. File: TestAttachSend.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestAttachSend.aspx.cs" Inherits="TestAttachSend" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <h1>Send Email with Image Attachment</h1> Email Address TO: <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox><br /> Attach JPEG Image: <asp:FileUpload ID="fuImage" runat="server" /><br /> <br /> <asp:Button ID="btnSend" runat="server" Text="Send" onclick="btnSend_Click" /><br /> <br /> <asp:label ID="lblSent" runat="server" text="Image Sent!" Visible="false" EnableViewState="false"></asp:label> </div> </form> </body> </html> File: TestAttachSend.aspx.cs using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Net.Mail; using System.IO; public partial class TestAttachSend : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnSend_Click(object sender, EventArgs e) { if (fuImage.HasFile && fuImage.PostedFile.ContentType == System.Net.Mime.MediaTypeNames.Image.Jpeg) { SmtpClient emailClient = new SmtpClient(); MailMessage EmailMsg = new MailMessage(); EmailMsg.To.Add(txtEmail.Text.Trim()); EmailMsg.From = new MailAddress(txtEmail.Text.Trim()); EmailMsg.Subject = "Attached Image"; EmailMsg.Body = "Image is attached!"; MemoryStream imgStream = new MemoryStream(); System.Drawing.Image img = System.Drawing.Image.FromStream(fuImage.PostedFile.InputStream); string filename = fuImage.PostedFile.FileName; img.Save(imgStream, System.Drawing.Imaging.ImageFormat.Jpeg); EmailMsg..Attachments.Add(new Attachment(imgStream, filename, System.Net.Mime.MediaTypeNames.Image.Jpeg)); emailClient.Send(EmailMsg); lblSent.Visible = true; } } }

    Read the article

  • Stream.CopyTo() extension method

    - by DigiMortal
    In one of my applications I needed copy data from one stream to another. After playing with streams a little bit I wrote CopyTo() extension method to Stream class you can use to copy the contents of current stream to target stream. Here is my extension method. It is my working draft and it is possible that there must be some more checks before we can say this extension method is ready to be part of some API or class library. public static void CopyTo(this Stream fromStream, Stream toStream) {     if (fromStream == null)         throw new ArgumentNullException("fromStream");     if (toStream == null)         throw new ArgumentNullException("toStream");       var bytes = new byte[8092];     int dataRead;     while ((dataRead = fromStream.Read(bytes, 0, bytes.Length)) > 0)         toStream.Write(bytes, 0, dataRead); } And here is example how to use this extension method. using(var stream = response.GetResponseStream()) using(var ms = new MemoryStream()) {     stream.CopyTo(ms);       // Do something with copied data } I am using this code to copy data from HTTP response stream to memory stream because I have to use serializer that needs more than response stream is able to offer.

    Read the article

  • WCF Stream.Read always returns 0 in client

    - by G_M
    I've spent most of my day trying to figure out why this isn't working. I have a WCF service that streams an object to the client. The client is then supposed to write the file to its disk. But when I call stream.Read(buffer, 0, bufferLength) it always returns 0. Here's my code: namespace StreamServiceNS { [ServiceContract] public interface IStreamService { [OperationContract] Stream downloadStreamFile(); } } class StreamService : IStreamService { public Stream downloadStreamFile() { ISSSteamFile sFile = getStreamFile(); BinaryFormatter bf = new BinaryFormatter(); MemoryStream stream = new MemoryStream(); bf.Serialize(stream, sFile); return stream; } } Service config file: <system.serviceModel> <services> <service name="StreamServiceNS.StreamService"> <endpoint address="stream" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IStreamService" name="BasicHttpEndpoint_IStreamService" contract="SWUpdaterService.ISWUService" /> </service> </services> <bindings> <basicHttpBinding> <binding name="BasicHttpBinding_IStreamService" transferMode="StreamedResponse" maxReceivedMessageSize="209715200"></binding> </basicHttpBinding> </bindings> <behaviors> <serviceBehaviors> <behavior> <serviceThrottling maxConcurrentCalls ="100" maxConcurrentSessions="400"/> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> </behaviors> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> </system.serviceModel> Client: TestApp.StreamServiceRef.StreamServiceClient client = new StreamServiceRef.StreamServiceClient(); try { Stream stream = client.downloadStreamFile(); int bufferLength = 8 * 1024; byte[] buffer = new byte[bufferLength]; FileStream fs = new FileStream(@"C:\test\testFile.exe", FileMode.Create, FileAccess.Write); int bytesRead; while ((bytesRead = stream.Read(buffer, 0, bufferLength)) > 0) { fs.Write(buffer, 0, bytesRead); } stream.Close(); fs.Close(); } catch (Exception e) { Console.WriteLine("Error: " + e.Message); } Client app.config: <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicHttpEndpoint_IStreamService" maxReceivedMessageSize="209715200" transferMode="StreamedResponse"> </binding> </basicHttpBinding> </bindings> <client> <endpoint address="http://[server]/StreamServices/streamservice.svc/stream" binding="basicHttpBinding" bindingConfiguration="BasicHttpEndpoint_IStreamService" contract="StreamServiceRef.IStreamService" name="BasicHttpEndpoint_IStreamService" /> </client> </system.serviceModel> (some code clipped for brevity) I've read everything I can find on making WCF streaming services, and my code looks no different than theirs. I can replace the streaming with buffering and send an object that way fine, but when I try to stream, the client always sees the stream as "empty". The testFile.exe gets created, but its size is 0KB. What am I missing?

    Read the article

  • Need Help Setting Transparent Image to Clipboard

    - by AMissico
    I need help setting a transparent image to the clipboard. I keep getting "handle is invalid". Following is the specific code with the complete working project at ftp://missico.net/ImageVisualizer.zip. This is an image Debug Visualizer class library, but I made to run as executable for testing. (Note that window is a toolbox window and show in taskbar is set to false.) I was tired of having to perform a screen capture on the toolbox window, open with an image editor, and then deleting the background added due to the screen capture. So I thought I would quickly put the transparent image onto the clipboard. Well, the problem is...no transparency support for Clipboard.SetImage. Google to the rescue...not quite. This is what I have so far pulled from a number of sources. See the code for the main reference. My problem is the "invalid handle" when using CF_DIBV5. I imagine the problem is related to BITMAPV5HEADER and CreateDIBitmap. Any help from you GDI/GDI+ Wizards would be greatly appreciated. public static void SetClipboardData(Bitmap bitmap, IntPtr hDC) { const uint SRCCOPY = 0x00CC0020; const int CF_DIBV5 = 17; const int CF_BITMAP = 2; //'reference //'http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/816a35f6-9530-442b-9647-e856602cc0e2 IntPtr memDC = CreateCompatibleDC(hDC); IntPtr memBM = CreateCompatibleBitmap(hDC, bitmap.Width, bitmap.Height); SelectObject(memDC, memBM); using (Graphics g = Graphics.FromImage(bitmap)) { IntPtr hBitmapDC = g.GetHdc(); IntPtr hBitmap = bitmap.GetHbitmap(); SelectObject(hBitmapDC, hBitmap); BitBlt(memDC, 0, 0, bitmap.Width, bitmap.Height, hBitmapDC, 0, 0, SRCCOPY); if (!OpenClipboard(IntPtr.Zero)) { throw new System.Runtime.InteropServices.ExternalException("Could not open Clipboard", new Win32Exception()); } if (!EmptyClipboard()) { throw new System.Runtime.InteropServices.ExternalException("Unable to empty Clipboard", new Win32Exception()); } //IntPtr hClipboard = SetClipboardData(CF_BITMAP, memBM); //works but image is not transparent //all my attempts result in SetClipboardData returning hClipboard = IntPtr.Zero IntPtr hClipboard = SetClipboardData(CF_DIBV5, memBM); //because if (hClipboard == IntPtr.Zero) { // InnerException: System.ComponentModel.Win32Exception // Message="The handle is invalid" // ErrorCode=-2147467259 // NativeErrorCode=6 // InnerException: throw new System.Runtime.InteropServices.ExternalException("Could not put data on Clipboard", new Win32Exception()); } if (!CloseClipboard()) { throw new System.Runtime.InteropServices.ExternalException("Could not close Clipboard", new Win32Exception()); } g.ReleaseHdc(hBitmapDC); } } private void __copyMenuItem_Click(object sender, EventArgs e) { //'Applications that I have verified can paste the clipboard custom data format PNG are: //' Word 2003 //' Excel 2003 using (Graphics g = __pictureBox.CreateGraphics()) { IntPtr hDC = g.GetHdc(); MemoryStream ms = new MemoryStream(); __pictureBox.Image.Save(ms, ImageFormat.Png); ms.Seek(0, SeekOrigin.Begin); Image imag = Image.FromStream(ms); // Derive BitMap object using Image instance, so that you can avoid the issue //"a graphics object cannot be created from an image that has an indexed pixel format" Bitmap img = new Bitmap(new Bitmap(imag)); SetClipboardData(img, hDC); g.ReleaseHdc(); } }

    Read the article

  • Compress file to bytes for uploading to SQL Server

    - by Chris
    I am trying to zip files to an SQL Server database table. I can't ensure that the user of the tool has write priveledges on the source file folder so I want to load the file into memory, compress it to an array of bytes and insert it into my database. This below does not work. class ZipFileToSql { public event MessageHandler Message; protected virtual void OnMessage(string msg) { if (Message != null) { MessageHandlerEventArgs args = new MessageHandlerEventArgs(); args.Message = msg; Message(this, args); } } private int sourceFileId; private SqlConnection Conn; private string PathToFile; private bool isExecuting; public bool IsExecuting { get { return isExecuting; } } public int SourceFileId { get { return sourceFileId; } } public ZipFileToSql(string pathToFile, SqlConnection conn) { isExecuting = false; PathToFile = pathToFile; Conn = conn; } public void Execute() { isExecuting = true; byte[] data; byte[] cmpData; //create temp zip file OnMessage("Reading file to memory"); FileStream fs = File.OpenRead(PathToFile); data = new byte[fs.Length]; ReadWholeArray(fs, data); OnMessage("Zipping file to memory"); MemoryStream ms = new MemoryStream(); GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true); zip.Write(data, 0, data.Length); cmpData = new byte[ms.Length]; ReadWholeArray(ms, cmpData); OnMessage("Saving file to database"); using (SqlCommand cmd = Conn.CreateCommand()) { cmd.CommandText = @"MergeFileUploads"; cmd.CommandType = CommandType.StoredProcedure; //cmd.Parameters.Add("@File", SqlDbType.VarBinary).Value = data; cmd.Parameters.Add("@File", SqlDbType.VarBinary).Value = cmpData; SqlParameter p = new SqlParameter(); p.ParameterName = "@SourceFileId"; p.Direction = ParameterDirection.Output; p.SqlDbType = SqlDbType.Int; cmd.Parameters.Add(p); cmd.ExecuteNonQuery(); sourceFileId = (int)p.Value; } OnMessage("File Saved"); isExecuting = false; } private void ReadWholeArray(Stream stream, byte[] data) { int offset = 0; int remaining = data.Length; float Step = data.Length / 100; float NextStep = data.Length - Step; while (remaining > 0) { int read = stream.Read(data, offset, remaining); if (read <= 0) throw new EndOfStreamException (String.Format("End of stream reached with {0} bytes left to read", remaining)); remaining -= read; offset += read; if (remaining < NextStep) { NextStep -= Step; } } } }

    Read the article

  • WCF DataContractSerializer Behavior

    - by sbanwart
    I'm seeing some unusual behavior when using the DataContractSerializer. I have defined a message contract like so: namespace MyNamespace.DataContracts { [MessageContract(WrapperName = "order", WrapperNamespace = @"http://example.com/v1/order")] public class MyOrder { [MessageBodyMember(Namespace = @"http://http://example.com/v1/order", Order = 1)] public MyStore store; [MessageBodyMember(Namespace = @"http://http://example.com/v1/order", Order = 2)] public MyOrderHeader orderHeader; [MessageBodyMember(Namespace = @"http://example.com/v1/order", Order = 3)] public List<MyPayment> payments; [MessageBodyMember(Namespace = @"http://example.com/v1/order", Order = 4)] public List<MyShipment> shipments; } . . I'm sending it an XML message that looks like this: <?xml version="1.0" encoding="utf-8"?> <order xmlns="http://example.com/v1/order> <store> ... </store> <orderHeader> ... </orderHeader> <payments> <payment> ... </payment> </payments> <shipments> <shipment> ... </shipment> </shipments> </order> My service deserializes this XML as expected. Inside my service, I'm using the DataContractSerializer to create an XML string and that's where things get weird. I'm using the serializer like this: DataContractSerializer serializer = new DataContractSerializer(typeof(MyOrder)); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, order); ms.Position = 0; StreamReader sr = new StreamReader(ms); string outputMessage = sr.ReadToEnd(); } Once this finishes, the outputMessage contains the following XML: <?xml version="1.0" encoding="utf-8"?> <MyOrder xmlns="http://example.com/v1/order" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <order> <store> ... </store> <orderHeader> ... </orderHeader> <payments> <payment> ... </payment> </payments> <shipments> <shipment> ... </shipment> </shipments> </order> </MyOrder> Needless to say, anything expecting to receive the original XML message will fail to parse this. So I guess I have two questions: Why is the DataContractSerializer adding the extra outer node to my XML output? Is there a way to stop it from doing this? Thanks.

    Read the article

  • ASP.NET: Serializing and deserializing JSON objects

    - by DigiMortal
    ASP.NET offers very easy way to serialize objects to JSON format. Also it is easy to deserialize JSON objects using same library. In this posting I will show you how to serialize and deserialize JSON objects in ASP.NET. All required classes are located in System.Servicemodel.Web assembly. There is namespace called System.Runtime.Serialization.Json for JSON serializer. To serialize object to stream we can use the following code. var serializer = new DataContractJsonSerializer(typeof(MyClass)); serializer.WriteObject(myStream, myObject); To deserialize object from stream we can use the following code. CopyStream() is practically same as my Stream.CopyTo() extension method. var serializer = new DataContractJsonSerializer(typeof(MyClass));   using(var stream = response.GetResponseStream()) using (var ms = new MemoryStream()) {     CopyStream(stream, ms);     results = serializer.ReadObject(ms) as MyClass; } Why I copied data from response stream to memory stream? Point is simple – serializer uses some stream features that are not supported by response stream. Using memory stream we can deserialize object that came from web.

    Read the article

  • how convert this c# cod to php

    - by user3694473
    I'm trying to convert this class from C# to php and i wante to convert this c# class to php ... how i can do it Thanks in advance hi I'm trying to convert this class from C# to php and i wante to convert this c# class to php ... how i can do it Thanks in advance public class CreateCode { public string SazBon(string MM) { string RET = ""; string[] ME = new string[25]; for (int i = 1; i < MM.Length; i += 2) { ME[i] = MM[i - 1].ToString(); } for (int j = 0; j < MM.Length; j += 2) { ME[j] = MM[j + 1].ToString(); } ME[20] = "1"; ME[21] = "OH"; ME[22] = "23"; ME[23] = "fXC"; ME[24] = "5"; ME[5] = ME[14]; ME[13] = ME[23]; ME[2] = ME[22]; ME[18] = ME[21]; ME[23] = ME[11]; ME[19] = ME[0]; foreach (string item in ME) { RET += item; } string BACK = Encrypt(RET, RET, 256); BACK = encryptString(BACK); return BACK; } string encryptString(string strToEncrypt) // md5 { UTF8Encoding ue = new UTF8Encoding(); byte[] bytes = ue.GetBytes(strToEncrypt); MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] hashBytes = md5.ComputeHash(bytes); // Bytes to string return System.Text.RegularExpressions.Regex.Replace (BitConverter.ToString(hashBytes), "-", "").ToLower(); } private byte[] Encrypt(byte[] clearData, byte[] Key, byte[] IV) { MemoryStream ms = new MemoryStream(); Rijndael alg = Rijndael.Create(); alg.Key = Key; alg.IV = IV; CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(clearData, 0, clearData.Length); cs.Close(); byte[] encryptedData = ms.ToArray(); return encryptedData; } byte[] A; private string Encrypt(string Data, string Password, int Bits) { byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(Data); PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 0x00, 0x01, 0x02, 0x1C, 0x1D, 0x1E, 0x03, 0x04, 0x05, 0x0F, 0x20, 0x21, 0xAD, 0xAF, 0xA4 }); if (Bits == 128) { byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(16), pdb.GetBytes(16)); return Convert.ToBase64String(encryptedData); } else if (Bits == 192) { byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(24), pdb.GetBytes(16)); return Convert.ToBase64String(encryptedData); } else if (Bits == 256) { byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16)); return Convert.ToBase64String(encryptedData); } else { return string.Concat(Bits); } } // AES }

    Read the article

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