without page load how to get response using asp.net - asp.net

I need a coding to get response from my desktop application to my web page using asp.net
I send a request from my recharge.aspx page to desktop application.
http://122.172.208.202/MARSrequest/?operator=RA&number=9900122334&amount=100&reqref=A0000001
so my desktop application get the request and perform the task and send the response to other page that is responseparser.aspx
the response like
http://www.abc.com/responseparser.aspx?ref=10293&number=9894380156&amount=100&status=SUCCESS&transid=547965399 &simbal=1000
so how to get response with out loading the responseparser page it is possible or any other idea to get the response.
my doubt is without loading a page can able to perform some operation like insert a record or create text file using asp.net

You appear to have asked this question several times in several different ways. This is not an acceptable way of using StackOverflow. If your original question is not getting the answer(s) your looking for, please consider editing and revising your question. Please consider commenting on your questions and taking the advice of other commenters.
To answer your question. I think you're looking to execute some sort of Web Service instead of loading a page. Does this sound right?
If so, I'd suggest either using one of the following
a generic HttpHandler (more info in this forum post)
a WCF application that can manage your service layer.
an MVC Application that manages the requests (this is my personal favorite - I build these completely without Views and simply return JSON for all of my {success: true/false}.)
In short, the quickest way I can think of to do this would be to use the FIRST option (HttpHandler) and change your request to the following
http://localhost/responsepage.ashx?number=9894380156&amount=10&status=success
Notice the ashx extension on the response page. It's no longer a web page but a web handler... you'll want to do some research in order to get a handle on it.

Not sure if this if this works same for desktop applications but maybe it works with
protected void YourThing()
{
Refresh();
}
protected void Refresh()
{
Response.redirect(Request.Rawurl);
}

not sure but try
for(!Page.IsPostback)
{
do stuf here
}

You can use WebService or HttpHandler.
I would prefer WebService (parser.asmx):
namespace Test.Service
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class WebService1 : WebService
{
[WebMethod]
public void Parse(string #ref, long number, double amount, string status, int transid, int simbal)
{
// some code
}
}
}
POST-request example:
POST /{path}/Parser.asmx/Parse HTTP/1.1
Host: ***
Content-Type: application/x-www-form-urlencoded
Content-Length: ***
ref=string&number=string&amount=string&status=string&transid=string&simbal=string

I think you can easily port your ASP code using the SqlClient classes.
Most suitable variant for you is SqlCommand with ExecuteNonQuery method:
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}

In that case, I usually put whatever appropriate ADO.NET code into page_load but since you want to do it before page loading, why don't you use "page_init"? For example, put following code into code-behind
protected void Page_Init(object sender, EventArgs e)
{
//your code is here
}

Related

Request param missing on POST

I am re-writing an ASP.NET application and noticed a difference in behaviour ...
In my Page_Load event I have some code such as:
string id = Request["id"]
which gets the id param from the URL. On page load (ie a HTTP GET), this works as expected in both versions. I also have a button onclick event handler. Clearly, this performs a POST to the server, and also invokes the Page_Load handler. The difference is, that in the original version of the app, the id is successfully loaded from the request. In the new version of the app, id comes back as null. I have discovered that I need to use Request.Params["id"] instead, but am totally puzzled as to why Request["id"] works for POST requests in one app but not the other.
The only difference between the apps is that the first was created as File -> New Website and the second File -> New Web Application. I think this is what is causing the difference in behaviour, but am wondering why this subtle difference, and also if there is anything else I should be aware of between the 2.
Any advice greatly appreciated.
As you have mentioned, you have the id parameter coming through twice. This will be because you have one in the query string parameters and one in the form parameters. I'm not sure why this would be occurring in one web app and not the other, but you can make changes to your code to account for it in a more correct way.
If you view the source of the HTML in your browser, you will see that the action value for the form will be current pages URL, including the query string. This is why the first id is being sent through. Evidently, the second id is coming through via the form itself:
HTML Source of basic web form
<form method="post" action="Default.aspx?id=3" id="ctl01">
<input type="text" name="id">
</div>
There are a couple of things you can do here:
first off, I wouldn't use Request.Params["id"] for this, as it combines the query string, form, cookies and server variables into one collection. You should use Request.Querystring and Request.Form properties, based on what you require and when
In your Page_Load handler, use the Page.IsPostBack property to determine whether the page is loading for a GET or POST and use the Request properties described above.
Example of Page.IsPostBack usage:
protected void Page_Load(object sender, EventArgs e)
{
string id = string.Empty;
if (Page.IsPostBack)
{
id = Request.Form["id"];
}
else
{
id = Request.QueryString["id"];
}
}
I always use web applications project but the difference is compilation. Website has a dynamic compilation, which means that the first request will be slower and web app has pre-compiled release dlls.
Check this for pro's and con's : http://maordavid.blogspot.ca/2007/06/aspnet-20-web-site-vs-web-application.html

