C# - Can Reuse HttpWebRequest Without Disconnecting From The Server

Feb 8, 2011

I'm trying to debug a specific issue with my ASP.NET application. The client runs the following code:

void uploadFile( string serverUrl, string filePath )
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.
Create( serverUrl );
CredentialCache cache = new CredentialCache();
cache.Add( new Uri( serverUrl ), "Basic", new NetworkCredential( "User", "pass" ) );
request.Credentials = cache;
request.Method = "POST";
request.ContentType = "application/octet-stream";
request.Timeout = 60000;
request.KeepAlive = true;
using( BinaryReader reader = new BinaryReader(
File.OpenRead( filePath ) ) ) {
request.ContentLength = reader.BaseStream.Length;
using( Stream stream = request.GetRequestStream() ) {
byte[] buffer = new byte[1024];
while( true ) {
int bytesRead = reader.Read( buffer, 0, buffer.Length );
if( bytesRead == 0 ) {
break;
}
stream.Write( buffer, 0, bytesRead );
}
}
}
HttpWebResponse result = (HttpWebResponse)request.GetResponse();
//handle result - not relevant
}

and Write() throws an exception with "Unable to write data to the transport connection: An established connection was aborted by the software in your host machine." text. I used System.Net tracing and found that something goes wrong when I send the request with Content-Length set.

Specifically if I omit everything that is inside using statement in the code above the server promptly replies with WWW-Authenticate and then the client reposts the request with WWW-Authenticate and everything goes fine except the file in not uploaded and the request fails much later.

I'd like to do the following: send an request without data, wait for WWW-Authenticate, then repeat it with WWW-Authenticate and data. So I tried to modify the code above: first set all the parameters, then call GetResponse(), then do sending, but when I try to set ContentLength property an exception is thrown with "This property cannot be set after writing has started" text. So HttpWebRequest seems to be non-reusable.

How do I reuse it for resending the request without closing the connection?

View 2 Replies


Similar Messages:

C# - Disconnecting Users Terminal Service Session Via Local Intranet

Aug 11, 2010

I have written code that uses a .bat file (code: rwvinstat /server:servername) that populates a DataGrid of users logged in to a terminal service session in c#. The .bat lives on the server with the app. files and will run properly if executed manually on the server .Also if i run the app. locally and call the .bat file on the server it works fine.

The problem is when i deploy my web app on the server the DataGrid never populates nor do i get any errors. i have given full permissions to IUSER_MACHINENAME(and various users) and i set the virtual directory permissions to read, run, execute. Ialso have set my web.conf fig to:< "identity impersonate="true" userName="username" password="password"/> Here is my Source code:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.IO;
public partial class ilsap01_users : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("C:\listUsersIlsap01.bat");
psi.RedirectStandardOutput = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
System.Diagnostics.Process listFiles;
listFiles = System.Diagnostics.Process.Start(psi);
System.IO.StreamReader rawUserData = listFiles.StandardOutput;
listFiles.WaitForExit(20000);
try..................

View 2 Replies

C# - Using HttpWebRequest To POST To A Form On An Outside Server?

Jan 26, 2010

I am trying to simulate a POST to a form on an external server that does not require any authentication, and capture a sting containing the resulting page. This is what the form looks like:

<FORM METHOD="POST" ACTION="/controller" NAME="GIN">
<INPUT type="hidden" name="JSPName" value="GIN">

Field1:

<INPUT type="text" name="Field1" size="30"
maxlength="60" class="txtNormal" value="">
</FORM>

This is what my code looks like:

ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "Field1=VALUE1&JSPName=GIN";
byte[] data = encoding.GetBytes(postData);
// Prepare web request...
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("https://XXX/controller");
myRequest.Method = "POST";
myRequest.ContentType = "text/html";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
// Send the data.
newStream.Write(data, 0, data.Length);
StreamReader reader = new StreamReader(newStream);
string text = reader.ReadToEnd();
MessageBox.Show(text);
newStream.Close();

Currently, the code returns "Stream was not readable".

View 2 Replies

C# - HttpWebRequest Connection Limit And RestFUL Server?

Dec 21, 2010

I have created a server product that is connecting to some social network servers and sending to data which status update etc. The server already authenticated to necessary social networks servers by users who is using this solution.

Actually, I have no problem at this time, but I think I will.

My server will be open a thousands of concurrent request to neccessary servers via Http with C# HttpWebRequest instance. I already know that It's possible to change concurrent request limits with below propery.

ServicePointManager.DefaultConnectionLimit AFAIK, this limit is max 100 evet you set more than 100. So, I will be faced with bottleneck problem with HttpWebRequest even change the DefaultConnectionLimit property of ServicePointManager.

