Call another aspx page in a different application - c#

I have 2 different system, lets say SystemA and SystemB.
In SystemB, there is page, say calculate.aspx, where it receive certain parameter and will perform some calculation. This page doesn't display and info, and only serves to execute the code behind.
Now i have a page in SystemA, lets say execute.aspx, that will need to call calculate.aspx in SystemB to run the desired calculation. I cannot use redirect, since that will redirect me to the calculation.aspx page on SystemB.
I had tried using HttpWebRequest but it doesn't call to the page. The code is as below:
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create(nUrl + '?' + fn);
myRequest.Method = "GET";
WebResponse response = myRequest.GetResponse();
Does anyone know what is the correct way of doing it? Thanks.
EDIT
Manage to get it done after changing my codes to above. Thank you all.

You can either use a web service which would be the preferred way or use AJAX to send data to the page and get result in response.

I am probably missing something obvious here, but I'm puzzled by the whole part about the data and content which I'm not used to see in a GET Request.
You should, at your choice :
convert your request to POST
remove the part concerning the data

try this
namespace SampleService // this is service
{
public class Service1 : IService1
{
public string GetMessage()
{
return "Hello World";
}
public string GetAddress()
{
return "123 New Street, New York, NY 12345";
}
}
}
protected void Page_Load(object sender, EventArgs e) // calling the service
{
using (ServiceClient<IService1> ServiceClient =
new ServiceClient<IService1>("BasicHttpBinding_IService1"))
{
this.Label1.Text = ServiceClient.Proxy.GetMessage();
//once you have done the build inteli sense
//will automatically gets the new function
this.Label2.Text = ServiceClient.Proxy.GetAddress();
}
}
refer this link
http://www.codeproject.com/Articles/412363/How-to-Use-a-WCF-Service-without-Adding-a-Service

You can create a WebMethod in your application then you call this WebMethod from any other application, you can return Json serializable or XML data from this WebMethod

Related

Creating an embedded image button in ASP.net?

I need to create a button in ASP.net that I can embed into another web page.
Essentially the button will query a DB server side on page load and then change it's image depending on the return of the query.
Does anyone know the best approach for this? I am not a pro at ASP.net as you can tell. Written in C# preferably.
In this case I would suggest using a IHttpHandler instead of a generic WebForm. https://msdn.microsoft.com/en-us/library/system.web.ihttphandler(v=vs.110).aspx
The handler is more suitable for this request as it will be able to respond quickly and is purpose built for handling specific requests that are not necessarily HTML based. This can be quite simple to wire up to accept a request, query the database and generate an image that you choose. Now you haven't provided much information about where the image comes from but lets look at a simple request.
To begin in a webforms web application select a new GenericHandler which we will name DynamicImage.ashx. Which will build our initial template as below.
public class DynamicImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable
{
get
{
return false;
}
}
}
This template provides the basics to handle our request. When the request arrives the WebServer will execute the ProcessRequest() method passing in the HttpContext as a parameter. From here we can use this to deliver our response.
For argument sakes lets say we are querying the image based on the QueryString parameter username which represents a user in our database. I have included some basic code on your steps to achieve this. (Code commented)
public void ProcessRequest(HttpContext context)
{
//get our username from the query string
var username = context.Request.QueryString["username"];
//clear the response and set the content type headers
context.Response.Clear();
context.Response.ContentType = "image/png";
//if the username is empty then end the response with a 401 not found status code
if (string.IsNullOrWhiteSpace(username))
{
context.Response.StatusCode = 401;
context.Response.End();
return;
}
//do a db query to validate the user. If not valid do a 401 not found
bool isValidUser = new UserManager().IsValidUser(username);
if (!isValidUser)
{
context.Response.StatusCode = 401;
context.Response.End();
return;
}
//get the user image file path from a server directory. If not found end with 401 not found
string filePath = context.Server.MapPath(string.Format("~/App_Data/userimages/{0}.png", username));
if (!System.IO.File.Exists(filePath))
{
context.Response.StatusCode = 401;
context.Response.End();
return;
}
//finish the response by transmitting the file
context.Response.StatusCode = 200;
context.Response.TransmitFile(filePath);
context.Response.Flush();
context.Response.End();
}
To call this handler you can simply set the src of the image to a path similar to /DynamicImage.ashx?username=johndoe.
Now your requirement may be slightly different. For example you may be retrieving the image from the database as a byte[] therefore instead of using the context.Response.TransmitFile() method you may wish to use the context.Response.BinaryWrite() method. This method transmits a byte[] as the response stream.
Finally I would refer you to another post (of mine) that talks about caching these images from a client perspective. This is very helpful if your button will be generated quite frequently. Leverage browser caching in IIS (google pagespeed issue)
It can be something as simple as
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/arrow-down.gif" OnClick="ImageButton1_Click" />
and code behind:
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
// do some DB processing here
ImageButton1.ImageUrl = "~/arrow-up.gif";
}
If I understand what you are asking.
To put it under the page load would look something like:
private void Page_Load()
{
if(!Page.IsPostBack)
{
// perform db processing here
ImageButton.ImageUrl = "~/arrow-up.gif";
}
}
is all that is needed. Setting the ImageUrl line can be put wherever you need it.

Is this a safe way to get body of a HttpContext request