service unavailable message

There is a web site, and when user exceed 1000, there is an error which is called
Service unavailable
And I want to show a text, when the system gives "service unavailable" error. How can I do it?
(app_offline.htm can be used but I want to automize it)
In case you're dealing with ASP.NET, you can create your own html page with your custom text, then configure the web.config file, more specifically the customErrors tag, to show that file when a 503 Http code is sent to the client (that is again, assuming that IIS is sending the 503 code to the browser).
Hope that helps.
Cheers.
There may be sevaral possible reasons this problem,
Simultaneous connection may reached the time limit
Your app pool may not starting properly
There is an interesting article about One more reason problem that causes the 'Service Unavailable' error from IIS, which might give you a better understand.
As you state that you're using ASP.NET you should look at trapping errors using the Page_Error event handler.
As this tends to be repeated code both in one project and many other projects, I use a base class that inherits from System.Web.UI.Page and fill in the handler there.
For example all pages based on MyBasePage
protected void Page_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
this.ErrorRedirect(ex, false);
}
/// <summary>
/// Redirects to a custom error page
/// </summary>
/// <param name="ex">the caught exception</param>
/// <param name="errorCaught">true if the error is handled within a try catch block, false otherwise</param>
protected void ErrorRedirect(Exception ex, bool errorCaught)
{
/* some logging code here for use by support team */
if (ex.GetType().FullName == "BusinessObjects.BrokenRulesException" )
{
Response.Redirect("ContactHelpdesk.aspx");
}
if (errorCaught)
{
Response.Redirect("ContactHelpdesk.aspx");
}
else
{
Response.Redirect("Error.aspx");
}
}
In this code "BusinessObjects.BrokenRulesException" are thrown when my there are issues with user entered Model data that doesn't match specified rules e.g. postcodes, passwords etc. in which case a user help page pops up.
In your case you'd be looking at errors to maybe pop up the Error page.

How do I get the parameter values from in a web service

I have a web service (an ASP.NET .asmx page), and for debugging purposes I need to log all calls to the webservice, including values of all parameters passed into each call. So basically the first thing each WebMethod should do is log it's state with details of all the parameter values passed in to it.
So far so good. The complication is that I also want an automated way of getting the parameter values - there's quite a few webmethods with different signatures, and some of them have up to ~30 parameters, so manually coding against each specific parameter would likely be massively error-prone. I'd rather be able to call a method that looks at the current Http context and automatically uses that to grab and parse whatever has been passed in by the client.
But I hit a snag. When I look at HttpContext.Current.Request, it turns out that both the Form and QueryString collections are empty. So if the arguments passed to the webmethod aren't in either of those collections, where would they be? Anyone know how I can retrieve them?
You can use AOP techniques for this task. Considering PostSharp, you can create custom aspect like this:
[Serializable]
public class TraceAttribute : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionArgs args)
{
Trace.WriteLine(string.Format("Entering {0}", args.Method.Name));
for (int i = 0; i < args.Arguments.Count; i++)
{
Trace.WriteLine(string.Format(" {0}", args.Arguments.GetArgument(i)));
}
}
}
and then apply it to your web-service methods:
[WebMethod, Trace]
public string HelloWorld()
{
return "Hello World";
}
You could use SOAP extensions and follow the example in this post to log the request which would have the method name and parameters.
SOAP Extentions is a better choice. Here is another example to retreive SOAP request and SOAP response as XML. All you do is parse the XML to retreive parameter name value pairs.

How to pass data between pages without sessions in ASP.net MVC