View 1 Replies

Web Forms :: HttpWebRequest - Download File From Web Server?

Oct 19, 2010

I am working on a .NET1.1 application. I want to download file on the web servers using httpwebresponse.

How to download a file on the webserver using httpwebresponse using C# code?

View 3 Replies

C# - Underlying Connection Closed On HttpWebRequest POST On Production Server?

Nov 23, 2010

I'm getting the "The underlying connection was closed: The connection was closed unexpectedly." error while trying to POST using the HttpWebRequest class on the production server, on my dev machine it works fine.

I originally tried using the WebClient class but I switched to the HttpWebRequest to try some of the suggestions I found while researching the issue (such as setting KeepAlive to false, PreAuthenticate true and ProtocolVersion to 1.0).

Since it's only happening on the production server, i'm guessing that it might have something to do with IIS.

Here's my code

[Code]....

If set the Target Framework (I used a new project for testing) to 2.0 (I didn't test every version of the framework) it works. I'm guessing that .net handles the security differently in .net 4.0.

View 3 Replies

Web Forms :: Posting To External Site Using HttpWebRequest Not Like Server.transfer?

Jun 18, 2010

I'm trying to post a value to an external site and have managed to piece it together using HttpWebRequest. My problem is that this behaves like a server.transfer. ie it maintains the url. As a result the page I'm posting to doesn't link to any of it's images or stylesheet. Can anyone give me a simple way to do an old style post to an external site?

View 5 Replies

WCF / ASMX :: Accessing Response Of HttpWebRequest, Even When Request Returns 500 Internal Server Error

Oct 22, 2010

Hoping someone can point me to a solution, haven't been able to find one yet.

I'm using the standard way for send HttpWebRequest

[Code]....

As you can see from Fiddler/SOAPUI it does return the SOAP fault, however using HttpWebRequest i can't capture the response.

Returning 500 triggers my exception handling and Capturing the WebException doesn't expose the response.

Does anyone know how to capture this response xml in the case of 500 Internal Server Errors.

View 1 Replies

Call WebService Using HttpWebRequest "remote Server Returned An Error: (500) Internal Server Error"

Aug 16, 2010

I want to call my WebService using HttpWebRequest, but I get Error:The remote server returned an error: (500) Internal Server Error. The webservice works fine through the following url: [URL]

[Code]....

View 3 Replies

About "Unable To Connect To Remote Server." Using HttpWebRequest?

Aug 24, 2010

about "Unable to connect to remote server." using HttpWebRequest?

View 4 Replies

C# - How To Reuse A WMI Or DB Connections

Dec 12, 2010

I have simple asp.net web service, for monitoring and managing about 10 computers, with 4 webMethods and all of this methods are quite simple. In general they look sometning like: (1)make WMI connections to certain machine, (2)do some simple task, (3)return result.

Problem is that WMI connections to remote computers takes about 15s and I offten need to call 2 or 3 methods successively for the same machine.

From what I know, there is new instance of my service class (public class MonSvr :

System.Web.Services.WebService ) created every time webMethod is called.

So how can I share WMI or DB connection betwen all instances of my service that I could reuse this connection ? When there all multiple calls to webMethods of my service, does then each instance of web service runs in separate thread ?

View 2 Replies

Reuse Popup Window?

Jul 16, 2010

Is there a way to accomplish this? Let me give you a scenario:

The user clicks on a button "Click Me", then it opens a new window that is aspx page. The user didn't close that page, and went back and click on the same button "Click Me" again. At this point, instead of open a brand new window, I want to be able to reuse the same opened aspx page earlier and concatenate some information...

View 2 Replies

C# - Reuse Of WCF Service Clients

Jan 10, 2011

I have a WCF webservice that acts as a data provider for my ASP.NET web page. Throughout the web page a number of calls are made to the web service via the auto-generated ServiceClient. Currently I create a new ServiceClient and open it for each request i.e. Get Users, Get Roles, Get Customer list etc.... Each one of these would create a new ServiceClient and open a new connection.

Can I make my ServiceClient class a global or statically available class so that all functions within my ASP.NET web page can use the same client. This would seem to be far more efficient. Are there any issues with doing it this way? Any advice I should take into account when doing this? What happens if I make multiple requests to a client? Presumably it is all synchronous so it shouldn't matter if I make 1 or 50 calls to it?

View 2 Replies

MVC :: Reuse Certain Data Across Application?

Nov 16, 2010

Using a SQL Server back end, I have a Company Name field that I want to reuse in different views of my application. I do not want to use it only in the Master layout but within the "view space". Is there another way to access this data without using a ".include" for that table in all of my methods? Is there a way to add dynamic data in the Shared folder that can be called up anytime? If it is in the Master page can I pull the variable into the specific "view space"?

View 5 Replies

How To Reuse Logic In A Context Sensitive Way In MVC

Feb 9, 2011

Trying to figure out the best way to organize a ASP.NET MVC site. Take a very simple 1..N relationship: Company can have many Contacts, Contacts must have exactly one Company.I have your typical routes:

Company/Index (list all companies)
Company/Details/{int} (details of Company {int})
Company/Create (create new company)
Contact/Index (list all contacts)
Contact/Create (create new contact, company is selected from drop down)

Now if I wanted to create a page that created a Contact in the context of a Company (from the Company detail page) so that the required company is filled in/not editable), what would be the best route of going about that, while not duplicating code where possible.Not sure if I can leverage the Contact/Create logic/view from the Company controller (and be able to route back to the Company Details page when complete), or mess with the routes to do something like Company/Details/{int}/Contact/Create (not even sure if that makes sense or would work)?There has got to be a better way then me adding my logic and view for adding a Contact into my Controller view and having it duplicated.