public static class HttpRequestHelper
{
public static string RequestBody()
{
var bodyStream = new StreamReader(HttpContext.Current.Request.InputStream);
bodyStream.BaseStream.Seek(0, SeekOrigin.Begin);
var bodyText = bodyStream.ReadToEnd();
return bodyText;
}
}
I plan to call this from ActionFilters to log incoming requests. Of course there could be multiple simultaneous requests.
Is this approach ok?
Is your question from the perspective of concurrency or ASP.NET Web API in general? Every request has its own context and you are okay with multiple requests going on in parallel. But here are two things for you to look at.
(1) Since you are using HttpContext, you are locking yourself to web hosting (IIS), which in many cases should be okay. But I would like you to be aware of this.
(2) Your code HttpRequestHelper.RequestBody() will work when called from an action filter, as you mentioned. However, if you try to call this from other places, say a message handler, this will not work. When I say this will not work, parameter binding that binds request body to action method parameter will not work. You will need to seek to the beginning once you are done. The reason it works from action filter is that binding would have already happened by the time action filter runs in the pipeline. This is another thing you might need to be aware of.
I've needed use InputStream of Http Request. I have a WebApp and IOS App that navigates to a aspx page, if the url request contains some parameters i read the information in database and if i not find any parameters in url request i read the request body and i work fine !
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (string.IsNullOrEmpty(Request.QueryString["AdHoc"]) == false)
{
string v_AdHocParam = Request.QueryString["AdHoc"];
string [] v_ListParam = v_AdHocParam.Split(new char[] {','});
if (v_ListParam.Length < 2)
{
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(WS_DemandeIntervention));
WS_DemandeIntervention response = (WS_DemandeIntervention)jsonSerializer.ReadObject(Request.InputStream);
....
}
if (string.IsNullOrEmpty(Request.QueryString["IdBonDeCommande"])==false)
{
....

Getting URL of next page

Is it possible to get the URL of the next page when leaving the current page in C#?
On my current page I would like to capture the url of the next page before the next page loads. I'm not sure where to start for this...or in which method on my page I would place this logic (such as page_load, buttonClick etc.)
I don't think that it's possible to "capture the url of the next page", but you can get the current request as soon as possible. Use Global.asax therefore:
public class Global : System.Web.HttpApplication
{
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext context = base.Context;
HttpResponse response = context.Response;
HttpRequest request = context.Request;
var url = request.RawUrl;
// and many other properties ...
}
}
Assuming you're doing paging through query strings and your current page is:
url.com/default.aspx?page=1
Then getting the next page URL would just be incrementing the page query string, so:
if (!String.IsNullOrempty(Request.QueryString["page"]) {
int nextPageNumber = int.Parse(Request.QueryString["page"] + 1;
string nextPageUrl = String.Format("url.com/default.aspx?page={0}, nextPageNumber);
}
Ideally you would use UriBuilder to reconstruct the domain and not hard code it as I have in the String.Format method. I did this just for brevity.
CodeProject has a project for saving change on close or exiting page which might be helpful to you.

How use javascript as the argument in asp.net <%= %> script

The path is javascript path
var fileName = args.get_fileName();
lstImg.src = <%=GetListImageFilePath(fileName) %>
file name is error because it is javascript and not in .NET
how to put this argument in .NET Code
You'll need to use AJAX. One easy way to do it would be to use PageMethods. First, add a [WebMethod] attribute to your method:
[WebMethod]
protected static string GetListImageFilePath(string fileName)
{
This method must be static.
Then set EnablePageMethods="True" on your script manager. Then you can call your c# code from JavaScript like this:
var fileName = args.get_fileName();
PageMethods.GetListImageFilePath(fileName, function (path) {
lstImg.src = path;
});
You can't. The JavaScript runs on the client, and the asp.net code is on the server. You need to use some other way of communicating with the server eg: Ajax to a web service, a postback, etc
You simply can not do it because javascript is running at client side i.e on browser where as server code run at server. What you could do is change the your GetListImageFilePath function so that it returns the base URL for your image directory and then append the file name to create the image path.
var fileName = args.get_fileName();
lstImg.src = <%=GetListImageFilePath() %> + '/' + fileName;
For more information, like how server tags in Javascript are processed, I have answered a StackOverFlow thread here. Please have a look to clarify your doubt.
I think get_fileName() is server side function. So you can call it from the HTML directly.
Check these links
http://weblogs.asp.net/jalpeshpvadgama/archive/2012/01/07/asp-net-page-methods-with-parameters.aspx
http://stackoverflow.com/questions/7633557/asp-net-is-it-possible-to-call-methods-within-server-tag-using-eval
If you call the javascript function using RegisterStartupScript() or
RegisterClientScriptBlock() then these will be called in client side not in server side.
If you want to call the javascript function immediately in server side then declare an equivalent server side function.
add an ashx(http handler) in your website, then you can use lstImg.src = '/example.ashx?name=' + fileName.
public class ExampleHandler: IHttpHandler {
public void ProcessRequest (HttpContext context) {
var request = context.Request;
string fileName = (string)request.QueryString["name"];
// your logic
context.Response.Write(yourpath)
}
public bool IsReusable {
get {
return false;
}
}
}

How to make REST based WCF service Service file be index?

I have a service file, Service.svc that provides a Web Service. I would like the help page to be the main url (e.g. / instead of /Service.svc/help). Is this possible and can someone tell me how do do it?
Just redirect to help page. For example:
[WebInvoke(UriTemplate = "", Method = "GET")]
public void RedirectToHelp()
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Redirect;
WebOperationContext.Current.OutgoingResponse.Location = "help";
}

Categories

Resources