I have one application in which I want to pass data between Pages (Views) without sessions. Actually I want to apply some settings to all the pages using query string.
For example if my link is like "http://example.com?data=test1", then I want to append this query string to all the link there after and if there is no query string then normal flow.
I was thinking if there is any way that if we get the query string in any link for the web application then some application level user specific property can be set which can be used for subsequent pages.
Thanks,
Ashwani
You can get the query string using the
Request.Url.Query
and on your links to the other page you can send it.
Here is an idea of how you can find and change your page:
public abstract class BasePage : System.Web.UI.Page
{
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
// now you render the page on this buffer
base.Render(htmlWriter);
// get the buffer on a string
string html = stringWriter.ToString();
// manipulate your string html, and search all your links (hope full find only the links)
// this is a simple example of replace, THAT PROBABLY not work and need fix
html = html.Replace(".aspx", ".aspx?" + Request.Url.Query);
writer.Write(html);
}
}
I do not suggest it how ever, and I think that you must find some other way to avoid to manipulate all your links...
I don't undestand what kind of data are you trying to pass. Because it sounds weird to me the idea of trapping all links.
Anyway, I believe you may find the class TempData usefull for passing data between redirects.
And a final warning, be carefull about TempData, it has changed a little between MVC 1 and 2:
ASPNET MVC2: TempData Now Persists

Entity Framework ObjectContext re-usage

I'm learning EF now and have a question regarding the ObjectContext:
Should I create instance of ObjectContext for every query (function) when I access the database?
Or it's better to create it once (singleton) and reuse it?
Before EF I was using enterprise library data access block and created instance of dataacess for DataAccess function...
I think the most common way is to use it per request. Create it at the beginning, do what you need (most of the time these are operation that require common ObjectContext), dispose at the end. Most of DI frameworks support this scenario, but you can also use HttpModule to create context and place it in HttpContext.Current.Items. That is simple example:
public class MyEntitiesHttpModule : IHttpModule
{
public void Init(HttpApplication application)
{
application.BeginRequest += ApplicationBeginRequest;
application.EndRequest += ApplicationEndRequest;
}
private void ApplicationEndRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Items[#"MyEntities"] != null)
((MyEntities)HttpContext.Current.Items[#"MyEntities"]).Dispose();
}
private static void ApplicationBeginRequest(Object source, EventArgs e)
{
var context = new MyEntities();
HttpContext.Current.Items[#"MyEntities"] = context;
}
}
Definitely for every query. It's a lightweight object so there's not much cost incurred creating one each time you need it.
Besides, the longer you keep an ObjectContext alive, the more cached objects it will contain as you run queries against it. This may cause memory problems. Therefore, having the ObjectContext as a singleton is a particularly bad idea. As your application is being used you load more and more entities in the singleton ObjectContext until finally you have the entire database in memory (unless you detach entities when you no longer need them).
And then there's a maintainability issue. One day you try to track down a bug but can't figure out where the data was loaded that caused it.
Don't use a singleton.. everyone using your app will share that and all sorts of crazy things will happen when that object context is tracking entities.
I would add it as a private member
Like Luke says this question has been asked numerous times on SO.
For a web application, per request cycle seems to work best. Singleton is definitely a bad idea.
Per request works well because one web page has a User, maybe some Projects belonging to that user, maybe some Messages for that user. You want the same ObjectContext so you can go User.Messages to get them, maybe mark some messages as read, maybe add a Project and then either commit or abandon the whole object graph at the completion of the page cycle.
Late post here by 7 months. I am currently tackling this question in my app and I'm leaning towards the #LukLed solution by creating a singleton ObjectContext for the duration of my HttpRequest. For my architecture, I have several controls that go into building a page and these controls all have their own data concerns that pull read-only data from the EF layer. It seems wasteful for them to each create and use their own ObjectContext's. Besides, there are a few situations where one control may pull data into the Context that could be reused by other controls. For instance, in my masterpage, my header at the top of the page has user information that can be reused by the other controls on the page.
My only worry is that I may pull entities into the context that will affect the queries of other controls. I haven't seen that yet but don't know if I'm asking for trouble. I guess we'll see!
public class DBModel {
private const string _PREFIX = "ObjectContext";
// DBModel.GetInstance<EntityObject>();
public static ObjectContext GetInstance<T>() {
var key = CreateKey<T>();
HttpContext.Current.Items[key] = HttpContext.Current.Items[key] ?? Activator.CreateInstance<T>();
return HttpContext.Current.Items[key] as ObjectContext;
}
private static string CreateKey<T>() {
return string.Format("{0}_{1}", _PREFIX, typeof(T).Name);
}
}

Resources