View 1 Replies

C# - Reuse A Dropdownlist Each Row Of A Table Instead Of Rebuilding It?

Apr 30, 2010

I have a table the uses the same dropdown list in each row. I thought that I could just create one dropdown list and then reuse it in each new row, but the table only ends up with one row unless I create "new" dropdownlist. Am I approaching this all wrong? In the interest of efficiency, is there a way to build the list once and then reuse it by creating another instance of it or something? I was trying to avoid rebuilding that list umpteen times.

private void UserRoles()
{
Table table = MakeTable();
Ewo.sqlDataStore.Administrator sql = new Ewo.sqlDataStore.Administrator();
DataSet dataset =sql.SiteUserRoleList();
DropDownList sel = RoleList(dataset.Tables[0]);
if(tools.validDataSet(dataset))
{
if (dataset.Tables.Count > 1)//existing roles are #2, show the roles the user is part of
{
foreach (DataRow dRow in dataset.Tables[1].Rows)
{
table.Rows.Add(CreateRoleRow(Convert.ToString(dRow["SitePageGroupName"]), sel));//add a row with data
}
}
table.Rows.Add(CreateRoleRow(sel));//add a blank row on the bottom
}
AdminSiteUerRoles.Controls.Add(table);//add it all to the page
}

View 2 Replies

Web Forms :: Reuse A Created Web Project?

Jul 22, 2010

i have created a dynamic web site that is made of these parts

1- Main Site (clients use this part to view the main site

2-Control Panel side (Admins can view and manage the First Part's content)

my problem is that i want to use both projects for another client's web site,but client 2 needs some custom features that should integrated with the existing control panel or Main Site, what is the efficient plan for do this?

View 2 Replies

Websites Functionality Reuse By Desktop Application

Nov 10, 2010

We are implementing some business functionality that it exposed through the asp.net web service. At the current stage user interface is required for some peace of it and we are going to implement it inside of already existing desktop application (it is MFC C++ application, but we are considering to integrate some WinForms/Wpf components). In the nearest future we plan to replace current desktop application with a web site version (it will be asp.net web site, or PROBABLY Silverlight application). Therefore, I would like to implement UI once on the web site and just re-use it in some way from desktop application. Am I clear enough? Is there any way to do that? For sure, I can implement web service and use it from desktop application right now and re-use it from web application when it will be required... But I hope there is a better way to do that.

View 3 Replies

Reuse CSS From The Ajax Control Toolkit Controls?

Mar 23, 2011

I'm developping an ASP.NET 4.0 application with several controls from the Ajax Toolkit Control.I need a tooltip component, so I use the HoverMenu (displays a Panel when hovering something) and I really like the design used by the ValidatorCallout.So I copied the HTML generated by the framework and added that to my panel.The problem is that it seems that the Ajax Toolkit controls dynamically load the CSS part they need. So it doesn't display anything as there are no ValidatorCallout on the page.I would be really annoyed if I had to add that control only to get the CSS.My solution so far is to also copy the CSS from the ASP.NET website, but I'm looking for a nicer way to reuse the existing Toolkit CSS.Is there a way to load the parts I want "manually" ?

View 1 Replies

AJAX :: Reuse Update Panel In The Same Page?

Dec 15, 2010

in one table

<asp:UpdatePanel ID="Operations" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="txtOperations" runat="server" Font-Names="Code128bWin" OnTextChanged="OperationEventHandler" AutoPostBack="true"></asp:TextBox>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID = "txtOperations" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>

and a label in other table

<asp:Label ID="lblOperation" Text="OperationID not Valid" runat="></asp:Label>

and the code behind page is

protected void OperationEventHandler(object sender, EventArgs e)
{
GridView GridViewValidOps = new GridView();
GridViewValidOps.DataSource = TB.ValidateOperations(txtOperations.Text);
GridViewValidOps.DataBind();
if (GridViewValidOps.Rows.Count <= 0)
{
lblOperation.Text = "OperationID Not Valid";
}
}

Is there a way to use the same update panel for the label , because i want the value of the label to be updated if the user enters wrong value.

View 3 Replies

Splitting Up EDM To Reuse Functionality Across Multiple Projects?

Jan 30, 2011

I currently have an ASP .NET MVC / EF4 project that contains many pieces of autonomous functionality such as a blogging, events, contests, wiki, etc.

The entities used by each system are all mapped to my database through one giant EDM file.

This works well for the main site, but I also have a few personal sites where I want to reuse just the blogging functionality from the mains ite.

My biggest problem is that due to the mac daddy EDM file, my blog sites have to constantly have their database schemas updated to reflect changes made to areas of functionality that they don't use (i.e. changes to the events system).

The only other gotcha is that there are some entities (Users and Tags) that have relationships with entities from each area of functionality, making it hard to simply split each area of functionality off into its own EDM.

With all of this said, I'm trying to figure out the most efficient way to set this up.

Should I go down the road of splitting up the EDMs by each area (blogs, events, contests, wiki) and figuring out a way to maintain relationships for the User and Tag entities?

Or should I just perhaps be creating an EDM for each website that only maps the entities that it will actually need? The only problem with this is that my repository layer takes in a UnitOfWork/ObjectContext, and by creating new ObjectContexts for each site I'd have problems reusing my repository code.

View 1 Replies

MVC :: How To Reuse Model Metadata For Custom View Models

Oct 19, 2010

I'm working on an ASP.NET MVC 2 project with some business entities that have metadata dataannotations attributes applied to them (Validation attributes, Display attributes, etc.).

Something like:

[Code]....

Using the metadata from different views is no problem, as long as I am using my business entities as viewmodels or as part of a viewmodel like this:

[Code]....

However, sometimes I need to code a view for editing some, but not all fields of an entity. For those fields I want to reuse the metadata already specified in my user entity. The other fields should be ignored. I'm talking about custom view models like this:

[Code]....

That's where I am running into problems. The custom view model above leads to an exception when the view is generated, because it has no password property.

The associated metadata type for type 'Zeiterfassung.Models.ViewModels.Users.UserNameViewModel+UserModel' contains the following unknown properties or fields: Password. make sure that the names of these members match the names of the properties on the main type.

Also, even if this exception did not occur, I expect to get into even more trouble with model validation on form submit because Password is marked as required in my business entity.

I can think of several workarounds, but none seem really ideal. In any case I can't change the database layout so that the password field would be in a separate entity in my example above.

How would you handle this scenario?

View 3 Replies

C# - Can Reuse Built-in IIS Authentication But Provide Own Credentials Checking

Feb 14, 2011

I'd like to use built-in IIS authentication with non-Windows accounts. There's this module that does that for basic authentication, but it in fact does both the authentication and credentials checking.The problem is I also need to support digest authentication and I could try to do it, but it would be a lot of hassle - I need to generate challenges ("nonces") securely, store them and check for replays, etc. - lots of things I can screw up and make determined attackers happy. So I'd prefer to reuse the digest authentication functionality in IIS, but use my own module for credentials validation. How can I do that?

View 1 Replies

How To Write Partial Views With Form That Supports Reuse

Feb 18, 2011

I have a partial view that has a form to post to a controller. I can include it into another view using @Html.RenderPartial. The problem is that the parent view is linked with another controller. And the partial view post to its orginal controller.Is it possible and how to write partial views with form that supports reuse?

View 1 Replies

C# - How To Load Javascript Files In Client System Once And Reuse Them

Feb 20, 2010

I have a large scale application which uses javascript for many reasons. these javascript files included in some JS files and JS files imported to Asp.net Masterpage files.

this JS files contents (javascript functions) will add to page when page display to user, so a Bunch of waste Javascript functions will include in Asp.net pages.

I'm lookingfor a way which these JS files downloads to users computer (any where, e.g: temporary internet files or some where else) and the Asp.net page use that functions which downloaded with page.

I also want to download 1 time ( per user login or per Open Session ) to users computer.

So How to download JS file to Users PC and Use them in Asp.net Pages

View 4 Replies







Copyrights 2005-15 www.BigResource.com, All rights reserved