Search Results

Search found 58 results on 3 pages for 'asciiencoding'.

Page 3/3 | < Previous Page | 1 2 3 

  • How to change the Array Element names in XmlSerialization?

    - by MSDN Geek
    Hi Guys, Consider the following code: [Serializable] public class Human { public string Name { get; set; } } Then, using (MemoryStream ms = new MemoryStream()) { Human[] mans = new Human[] { new Human() { Name = "Moim" } }; XmlSerializer xs = new XmlSerializer(typeof(Human[])); xs.Serialize(ms, mans); string s = System.Text.ASCIIEncoding.ASCII.GetString(ms.ToArray()); } At this point, the variable s will hold a value like, <?xml version="1.0"?> <ArrayOfHuman xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Human> <Name>Moim</Name> </Human> </ArrayOfHuman> Now all I need to do is, changing the xml array root element 'ArrayOfHuman' to something like 'MyFavoriteArrayRootName'. I have seen the IXmlSerializable interface but, that skips the root element name. Anybody has got any idea how to achieve this? All comments will be greatly appreciated. Best regards.

    Read the article

  • Loading XML from Web Service

    - by Lukasz
    I am connecting to a web service to get some data back out as xml. The connection works fine and it returns the xml data from the service. var remoteURL = EveApiUrl; var postData = string.Format("userID={0}&apikey={1}&characterID={2}", UserId, ApiKey, CharacterId); var request = (HttpWebRequest)WebRequest.Create(remoteURL); request.Method = "POST"; request.ContentLength = postData.Length; request.ContentType = "application/x-www-form-urlencoded"; // Setup a stream to write the HTTP "POST" data var WebEncoding = new ASCIIEncoding(); var byte1 = WebEncoding.GetBytes(postData); var newStream = request.GetRequestStream(); newStream.Write(byte1, 0, byte1.Length); newStream.Close(); var response = (HttpWebResponse)request.GetResponse(); var receiveStream = response.GetResponseStream(); var readStream = new StreamReader(receiveStream, Encoding.UTF8); var webdata = readStream.ReadToEnd(); Console.WriteLine(webdata); This prints out the xml that comes from the service. I can also save the xml as an xml file like so; TextWriter writer = new StreamWriter(@"C:\Projects\TrainingSkills.xml"); writer.WriteLine(webdata); writer.Close(); Now I can load the file as an XDocument to perform queries on it like this; var data = XDocument.Load(@"C:\Projects\TrainingSkills.xml"); What my problem is that I don't want to save the file and then load it back again. When I try to load directly from the stream I get an exception, Illegal characters in path. I don't know what is going on, if I can load the same xml as a text file why can't I load it as a stream. The xml is like this; <?xml version='1.0' encoding='UTF-8'?> <eveapi version="2"> <currentTime>2010-04-28 17:58:27</currentTime> <result> <currentTQTime offset="1">2010-04-28 17:58:28</currentTQTime> <trainingEndTime>2010-04-29 02:48:59</trainingEndTime> <trainingStartTime>2010-04-28 00:56:42</trainingStartTime> <trainingTypeID>3386</trainingTypeID> <trainingStartSP>8000</trainingStartSP> <trainingDestinationSP>45255</trainingDestinationSP> <trainingToLevel>4</trainingToLevel> <skillInTraining>1</skillInTraining> </result> <cachedUntil>2010-04-28 18:58:27</cachedUntil> </eveapi> Thanks for your help!

    Read the article

  • Defining where on the page the flowdocument I am printing will 'start' and 'end'

    - by Sagi1981
    Dear community. I am almost done with implementing a printing functionality, but I am having trouble getting the last hurdle done with. My problem is, that I am printing some reports, consisting of a header (with information about the person the report is about), a footer (with a page number) and the content in the middle, which is a FlowDocument. Since the flowdocuments can be fairly long, It is very possible that they will span multiple pages. My approach is to make a custom FlowDocumentPaginator which derives from DocumentPaginator. In there i define my header and my footer. However, when I print my page, the flowdocument and my header and footer are on top of eachother. So my question is plain and simple - how do I define from where and to where the flowdocument part on the pages will be placed? here is the code from my custommade Paginator: public class HeaderedFlowDocumentPaginator : DocumentPaginator { private DocumentPaginator flowDocumentpaginator; public HeaderedFlowDocumentPaginator(FlowDocument document) { flowDocumentpaginator = ((IDocumentPaginatorSource) document).DocumentPaginator; } public override bool IsPageCountValid { get { return flowDocumentpaginator.IsPageCountValid; } } public override int PageCount { get { return flowDocumentpaginator.PageCount; } } public override Size PageSize { get { return flowDocumentpaginator.PageSize; } set { flowDocumentpaginator.PageSize = value; } } public override IDocumentPaginatorSource Source { get { return flowDocumentpaginator.Source; } } public override DocumentPage GetPage(int pageNumber) { DocumentPage page = flowDocumentpaginator.GetPage(pageNumber); ContainerVisual newVisual = new ContainerVisual(); newVisual.Children.Add(page.Visual); DrawingVisual header = new DrawingVisual(); using (DrawingContext dc = header.RenderOpen()) { //Header data } newVisual.Children.Add(header); DrawingVisual footer = new DrawingVisual(); using (DrawingContext dc = footer.RenderOpen()) { Typeface typeface = new Typeface("Trebuchet MS"); FormattedText text = new FormattedText("Page " + (pageNumber + 1).ToString(), CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, 14, Brushes.Black); dc.DrawText(text, new Point(page.Size.Width - 100, page.Size.Height-30)); } newVisual.Children.Add(footer); DocumentPage newPage = new DocumentPage(newVisual); return newPage; } } And here is the printdialogue call: private void btnPrint_Click(object sender, RoutedEventArgs e) { try { PrintDialog printDialog = new PrintDialog(); if (printDialog.ShowDialog() == true) { FlowDocument fd = new FlowDocument(); MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(<My string of text - RTF formatted>)); TextRange tr = new TextRange(fd.ContentStart, fd.ContentEnd); tr.Load(stream, DataFormats.Rtf); stream.Close(); fd.ColumnWidth = printDialog.PrintableAreaWidth; HeaderedFlowDocumentPaginator paginator = new HeaderedFlowDocumentPaginator(fd); printDialog.PrintDocument(paginator, "myReport"); } } catch (Exception ex) { //Handle } }

    Read the article

  • .NET C# Filestream writing to file and reading the bfile

    - by pythonrg7
    I have a web service that checks a dictionary to see if a file exists and then if it does exist it reads the file, otherwise it saves to the file. This is from a web app. I wonder what is the best way to do this because I occasionally get a FileNotFoundException exception if the same file is accessed at the same time. Here's the relevant parts of the code: String signature; signature = "FILE," + value1 + "," + value2 + "," + value3 + "," + value4; // this is going to be the filename string result; MultipleRecordset mrSummary = new MultipleRecordset(); // MultipleRecordset is an object that retrieves data from a sql server database if (mrSummary.existsFile(signature)) { result = mrSummary.retrieveFile(signature); } else { result = mrSummary.getMultipleRecordsets(System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString(), value1, value2, value3, value4); mrSummary.saveFile(signature, result); } Here's the code to see if the file already exists: private static Dictionary dict = new Dictionary(); public bool existsFile(string signature) { if (dict.ContainsKey(signature)) { return true; } else { return false; } } Here's what I use to retrieve if it already exists: try { byte[] buffer; FileStream fileStream = new FileStream(@System.Configuration.ConfigurationManager.AppSettings["CACHEPATH"] + filename, FileMode.Open, FileAccess.Read, FileShare.Read); try { int length = 0x8000; // get file length buffer = new byte[length]; // create buffer int count; // actual number of bytes read JSONstring = ""; while ((count = fileStream.Read(buffer, 0, length)) > 0) { JSONstring += System.Text.ASCIIEncoding.ASCII.GetString(buffer, 0, count); } } finally { fileStream.Close(); } } catch (Exception e) { JSONstring = "{\"error\":\"" + e.ToString() + "\"}"; } If the file doesn't previously exist it saves the JSON to the file: try { if (dict.ContainsKey(filename) == false) { dict.Add(filename, true); } else { this.retrieveFile(filename, ipaddress); } } catch { } try { TextWriter tw = new StreamWriter(@System.Configuration.ConfigurationManager.AppSettings["CACHEPATH"] + filename); tw.WriteLine(JSONstring); tw.Close(); } catch { } Here are the details to the exception I sometimes get from running the above code: System.IO.FileNotFoundException: Could not find file 'E:\inetpub\wwwroot\cache\FILE,36,36.25,14.5,14.75'. File name: 'E:\inetpub\wwwroot\cache\FILE,36,36.25,14.5,14.75' at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) at com.myname.business.MultipleRecordset.retrieveFile(String filename, String ipaddress)

    Read the article

  • Invalid character in a Base-64 string when Concatenating and Url encoding a string

    - by Rob
    I’m trying to write some encryption code that is passed through a Url. For the sake of the issue I’ve excluded the actual encryption of the data and just shown the code causing the problem. I take a salt value, convert it to a byte array and then convert that to a base64 string. This string I concatenate to another base64 string (which was previously a byte array). These two base64 strings are then Url encoded. Here’s my code... using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; using System.IO; using System.Web; class RHEncryption { private static readonly Encoding ASCII_ENCODING = new System.Text.ASCIIEncoding(); private static readonly string SECRET_KEY = "akey"; private static string md5(string text) { return BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(ASCII_ENCODING.GetBytes(text))).Replace("-", "").ToLower(); } public string UrlEncodedData; public RHEncryption() { // encryption object RijndaelManaged aes192 = new RijndaelManaged(); aes192.KeySize = 192; aes192.BlockSize = 192; aes192.Mode = CipherMode.CBC; aes192.Key = ASCII_ENCODING.GetBytes(md5(SECRET_KEY)); aes192.GenerateIV(); // convert Ivector to base64 for sending string base64IV = Convert.ToBase64String(aes192.IV); // salt value string s = "maryhadalittlelamb"; string salt = s.Substring(0, 8); // convert to byte array // and base64 for sending byte[] saltBytes = ASCII_ENCODING.GetBytes(salt.TrimEnd('\0')); string base64Salt = Convert.ToBase64String(saltBytes); //url encode concatenated base64 strings UrlEncodedData = HttpUtility.UrlEncode(base64Salt + base64IV, ASCII_ENCODING); } public string UrlDecodedData() { // decode the url encode string string s = HttpUtility.UrlDecode(UrlEncodedData, ASCII_ENCODING); // convert back from base64 byte[] base64DecodedBytes = null; try { base64DecodedBytes = Convert.FromBase64String(s); } catch (FormatException e) { Console.WriteLine(e.Message.ToString()); Console.ReadLine(); } return s; } } If I then call the UrlDecodedData method I get a “Invalid character in a Base-64 string” exception. This is generated because the base64Salt variable contains an invalid character (I’m guessing a line termination) but I can’t seem to strip it off.

    Read the article

  • How to obtain the first cluster of the directory's data in FAT using C# (or at least C++) and Win32A

    - by DarkWalker
    So I have a FAT drive, lets say H: and a directory 'work' (full path 'H:\work'). I need to get the NUMBER of the first cluster of that directory. The number of the first cluster is 2-bytes value, that is stored in the 26th and 27th bytes of the folder enty (wich is 32 bytes). Lets say I am doing it with file, NOT a directory. I can use code like this: static public string GetDirectoryPtr(string dir) { IntPtr ptr = CreateFile(@"H:\Work\dover.docx", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0,//FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero); try { const uint bytesToRead = 2; byte[] readbuffer = new byte[bytesToRead]; if (ptr.ToInt32() == -1) return String.Format("Error: cannot open direcotory {0}", dir); if (SetFilePointer(ptr, 26, 0, 0) == -1) return String.Format("Error: unable to set file pointer on file {0}", ptr); uint read = 0; // real count of read bytes if (!ReadFile(ptr, readbuffer, bytesToRead, out read, 0)) return String.Format("cant read from file {0}. Error #{1}", ptr, Marshal.GetLastWin32Error()); int result = readbuffer[0] + 16 * 16 * readbuffer[1]; return result.ToString();//ASCIIEncoding.ASCII.GetString(readbuffer); } finally { CloseHandle(ptr); } } And it will return some number, like 19 (quite real to me, this is the only file on the disk). But I DONT need a file, I need a folder. So I am puttin FILE_FLAG_BACKUP_SEMANTICS param for CreateFile call... and dont know what to do next =) msdn is very clear on this issue http://msdn.microsoft.com/en-us/library/aa365258(v=VS.85).aspx It sounds to me like: "There is no way you can get a number of the folder's first cluster". The most desperate thing is that my tutor said smth like "You are going to obtain this or you wont pass this course". The true reason why he is so sure this is possible is because for 10 years (or may be more) he recieved the folder's first cluster number as a HASH of the folder's addres (and I was stupid enough to point this to him, so now I cant do it the same way) PS: This is the most spupid task I have ever had!!! This value is not really used anythere in program, it is only fcking pointless integer.

    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

  • HttpWebRequest: How to find a postal code at Canada Post through a WebRequest with x-www-form-enclos

    - by Will Marcouiller
    I'm currently writing some tests so that I may improve my skills with the Internet interaction through Windows Forms. One of those tests is to find a postal code which should be returned by Canada Post website. My default URL setting is set to: http://www.canadapost.ca/cpotools/apps/fpc/personal/findByCity?execution=e4s1 The required form fields are: streetNumber, streetName, city, province The contentType is "application/x-www-form-enclosed" EDIT: Please consider the value "application/x-www-form-encoded" instead of point 3 value as the contentType. (Thanks EricLaw-MSFT!) The result I get is not the result expected. I get the HTML source code of the page where I could manually enter the information to find the postal code, but not the HTML source code with the found postal code. Any idea of what I'm doing wrong? Shall I consider going the XML way? Is it first of all possible to search on Canada Post anonymously? Here's a code sample for better description: public static string FindPostalCode(ICanadadianAddress address) { var postData = string.Concat(string.Format("&streetNumber={0}", address.StreetNumber) , string.Format("&streetName={0}", address.StreetName) , string.Format("&city={0}", address.City) , string.Format("&province={0}", address.Province)); var encoding = new ASCIIEncoding(); byte[] postDataBytes = encoding.GetBytes(postData); request = (HttpWebRequest)WebRequest.Create(DefaultUrlSettings); request.ImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Anonymous; request.Container = new CookieContainer(); request.Timeout = 10000; request.ContentType = contentType; request.ContentLength = postDataBytes.LongLength; request.Method = @"post"; var senderStream = new StreamWriter(request.GetRequestStream()); senderStream.Write(postDataBytes, 0, postDataBytes.Length); senderStream.Close(); string htmlResponse = new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd(); return processedResult(htmlResponse); // Processing the HTML source code parsing, etc. } I seem stuck in a bottle neck in my point of view. I find no way out to the desired result. EDIT: There seems to have to parameters as for the ContentType of this site. Let me explain. There's one with the "meta"-variables which stipulates the following: meta http-equiv="Content-Type" content="application/xhtml+xml, text/xml, text/html; charset=utf-8" And another one later down the code that is read as: form id="fpcByAdvancedSearch:fpcSearch" name="fpcByAdvancedSearch:fpcSearch" method="post" action="/cpotools/apps/fpc/personal/findByCity?execution=e1s1" enctype="application/x-www-form-urlencoded" My question is the following: With which one do I have to stick? Let me guess, the first ContentType is to be considered as the second is only for another request to a function or so when the data is posted? EDIT: As per request, the closer to the solution I am is listed under this question: WebRequest: How to find a postal code using a WebRequest against this ContentType=”application/xhtml+xml, text/xml, text/html; charset=utf-8”? Thanks for any help! :-)

    Read the article

< Previous Page | 1 2 3