Search Results

Search found 460 results on 19 pages for 'streamreader'.

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

  • FtpWebRequest Download File

    - by pm_2
    The following code is intended to retrieve a file via FTP. However, I'm getting an error with it. serverPath = "ftp://x.x.x.x/tmp/myfile.txt"; FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverPath); request.KeepAlive = true; request.UsePassive = true; request.UseBinary = true; request.Method = WebRequestMethods.Ftp.DownloadFile; request.Credentials = new NetworkCredential(username, password); // Read the file from the server & write to destination using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) // Error here using (Stream responseStream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(responseStream)) using (StreamWriter destination = new StreamWriter(destinationFile)) { destination.Write(reader.ReadToEnd()); destination.Flush(); } The error is: The remote server returned an error: (550) File unavailable (e.g., file not found, no access) The file definately does exist on the remote machine and I am able to perform this ftp manually (i.e. I have permissions). Can anyone tell me why I might be getting this error?

    Read the article

  • Codemetric optimized httpwebrequest in C#

    - by Omegavirus
    Hello, the problem is the httpwebrequest method in my c# program. visual studio gives it a metric of 60, thats pretty lame.. so how can i program it more efficient? (: my actual code: public string httpRequest(string url) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.Proxy = WebRequest.DefaultWebProxy; request.MediaType = "HTTP/1.1"; request.ContentType = "text/xml"; request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader streamr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); String sresp = streamr.ReadToEnd(); streamr.Close(); return sresp; } thanks for helping. ;)

    Read the article

  • Parsing large delimited files with dynamic number of columns

    - by annelie
    Hi, What would be the best approach to parse a delimited file when the columns are unknown before parsing the file? The file format is Rightmove v3 (.blm), the structure looks like this: #HEADER# Version : 3 EOF : '^' EOR : '~' #DEFINITION# AGENT_REF^ADDRESS_1^POSTCODE1^MEDIA_IMAGE_00~ // can be any number of columns #DATA# agent1^the address^the postcode^an image~ agent2^the address^the postcode^^~ // the records have to have the same number of columns as specified in the definition, however they can be empty etc #END# The files can potentially be very large, the example file I have is 40Mb but they could be several hundred megabytes. Below is the code I had started on before I realised the columns were dynamic, I'm opening a filestream as I read that was the best way to handle large files. I'm not sure my idea of putting every record in a list then processing is any good though, don't know if that will work with such large files. List<string> recordList = new List<string>(); try { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { StreamReader file = new StreamReader(fs); string line; while ((line = file.ReadLine()) != null) { string[] records = line.Split('~'); foreach (string item in records) { if (item != String.Empty) { recordList.Add(item); } } } } } catch (FileNotFoundException ex) { Console.WriteLine(ex.Message); } foreach (string r in recordList) { Property property = new Property(); string[] fields = r.Split('^'); // can't do this as I don't know which field is the post code property.PostCode = fields[2]; // etc propertyList.Add(property); } Any ideas of how to do this better? It's C# 3.0 and .Net 3.5 if that helps. Thanks, Annelie

    Read the article

  • Asp.net Crawler Webresponse Operation Timed out.

    - by Leon
    Hi I have built a simple threadpool based web crawler within my web application. Its job is to crawl its own application space and build a Lucene index of every valid web page and their meta content. Here's the problem. When I run the crawler from a debug server instance of Visual Studio Express, and provide the starting instance as the IIS url, it works fine. However, when I do not provide the IIS instance and it takes its own url to start the crawl process(ie. crawling its own domain space), I get hit by operation timed out exception on the Webresponse statement. Could someone please guide me into what I should or should not be doing here? Here is my code for fetching the page. It is executed in the multithreaded environment. private static string GetWebText(string url) { string htmlText = ""; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.UserAgent = "My Crawler"; using (WebResponse response = request.GetResponse()) { using (Stream stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream)) { htmlText = reader.ReadToEnd(); } } } return htmlText; } And the following is my stacktrace: at System.Net.HttpWebRequest.GetResponse() at CSharpCrawler.Crawler.GetWebText(String url) in c:\myAppDev\myApp\site\App_Code\CrawlerLibs\Crawler.cs:line 366 at CSharpCrawler.Crawler.CrawlPage(String url, List1 threadCityList) in c:\myAppDev\myApp\site\App_Code\CrawlerLibs\Crawler.cs:line 105 at CSharpCrawler.Crawler.CrawlSiteBuildIndex(String hostUrl, String urlToBeginSearchFrom, List1 threadCityList) in c:\myAppDev\myApp\site\App_Code\CrawlerLibs\Crawler.cs:line 89 at crawler_Default.threadedCrawlSiteBuildIndex(Object threadedCrawlerObj) in c:\myAppDev\myApp\site\crawler\Default.aspx.cs:line 108 at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state) at System.Threading.ExecutionContext.runTryCode(Object userData) at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() at System.Threading.ThreadPoolWorkQueue.Dispatch() at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() Thanks and cheers, Leon.

    Read the article

  • Dynamically create a text file from a C# program

    - by techstu
    Can I dynamically create a text file from a C# program, using data from a previously created xml file and text file, I have written half the code, but can't go any further please help using System; using System.IO; using System.Xml; namespace Task3 { class TextFileReader { static void Main(string[] args) { String strn=" ", strsn=String.Empty; XmlTextReader reader = new XmlTextReader("my.xml"); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: // The node is an element. if (reader.HasAttributes) { strn = reader.GetAttribute(0); strsn = reader.GetAttribute(1); int counter = 0; string line; // Read the file and display it line by line. System.IO.StreamReader file = new System.IO.StreamReader("read_file.txt"); string ch, ch1; while ((line = file.ReadLine()) != null) { if (line.Substring(0, 1).Equals("%")) { int a = line.IndexOf('%'); int b = line.LastIndexOf('%'); ch = line.Substring(a + 1, b - 1); ch1 = line.Substring(a, b+1); if (ch == "name") { string test = line.Replace(ch1, strn); Console.WriteLine(test); } else if (ch == "sirname") { string test = line.Replace(ch1, strsn); Console.WriteLine(test); } } else { Console.WriteLine(line); } counter++; } file.Close(); } break; } } // Suspend the screen. Console.ReadLine(); } } } the xml file from which i am reading is: <?xml version="1.0" encoding="utf-8" ?> - <Workflow> <User UserName="pqr" Sirname="sbd" /> <User UserName="abc" Sirname="xyz" /> </Workflow> and the text file is: hi this is me %sirname% %name% but this is not wat i want..please help

    Read the article

  • How to log in to craigslist using c#

    - by kosikiza
    i m using the following code to log in to craigslist, but haven't succeeded yet. string formParams = string.Format("inputEmailHandle={0}&inputPassword={1}", "[email protected]", "removed"); //string postData = "[email protected]&inputPassword=removed"; string uri = "https://accounts.craigslist.org/"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.KeepAlive = true; request.ProtocolVersion = HttpVersion.Version10; request.Method = "POST"; byte[] postBytes = Encoding.ASCII.GetBytes(formParams); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = postBytes.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(postBytes, 0, postBytes.Length); requestStream.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); cookyHeader = response.Headers["Set-cookie"]; string pageSource; string getUrl = "https://post.craigslist.org/del"; WebRequest getRequest = WebRequest.Create(getUrl); getRequest.Headers.Add("Cookie", cookyHeader); WebResponse getResponse = getRequest.GetResponse(); using (StreamReader sr = new StreamReader(getResponse.GetResponseStream())) { pageSource = sr.ReadToEnd(); }

    Read the article

  • ftp .net getdirectory size

    - by Xaver
    hi i write method which must to know that is size of specified directory i get response from server which contains flags of file name size and other info and on the different ftp servers format of answer is different how to know format of answer? unsigned long long GetFtpDirSize(String^ ftpDir) { unsigned long long size = 0; int j = 0; StringBuilder^ result = gcnew StringBuilder(); StreamReader^ reader; FtpWebRequest^ reqFTP; reqFTP = (FtpWebRequest^)FtpWebRequest::Create(gcnew Uri(ftpDir)); reqFTP->UseBinary = true; reqFTP->Credentials = gcnew NetworkCredential("anonymous", "123"); reqFTP->Method = WebRequestMethods::Ftp::ListDirectoryDetails; reqFTP->KeepAlive = false; reqFTP->UsePassive = false; try { WebResponse^ resp = reqFTP->GetResponse(); Encoding^ code; code = Encoding::GetEncoding(1251); reader = gcnew StreamReader(resp->GetResponseStream(), code); String^ line = reader->ReadToEnd(); array<Char>^delimiters = gcnew array<Char>{ '\r', '\n' }; array<Char>^delimiters2 = gcnew array<Char>{ ' ' }; array<String^>^words = line->Split(delimiters, StringSplitOptions::RemoveEmptyEntries); array<String^>^DetPr; System::Collections::IEnumerator^ myEnum = words->GetEnumerator(); while ( myEnum->MoveNext() ) { String^ word = safe_cast<String^>(myEnum->Current); DetPr = word->Split(delimiters2); } }

    Read the article

  • copy a text file in C#

    - by melt
    I am trying to copy a text file in an other text file line by line. It seems that there is a buffer of 1024 character. If there is less than 1024 character in my file, my function will not copie in the other file. Also if there is more than 1024 character but less a factor of 1024, these exceeding characters will not be copied. Ex: 2048 character in initial file - 2048 copied 988 character in initial file - 0 copied 1256 character in initial file - 1024 copied Thks! private void button3_Click(object sender, EventArgs e) { // écrire code pour reprendre le nom du fichier sélectionné et //ajouter un suffix "_poly.txt" string ma_ligne; const int RMV_CARCT = 9; //délcaration des fichier FileStream apt_file = new FileStream(textBox1.Text, FileMode.Open, FileAccess.Read); textBox1.Text = textBox1.Text.Replace(".txt", "_mod.txt"); FileStream mdi_file = new FileStream(textBox1.Text, FileMode.OpenOrCreate,FileAccess.ReadWrite); //lecture/ecriture des fichiers en question StreamReader apt = new StreamReader(apt_file); StreamWriter mdi_line = new StreamWriter(mdi_file, System.Text.Encoding.UTF8, 16); while (apt.Peek() >= 0) { ma_ligne = apt.ReadLine(); //if (ma_ligne.StartsWith("GOTO")) //{ // ma_ligne = ma_ligne.Remove(0, RMV_CARCT); // ma_ligne = ma_ligne.Replace(" ",""); // ma_ligne = ma_ligne.Replace(",", " "); mdi_line.WriteLine(ma_ligne); //} } apt_file.Close(); mdi_file.Close(); }

    Read the article

  • SEO: A whois server that work for .SE domains?

    - by Niels Bosma
    I'm developing a small domain checker and I can't get .SE to work: public string Lookup(string domain, RecordType recordType, SeoToolsSettings.Tld tld) { TcpClient tcp = new TcpClient(); tcp.Connect(tld.WhoIsServer, 43); string strDomain = recordType.ToString() + " " + domain + "\r\n"; byte[] bytDomain = Encoding.ASCII.GetBytes(strDomain.ToCharArray()); Stream s = tcp.GetStream(); s.Write(bytDomain, 0, strDomain.Length); StreamReader sr = new StreamReader(tcp.GetStream(), Encoding.ASCII); string strLine = ""; StringBuilder builder = new StringBuilder(); while (null != (strLine = sr.ReadLine())) { builder.AppendLine(strLine); } tcp.Close(); if (tld.WhoIsDelayMs > 0) System.Threading.Thread.Sleep(tld.WhoIsDelayMs); return builder.ToString(); } I've tried whois servers whois.nic-se.se and whois.iis.se put I keep getting: # Copyright (c) 1997- .SE (The Internet Infrastructure Foundation). # All rights reserved. # The information obtained through searches, or otherwise, is protected # by the Swedish Copyright Act (1960:729) and international conventions. # It is also subject to database protection according to the Swedish # Copyright Act. # Any use of this material to target advertising or # similar activities is forbidden and will be prosecuted. # If any of the information below is transferred to a third # party, it must be done in its entirety. This server must # not be used as a backend for a search engine. # Result of search for registered domain names under # the .SE top level domain. # The data is in the UTF-8 character set and the result is # printed with eight bits. "domain google.se" not found. Edit: I've tried changing to UTF8 with no other result. When I try using whois from sysinternals I get the correct result, but not with my code, not even using SE.whois-servers.net. /Niels

    Read the article

  • How to pass filename to StandardInput (Process) in C#?

    - by Cosmo
    Hello Guys! I'm using the native windows application spamc.exe (SpamAssassin - sawin32) from command line as follows: C:\SpamAssassin\spamc.exe -R < C:\email.eml Now I'd like to call this process from C#: Process p = new Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardInput = true; p.StartInfo.FileName = @"C:\SpamAssassin\spamc.exe"; p.StartInfo.Arguments = @"-R"; p.Start(); p.StandardInput.Write(@"C:\email.eml"); p.StandardInput.Close(); Console.Write(p.StandardOutput.ReadToEnd()); p.WaitForExit(); p.Close(); The above code just passes the filename as string to spamc.exe (not the content of the file). However, this one works: Process p = new Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardInput = true; p.StartInfo.FileName = @"C:\SpamAssassin\spamc.exe"; p.StartInfo.Arguments = @"-R"; p.Start(); StreamReader sr = new StreamReader(@"C:\email.eml"); string msg = sr.ReadToEnd(); sr.Close(); p.StandardInput.Write(msg); p.StandardInput.Close(); Console.Write(p.StandardOutput.ReadToEnd()); p.WaitForExit(); p.Close(); Could someone point me out why it's working if I read the file and pass the content to spamc, but doesn't work if I just pass the filename as I'd do in windows command line?

    Read the article

  • Keeping the UI responsive while parsing a very large logfile

    - by Carlos
    I'm writing an app that parses a very large logfile, so that the user can see the contents in a treeview format. I've used a BackGroundWorker to read the file, and as it parses each message, I use a BeginInvoke to get the GUI thread to add a node to my treeview. Unfortunately, there's two issues: The treeview is unresponsive to clicks or scrolls while the file is being parsed. I would like users to be able to examine (ie expand) nodes while the file is parsing, so that they don't have to wait for the whole file to finish parsing. The treeview flickers each time a new node is added. Here's the code inside the form: private void btnChangeDir_Click(object sender, EventArgs e) { OpenFileDialog browser = new OpenFileDialog(); if (browser.ShowDialog() == DialogResult.OK) { tbSearchDir.Text = browser.FileName; BackgroundWorker bgw = new BackgroundWorker(); bgw.DoWork += (ob, evArgs) => ParseFile(tbSearchDir.Text); bgw.RunWorkerAsync(); } } private void ParseFile(string inputfile) { FileStream logFileStream = new FileStream(inputfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); StreamReader LogsFile = new StreamReader(logFileStream); while (!LogsFile.EndOfStream) { string Msgtxt = LogsFile.ReadLine(); Message msg = new Message(Msgtxt.Substring(26)); //Reads the text into a class with appropriate members AddTreeViewNode(msg); } } private void AddTreeViewNode(Message msg) { TreeNode newNode = new TreeNode(msg.SeqNum); BeginInvoke(new Action(() => { treeView1.BeginUpdate(); treeView1.Nodes.Add(newNode); treeView1.EndUpdate(); Refresh(); } )); } What needs to be changed?

    Read the article

  • How can I get at the raw bytes of the request in WCF?

    - by Gregory Higley
    For logging purposes, I want to get at the raw request sent to my RESTful web service implemented in WCF. I have already implemented IDispatchMessageInspector. In my implementation of AfterReceiveRequest, I want to spit out the raw bytes of the message even (and especially) if the content of the message is invalid. This is for debugging purposes. My service works perfectly already, but it is often helpful when working through problems with clients who are trying to call the service to know what it was they sent, i.e., the raw bytes. For example, let's say that instead of sending a well-formed XML document, they post the string "your mama" to my service endpoint. I want to see that that's what they did. Unfortunately using MessageBuffer::CreateBufferedCopy() won't work unless the contents of the message are already well-formed XML. Here's (roughly) what I already have in my implementation of AfterReceiveRequest: // The immediately following line raises an exception if the message // does not contain valid XML. This is uncool because I want // the raw bytes regardless of whether they are valid or not. using (MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue)) { using (MemoryStream stream = new MemoryStream()) using (StreamReader reader = new StreamReader(stream)) { buffer.WriteMessage(stream); stream.Position = 0; Trace.TraceInformation(reader.ReadToEnd()); } request = buffer.CreateMessage(); } My guess here is that I need to get at the raw request before it becomes a Message. This will most likely have to be done at a lower level in the WCF stack than an IDispatchMessageInspector. Anyone know how to do this?

    Read the article

  • Reading and writing XML over an SslStream

    - by Mark
    I want to read and write XML data over an SslStream. The data (written and read) consists of objects serialized by an XmlSerializer. I have tried the following; (left some details out for clarity!) TcpClient tcpClient = new TcpClient(server, port); SslStream sslStream = new SslStream(tcpClient.GetStream(), true, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); sslStream.AuthenticateAsClient(server); XmlReader xmlReader = XmlReader.Create(sslStream,readerSettings); XmlWriter xmlWriter = XmlWriter.Create(sslStream,writerSettings); myClass c = new myClass (); XmlSerializer serializer = new XmlSerializer(typeof(myClass)); serializer.Serialize(xmlWriter, c); myClass c2 = (myClass )serializer.Deserialize(xmlReader); First of all, it appears that writing to the stream succeeds. But the XmlSerializer throws an error because of invalid XML. It appears that the first character read from the stream is '00' or a null-character. (I have googled this problem, and see a million people with the same 'problem', but no viable solution.) I can work around this 'issue' by using a StreamReader, read everything into a string and then use that string as input for another stream that the serializer can use. (Very dirty, but it works.) Second problem is, that when I try to use the same SslStream to write a second request, I do not get a response from the Reader. (The server DOES send a valid XML response though!) So the serializer.Serialize(xmlWriter, c3) works, but reading from the stream yields no results. I have tried several different classes that implement Stream. (StreamReader, XmlTextReader, etc.) Anyone has an idea how reading and writing XML data to and from an SslStream is supposed to work? Thanks in advance!

    Read the article

  • How to send a JSONObject to a REST service?

    - by Sebi
    Retrieving data from the REST Server works well, but if I want to post an object it doesn't work: public static void postJSONObject(int store_type, FavoriteItem favorite, String token, String objectName) { String url = ""; switch(store_type) { case STORE_PROJECT: url = URL_STORE_PROJECT_PART1 + token + URL_STORE_PROJECT_PART2; //data = favorite.getAsJSONObject(); break; } HttpClient httpClient = new DefaultHttpClient(); HttpPost postMethod = new HttpPost(url); try { HttpEntity entity = new StringEntity("{\"ID\":0,\"Name\":\"Mein Projekt10\"}"); postMethod.setEntity(entity); HttpResponse response = httpClient.execute(postMethod); Log.i("JSONStore", "Post request, to URL: " + url); System.out.println("Status code: " + response.getStatusLine().getStatusCode()); } catch (ClientProtocolException e) { I always get a 400 Error Code. Does anybody know whats wrong? I have working C# code, but I can't convert: System.Net.WebRequest wr = System.Net.HttpWebRequest.Create("http://localhost:51273/WSUser.svc/pak3omxtEuLrzHSUSbQP/project"); wr.Method = "POST"; string data = "{\"ID\":1,\"Name\":\"Mein Projekt\"}"; byte [] d = UTF8Encoding.UTF8.GetBytes(data); wr.ContentLength = d.Length; wr.ContentType = "application/json"; wr.GetRequestStream().Write(d, 0, d.Length); System.Net.WebResponse wresp = wr.GetResponse(); System.IO.StreamReader sr = new System.IO.StreamReader(wresp.GetResponseStream()); string line = sr.ReadToEnd();

    Read the article

  • Exception handling in biztalk 2006 R2

    - by IB
    Hello I have a Biztalk 2006 R2 project (used with ESB Guidance 1) I am calling from orchstration to a static method in c# code, this method uses a class to load a file data into xlang message body at part 0 When i pass filepath which doesnt exists the inside class catch the exception but dont throw it up (in the static method there is a catch block and in the orchstration there is the real handling of the exception) The static method is : public static XLANGMessage LoadFileIntoMessage(XLANGMessage message, string filePath,Encoding encoding) { try { IStreamFactory sf = new FileStreamFactory(filePath,encoding); message[0].LoadFrom(sf); return message; } catch (Exception ex) { throw ex; } } The Class which load the file stream is : private class FileStreamFactory : IStreamFactory { string _fname; Encoding _encoding; public FileStreamFactory(string fname,Encoding encoding) { _fname = fname; _encoding = encoding; } public Stream CreateStream() { try { StreamReader sr; sr = new StreamReader ( _fname, _encoding ); return sr.BaseStream; } catch (Exception ex) { throw ex; } } } I call the static method from the orchstration and expect to catch the exception in my orchstration after the class and the emthod gets it

    Read the article

  • C# Find and Replace a section of a string with wildcard type search using RegEx (while retaining som

    - by fraXis
    Hello, I am trying to replace some text in a string with different text while retaining some of the text and I am having trouble doing it. My code is: StreamReader reader = new StreamReader(fDialog.FileName.ToString()); string content = reader.ReadToEnd(); reader.Close(); /Replace M2 with M3 (this works fine) content = Regex.Replace(content, "M2", "M3"); I want to replace a string that contains this: Z0.1G0H1E1 and turn it into: G54G43Z.1H1M08 (Note the Z value and the H value contain the same numeric value before the text change) The trouble I am having is that when I replace the values, I need to retain the H value and the Z value from the first set of text. For example, Z0.5G0H5E1 I need to add the new text, but also add the H5 and Z0.5 back into the text such as: G54G43Z0.5H5M08 But the Z values and H values will be different every time, so I need to capture those values and reinsert them back into the string when add the new G54G43 values. Can someone please show me how to do this using Regex.Replace? Thanks so much, Shawn

    Read the article

  • How do I simulate the usage of a sequence of web pages?

    - by Rory Becker
    I have a simple sequence of web pages written in ASP.Net 3.5 SP1. Page1 - A Logon Form.... txtUsername, txtPassword and cmdLogon Page2 - A Menu (created using DevExpress ASP.Net controls) Page3 - The page redirected to by the server in the event that the user picks the right menu option in Page2 I would like to create a threaded program to simulate many users trying to use this sequence of pages. I have managed to create a host Winforms app which Launches a new thread for each "User" I have further managed to work out the basics of WebRequest enough to perform a request which retrieves the Logon page itself. Dim Request As HttpWebRequest = TryCast(WebRequest.Create("http://MyURL/Logon.aspx"), HttpWebRequest) Dim Response As HttpWebResponse = TryCast(Request.GetResponse(), HttpWebResponse) Dim ResponseStream As StreamReader = New StreamReader(Response.GetResponseStream(), Encoding.GetEncoding(1252)) Dim HTMLResponse As String = ResponseStream.ReadToEnd() Response.Close() ResponseStream.Close() Next I need to simulate the user having entered information into the 2 TextBoxes and pressing logon.... I have a hunch this requires me to add the right sort of "PostData" to the request. before submitting. However I'm also concerned that "ViewState" may be an issue. Am I correct regarding the PostData? How do I add the postData to the request? Do I need to be concerned about Viewstate? Update: While I appreciate that Selenium or similar products are useful for acceptance testing , I find that they are rather clumsy for what amounts to load testing. I would prefer not to load 100 instances of Firefox or IE in order to simulate 100 users hitting my site. This was the reason I was hoping to take the ASPNet HttpWebRequest route.

    Read the article

  • Understanding F# Asynchronous Programming

    - by Yin Zhu
    I kind of know the syntax of asynchronous programming in F#. E.g. let downloadUrl(url:string) = async { let req = HttpWebRequest.Create(url) // Run operation asynchronously let! resp = req.AsyncGetResponse() let stream = resp.GetResponseStream() // Dispose 'StreamReader' when completed use reader = new StreamReader(stream) // Run asynchronously and then return the result return! reader.AsyncReadToEnd() } In F# expert book (and many other sources), they say like let! var = expr simply means "perform the asynchronous operation expr and bind the result to var when the operation completes. Then continue by executing the rest of the computation body" I also know that a new thread is created when performing async operation. My original understanding was that there are two parallel threads after the async operation, one doing I/O and one continuing to execute the async body at the same time. But in this example, I am confused at let! resp = req.AsyncGetResponse() let stream = resp.GetResponseStream() What happens if resp has not started yet and the thread in the async body wants to GetResponseStream? Is this a possible error? So maybe my original understanding was wrong. The quoted sentences in the F# expert book actually means that "creating a new thread, hang the current thread up, when the new thread finishes, wake up the body thread and continue", but in this case I don't see we could save any time. In the original understanding, the time is saved when there are several independent IO operations in one async block so that they could be done at the same time without intervention with each other. But here, if I don't get the response, I cannot create the stream; only I have stream, I can start reading the stream. Where's the time gained?

    Read the article

  • How can I add the column data type after adding the column headers to my datatable?

    - by Kevin
    Using the code below (from a console app I've cobbled together), I add seven columns to my datatable. Once this is done, how can I set the data type for each column? For instance, column 1 of the datatable will have the header "ItemNum" and I want to set it to be an Int. I've looked at some examples on thet 'net, but most all of them show creating the column header and column data type at once, like this: loadDT.Columns.Add("ItemNum", typeof(Int)); At this point in my program, the column already has a name. I just want to do something like this (not actual code): loadDT.Column[1].ChangeType(typeof(int)); Here's my code so far (that gives the columns their name): // get column headings for datatable by reading first line of csv file. StreamReader sr = new StreamReader(@"c:\load_forecast.csv"); headers = sr.ReadLine().Split(','); foreach (string header in headers) { loadDT.Columns.Add(header); } Obviously, I'm pretty new at this, but trying very hard to learn. Can someone point me in the right direction? Thanks!

    Read the article

  • How to intercept, parse and compile?

    - by epitka
    This is a problem I've been struggling to solve for a while. I need a way to either replace code in the method with a parsed code from the template at compile time (PostSharp comes to mind) or to create a dynamic proxy (Linfu or Castle). So given a source code like this [Template] private string GetSomething() { var template = [%=Customer.Name%] } I need it to be compiled into this private string GetSomething() { MemoryStream mStream = new MemoryStream(); StreamWriter writer = new StreamWriter(mStream,System.Text.Encoding.UTF8); writer.Write(@"" ); writer.Write(Customer.Name); StreamReader sr = new StreamReader(mStream); writer.Flush(); mStream.Position = 0; return sr.ReadToEnd(); } It is not important what technology is used. I tried with PostSharp's ImplementMethodAspect but got nowhere (due to lack of experience with it). I also looked into Linfu framework. Can somebody suggest some other approach or way to do this, I would really appreciate. My whole project depends on this.

    Read the article

  • how to login to criaglist through c#

    - by kosikiza
    i m using the following code to login to criaglist, but hav't successsed yet. string formParams = string.Format("inputEmailHandle={0}&inputPassword={1}", "[email protected]", "pakistan01"); //string postData = "[email protected]&inputPassword=pakistan01"; string uri = "https://accounts.craigslist.org/"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.KeepAlive = true; request.ProtocolVersion = HttpVersion.Version10; request.Method = "POST"; byte[] postBytes = Encoding.ASCII.GetBytes(formParams); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = postBytes.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(postBytes, 0, postBytes.Length); requestStream.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); cookyHeader = response.Headers["Set-cookie"]; string pageSource; string getUrl = "https://post.craigslist.org/del"; WebRequest getRequest = WebRequest.Create(getUrl); getRequest.Headers.Add("Cookie", cookyHeader); WebResponse getResponse = getRequest.GetResponse(); using (StreamReader sr = new StreamReader(getResponse.GetResponseStream())) { pageSource = sr.ReadToEnd(); }

    Read the article

  • Memory leak when changing Text field of a Scintilla object.

    - by PlaZmaZ
    I have a relatively large program that I'm optimizing for ASCII input files around 10-80mB in size. The program reads every line of the file into a stringbuilder and then sets the Text field of the ScintillNET object to the stringbuilder. The stringbuilder is then set to null. private void ReloadFile(string sFile) { txt_log.ResetText(); try { StringBuilder sLine = new StringBuilder(""); using (StreamReader sr = new StreamReader(sFile)) { while (true) { string temp = sr.ReadLine(); if (temp == null) break; sLine.AppendLine(temp); } sr.Close(); } txt_log.Text = sLine.ToString(); sLine = null; } catch (Exception ex) { MessageBox.Show(this, "An error occurred opening this file.\n\n" + ex.Message, "File Open Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } GC.Collect(); } The program has an option to reload or open a file. This is irrelevant, as any call to txt_log.Text seems to not get rid of the previous memory used for the .Text field. Commenting out the txt_log.Text line gives proper memory behavior. The GC.Collect() line seems pointless, and I have tried both with and without it. Is there something I'm missing here? I HIGHLY doubt it's a problem with the ScintillaNET component itself--rather something in this 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 get the source code as register user.

    - by nir143
    hi. i downloaded a sourcecode of a site,but i downloaded it i saw it identify my program as a guest,i search at google and figure out that i can send a cookie when i "ask" the source code. that what i have managed to do and it still dont identify me as register user: CookieContainer cj = new CookieContainer(); string all = ""; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Url); req.CookieContainer = cj; HttpWebResponse res = (HttpWebResponse)req.GetResponse(); CookieCollection cs=cj.GetCookies(req.RequestUri); CookieContainer cc = new CookieContainer(); cc.Add(cs); req.CookieContainer = cc; StreamReader read = new StreamReader(res.GetResponseStream()); all = read.ReadToEnd(); read.Close(); return all; what is wrong here? tyvm for help:) (if that help,i can have a simple details of a register user of the site).

    Read the article

  • How do I use HttpWebRequest GET method w/ ContentType="application/json"

    - by Stephen Patten
    Hello, This one is real simple, run this Silverlight4 example with the ContentType property commented out and you'll get back a response from from my service in xml. Now uncomment the property and run it and you'll get an ProtocolViolationException, what should happen is the service returns JSON formatted data. HttpWebRequest wreq = (HttpWebRequest)WebRequestCreator.ClientHttp.Create(new Uri("http://stephenpattenconsulting.com/Services/GetFoodDescriptionsLookup(2100)")); //wreq.ContentType = "application/json"; wreq.BeginGetResponse((cb) => { HttpWebRequest rq = cb.AsyncState as HttpWebRequest; HttpWebResponse resp = rq.EndGetResponse(cb) as HttpWebResponse; // Exception StreamReader rdr = new StreamReader(resp.GetResponseStream()); string result = rdr.ReadToEnd(); rdr.Close(); }, wreq); EDIT: While perusing SO, I noticed similar posts, like this one Why am I getting ProtocolViolationException when trying to use HttpWebRequest? and this one How do I use HttpWebRequest with GET method EDIT: The WCF 4 end point is 'adapted' from this link http://geekswithblogs.net/michelotti/archive/2010/08/21/restful-wcf-services-with-no-svc-file-and-no-config.aspx. I can use Fiddler's request builder to to construct the proper requests and changing the content type does yield the correct results.

    Read the article

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