Search Results

Search found 349 results on 14 pages for 'webrequest'.

Page 4/14 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • FileNet P8 workplace token issue in C#

    - by acadia
    Hello, I am trying to get user token and build the URL so that user need not login everytime they click the file. below is my code. My question is do I need to pass whole of the token value shown below or?? The token value I am getting is symmetric:algorithm:QUVT:keyid:NTZkYTNkNmI=:data:7P9aJHzkfGTOlwtotuWGaMqfU9COECscA9yxMdK64ZLa298A3tsGlHKHDFp0cH+gn/SiMrwKfbWNZybPXaltgo5e4H4Ak8KUiCRKWfS68qhmjfw69qPv9ib96vL3TzNORYFpp/hrwvp8aX4CQIZlBA== The problem is, once i copy the URL and past it in the browser, it is taking me to the login page. Though I am not getting any errors, it should take users directly to the imageviewer but instead it takes me to login page, if I login it is opening the file correctly. What am I doing wrong? string text = ""; string userName = "userName"; string pwd = "*****"; fileNetID = "{5FCE7E04-3D74-4A93-AA53-26C12A2FD4FC}"; Uri uri = null; string workplaceURL = "http://filenet:9081/WorkPlaceXT"; uri = new Uri(workplaceURL + "/setCredentials?op=getUserToken&userId=" + this.encodeLabel(userName) + "&password=" + this.encodeLabel(pwd) + "&verify=true"); System.Net.WebRequest webRequest = System.Net.WebRequest.Create(uri); System.Net.WebResponse webResponse = webRequest.GetResponse(); StreamReader streamReader = new StreamReader(webResponse.GetResponseStream()); String token = streamReader.ReadToEnd(); string contentURL = string.Empty; contentURL = workplaceURL + "/getContent?objectType=document&impersonate=true&objectStoreName=OBJECTSTORE&id=" + HttpUtility.UrlEncode(fileNetID); contentURL += "&ut=" + HttpUtility.UrlEncode(encodeLabel(token)); return contentURL;

    Read the article

  • Login to website and use cookie to get source for another page

    - by Stu
    I am trying to login to the TV Rage website and get the source code of the My Shows page. I am successfully logging in (I have checked the response from my post request) but then when I try to perform a get request on the My Shows page, I am re-directed to the login page. This is the code I am using to login: private string LoginToTvRage() { string loginUrl = "http://www.tvrage.com/login.php"; string formParams = string.Format("login_name={0}&login_pass={1}", "xxx", "xxxx"); string cookieHeader; WebRequest req = WebRequest.Create(loginUrl); req.ContentType = "application/x-www-form-urlencoded"; req.Method = "POST"; byte[] bytes = Encoding.ASCII.GetBytes(formParams); req.ContentLength = bytes.Length; using (Stream os = req.GetRequestStream()) { os.Write(bytes, 0, bytes.Length); } WebResponse resp = req.GetResponse(); cookieHeader = resp.Headers["Set-cookie"]; String responseStream; using (StreamReader sr = new StreamReader(resp.GetResponseStream())) { responseStream = sr.ReadToEnd(); } return cookieHeader; } I then pass the cookieHeader into this method which should be getting the source of the My Shows page: private string GetSourceForMyShowsPage(string cookieHeader) { string pageSource; string getUrl = "http://www.tvrage.com/mytvrage.php?page=myshows"; WebRequest getRequest = WebRequest.Create(getUrl); getRequest.Headers.Add("Cookie", cookieHeader); WebResponse getResponse = getRequest.GetResponse(); using (StreamReader sr = new StreamReader(getResponse.GetResponseStream())) { pageSource = sr.ReadToEnd(); } return pageSource; } I have been using this previous question as a guide but I'm at a loss as to why my code isn't working.

    Read the article

  • VB.net, disable proxy for entire program

    - by Brent
    Ever since upgrading to Visual Studio 2010, I'm running into an issue where the first web request of any type (WebRequest, WebClient, etc.) hangs for about 20 seconds before completing. Subsequent calls work quickly. I've narrowed down the problem to a proxy issue. If I manually disable proxy settings, I don't experience this delay: Dim wrq As WebRequest = WebRequest.Create(Url) wrq.Proxy = Nothing What's strange is that there are no proxy settings enabled on this machine in Internet Options. What I'm wondering is if there is a way to disable proxy settings for my entire project in one shot without explicitly disabling as above for every web object. The main reason I want to be able to do this is that I'm trying to use an API (http://code.google.com/p/google-api-for-dotnet/) which uses web requests, but does not provide any way to manually disable proxy settings. Can anyone point me in the right direction? Thanks!

    Read the article

  • HttpWebRequest and Ignoring SSL Certificate Errors

    - by Rick Strahl
    Man I can't believe this. I'm still mucking around with OFX servers and it drives me absolutely crazy how some these servers are just so unbelievably misconfigured. I've recently hit three different 3 major brokerages which fail HTTP validation with bad or corrupt certificates at least according to the .NET WebRequest class. What's somewhat odd here though is that WinInet seems to find no issue with these servers - it's only .NET's Http client that's ultra finicky. So the question then becomes how do you tell HttpWebRequest to ignore certificate errors? In WinInet there used to be a host of flags to do this, but it's not quite so easy with WebRequest. Basically you need to configure the CertificatePolicy on the ServicePointManager by creating a custom policy. Not exactly trivial. Here's the code to hook it up: public bool CreateWebRequestObject(string Url) {    try     {        this.WebRequest =  (HttpWebRequest) System.Net.WebRequest.Create(Url);         if (this.IgnoreCertificateErrors)            ServicePointManager.CertificatePolicy = delegate { return true; };}One thing to watch out for is that this an application global setting. There's one global ServicePointManager and once you set this value any subsequent requests will inherit this policy as well, which may or may not be what you want. So it's probably a good idea to set the policy when the app starts and leave it be - otherwise you may run into odd behavior in some situations especially in multi-thread situations.Another way to deal with this is in you application .config file. Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin-top:0in; mso-para-margin-right:0in; mso-para-margin-bottom:10.0pt; mso-para-margin-left:0in; line-height:115%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi;} <configuration>   <system.net>     <settings>       <servicePointManager           checkCertificateName="false"           checkCertificateRevocationList="false"                />     </settings>   </system.net> </configuration> This seems to work most of the time, although I've seen some situations where it doesn't, but where the code implementation works which is frustrating. The .config settings aren't as inclusive as the programmatic code that can ignore any and all cert errors - shrug. Anyway, the code approach got me past the stopper issue. It still amazes me that theses OFX servers even require this. After all this is financial data we're talking about here. The last thing I want to do is disable extra checks on the certificates. Well I guess I shouldn't be surprised - these are the same companies that apparently don't believe in XML enough to generate valid XML (or even valid SGML for that matter)...© Rick Strahl, West Wind Technologies, 2005-2011Posted in .NET  CSharp  HTTP  

    Read the article

  • Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host

    - by Paul J. Warner
    I am having an issue with a program where after 6 mins +- 5 secs we get the above exception. Some more info about the exception stacktrace is below. This all happens pretty religiously, 6 mins goes by and bam the following 3 exeptions. We have the application installed in 2 other environments and it is working fine there. I am hoping to find some server settings either IIS 6 or Server 2003 settings that may be causing this issue to occur. I have reviewed some of the similar questions and don't see very many answers. I am hoping that maybe the information I have provided may help a little bit. 208741,Exception,,,,2011-06-21 00:30:14.193,SERVERNAME,2624,1,CLIENTNAME,The underlying connection was closed: An unexpected error occurred on a receive. , at System.Web.Services.Protocols.WebClientProtocol.GetWebResponse(WebRequest request) at System.Web.Services.Protocols.HttpWebClientProtocol.GetWebResponse(WebRequest request) at Microsoft.Web.Services3.WebServicesClientProtocol.GetResponse(WebRequest request, IAsyncResult result) at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count) at System.Net.Security._SslStream.StartFrameHeader(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security._SslStream.StartReading(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security._SslStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.TlsStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead),2004437127,114,1 208742,Exception,,,,2011-06-21 00:30:14.227,SERVERNAME,2624,1,CLIENTNAME,Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. , at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count) at System.Net.Security._SslStream.StartFrameHeader(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security._SslStream.StartReading(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security._SslStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.TlsStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead),2004437127,114,1 208743,Exception,,,,2011-06-21 00:30:14.287,SERVERNAME,2624,1,CLIENTNAME,An existing connection was forcibly closed by the remote host , at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size),-691097507,62,1

    Read the article

  • Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

    - by Paul J. Warner
    I am having an issue with a program where after 6 mins +- 5 secs we get the above exception. Some more info about the exception stacktrace is below. This all happens pretty religiously, 6 mins goes by and bam the following 3 exeptions. We have the application installed in 2 other environments and it is working fine there. I am hoping to find some server settings either IIS 6 or Server 2003 settings that may be causing this issue to occur. I have reviewed some of the similar questions and don't see very many answers. I am hoping that maybe the information I have provided may help a little bit. 208741,Exception,,,,2011-06-21 00:30:14.193,SERVERNAME,2624,1,CLIENTNAME,The underlying connection was closed: An unexpected error occurred on a receive. , at System.Web.Services.Protocols.WebClientProtocol.GetWebResponse(WebRequest request) at System.Web.Services.Protocols.HttpWebClientProtocol.GetWebResponse(WebRequest request) at Microsoft.Web.Services3.WebServicesClientProtocol.GetResponse(WebRequest request, IAsyncResult result) at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count) at System.Net.Security._SslStream.StartFrameHeader(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security._SslStream.StartReading(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security._SslStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.TlsStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead),2004437127,114,1 208742,Exception,,,,2011-06-21 00:30:14.227,SERVERNAME,2624,1,CLIENTNAME,Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. , at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count) at System.Net.Security._SslStream.StartFrameHeader(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security._SslStream.StartReading(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security._SslStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.TlsStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead),2004437127,114,1 208743,Exception,,,,2011-06-21 00:30:14.287,SERVERNAME,2624,1,CLIENTNAME,An existing connection was forcibly closed by the remote host , at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size),-691097507,62,1

    Read the article

  • Easiest Way to read the response from WebResponse

    - by Stacker
    private void RespCallback(IAsyncResult asynchronousResult) { try { WebRequest myWebRequest1 = (WebRequest)asynchronousResult.AsyncState; // End the Asynchronous response. WebResponse webResponse = myWebRequest1.EndGetResponse(asynchronousResult); } catch (Exception) { //TODO:Log the error } } now having the webResponse Object ,what is the easiest way to read its contents?

    Read the article

  • Getresponse not working after authentication

    - by Hazler
    For starters, here's my code: // Create a request using a URL that can receive a post. WebRequest request = WebRequest.Create("http://mydomain.com/cms/csharptest.php"); request.Credentials = new NetworkCredential("myUser", "myPass"); // Set the Method property of the request to POST. request.Method = "POST"; // Create POST data and convert it to a byte array. string postData = "name=PersonName&age=25"; byte[] byteArray = Encoding.UTF8.GetBytes(postData); // Set the ContentType property of the WebRequest. request.ContentType = "application/x-www-form-urlencoded"; // Set the ContentLength property of the WebRequest. request.ContentLength = byteArray.Length; // Get the request stream. Stream dataStream = request.GetRequestStream(); // Write the data to the request stream. dataStream.Write(byteArray, 0, byteArray.Length); // Close the Stream object. dataStream.Close(); // Get the response. HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // Display the status. Console.WriteLine((response).StatusDescription); // Get the stream containing content returned by the server. dataStream = response.GetResponseStream(); // Open the stream using a StreamReader for easy access. StreamReader reader = new StreamReader(dataStream); // Read the content. string responseFromServer = reader.ReadToEnd(); // Display the content. Console.WriteLine(responseFromServer); // Clean up the streams. reader.Close(); dataStream.Close(); response.Close(); The directory cms/ requires authentication, but if I try running this same code somewhere, where authentication isn't needed, it works fine. The error (System.Net.WebException: The remote server returned an error: (403) Forbidden) occurs at HttpWebResponse response = (HttpWebResponse)request.GetResponse(); I have managed in reading data after authenticating, but not if I also send POST data. What's wrong with this?

    Read the article

  • Create folder on ftp

    - by Afnan
    I am using method to create folder on ftp i want get exception if folder already exsists how to make it over write the existing folder using System; using System.Net; class Test { static void Main() { WebRequest request = WebRequest.Create("ftp://host.com/directory"); request.Method = WebRequestMethods.Ftp.MakeDirectory; request.Credentials = new NetworkCredential("user", "pass"); using (var resp = (FtpWebResponse) request.GetResponse()) { Console.WriteLine(resp.StatusCode); } } } it is "remote server returned error (550) file not found"

    Read the article

  • '--' is an unexpected token. The expected token is '>'. Line 81, position 5.

    - by vamsivanka
    I am trying to get the html for this link http://slashdot.org/firehose.pl?op=rss&content_type=rss&orderby=createtime&fhfilter="home:vamsivanka" Dim myRequest As WebRequest Dim myResponse As WebResponse Try myRequest = System.Net.WebRequest.Create(url) myRequest.Timeout = 10000 myResponse = myRequest.GetResponse() Dim rssStream As Stream = myResponse.GetResponseStream() Dim rssDoc As New XmlDocument() rssDoc.Load(rssStream) Catch ex As Exception End Try But the rssDoc.Load is giving me an error '--' is an unexpected token. The expected token is ''. Line 81, position 5. Please Let me know your suggestions.

    Read the article

  • In .NET when I get a response stream from the server what type of encoding type should I use?

    - by Max
    In the following example I m getting a response from the server; however do I need to set ASCII or UTF8 encoding type ? Dim objURI As Uri = New Uri(URL) Dim wReq As WebRequest = WebRequest.Create(objURI) Dim wResp As WebResponse = wReq.GetResponse() Dim respStream As Stream = wResp.GetResponseStream() Dim reader As StreamReader = New StreamReader(respStream, Encoding.ASCII) Dim respHTML As String = reader.ReadToEnd() wResp.Close()

    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

  • Disable proxy for entire application?

    - by Brent
    Ever since upgrading to Visual Studio 2010, I'm running into an issue where the first web request of any type (WebRequest, WebClient, etc.) hangs for about 20 seconds before completing. Subsequent calls work quickly. I've narrowed down the problem to a proxy issue. If I manually disable proxy settings, I don't experience this delay: Dim wrq As WebRequest = WebRequest.Create(Url) wrq.Proxy = Nothing What's strange is that there are no proxy settings enabled on this machine in Internet Options. What I'm wondering is if there is a way to disable proxy settings for my entire project in one shot without explicitly disabling as above for every web object. The main reason I want to be able to do this is that I'm trying to use an API (http://code.google.com/p/google-api-for-dotnet/) which uses web requests, but does not provide any way to manually disable proxy settings. I have found some information suggesting that I need to add some proxy information to the app.config file, but I get errors building my program if I make an edits to that file. Can anyone point me in the right direction?

    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

  • WCF REST adding data using POST or PUT 400 Bad Request

    - by user55474
    HI How do i add data using wcf rest architecture. I dont want to use the channelfactory to call my method. Something similar to the webrequest and webresponse used for GET. Something similar to the ajax WebServiceProxy restInvoke Or do i always have to use the Webchannelfactory implementation I am getting a 400 BAD request by using the following Dim url As String = "http://localhost:4475/Service.svc/Entity/Add" Dim req As WebRequest = WebRequest.Create(url) req.Method = "POST" req.ContentType = "application/xml; charset=utf-8" req.Timeout = 30000 req.Headers.Add("SOAPAction", url) Dim xEle As XElement xEle = <Entity xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <Name>Entity1</Name> </Entity> Dim sXML As String = xEle .Value req.ContentLength = sXML.Length Dim sw As New System.IO.StreamWriter(req.GetRequestStream()) sw.Write(sXML) sw.Close() Dim res as HttpWebResponse = req.GetResponse() Sercice Contract is as follows <OperationContract()> _ <WebInvoke(Method:="PUT", UriTemplate:="Entity/Add")> _ Function AddEntity(ByVal e1 As Entity) DataContract is as follows <Serializable()> _ <DataContract()> _ Public Class Entity private m_Name as String <DataMember()> _ Public Property Name() As String Get Return m_Name End Get Set(ByVal value As String) m_Name = value End Set End Property End Class thanks

    Read the article

  • web service client authentication

    - by Jack
    I want to consume Java based web service with c#.net client. The problem is, I couldnt authenticate to the service. it didnt work with this: mywebservice.Credentials = new System.Net.NetworkCredential(userid, userpass); I tried to write base class for my client method. public class ClientProtocols : SoapHttpClientProtocol { protected override WebRequest GetWebRequest(Uri uri) { System.Net.WebRequest request = base.GetWebRequest(uri); if (null != Credentials) request.Headers.Add("Authorization", GetAuthHeader()); return request; } protected override WebResponse GetWebResponse(WebRequest request) { WebResponse response = base.GetWebResponse(request); return response; } private string GetAuthHeader() { StringBuilder sb = new StringBuilder(); sb.Append("Basic "); NetworkCredential cred = Credentials.GetCredential(new Uri(Url), "Basic"); string s = string.Format("{0}:{1}", cred.UserName, cred.Password); sb.Append(Convert.ToBase64String(Encoding.ASCII.GetBytes(s))); return sb.ToString(); } } How can I use this class and authorize to the web service? Thanks.

    Read the article

  • Change cookies when doing jQuery.ajax requests in Chrome Extensions

    - by haskellguy
    I have wrote a plugin for facebook that sends data to testing-fb.local. The request goes through if the user is logged in. Here is the workflow: User logs in from testing-fb.local Cookies are stored When $.ajax() are fired from the Chrome extension Chrome extension listen with chrome.webRequest.onBeforeSendHeaders Chrome extension checks for cookies from chrome.cookies.get Chrome changes the Set-Cookies header to be sent And the request goes through. I wrote this part of code that shoud be this: function getCookies (callback) { chrome.cookies.get({url:"https://testing-fb.local", name: "connect.sid"}, function(a){ return callback(a) }) } chrome.webRequest.onBeforeSendHeaders.addListener( function(details) { getCookies(function(a){ // Here something happens }) }, {urls: ["https://testing-fb.local/*"]}, ['blocking']); Here is my manifest.json: { "name": "test-fb", "version": "1.0", "manifest_version": 1, "description": "testing", "permissions": [ "cookies", "webRequest", "tabs", "http://*/*", "https://*/*" ], "background": { "scripts": ["background.js"] }, "content_scripts": [ { "matches": ["http://*.facebook.com/*", "https://*.facebook.com/*"], "exclude_matches" : [ "*://*.facebook.com/ajax/*", "*://*.channel.facebook.tld/*", "*://*.facebook.tld/pagelet/generic.php/pagelet/home/morestories.php*", "*://*.facebook.tld/ai.php*" ], "js": ["jquery-1.8.3.min.js", "allthefunctions.js"] } ] } In allthefunction.js I have the $.ajax calls, and in background.js is where I put the code above which however looks not to run.. In summary, I have not clear: What I should write in Here something happens If this strategy is going to work Where should I put this code?

    Read the article

  • A DirectoryCatalog class for Silverlight MEF (Managed Extensibility Framework)

    - by Dixin
    In the MEF (Managed Extension Framework) for .NET, there are useful ComposablePartCatalog implementations in System.ComponentModel.Composition.dll, like: System.ComponentModel.Composition.Hosting.AggregateCatalog System.ComponentModel.Composition.Hosting.AssemblyCatalog System.ComponentModel.Composition.Hosting.DirectoryCatalog System.ComponentModel.Composition.Hosting.TypeCatalog While in Silverlight, there is a extra System.ComponentModel.Composition.Hosting.DeploymentCatalog. As a wrapper of AssemblyCatalog, it can load all assemblies in a XAP file in the web server side. Unfortunately, in silverlight there is no DirectoryCatalog to load a folder. Background There are scenarios that Silverlight application may need to load all XAP files in a folder in the web server side, for example: If the Silverlight application is extensible and supports plug-ins, there would be a /ClinetBin/Plugins/ folder in the web server, and each pluin would be an individual XAP file in the folder. In this scenario, after the application is loaded and started up, it would like to load all XAP files in /ClinetBin/Plugins/ folder. If the aplication supports themes, there would be a /ClinetBin/Themes/ folder, and each theme would be an individual XAP file too. The application would qalso need to load all XAP files in /ClinetBin/Themes/. It is useful if we have a DirectoryCatalog: DirectoryCatalog catalog = new DirectoryCatalog("/Plugins"); catalog.DownloadCompleted += (sender, e) => { }; catalog.DownloadAsync(); Obviously, the implementation of DirectoryCatalog is easy. It is just a collection of DeploymentCatalog class. Retrieve file list from a directory Of course, to retrieve file list from a web folder, the folder’s “Directory Browsing” feature must be enabled: So when the folder is requested, it responses a list of its files and folders: This is nothing but a simple HTML page: <html> <head> <title>localhost - /Folder/</title> </head> <body> <h1>localhost - /Folder/</h1> <hr> <pre> <a href="/">[To Parent Directory]</a><br> <br> 1/3/2011 7:22 PM 185 <a href="/Folder/File.txt">File.txt</a><br> 1/3/2011 7:22 PM &lt;dir&gt; <a href="/Folder/Folder/">Folder</a><br> </pre> <hr> </body> </html> For the ASP.NET Deployment Server of Visual Studio, directory browsing is enabled by default: The HTML <Body> is almost the same: <body bgcolor="white"> <h2><i>Directory Listing -- /ClientBin/</i></h2> <hr width="100%" size="1" color="silver"> <pre> <a href="/">[To Parent Directory]</a> Thursday, January 27, 2011 11:51 PM 282,538 <a href="Test.xap">Test.xap</a> Tuesday, January 04, 2011 02:06 AM &lt;dir&gt; <a href="TestFolder/">TestFolder</a> </pre> <hr width="100%" size="1" color="silver"> <b>Version Information:</b>&nbsp;ASP.NET Development Server 10.0.0.0 </body> The only difference is, IIS’s links start with slash, but here the links do not. Here one way to get the file list is read the href attributes of the links: [Pure] private IEnumerable<Uri> GetFilesFromDirectory(string html) { Contract.Requires(html != null); Contract.Ensures(Contract.Result<IEnumerable<Uri>>() != null); return new Regex( "<a href=\"(?<uriRelative>[^\"]*)\">[^<]*</a>", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant) .Matches(html) .OfType<Match>() .Where(match => match.Success) .Select(match => match.Groups["uriRelative"].Value) .Where(uriRelative => uriRelative.EndsWith(".xap", StringComparison.Ordinal)) .Select(uriRelative => { Uri baseUri = this.Uri.IsAbsoluteUri ? this.Uri : new Uri(Application.Current.Host.Source, this.Uri); uriRelative = uriRelative.StartsWith("/", StringComparison.Ordinal) ? uriRelative : (baseUri.LocalPath.EndsWith("/", StringComparison.Ordinal) ? baseUri.LocalPath + uriRelative : baseUri.LocalPath + "/" + uriRelative); return new Uri(baseUri, uriRelative); }); } Please notice the folders’ links end with a slash. They are filtered by the second Where() query. The above method can find files’ URIs from the specified IIS folder, or ASP.NET Deployment Server folder while debugging. To support other formats of file list, a constructor is needed to pass into a customized method: /// <summary> /// Initializes a new instance of the <see cref="T:System.ComponentModel.Composition.Hosting.DirectoryCatalog" /> class with <see cref="T:System.ComponentModel.Composition.Primitives.ComposablePartDefinition" /> objects based on all the XAP files in the specified directory URI. /// </summary> /// <param name="uri"> /// URI to the directory to scan for XAPs to add to the catalog. /// The URI must be absolute, or relative to <see cref="P:System.Windows.Interop.SilverlightHost.Source" />. /// </param> /// <param name="getFilesFromDirectory"> /// The method to find files' URIs in the specified directory. /// </param> public DirectoryCatalog(Uri uri, Func<string, IEnumerable<Uri>> getFilesFromDirectory) { Contract.Requires(uri != null); this._uri = uri; this._getFilesFromDirectory = getFilesFromDirectory ?? this.GetFilesFromDirectory; this._webClient = new Lazy<WebClient>(() => new WebClient()); // Initializes other members. } When the getFilesFromDirectory parameter is null, the above GetFilesFromDirectory() method will be used as default. Download the directory’s XAP file list Now a public method can be created to start the downloading: /// <summary> /// Begins downloading the XAP files in the directory. /// </summary> public void DownloadAsync() { this.ThrowIfDisposed(); if (Interlocked.CompareExchange(ref this._state, State.DownloadStarted, State.Created) == 0) { this._webClient.Value.OpenReadCompleted += this.HandleOpenReadCompleted; this._webClient.Value.OpenReadAsync(this.Uri, this); } else { this.MutateStateOrThrow(State.DownloadCompleted, State.Initialized); this.OnDownloadCompleted(new AsyncCompletedEventArgs(null, false, this)); } } Here the HandleOpenReadCompleted() method is invoked when the file list HTML is downloaded. Download all XAP files After retrieving all files’ URIs, the next thing becomes even easier. HandleOpenReadCompleted() just uses built in DeploymentCatalog to download the XAPs, and aggregate them into one AggregateCatalog: private void HandleOpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { Exception error = e.Error; bool cancelled = e.Cancelled; if (Interlocked.CompareExchange(ref this._state, State.DownloadCompleted, State.DownloadStarted) != State.DownloadStarted) { cancelled = true; } if (error == null && !cancelled) { try { using (StreamReader reader = new StreamReader(e.Result)) { string html = reader.ReadToEnd(); IEnumerable<Uri> uris = this._getFilesFromDirectory(html); Contract.Assume(uris != null); IEnumerable<DeploymentCatalog> deploymentCatalogs = uris.Select(uri => new DeploymentCatalog(uri)); deploymentCatalogs.ForEach( deploymentCatalog => { this._aggregateCatalog.Catalogs.Add(deploymentCatalog); deploymentCatalog.DownloadCompleted += this.HandleDownloadCompleted; }); deploymentCatalogs.ForEach(deploymentCatalog => deploymentCatalog.DownloadAsync()); } } catch (Exception exception) { error = new InvalidOperationException(Resources.InvalidOperationException_ErrorReadingDirectory, exception); } } // Exception handling. } In HandleDownloadCompleted(), if all XAPs are downloaded without exception, OnDownloadCompleted() callback method will be invoked. private void HandleDownloadCompleted(object sender, AsyncCompletedEventArgs e) { if (Interlocked.Increment(ref this._downloaded) == this._aggregateCatalog.Catalogs.Count) { this.OnDownloadCompleted(e); } } Exception handling Whether this DirectoryCatelog can work only if the directory browsing feature is enabled. It is important to inform caller when directory cannot be browsed for XAP downloading. private void HandleOpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { Exception error = e.Error; bool cancelled = e.Cancelled; if (Interlocked.CompareExchange(ref this._state, State.DownloadCompleted, State.DownloadStarted) != State.DownloadStarted) { cancelled = true; } if (error == null && !cancelled) { try { // No exception thrown when browsing directory. Downloads the listed XAPs. } catch (Exception exception) { error = new InvalidOperationException(Resources.InvalidOperationException_ErrorReadingDirectory, exception); } } WebException webException = error as WebException; if (webException != null) { HttpWebResponse webResponse = webException.Response as HttpWebResponse; if (webResponse != null) { // Internally, WebClient uses WebRequest.Create() to create the WebRequest object. Here does the same thing. WebRequest request = WebRequest.Create(Application.Current.Host.Source); Contract.Assume(request != null); if (request.CreatorInstance == WebRequestCreator.ClientHttp && // Silverlight is in client HTTP handling, all HTTP status codes are supported. webResponse.StatusCode == HttpStatusCode.Forbidden) { // When directory browsing is disabled, the HTTP status code is 403 (forbidden). error = new InvalidOperationException( Resources.InvalidOperationException_ErrorListingDirectory_ClientHttp, webException); } else if (request.CreatorInstance == WebRequestCreator.BrowserHttp && // Silverlight is in browser HTTP handling, only 200 and 404 are supported. webResponse.StatusCode == HttpStatusCode.NotFound) { // When directory browsing is disabled, the HTTP status code is 404 (not found). error = new InvalidOperationException( Resources.InvalidOperationException_ErrorListingDirectory_BrowserHttp, webException); } } } this.OnDownloadCompleted(new AsyncCompletedEventArgs(error, cancelled, this)); } Please notice Silverlight 3+ application can work either in client HTTP handling, or browser HTTP handling. One difference is: In browser HTTP handling, only HTTP status code 200 (OK) and 404 (not OK, including 500, 403, etc.) are supported In client HTTP handling, all HTTP status code are supported So in above code, exceptions in 2 modes are handled differently. Conclusion Here is the whole DirectoryCatelog’s looking: Please click here to download the source code, a simple unit test is included. This is a rough implementation. And, for convenience, some design and coding are just following the built in AggregateCatalog class and Deployment class. Please feel free to modify the code, and please kindly tell me if any issue is found.

    Read the article

  • WebClient.DownloadData hangs

    - by sagie
    Hi. I am trying to download file using WebClient.DownloadData. Usually the download is Ok, but for some Urls the download just hangs. I've tried to override the WebClient, and set a timeout to the WebRequest, and it didn't help. I've also tried to create WebRequest (with time out), then get the WebResponse, and then get the stream. When I've read the stream, It hangs again. This is an example for a url that hangs: http://www.daikodo.com/genki-back/back-img/10genki-2.jpg. Any Idea?

    Read the article

  • RSS parsing last build Date. Fastest way to do so please.

    - by Paul
    Dim myRequest As System.Net.WebRequest = System.Net.WebRequest.Create(url) Dim myResponse As System.Net.WebResponse = myRequest.GetResponse() Dim rssStream As System.IO.Stream = myResponse.GetResponseStream() Dim rssDoc As New System.Xml.XmlDocument() Try rssDoc.Load(rssStream) Catch nosupport As NotSupportedException Throw nosupport End Try Dim rssItems As System.Xml.XmlNodeList = rssDoc.SelectNodes("rss/channel") 'For i As Integer = 0 To rssItems.Count - 1 Dim rssDetail As System.Xml.XmlNode rssDetail = rssItems.Item(0).SelectSingleNode("lastBuildDate") Folks this is what I'm using to parse an RSS feed for the last updated time. Is there a quicker way? Speed seems to be a bit slow on it as it pulls down the entire feed before parsing.

    Read the article

  • How to convert *.aspx (HTML) page to Image format

    - by Swapnil Fegade
    I want to convert *.aspx (HTML) page's (User Interface) to Image such as JPEG. I am using below code for that Protected Sub btnGet_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGet.Click saveURLToImage("http://google.co.in") End Sub Private Sub saveURLToImage(ByVal url As String) If Not String.IsNullOrEmpty(url) Then Dim content As String = "" Dim webRequest__1 As System.Net.WebRequest = WebRequest.Create(url) Dim webResponse As System.Net.WebResponse = webRequest__1.GetResponse() Dim sr As System.IO.StreamReader = New StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8")) content = sr.ReadToEnd() 'save to file Dim b As Byte() = Convert.FromBase64String(content) Dim ms As New System.IO.MemoryStream(b, 0, b.Length) Dim img As System.Drawing.Image = System.Drawing.Image.FromStream(ms) img.Save("c:\pic.jpg", System.Drawing.Imaging.ImageFormat.Jpeg) img.Dispose() ms.Close() End If End Sub But I am getting Error as "Invalid character in a Base-64 string" at line Dim b As Byte() = Convert.FromBase64String(content)

    Read the article

  • Debug .Net Framework's source code only shows disassembly in Visual Studio 2010

    - by jdecuyper
    Hi! I'm trying to debug .Net Framework's source code using Visual Studio 2010 Professional. I followed the steps described in Raj Kaimal's post but I must be doing something wrong since the only code I'm getting to see is the disassembly code: As you can see in the image, the Go to Source Code and the Load Symbols options are disabled. Nevertheless, symbols are downloaded from Microsoft's server since I can see them inside the local cache directory. The code I'm debugging goes as follow: var wr = WebRequest.Create("http://www.google.com"); Console.WriteLine("Web request created"); var req = wr.GetRequestStream(); Console.Read(); When I hit F11 to step into the first line of code, a window pops us looking for the "WebRequst.cs" file inside "f:\dd\ndp\fx\src\Net\System\Net\WebRequest.cs" which does not exists on my machine. What am I missing? Thanks a lot for your help.

    Read the article

  • How to stream video content in asp.net?

    - by Kon
    Hi, I have the following code which downloads video content: WebRequest wreq = (HttpWebRequest)WebRequest.Create(url); using (HttpWebResponse wresp = (HttpWebResponse)wreq.GetResponse()) using (Stream mystream = wresp.GetResponseStream()) { using (BinaryReader reader = new BinaryReader(mystream)) { int length = Convert.ToInt32(wresp.ContentLength); byte[] buffer = new byte[length]; buffer = reader.ReadBytes(length); Response.Clear(); Response.Buffer = false; Response.ContentType = "video/mp4"; //Response.BinaryWrite(buffer); Response.OutputStream.Write(buffer, 0, buffer.Length); Response.End(); } } But the problem is that the whole file downloads before being played. How can I make it stream and play as it's still downloading? Or is this up to the client/receiver application to manage?

    Read the article

  • how to run javascript from c# code ?

    - by dotnetcoder
    I have a webrequest that returns a html response which has form inside with hidden fields with some javascript that submits the form automatically on pageload ( if this was run in a browser). If I save this file as *.html and run this file in browser , the java script code automatically posts the form and the output is excel file. I want to be able to generate this file from a c# code which is not running in broswer. I tried mocking thr form post but its complicated and has various scenarios based on the original webrequest querystring. any pointers.... i know its not possible to probably run JS code that posts the form - from within c# code but still thought of chekcing if someone has done that.

    Read the article

  • Call HttpWebRequest in another thread as UI with Task class - avoid to dispose object created in Task scope

    - by John
    I would like call HttpWebRequest on another thread as UI, because I must make 200 request or server and downloaded image. My scenation is that I make a request on server, create image and return image. This I make in another thread. I use Task class, but it call automaticaly Dispose method on all object created in task scope. So I return null object from this method. public BitmapImage CreateAvatar(Uri imageUri, int sex) { if (imageUri == null) return CreateDefaultAvatar(sex); BitmapImage image = null; new Task(() => { var request = WebRequest.Create(imageUri); var response = request.GetResponse(); using (var stream = response.GetResponseStream()) { Byte[] buffer = new Byte[response.ContentLength]; int offset = 0, actuallyRead = 0; do { actuallyRead = stream.Read(buffer, offset, buffer.Length - offset); offset += actuallyRead; } while (actuallyRead > 0); image = new BitmapImage { CreateOptions = BitmapCreateOptions.None, CacheOption = BitmapCacheOption.OnLoad }; image.BeginInit(); image.StreamSource = new MemoryStream(buffer); image.EndInit(); image.Freeze(); } }).Start(); return image; } How avoid it? Thank Mr. Jon Skeet try this: private Stream GetImageStream(Uri imageUri) { Byte[] buffer = null; //new Task(() => //{ var request = WebRequest.Create(imageUri); var response = request.GetResponse(); using (var stream = response.GetResponseStream()) { buffer= new Byte[response.ContentLength]; int offset = 0, actuallyRead = 0; do { actuallyRead = stream.Read(buffer, offset, buffer.Length - offset); offset += actuallyRead; } while (actuallyRead > 0); } //}).Start(); return new MemoryStream(buffer); } It return object which is null a than try this: private Stream GetImageStream(Uri imageUri) { Byte[] buffer = null; new Task(() => { var request = WebRequest.Create(imageUri); var response = request.GetResponse(); using (var stream = response.GetResponseStream()) { buffer= new Byte[response.ContentLength]; int offset = 0, actuallyRead = 0; do { actuallyRead = stream.Read(buffer, offset, buffer.Length - offset); offset += actuallyRead; } while (actuallyRead > 0); } }).Start(); return new MemoryStream(buffer); } Method above return null

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >