C# - HttpListener Windows Service Vs HttpHandler .aspx Dilemma
Mar 31, 2011
In a Windows Service I implemented an HttpListener that will handle incoming HTTP Requests to a certain port, parse the query string, insert it in database and send a confirmation response. However, the clients said that they were a bit skeptical and asked if the same could have been done via a webpage. Like having an HTTPHandler listen to a certain port. Got me thinking. What would you do in my situation? Go with the HttpListener/Windows Service or HTTPHandler/.aspx?
Wondering if there is a performance difference between letting a long running process hang in asp.net vs running the process via a windows service. I have done this once before and the windows service was much quicker and didnt bog down my system, whereas the asp.net request seemed to wreak havoc.
Im using a httphandler to response another pdf file in case requested file not found. Its working fine in local development pc but not working in web server. Mapped .pdf as wild card mapping too but no result yet. Still i'm getting the 404 error.
We have encountered this difference in file creation while using a HttpHandler Versus a Code Behind Aspx page. We are reading a saved jpg/png picture as byte array from a 'Image' field in sql server database and create a physical file in the server. Both the Aspx Page and Httphandler use the same code pasted below.
//Begin int docID = Convert.ToInt32(Request.QueryString["DocID"]); var docRow = documentDB.GetDocument(docID); // Retrieve the physical directory path for the Uploads subdirectory string destDir = Server.MapPath("../../Uploads").ToString() + "\"; string strFileName = destDir + DateTime.Now.ToFileTime() + "_" + docRow.DocName.ToString(); FileStream fs = new FileStream(strFileName, FileMode.CreateNew, FileAccess.Write); fs.Write(docRow.DocData, 0, docRow.DocData.Length); fs.Flush(); fs.Close(); // End
After the file is created, it is viewable as a jpg/png Image only in Aspx Code Behind. While in case of HttpHandler it is not a valid Image.
I want to develop my own REST service, so I've created an IHttpHandler that is configured with verb="*" and path="*", the the application in ~/MyRESTsrv/ will handle any derived URL.
This approach works good in IIS7 with "integrated mode" and apparently in IIS6 if you map all the extensions to "aspnet_isapi.dll".
Is this possible in Apache/XSP with Mono? Do I have to do something special or it will work out of the box?
When i create a Windows Service for getting information from a Web Application(ASP.NET c#) for scheduling some task in the client machine.
To consume WCF from the web application. I added WCF reference to Window Service project as a service reference, everything seems fine. It updated app.config file, added service reference etc. it was not working.
I'm having some problems using the httplistener. Basically what I want to do is have my localhost running on [URL]. Under default.aspx.cs I want a listener waiting for the page to get a request. The webpage is then called by for example a console application doing a request to [URL] The problem I'm expering is that I have this code on the localhost running in page load for the page. I realize now that this will just keep my localhost waiting for a reply
[Code]....
This code is run from a console application
[Code]....
Then when I run my console application with this code, I get an error indication the connection had to be forcibly closed. What I'm guessing is that the IIS collides with the listener. Im wondering how and where do I set up a httplistener in a web page?? Is a httplistener neccesary for IIS, or is httplistener used instead of a IIS?? I can't change any port because localhost can only use one at a time? I cant use requeststring because the amount of data I need to send surpass the limit of requeststring.
I am instructed to use an HttpListener. A Service will call my URL, for example: [URL] My question is this. What kind of file do I use for a listener. Is it an .aspx file together with its .cs file as usual? If that is the case, I am told to retreive a string in this function below. I wonder how I will set this up in this function below correctly in order for "listen" for this String. I need to see that ipnValid == true. Do I do this in the Page_Load in any way etc.. ? (I beleive the String that is listening for is parsed with request.Form.Keys)
For my CMS I want users to be able to upload pictures which connect to a product. This all goes well until someone wants to upload a picture when creating a new record.
The problem here is that every product has a GUID (next to the ProductID (PK)) and will be created when the product is saved for the first time. I'm uploading my images trough a webservice with Uploadify jquery plugin so it's all in an ajax based way. The image uploader however needs to know the GUID to store it in the right directory.
My temporary fix was to just let the user save the product before uploading so the GUID is known but it's not very user friendly and I'm sure there would be a better way but I cannot find a satisfying one myself.
This is the only option which I could come up with which is kinda ok but maybe I'm missing something completely:
Create a GUID without saving the product, so the image can be uploaded and the product with the GUID can be saved afterwards. But what if the user navigates away after uploading? I could maybe create a scheduled task to delete those orphant images
Has anyone dealt with similar scenarios? I'm very interested in your opions about his matter since this functionality will be used in multiple sections in my CMS.
I have to establish an HttpListener that will wait for requests made by our client's server. I have to receive that request on port 8088 and extract the query string. That is the easy part. I'm running the HttpListener in a windows service. I cannot get it to fire properly. I build the setup project install the service on our server and it never starts. I suspect there's an error with my code.
HttpListenerClass: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Net; using System.Threading; namespace lalalolo { class HttpListenerClass { bool keepAlive = true; public void AddToFile(string contents) { var fs = new FileStream(@"C:HttpListenerserv.txt", FileMode.OpenOrCreate, FileAccess.Write); var sw = new StreamWriter(fs); sw.BaseStream.Seek(0, SeekOrigin.End); sw.WriteLine(contents); sw.Flush(); sw.Close(); } private HttpListener listener; public HttpListenerClass() { ThreadPool.SetMaxThreads(50, 100); ThreadPool.SetMinThreads(50, 50); listener = new HttpListener(); listener.Prefixes.Add("http://*:8088/"); } public void Start() { listener.Start(); if(keepalive == true){ { try { HttpListenerContext ctx = listener.GetContext(); ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessRequest), ctx); } catch(Exception ex) { AddToFile(ex.Message); } } } } public void Stop() { listener.Stop(); keepalive == false; } public void ProcessRequest(object listenerContext) { try { var context = (HttpListenerContext)listenerContext; string QS = context.Request.QueryString["ID"]; AddToFile(QS); } catch(Exception ex) { AddToFile(ex.Message); } } } } Service1.cs: using System.ComponentModel; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.ServiceProcess; using System.Text; using System.Threading; namespace lalalolo { public partial class HttpListenerTest1 : ServiceBase { HttpListenerClass HTTP = new HttpListenerClass(); public void AddToFile(string contents) { var fs = new FileStream(@"C:HttpListenerserv.txt", FileMode.OpenOrCreate, FileAccess.Write); var sw = new StreamWriter(fs); sw.BaseStream.Seek(0, SeekOrigin.End); sw.WriteLine(contents); sw.Flush(); sw.Close(); } public HttpListenerTest1() { InitializeComponent(); } protected override void OnStart(string[] args) { HTTP.Start(); } protected override void OnStop() { HTTP.Stop(); } } }
- i want to use AJAX color picker extender.i understand its available in .NET 3.5 and above and i am using .NET 2.0.My dilemma is,- My whole webapplication is in .NET 2.0 using VS 2005,C# and i am concerned that i will run into the issues if i upgrade the framework at this point of development.Also even if i do upgrade framework,i can't pgrade vs 2005 to higher just yet.Is there a workaround??thanks a lot.
public dynamic GetReferenceTableData(string tableName) { try { dynamic tableData = ReferenceTableDAL.GetReferenceTableData(tableName); return tableData; } catch (Exception ex) { throw; } } method at DAL(ReferenceTableDAL): public static dynamic GetReferenceTableData(string tableName) { Database db = DatabaseFactory.CreateDatabase(Flags.ConnectionStringKey); DbCommand dbCommand = db.GetStoredProcCommand("USP_GETTABLEDATA"); dynamic objDynamic = null; if (tableName.ToLower() == "a") { objDynamic = new List<A>(); } else if (tableName.ToLower() == "b") { objDynamic = new List<B>(); } else if (tableName.ToLower() == "c") { objDynamic = new List<C>(); } try { db.DiscoverParameters(dbCommand); dbCommand.Parameters["IN_TABLENAME"].Value = tableName; DataSet dsTableData = db.ExecuteDataSet(dbCommand); if (tableName.ToLower() == "a") { foreach (DataRow dataRow in dsTableData.Tables[0].Rows) { objDynamic.Add((A)dataRow); } } else if (tableName.ToLower() == "b") { foreach (DataRow dataRow in dsTableData.Tables[0].Rows) { objDynamic.Add((B)dataRow); } } else if (tableName.ToLower() == "c") { foreach (DataRow dataRow in dsTableData.Tables[0].Rows) { objDynamic.Add((C)dataRow); } } } catch (Exception ex) { throw; } return objDynamic; } @ Aspx try { using (DataServiceRef.DataServiceClient petService = new DataServiceRef.DataServiceClient()) { dynamic tableData = petService.GetReferenceTableData(tableName); //tableData is null ,exception } } catch (Exception ex) { throw; }
There is no exception at dal or service end when i debug list gets filled ok but when returns to aspx error at aspx(no exception gets caught at @ service) but exception at aspx i.e:
Message:The underlying connection was closed: The connection was closed unexpectedly. Stack Trace: at System.Net.HttpWebRequest.GetResponse() at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
I have a web application - .net 4. The client is having a requirement that he want to send email to his users on a regular basis about his new courses etc.
The webapplication created will hosted on a "Shared hosting environment" with no excess to windows services - file system other than the web root folder through FTP.
Due to shared hosting i cannot create a windows service for him which will check the database - if there are any scheduled mail to send every 5 min.
So my question is - Is there anyway i can run a wcf web service or any other web based service or page or handler which can keep running and automatically checks the database for any new scheduled mails - if yes start sending it automatically in an different thread.
We have two servers, both are containing a local application connecting to local web service, applications and services are identical on both servers. One of the servers work just fine, The other one is just dead, I have impression the the security configuration are different on those servers. What prevents an application X from connecting a web-service, given that another application y on the same server can connect to it. and X is a windows service. What I should check, what is chances?
I need to read the data from the COM port in a web application, so I have written a Windows Service for reading data from serial ports. Now I need to access that data in a web application. Can anyone tell me how to access it? Is using threads the best way to do this or not? What other possible ways are there?
I wanna embed the windows service in the web application. I have seen few posts in the web. where they generate separate exe for the windows service and use it as an installable.
The same process i tried doing it but it threw an OS error in my server which is windows 2000 and didnt supported the executable.
However the website of mine runs fine in the same server. Thus i was thinking if i cd embed the same code in the web application.
Also, in my case the website of mine takes job for simulation. These jobs are taken for simulation execution and nearly takes 12hrs for completion and if they are not completed within twelve hours then they are supplied extra twelve hours to complete the simulation jobs.
The simulation executables are a series of executable and bat files.
The results of the simulation gets updated in the tables of MySql and hence are displayed to the user.
I have built a web page that does a complex processing, and I realized recently that I need to convert it to a windows service running at the background and keeping the web page for monitoring and initiating the service.
The service will process some files, and provides information messages to the user.
I'm not sure how to implement the link between the windows service and the web site, but i was trying to avoid using MSMQ to connect both application together.
I have a web application that uses a SQL database which contains all the standard asp membership tables.Within my Web application I use the standard asp.net membersip logic for adding new users, roles, etc...The point here is I dont use any custom providers for anything.Now on that same machine that is hosting my web application I am writing a Windows service in c# .net.As part of one of the method calls to the windows service application I was curious if I would be able to use any type of membership classes that would connect to my existing database and perform the same functionality as does the ASP.NET membership classes.
I want to develop a windows service which will be accepting a datatable from an aspx page. Both the windows service and the website are hosted on same machine.
Also I need to set a date and time on which this service is to work. this date and time are to change according to customer needs. once again the date and time are to be fed from the aspx page.
I have an web application which needs some calculations and processing on data. This job is a long running job(few hours). Job is initiated by user.
Requirement.
User Clicks on Process Data. Some functions are called to start data processing. Data Processing runs for hours. User is given feedback of percentage completed etc. Even if user logs off and then again log on he should get this feedback.
The requirement is somewhat similar to Spiceworks. Where it runs in background to detect the devices/computers in network and the user is notified in his page about the progress. But spicework uses windows service. We don't want to us windows service.
Now the question is.
What if user closes the page, will the task still run in background. This task has to be completed fully.If terminated in between output will not have any meaning. How to actually to design this long running process. In ASP.Net environment. Also is there a way to show all/same user who logs in the status of processing.
I have application that runs non stop in the background on a dedicated remote server.The application is build in .NET 4 using log4net for logging and SQL Server.I i think it would be best to use Windows Service for the main background application.I want to build a second application to manage and view the status and logs of the main application.Any recommendation on the best way to do that?How should i connect to the service to get the status or attach to log4net logging?Windows Service + Asp.net Website?Windows Service + Remote WinForms Application?On Server WinForms Application?