Search Results

Search found 16 results on 1 pages for 'preauthenticate'.

Page 1/1 | 1 

  • .NET WebRequest.PreAuthenticate not quite what it sounds like

    - by Rick Strahl
    I’ve run into the  problem a few times now: How to pre-authenticate .NET WebRequest calls doing an HTTP call to the server – essentially send authentication credentials on the very first request instead of waiting for a server challenge first? At first glance this sound like it should be easy: The .NET WebRequest object has a PreAuthenticate property which sounds like it should force authentication credentials to be sent on the first request. Looking at the MSDN example certainly looks like it does: http://msdn.microsoft.com/en-us/library/system.net.webrequest.preauthenticate.aspx Unfortunately the MSDN sample is wrong. As is the text of the Help topic which incorrectly leads you to believe that PreAuthenticate… wait for it - pre-authenticates. But it doesn’t allow you to set credentials that are sent on the first request. What this property actually does is quite different. It doesn’t send credentials on the first request but rather caches the credentials ONCE you have already authenticated once. Http Authentication is based on a challenge response mechanism typically where the client sends a request and the server responds with a 401 header requesting authentication. So the client sends a request like this: GET /wconnect/admin/wc.wc?_maintain~ShowStatus HTTP/1.1 Host: rasnote User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506) Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en,de;q=0.7,en-us;q=0.3 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive and the server responds with: HTTP/1.1 401 Unauthorized Cache-Control: private Content-Type: text/html; charset=utf-8 Server: Microsoft-IIS/7.5 WWW-Authenticate: basic realm=rasnote" X-AspNet-Version: 2.0.50727 WWW-Authenticate: Negotiate WWW-Authenticate: NTLM WWW-Authenticate: Basic realm="rasnote" X-Powered-By: ASP.NET Date: Tue, 27 Oct 2009 00:58:20 GMT Content-Length: 5163 plus the actual error message body. The client then is responsible for re-sending the current request with the authentication token information provided (in this case Basic Auth): GET /wconnect/admin/wc.wc?_maintain~ShowStatus HTTP/1.1 Host: rasnote User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506) Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en,de;q=0.7,en-us;q=0.3 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive Cookie: TimeTrakker=2HJ1998WH06696; WebLogCommentUser=Rick Strahl|http://www.west-wind.com/|[email protected]; WebStoreUser=b8bd0ed9 Authorization: Basic cgsf12aDpkc2ZhZG1zMA== Once the authorization info is sent the server responds with the actual page result. Now if you use WebRequest (or WebClient) the default behavior is to re-authenticate on every request that requires authorization. This means if you look in  Fiddler or some other HTTP client Proxy that captures requests you’ll see that each request re-authenticates: Here are two requests fired back to back: and you can see the 401 challenge, the 200 response for both requests. If you watch this same conversation between a browser and a server you’ll notice that the first 401 is also there but the subsequent 401 requests are not present. WebRequest.PreAuthenticate And this is precisely what the WebRequest.PreAuthenticate property does: It’s a caching mechanism that caches the connection credentials for a given domain in the active process and resends it on subsequent requests. It does not send credentials on the first request but it will cache credentials on subsequent requests after authentication has succeeded: string url = "http://rasnote/wconnect/admin/wc.wc?_maintain~ShowStatus"; HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest; req.PreAuthenticate = true; req.Credentials = new NetworkCredential("rick", "secret", "rasnote"); req.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested; req.UserAgent = ": Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)"; WebResponse resp = req.GetResponse(); resp.Close(); req = HttpWebRequest.Create(url) as HttpWebRequest; req.PreAuthenticate = true; req.Credentials = new NetworkCredential("rstrahl", "secret", "rasnote"); req.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested; req.UserAgent = ": Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)"; resp = req.GetResponse(); which results in the desired sequence: where only the first request doesn’t send credentials. This is quite useful as it saves quite a few round trips to the server – bascially it saves one auth request request for every authenticated request you make. In most scenarios I think you’d want to send these credentials this way but one downside to this is that there’s no way to log out the client. Since the client always sends the credentials once authenticated only an explicit operation ON THE SERVER can undo the credentials by forcing another login explicitly (ie. re-challenging with a forced 401 request). Forcing Basic Authentication Credentials on the first Request On a few occasions I’ve needed to send credentials on a first request – mainly to some oddball third party Web Services (why you’d want to use Basic Auth on a Web Service is beyond me – don’t ask but it’s not uncommon in my experience). This is true of certain services that are using Basic Authentication (especially some Apache based Web Services) and REQUIRE that the authentication is sent right from the first request. No challenge first. Ugly but there it is. Now the following works only with Basic Authentication because it’s pretty straight forward to create the Basic Authorization ‘token’ in code since it’s just an unencrypted encoding of the user name and password into base64. As you might guess this is totally unsecure and should only be used when using HTTPS/SSL connections (i’m not in this example so I can capture the Fiddler trace and my local machine doesn’t have a cert installed, but for production apps ALWAYS use SSL with basic auth). The idea is that you simply add the required Authorization header to the request on your own along with the authorization string that encodes the username and password: string url = "http://rasnote/wconnect/admin/wc.wc?_maintain~ShowStatus"; HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest; string user = "rick"; string pwd = "secret"; string domain = "www.west-wind.com"; string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(user + ":" + pwd)); req.PreAuthenticate = true; req.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;req.Headers.Add("Authorization", auth); req.UserAgent = ": Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)"; WebResponse resp = req.GetResponse(); resp.Close(); This works and causes the request to immediately send auth information to the server. However, this only works with Basic Auth because you can actually create the authentication credentials easily on the client because it’s essentially clear text. The same doesn’t work for Windows or Digest authentication since you can’t easily create the authentication token on the client and send it to the server. Another issue with this approach is that PreAuthenticate has no effect when you manually force the authentication. As far as Web Request is concerned it never sent the authentication information so it’s not actually caching the value any longer. If you run 3 requests in a row like this: string url = "http://rasnote/wconnect/admin/wc.wc?_maintain~ShowStatus"; HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest; string user = "ricks"; string pwd = "secret"; string domain = "www.west-wind.com"; string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(user + ":" + pwd)); req.PreAuthenticate = true; req.Headers.Add("Authorization", auth); req.UserAgent = ": Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)"; WebResponse resp = req.GetResponse(); resp.Close(); req = HttpWebRequest.Create(url) as HttpWebRequest; req.PreAuthenticate = true; req.Credentials = new NetworkCredential(user, pwd, domain); req.UserAgent = ": Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)"; resp = req.GetResponse(); resp.Close(); req = HttpWebRequest.Create(url) as HttpWebRequest; req.PreAuthenticate = true; req.Credentials = new NetworkCredential(user, pwd, domain); req.UserAgent = ": Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)"; resp = req.GetResponse(); you’ll find the trace looking like this: where the first request (the one we explicitly add the header to) authenticates, the second challenges, and any subsequent ones then use the PreAuthenticate credential caching. In effect you’ll end up with one extra 401 request in this scenario, which is still better than 401 challenges on each request. Getting Access to WebRequest in Classic .NET Web Service Clients If you’re running a classic .NET Web Service client (non-WCF) one issue with the above is how do you get access to the WebRequest to actually add the custom headers to do the custom Authentication described above? One easy way is to implement a partial class that allows you add headers with something like this: public partial class TaxService { protected NameValueCollection Headers = new NameValueCollection(); public void AddHttpHeader(string key, string value) { this.Headers.Add(key,value); } public void ClearHttpHeaders() { this.Headers.Clear(); } protected override WebRequest GetWebRequest(Uri uri) { HttpWebRequest request = (HttpWebRequest) base.GetWebRequest(uri); request.Headers.Add(this.Headers); return request; } } where TaxService is the name of the .NET generated proxy class. In code you can then call AddHttpHeader() anywhere to add additional headers which are sent as part of the GetWebRequest override. Nice and simple once you know where to hook it. For WCF there’s a bit more work involved by creating a message extension as described here: http://weblogs.asp.net/avnerk/archive/2006/04/26/Adding-custom-headers-to-every-WCF-call-_2D00_-a-solution.aspx. FWIW, I think that HTTP header manipulation should be readily available on any HTTP based Web Service client DIRECTLY without having to subclass or implement a special interface hook. But alas a little extra work is required in .NET to make this happen Not a Common Problem, but when it happens… This has been one of those issues that is really rare, but it’s bitten me on several occasions when dealing with oddball Web services – a couple of times in my own work interacting with various Web Services and a few times on customer projects that required interaction with credentials-first services. Since the servers determine the protocol, we don’t have a choice but to follow the protocol. Lovely following standards that implementers decide to ignore, isn’t it? :-}© Rick Strahl, West Wind Technologies, 2005-2010Posted in .NET  CSharp  Web Services  

    Read the article

  • Why PreAuthenticate is not enabled by default?

    - by dr. evil
    As far as I understand WebRequest.PreAuthenticate is almost always good. If I enable it even when there is no credential it won't try to authenticate, if there is a credential it'll. So is there any legitimate reason to set it False? Or is it OK to set it True even when there is no credentials? And since it's quite useful why it's not enabled by default just like many other HTTP features?

    Read the article

  • "too many automatic redirections were attempted" error message when using a httpWebRequest in .NET

    - by tooleb
    I am attempting to request a page like "http://www.google.com/?q=random" using the webrequest class in vb.net. we are behind a firewall, so we have to authenticate our requests. I have gotten past the authentication part by adding my credentials. But once that works it seems to go into a redirecting loop. Does anyone have an ideas, comments, suggetions why this is? Has anyone else experienced this problem? Dim loHttp As HttpWebRequest = CType(WebRequest.Create(_url), HttpWebRequest) loHttp.Timeout = 10000 loHttp.Method = "GET" loHttp.KeepAlive = True loHttp.AllowAutoRedirect = True loHttp.PreAuthenticate = True Dim _cred1 As NetworkCredential = ... //this is setup //snip out this stuff loHttp.Credentials = _cc loWebResponse = loHttp.GetResponse()

    Read the article

  • Sending Client Certificate in HttpWebRequest

    - by Aaron Fischer
    I am trying to pass a client certificate to a server using the code below however I still revive the HTTP Error 403.7 - Forbidden: SSL client certificate is required. What are the possible reasons the HttpWebRequest would not send the client certificate? var clientCertificate = new X509Certificate2( @"C:\Development\TestClient.pfx", "bob" ); HttpWebRequest tRequest = ( HttpWebRequest )WebRequest.Create( "https://ofxtest.com/ofxr.dll" ); tRequest.ClientCertificates.Add( clientCertificate ); tRequest.PreAuthenticate = true; tRequest.KeepAlive = true; tRequest.Credentials = CredentialCache.DefaultCredentials; tRequest.Method = "POST"; var encoder = new ASCIIEncoding(); var requestData = encoder.GetBytes( "<OFX></OFX>" ); tRequest.GetRequestStream().Write( requestData, 0, requestData.Length ); tRequest.GetRequestStream().Close(); ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback( CertPolicy.ValidateServerCertificate ); WriteResponse( tRequest.GetResponse() );

    Read the article

  • How to Create Site using Sharepoint web services?

    - by Pari
    Hi All, I am tring to create site on sharepoint programatically using Sharepoint Web Services.(C#). I tried Admin.asmx service (CreateSite method). But it's showing error: "An unhandled exception of type 'System.InvalidOperationException' occurred in System.Web.Services.dll". I tried with all possible parameters. Curremtly referring Below Links: http://www.oliebol.org/blog/Lists/Posts/Post.aspx?ID=6 http://msdn.microsoft.com/en-us/library/administration.admin.createsite.aspx My Code: Admin admService = new Admin(); admService.Credentials = new NetworkCredential(username,password,domain); admService.Url = "http://mychserver/_vti_adm/admin.asmx"; admService.PreAuthenticate = true; try { String SitePath = "http://myserver/SiteDirectory/SharepointSampleSite"; admService.CreateSite(SitePath,"First Site", "Sample Site", 1033, "STS#0", "Domain\\username",username,userid, "", ""); } catch (System.Web.Services.Protocols.SoapException ex) { MessageBox.Show("Message:\n" + ex.Message + "\nDetail:\n" +ex.Detail.InnerText + "\nStackTrace:\n" + ex.StackTrace); } Thanx,

    Read the article

  • Consume a WebService with Integrated authentication from WPF windows application

    - by Tr1stan
    I have written a WPF windows application that consumes a .net WebService. This works fine when the web service in hosted to allow anonymous connections, however the WebService I need to consume when we go live will be held within a website that has Integrated Authentication enabled. The person running the WPF application will be logged onto a computer within the same domain as the web server and will have permission to see the WebService (without entering any auth info) if browsing to it using a web browser that is NTLM auth enabled. Is it possible to pass through the details of the already logged in user running the application to the WebService? Here is the code I'm currently using: MyWebService.SearchSoapClient client = new SearchSoapClient(); //From the research I've done I think I need to something with these: //UserName.PreAuthenticate = true; //System.Net.CredentialCache.DefaultCredentials; List<Person> result = client.FuzzySearch("This is my search string").ToList(); Any pointers much appreciated.

    Read the article

  • Do we need to disconnect from sharepoint? If Yes How? ( using Web Services : C#)

    - by Pari
    Hi, I am using web services to access sharepoint list,sites and documents. Like: List.asmx,Site.asmx e.t.c. My question is that: Do we need to disconnect from sharepoint when using above services? And if yes then How? Example: GetSiteCollection(String login, String password, String url) { Webs ws = new Webs(); try { ws.Credentials = new NetworkCredential(login, password); } catch (Exception ex) { MessageBox.Show(ex.Message); } ws.Url = url + @"/_vti_bin/webs.asmx"; ws.PreAuthenticate = true; XmlNode websiteNode = ws.GetWebCollection(); XmlNodeList nodes = websiteNode.SelectNodes("*"); // getting list set of sites //Now here after this is there any way to disconnect from server? }

    Read the article

  • Newly created Document library are not visible on sharepoint using webservices

    - by Royson
    Hi, I am able to create Document library. Lists listService = new Lists(); listService.PreAuthenticate = true; listService.Credentials = new NetworkCredential(username,password,domain; String url = "http://YourServer/SiteName/"; listService.Url = url @ + /_vti_bin/lists.asmx"; XmlNode ndList = listService.AddList(NewListName, "Description", 101); It is working successfully. But Problem i am facing is: New Document library are not visible in site. I tried with comparing Field Value of Both Visible and No-Visible Document library. Difference i found is : Visible Library (Created Manually) doesn't contain Version value. were as it it present in library which are created by this code. Can you help me out in this?

    Read the article

  • HttpWebRequest issues

    - by Allen Ho
    Hi, Im still having issues using HttpWebRequest. For some reason sometimes in my app the call just times out... HttpWebRequest req = null; req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(aRequest)); req.PreAuthenticate = true; req.AllowAutoRedirect = true; req.KeepAlive = false; ..... resp = (HttpWebResponse)req.GetResponse(); resp.close(); I am closing the response but Im just wondering if it is more likely to fail since Im making requests all over the place? I tried playing around with the ServicePointManager class hoping it would help but it hasnt really System.Net.ServicePointManager.DefaultConnectionLimit = 100; System.Net.ServicePointManager.MaxServicePoints = 100;

    Read the article

  • Calling https process from ASP Net

    - by David M
    I have an ASP NET web server application that calls another process running on the same box that creates a pdf file and returns it. The second process requires a secure connection via SSL. The second process has issued my ASP NET application with a digital certificate but I still cannot authenticate, getting a 403 error. The code is a little hard to show but here's a simplified method ... X509Certificate cert = X509Certificate.CreateFromCertFile("path\to\cert.cer"); string URL = "https://urltoservice?params=value"; HttpWebRequest req = HttpWebRequest.Create(URL) as HttpWebRequest; req.ClientCertificates.Add(cert); req.Credentials = CredentialCache.DefaultCredentials; req.PreAuthenticate = true; /// error happens here WebResponse resp = req.GetResponse(); Stream input = resp.GetResponseStream(); The error text is "The remote server returned an error: (403) Forbidden." Any pointers are welcome.

    Read the article

  • How to update Properties of Uploaded Documents on Sharepoint using Web Services ? : c#

    - by Preeti
    Hi, I am trying to Update/Edit Properties of Uploaded Document on Sharepoint 2007. My code: Lists listService = new Lists(); listService.PreAuthenticate = true; listService.Credentials = new NetworkCredential(username,password); listService.Url = "http://myserver/SiteName/_vti_bin/lists.asmx"; string strBatch = "<Method ID='1' Cmd='Update'> " + " <Field Name='ID'>3</Field> " + " <Field Name='Name'>Preeti</Field> " + " </Method> "; XmlDocument xmlDoc = new System.Xml.XmlDocument(); System.Xml.XmlElement elBatch = xmlDoc.CreateElement("Batch"); elBatch.SetAttribute("OnError", "Continue"); elBatch.SetAttributeNode("UserName", "Preeti"); elBatch.InnerXml = strBatch; XmlNode ndReturn = listService.UpdateListItems(ListName, elBatch); MessageBox.Show(ndReturn.OuterXml); Refering Link. Getting Error: "One or more field types are not installed properly. Go to the list settings page to delete these fields". Regards, Preeti

    Read the article

  • How do I configure a C# web service client to send HTTP request header and body in parallel?

    - by Christopher
    Hi, I am using a traditional C# web service client generated in VS2008 .Net 3.5, inheriting from SoapHttpClientProtocol. This is connecting to a remote web service written in Java. All configuration is done in code during client initialization, and can be seen below: ServicePointManager.Expect100Continue = false; ServicePointManager.DefaultConnectionLimit = 10; var client = new APIService { EnableDecompression = true, Url = _url + "?guid=" + Guid.NewGuid(), Credentials = new NetworkCredential(user, password, null), PreAuthenticate = true, Timeout = 5000 // 5 sec }; It all works fine, but the time taken to execute the simplest method call is almost double the network ping time. Whereas a Java test client takes roughly the same as the network ping time: C# client ~ 550ms Java client ~ 340ms Network ping ~ 300ms After analyzing the TCP traffic for a session discovered the following: Basically, the C# client sent TCP packets in the following sequence. Client Send HTTP Headers in one packet. Client Waits For TCP ACK from server. Client Sends HTTP Body in one packet. Client Waits For TCP ACK from server. The Java client sent TCP packets in the following sequence. Client Sends HTTP Headers in one packet. Client Sends HTTP Body in one packet. Client Revieves ACK for first packet. Client Revieves ACK for second packet. Client Revieves ACK for second packet. Is there anyway to configure the C# web service client to send the header/body in parallel as the Java client appears to? Any help or pointers much appreciated.

    Read the article

  • Newly created Document library and columns using webservices are not visible on sharepoint

    - by Royson
    Hi, for creating a columns I worked on this code . and for creating document library Lists listService = new Lists(); listService.PreAuthenticate = true; listService.Credentials = new NetworkCredential(username,password,domain; String url = "http://YourServer/SiteName/"; listService.Url = url @ + /_vti_bin/lists.asmx"; XmlNode ndList = listService.AddList(NewListName, "Description", 101); Both are working successfully. But Problem i am facing is: New Columns and document library are not visible. I tried with comparing Field Value of Both Visible and No-Visible types. Difference i found is : Visible (Created Manually) doesn't contain Version value. were as i am creating have it. Can you help me out in this? EDIT: I checked contents of ndList node, List is created and it is visible on my UI. but on sharepoint it should be listed in 'Document' tab where default 'Shared Documents' library is shown. If i click on 'Documents' then we can also see all lib created by this code. Visible means library displayed under 'Documents' tab

    Read the article

  • Using IIS Logs for Performance Testing with Visual Studio

    - by Tarun Arora
    In this blog post I’ll show you how you can play back the IIS Logs in Visual Studio to automatically generate the web performance tests. You can also download the sample solution I am demo-ing in the blog post. Introduction Performance testing is as important for new websites as it is for evolving websites. If you already have your website running in production you could mine the information available in IIS logs to analyse the dense zones (most used pages) and performance test those pages rather than wasting time testing & tuning the least used pages in your application. What are IIS Logs To help with server use and analysis, IIS is integrated with several types of log files. These log file formats provide information on a range of websites and specific statistics, including Internet Protocol (IP) addresses, user information and site visits as well as dates, times and queries. If you are using IIS 7 and above you will find the log files in the following directory C:\Interpub\Logs\ Walkthrough 1. Download and Install Log Parser from the Microsoft download Centre. You should see the LogParser.dll in the install folder, the default install location is C:\Program Files (x86)\Log Parser 2.2. LogParser.dll gives us a library to query the iis log files programmatically. By the way if you haven’t used Log Parser in the past, it is a is a powerful, versatile tool that provides universal query access to text-based data such as log files, XML files and CSV files, as well as key data sources on the Windows operating system such as the Event Log, the Registry, the file system, and Active Directory. More details… 2. Create a new test project in Visual Studio. Let’s call it IISLogsToWebPerfTestDemo.   3.  Delete the UnitTest1.cs class that gets created by default. Right click the solution and add a project of type class library, name it, IISLogsToWebPerfTestEngine. Delete the default class Program.cs that gets created with the project. 4. Under the IISLogsToWebPerfTestEngine project add a reference to Microsoft.VisualStudio.QualityTools.WebTestFramework – c:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\PublicAssemblies\Microsoft.VisualStudio.QualityTools.WebTestFramework.dll LogParser also called MSUtil - c:\users\tarora\documents\visual studio 2010\Projects\IisLogsToWebPerfTest\IisLogsToWebPerfTestEngine\obj\Debug\Interop.MSUtil.dll 5. Right click IISLogsToWebPerfTestEngine project and add a new classes – IISLogReader.cs The IISLogReader class queries the iis logs using the log parser. using System; using System.Collections.Generic; using System.Text; using MSUtil; using LogQuery = MSUtil.LogQueryClassClass; using IISLogInputFormat = MSUtil.COMIISW3CInputContextClassClass; using LogRecordSet = MSUtil.ILogRecordset; using Microsoft.VisualStudio.TestTools.WebTesting; using System.Diagnostics; namespace IisLogsToWebPerfTestEngine { // By making use of log parser it is possible to query the iis log using select queries public class IISLogReader { private string _iisLogPath; public IISLogReader(string iisLogPath) { _iisLogPath = iisLogPath; } public IEnumerable<WebTestRequest> GetRequests() { LogQuery logQuery = new LogQuery(); IISLogInputFormat iisInputFormat = new IISLogInputFormat(); // currently these columns give us suffient information to construct the web test requests string query = @"SELECT s-ip, s-port, cs-method, cs-uri-stem, cs-uri-query FROM " + _iisLogPath; LogRecordSet recordSet = logQuery.Execute(query, iisInputFormat); // Apply a bit of transformation while (!recordSet.atEnd()) { ILogRecord record = recordSet.getRecord(); if (record.getValueEx("cs-method").ToString() == "GET") { string server = record.getValueEx("s-ip").ToString(); string path = record.getValueEx("cs-uri-stem").ToString(); string querystring = record.getValueEx("cs-uri-query").ToString(); StringBuilder urlBuilder = new StringBuilder(); urlBuilder.Append("http://"); urlBuilder.Append(server); urlBuilder.Append(path); if (!String.IsNullOrEmpty(querystring)) { urlBuilder.Append("?"); urlBuilder.Append(querystring); } // You could make substitutions by introducing parameterized web tests. WebTestRequest request = new WebTestRequest(urlBuilder.ToString()); Debug.WriteLine(request.UrlWithQueryString); yield return request; } recordSet.moveNext(); } Console.WriteLine(" That's it! Closing the reader"); recordSet.close(); } } }   6. Connect the dots by adding the project reference ‘IisLogsToWebPerfTestEngine’ to ‘IisLogsToWebPerfTest’. Right click the ‘IisLogsToWebPerfTest’ project and add a new class ‘WebTest1Coded.cs’ The WebTest1Coded.cs inherits from the WebTest class. By overriding the GetRequestMethod we can inject the log files to the IISLogReader class which uses Log parser to query the log file and extract the web requests to generate the web test request which is yielded back for play back when the test is run. namespace IisLogsToWebPerfTest { using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.TestTools.WebTesting; using Microsoft.VisualStudio.TestTools.WebTesting.Rules; using IisLogsToWebPerfTestEngine; // This class is a coded web performance test implementation, that simply passes // the path of the iis logs to the IisLogReader class which does the heavy // lifting of reading the contents of the log file and converting them to tests. // You could have multiple such classes that inherit from WebTest and implement // GetRequestEnumerator Method and pass differnt log files for different tests. public class WebTest1Coded : WebTest { public WebTest1Coded() { this.PreAuthenticate = true; } public override IEnumerator<WebTestRequest> GetRequestEnumerator() { // substitute the highlighted path with the path of the iis log file IISLogReader reader = new IISLogReader(@"C:\Demo\iisLog1.log"); foreach (WebTestRequest request in reader.GetRequests()) { yield return request; } } } }   7. Its time to fire the test off and see the iis log playback as a web performance test. From the Test menu choose Test View Window you should be able to see the WebTest1Coded test show up. Highlight the test and press Run selection (you can also debug the test in case you face any failures during test execution). 8. Optionally you can create a Load Test by keeping ‘WebTest1Coded’ as the base test. Conclusion You have just helped your testing team, you now have become the coolest developer in your organization! Jokes apart, log parser and web performance test together allow you to save a lot of time by not having to worry about what to test or even worrying about how to record the test. If you haven’t already, download the solution from here. You can take this to the next level by using LogParser to extract the log files as part of an end of day batch to a database. See the usage trends by user this solution over a longer term and have your tests consume the web requests now stored in the database to generate the web performance tests. If you like the post, don’t forget to share … Keep RocKiNg!

    Read the article

  • EWS - How to search for items [message] between dates ?

    - by SomFred
    Hi, I am trying to search for message items between two dates from the inbox folder. I use the following restrictionType but it throws this error: firmt.RootFolder = null What am I doing wrong? There is some messages between the mentionned dates ;-) Thanks for your suggestions. using (ExchangeServiceBinding esb = new ExchangeServiceBinding()) { esb.Url = ConfigurationManager.AppSettings["ExchangeWebServicesURL"].ToString(); esb.RequestServerVersionValue = new RequestServerVersion(); esb.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2007_SP1; esb.PreAuthenticate = true; esb.Credentials = new NetworkCredential(email, password); FindItemType findItemRequest = new FindItemType(); // paging IndexedPageViewType ipvt = new IndexedPageViewType(); ipvt.BasePoint = IndexBasePointType.Beginning; ipvt.MaxEntriesReturned = nombreMessage; ipvt.MaxEntriesReturnedSpecified = true; ipvt.Offset = offset; findItemRequest.Item = ipvt; // filter by dates AndType andType = new AndType(); List<SearchExpressionType> searchExps = new List<SearchExpressionType>(); RestrictionType restriction = new RestrictionType(); PathToUnindexedFieldType pteft = new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.itemDateTimeSent }; IsGreaterThanOrEqualToType IsGreaterThanOrEqualTo = new IsGreaterThanOrEqualToType { Item = pteft, FieldURIOrConstant = new FieldURIOrConstantType { Item = new ConstantValueType { Value = DateTime.Today.AddDays(-6d).ToString() } } }; searchExps.Add(IsGreaterThanOrEqualTo); IsLessThanOrEqualToType IsLessThanOrEqualTo = new IsLessThanOrEqualToType { Item = pteft, FieldURIOrConstant = new FieldURIOrConstantType { Item = new ConstantValueType { Value = DateTime.Today.AddDays(1d).ToString() } } }; searchExps.Add(IsLessThanOrEqualTo); andType.Items = searchExps.ToArray(); restriction.Item = andType; findItemRequest.Restriction = restriction; //// Define the sort order of items. FieldOrderType[] fieldsOrder = new FieldOrderType[1]; fieldsOrder[0] = new FieldOrderType(); PathToUnindexedFieldType dateOrder = new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.itemDateTimeReceived }; fieldsOrder[0].Item = dateOrder; fieldsOrder[0].Order = SortDirectionType.Descending; findItemRequest.SortOrder = fieldsOrder; findItemRequest.Traversal = ItemQueryTraversalType.Shallow; // define which item properties are returned in the response findItemRequest.ItemShape = new ItemResponseShapeType { BaseShape = DefaultShapeNamesType.IdOnly }; // identify which folder to search DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1]; folderIDArray[0] = new DistinguishedFolderIdType { Id = DistinguishedFolderIdNameType.inbox }; // add folders to request findItemRequest.ParentFolderIds = folderIDArray; // find the messages FindItemResponseType findItemResponse = esb.FindItem(findItemRequest); //------------- ArrayOfResponseMessagesType responseMessages = findItemResponse.ResponseMessages; ResponseMessageType responseMessage = responseMessages.Items[0]; if (responseMessage is FindItemResponseMessageType) { FindItemResponseMessageType firmt = (responseMessage as FindItemResponseMessageType); *******FindItemParentType fipt = firmt.RootFolder;******** object obj = fipt.Item; // FindItem contains an array of items. ArrayOfRealItemsType realitems = (obj as ArrayOfRealItemsType); ItemType[] items = realitems.Items; // if no messages were found, then return null -- we're done if (items == null || items.Count() <= 0) return null; // FindItem never gets "all" the properties, so now that we've found them all, we need to get them all. BaseItemIdType[] itemIds = new BaseItemIdType[items.Count()]; for (int i = 0; i < items.Count(); i++) itemIds[i] = items[i].ItemId; GetItemType getItemType = new GetItemType { ItemIds = itemIds, ItemShape = new ItemResponseShapeType { BaseShape = DefaultShapeNamesType.AllProperties, BodyType = BodyTypeResponseType.Text, BodyTypeSpecified = true, AdditionalProperties = new BasePathToElementType[] { new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.itemDateTimeSent }, new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageFrom }, new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageIsRead }, new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageSender }, new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageToRecipients }, new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageCcRecipients }, new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageBccRecipients } } } }; GetItemResponseType getItemResponse = esb.GetItem(getItemType); messages = ReadItems(getItemResponse, items.Count()); }

    Read the article

  • How to add Category in DotClear blog with HttpWebRequest or MetaWeblog API

    - by Pitming
    I'm trying to create/modify dotclear blogs. For most of the options, i use XmlRpc API (DotClear.MetaWeblog). But didn't find any way to handle categories. So I start to look at the Http packet and try to do "the same as the browser". Here si the method I use to "Http POST" protected HttpStatusCode HttpPost(Uri url_, string data_, bool allowAutoRedirect_) { HttpWebRequest Request; HttpWebResponse Response = null; Stream ResponseStream = null; Request = (System.Net.HttpWebRequest)HttpWebRequest.Create(url_); Request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)"; Request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; Request.AllowAutoRedirect = allowAutoRedirect_; // Add the network credentials to the request. Request.Credentials = new NetworkCredential(Username, Password); string authInfo = Username + ":" + Password; authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); Request.Headers["Authorization"] = "Basic " + authInfo; Request.Method = "POST"; Request.CookieContainer = Cookies; if(ConnectionCookie!=null) Request.CookieContainer.Add(url_, ConnectionCookie); if (dcAdminCookie != null) Request.CookieContainer.Add(url_, dcAdminCookie); Request.PreAuthenticate = true; ASCIIEncoding encoding = new ASCIIEncoding(); string postData = data_; byte[] data = encoding.GetBytes(postData); //Encoding.UTF8.GetBytes(data_); //encoding.GetBytes(postData); Request.ContentLength = data.Length; Request.ContentType = "application/x-www-form-urlencoded"; Stream newStream = Request.GetRequestStream(); // Send the data. newStream.Write(data, 0, data.Length); newStream.Close(); try { // get the response from the server. Response = (HttpWebResponse)Request.GetResponse(); if (!allowAutoRedirect_) { foreach (Cookie c in Response.Cookies) { if (c.Name == "dcxd") ConnectionCookie = c; if (c.Name == "dc_admin") dcAdminCookie = c; } Cookies.Add(Response.Cookies); } // Get the response stream. ResponseStream = Response.GetResponseStream(); // Pipes the stream to a higher level stream reader with the required encoding format. StreamReader readStream = new StreamReader(ResponseStream, Encoding.UTF8); string result = readStream.ReadToEnd(); if (Request.RequestUri == Response.ResponseUri) { _log.InfoFormat("{0} ==&gt; {1}({2})", Request.RequestUri, Response.StatusCode, Response.StatusDescription); } else { _log.WarnFormat("RequestUri:{0}\r\nResponseUri:{1}\r\nstatus code:{2} Status descr:{3}", Request.RequestUri, Response.ResponseUri, Response.StatusCode, Response.StatusDescription); } } catch (WebException wex) { Response = wex.Response as HttpWebResponse; if (Response != null) { _log.ErrorFormat("{0} ==&gt; {1}({2})", Request.RequestUri, Response.StatusCode, Response.StatusDescription); } Request.Abort(); } finally { if (Response != null) { // Releases the resources of the response. Response.Close(); } } if(Response !=null) return Response.StatusCode; return HttpStatusCode.Ambiguous; } So the first thing to do is to Authenticate as admin. Here is the code: protected bool HttpAuthenticate() { Uri u = new Uri(this.Url); Uri url = new Uri(string.Format("{0}/admin/auth.php", u.GetLeftPart(UriPartial.Authority))); string data = string.Format("user_id={0}&user_pwd={1}&user_remember=1", Username, Password); var ret = HttpPost(url,data,false); return (ret == HttpStatusCode.OK || ret==HttpStatusCode.Found); } 3.Now that I'm authenticate, i need to get a xd_chek info (that i can find on the page so basically it's a GET on /admin/category.php + Regex("dotclear[.]nonce = '(.*)'")) 4.so I'm authenticate and have the xd_check info. The last thing to do seems to post the next category. But of course it does not work at all... here is the code: string postData = string.Format("cat_title={0}&new_cat_parent={1}&xd_check={2}", category_, 0, xdCheck); HttpPost(url, postData, true); If anyone can help me and explain were is it wrong ? thanks in advance.

    Read the article

1