Disclaimer: I'm pretty new to ASP.NET, so I'm figuring it out as I go along.
I'm trying to output the results of a function in my code behind page on the webpage itself.
Example:
Code Behind:
public string POSTResult(string e) { ... return TheResult; }
ASPX Page:
Output is: <%=POSTResult("argument")%>
However, loading the page errors, saying "The name 'POSTResult' does not exist in the current context."
I'm apparently doing something a bit off with how I'm getting to the code behind page from the ASPX page. My ASPX page has this at the top:
<%# Page Title="" Language="C#" MasterPageFile="~/master/default.Master" AutoEventWireup="true" CodeBehind="login.aspx.cs" Inherits="Bitfork.login" %>
The listed CodeBehind value is the name of the code behind page.
ETA:
Contents of my code behind (login.aspx.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
namespace Bitfork.master
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public string POSTResult(string e)
{
// variables to store parameter values
string url = "https://accounts.google.com/o/oauth2/token";
// creates the post data for the POST request
string postData = (e);
// create the POST request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = postData.Length;
// POST the data
using (StreamWriter requestWriter2 = new StreamWriter(webRequest.GetRequestStream()))
{
requestWriter2.Write(postData);
}
// This actually does the request and gets the response back
HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
string responseData = string.Empty;
using (StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()))
{
// dumps the HTML from the response into a string variable
responseData = responseReader.ReadToEnd();
}
return responseData;
}
}
}
Example of argument being passed, with API secret keys redacted:
code=[redacted]&client_id=[redacted]&client_secret=[redacted]&redirect_uri=http://localhost:60284/login.aspx&grant_type=authorization_code
ETA2:
I don't know if it's related, but it seems like my code behind page and my webpage are not communicating with each other at all. For instance, I can't access DIVs by ID in my code behind page to change their contents.
Related
I am trying to run the following HTTP POST API Call using ASP.NET on Visual studio 2013. I created a new web application project as mentioned here
using System;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CreateNewAPICall("test api abc");
}
private object CreateNewAPICall(string apiDesc)
{
object result = null;
var accessKey = "myaccesskey";
var secretKey = "mysecretkey";
var uRLapiList = "http://myurl.com";
byte[] bytes = Encoding.UTF8.GetBytes("apiListDesc=" + apiDesc);
var method = "POST";
var timeString = DateTime.UtcNow.GetDateTimeFormats()[104];
var signature = GetSignature(secretKey, method, timeString);
var authorization = accessKey + ":" + signature;
HttpWebRequest request = CreateWebRequest(uRLapiList, "POST", bytes.Length, timeString, authorization);
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
var responseReader = new StreamReader(request.GetResponse().GetResponseStream());
// Return List api Data
result = responseReader.ReadToEnd();
}
}
return result;
}
private HttpWebRequest CreateWebRequest(string endPoint, string method, Int32 contentLength, string timeString, string authorization)
{
// Some code here
}
private string GetSignature(string secretKey, string method, string timeString)
{
// Some code here
}
private byte[] HMAC_SHA1(string signKey, string signMessage)
{
// Some code here
}
private string CreateSignature(string stringIn, string scretKey)
{
// Some code here
}
}
Right now, I am confused as to where to put this file in the "Solution Explorer" in order to
run the file and get the output on my browser?
Right now I have this code inside "Models-->Class1.cs" directory as shown in the image below:
So, when I press F-5 key, I am getting directed to the home page of the ASP.NET with the URL http://localhost:4439/
Do I need to make any changes here?
I have to accesss an get some data from one of API.This API has only mentoned this method.No documentation showing how to acess and all.Data will be returned as Json.
This is the product API
1. GetAllProducts
POST
http://api.domain.com/api/Products/All
Content-Type: application/json; charset=utf-8
{"Token":"EncryptedToken"}
I have generated the Token and I tried to access it like this.But nothing is recieving.I found an example and tried to do like this.May be this is wrong.Can any one show me how to access and get the data.Please see my code below and thanks in advanced.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;
using System.Web.Script;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using System.Text;
public partial class Products : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
WebRequest request = WebRequest.Create("http://api.domain.com/api/Products/All?Token=U5Y1oPjI4DqwZgZkp-pVSmbIpP9XuXquKGYuREGwSNDX5OUhHAQVzI3exVOVzDD3|qlFREqiRHuKDG3gN5Zk05M5YjtWOhD8A11oxT7wolQ0gSLyKzXxNHgj94idAm4Wy6|CVnC2pguIbugAfqxSSJvf1KE_");
request.Method = "POST";
string postData = "Data to post here";
byte[] post = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = post.Length;
Stream reqdataStream = request.GetRequestStream();
reqdataStream.Write(post, 0, post.Length);
reqdataStream.Close();
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse response = null;
try
{
response = request.GetResponse();
}
catch (Exception ex)
{
Response.Write("Error Occured.");
}
}
}
I think you should change these things:
content type
request.ContentType = "application/json";
the post data
string postData = "{\"Token\":\"U5Y1oPjI4DqwZgZkp-pVSmbIpP9XuXquKGYuREGwSNDX5OUhHAQVzI3exVOVzDD3|qlFREqiRHuKDG3gN5Zk05M5YjtWOhD8A11oxT7wolQ0gSLyKzXxNHgj94idAm4Wy6|CVnC2pguIbugAfqxSSJvf1KE_\"}";
the URI
WebRequest request = WebRequest.Create("http://api.domain.com/api/Products/All");
I have a label within a <table> in a repeater. I have an HttpHandler named "NameShow.ashx" to return the "name" as "text/plain" by passing an "id" to the handler.
I want to retrieve the "name" (similar to retrieving "image" from handler).
Here is my code:
<asp:Label ID="Label1" runat="server" Text='<%#""NameShow.ashx?id="+Eval("id") %>'>
</asp:Label>
I am getting the text of this label as ->> NameShow.ashx?id=123
Please help in finding where I am doing mistake.
Here is my Haldler code.
using System;
using System.Web;
public class NameShow : IHttpHandler {
public void ProcessRequest (HttpContext context)
{
string strid = context.Request.QueryString["id"];
long pro_id = int.Parse(strid);
string name = DBHelpername.name(pro_id);
context.Response.ContentType = "text/plain";
context.Response.Write(name);
}
public bool IsReusable {
get {
return false;
}
}
}
Here is my DBHelper code:
using System;
using System.Data;
using System.Configuration;
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.Data.SqlClient;
/// <summary>
/// Summary description for DBHelpername
/// </summary>
public class DBHelpername
{
public DBHelpername()
{
//
// TODO: Add constructor logic here
//
}
public static string name(long id)
{
SqlConnection connect = new SqlConnection
("Data Source=DELL-36B3EF6E9F;Integrated Security=True;Initial Catalog=pool");
connect.Open();
SqlCommand sc =
new SqlCommand("SELECT name FROM Profile WHERE profile_id=" + id + "", connect);
SqlDataAdapter da = new SqlDataAdapter(sc);
DataSet ds = new DataSet();
da.Fill(ds);
string nameret = ds.Tables[0].Rows[0][0].ToString();
return nameret;
connect.Close();
}
}
If you are not married to the idea of using an HTTP Handler, then I suggest making a method in your .aspx page's code-behind that does the same logic your handler is doing minus the content-type stuff, like this:
protected string GetName(int pro_id)
{
return DBHelpername.name(pro_id);
}
Now in your markup you can use this method, like this:
<asp:Label ID="Label1" runat="server" Text='<%# GetName((int)Eval("id")) %>'>
</asp:Label>
<%# new System.Net.WebClient().DownloadString("http://www.yoursite.com/NameShow.ashx?id="+Eval("id"))) %>
Something like this may work, although you might need to re-think your approach as you are going do a http request for each item in your repeater - and that isn't going to scale well! It looks like this is all in one application/website, so can you not call the code that looks up the name in the codebehind of this page?
I am trying to use an <%# Eval("name") %> to be the title of my page. I can't seem to figure out any solutions online. I have tried the other StackOverflow question but that did now work either.
The page is a bio.aspx and on the site it is displayed as bio.aspx?id=123 so the page title needs to vary depending on the ID. I figured I could just use the Eval("name") but no luck yet.
I currently am using JavaScript:
window.onload = function() {
document.title = '<%# Eval("name") %> | Title Line';
}
This works, but it still leaves the title tags empty, and it's kind of spammy.
Here is the codebehind:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class DoctorBio : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Page.Title = "Your Page Title";
HtmlMeta metaDescription = new HtmlMeta();
metaDescription.Name = "description";
metaDescription.Content = "brief description";
Page.Header.Controls.Add(metaDescription);
HtmlMeta metaKeywords = new HtmlMeta();
metaKeywords.Name = "keywords";
metaKeywords.Content = "keywords, keywords";
Page.Header.Controls.Add(metaKeywords);
}
protected void SetPageTitle(object title)
{
this.Title = title.ToString();
}
protected string ReplaceLineBreaks(object text)
{
string newText = text as string;
if (newText == null) { return string.Empty; }
return newText.Replace("\r\n", "<br />");
}
}
Replace your following code
Previous code
this.Title = title.ToString();
Replace with
Page.Title = title.ToString();
Try this one. It is working for me...
I'm targeting a web service that takes a single string parameter.
On a schedule I want to fire off approximately 100 calls to that web service for 100 values from my database.
To optimise the process I believe I need to do the WebRequest calls asynchronously.
I've come across the code example below on a variety of blogs etc. but can't figure out how to adapt it for my requirement.
How can I wrap up the RegisterAsyncTask inside a foreach loop, parsing through the uri for the WebRequest.Create() that's inside BeginAsyncOperation?
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
public partial class AsyncPageTask : System.Web.UI.Page
{
private WebRequest _request;
protected void Page_Load(object sender, EventArgs e)
{
PageAsyncTask task = new PageAsyncTask(
new BeginEventHandler(BeginAsyncOperation),
new EndEventHandler(EndAsyncOperation),
new EndEventHandler(TimeoutAsyncOperation),
null
);
RegisterAsyncTask(task);
}
IAsyncResult BeginAsyncOperation(object sender, EventArgs e,
AsyncCallback cb, object state)
{
_request = WebRequest.Create("http://msdn.microsoft.com");
return _request.BeginGetResponse(cb, state);
}
void EndAsyncOperation(IAsyncResult ar)
{
string text;
using (WebResponse response = _request.EndGetResponse(ar))
{
using (StreamReader reader =
new StreamReader(response.GetResponseStream()))
{
text = reader.ReadToEnd();
}
}
Output.Text = text;
}
void TimeoutAsyncOperation(IAsyncResult ar)
{
Output.Text = "Data temporarily unavailable";
}
}
My intention is to write the response string back into a database. Appreciate this is an additional question but, is there any reason not to include the insert method call within the EndAsyncOperation method ?
This Q&A hints towards my main question but which 4th argument?
First you need to add this to your Web.config file (default is just 2):
<configuration>
<system.net>
<connectionManagement>
<add address="*" maxconnection="100" />
</connectionManagement>
<system.net>
<configuration>
Then you need to add async directive to your page: <%# Page Async="true" %>
protected void Page_Load(object sender, EventArgs e)
{
//...first get UriStringArray from db, and then:
foreach(string uri in UriStringArray)
{
var task = new PageAsyncTask(
new BeginEventHandler(BeginAsyncOperation),
new EndEventHandler(EndAsyncOperation),
new EndEventHandler(TimeoutAsyncOperation),
uri,
true; //run in parallel
);
RegisterAsyncTask(task);
}
}
IAsyncResult BeginAsyncOperation(object sender, EventArgs e, AsyncCallback cb, object state)
{
var request = (HttpWebRequest)WebRequest.Create((string)state);
return request.BeginGetResponse(cb, request);
}
void EndAsyncOperation(IAsyncResult ar)
{
string text;
var request = (HttpWebRequest)ar.State;
using(WebResponse response = request.EndGetResponse(ar))
{
using(StreamReader reader = new StreamReader(response.GetResponseStream()))
text = reader.ReadToEnd();
}
//yes, you can insert in db here, even as a new PageAsyncTask - but then must call ExecuteRegisteredAsyncTasks() manually...
}