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

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

Related

Capture text from an Aspx page

I am trying to come up with a neat solution to create automated json schema markup on my aspx pages. The markup in question is FAQPage, but that's irrelevant.
I decided that I needed to scrape the content of the current page to find questions and answers. After a few false starts I came across the HtmlAgilityPack plugin which enables me to achieve what I want, but I've come across some issues.
The HtmlAgililtyPack parser can be initiated in a number of ways, but the only one I could get to work for me and my scenario (scrape current page) was to feed in a string.
First, I created an asp ID with a runat="server" tag.
To get the string, I used HTMLTextWriter; here's the code:
static string ConvertControlToString(Control ctl)
{
string s = null;
var sw = new StringWriter();
using (var w = new HtmlTextWriter(sw))
{
ctl.RenderControl(w);
s = sw.ToString();
}
return s;
}
Now, all that works fine - in most cases.
However, I'm running into edge cases where I use scriptmanager and updatepanels. I suspect there will be more. The error is: ... must be inside a form control with a runat="server". Of course it is but the rendercontrol doesn't realise it.
So, two questions:
Is there a way to feed HtmlAgilityPack parser in another way that doesn't
require a string (and that won't loop)?
Is there a better way to scrape the text other than Control.RenderControl() that won't cause errors?
Incidentally, I've found a solution to the problem I'm having but it involves manipulating each affected page, and that's not great.
So, thought I'd throw it out there and see if there are better workarounds or a better solution.
You can load HTML in a few different ways but ultimately HTML is a string so this is what the parser will operate on. I'm not sure what you mean about looping.
Rather than rendering controls as HTML and then parsing them it might be better to let the entire page load and parse it after it has rendered, this allows your javascript/updatepanels to finish transforming the page before you parse the HTML.
The LoadFromBrowser method (I believe) loads the specified url in a headless browser, allows any javascript to run and then parses the resulting HTML: https://html-agility-pack.net/from-browser
If you need to attach authentication credentials there is a question addressing that here: HtmlAgilityPack and Authentication
Alternatively (keeping your existing code) you might try instantiating a new HtmlControl with the tag "form", adding the the control passed in to ConvertControlToString to it and then parsing that which may avoid your error. You may need to check the control doesn't already have a form tag, this approach doesn't address javascript/update panels and I'm not 100% sure it would work.
HtmlGenericControl form = new HtmlGenericControl("form");
Control ctl = new Control();
form.Controls.Add(ctl);
string s = string.Empty;
var sw = new System.IO.StringWriter();
using (var w = new HtmlTextWriter(sw))
{
form.RenderControl(w);
s = sw.ToString();
}

without page load how to get response using 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
}

Programmatically Rendering an Umbraco Node

I'm using Umbraco 4.5.2 and I have a node with a number of child nodes. Each child node represents a fragment of HTML that will be rendered in a control. The control loops over all the child nodes and renders them.
For the moment I have a bit of a dirty hack going in order to get the thing going (still fairly new to Umbraco) but I'd rather do this better.
The code I have at the moment looks like this:
private string GetItemHtml(Node node)
{
// Work out the URL of the HTML fragment
string url = "http://" + Context.Request.Url.Host +
":" + Context.Request.Url.Port +
node.Url;
// Get the fragment by making a call to the page
WebRequest req = WebRequest.Create(url);
WebResponse res = req.GetResponse();
using (Stream stream = res.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
string result = reader.ReadToEnd();
return result;
}
}
As you can see, it is really rather ugly. I'm hoping there is some way to get this without having to make many HTTP calls, even if it is looping back to the same server - it can't be very efficient.
You can use the API to achieve what you are asking, try looking at the umbraco.library.RenderTemplate method. It accepts two parameters, the first is the id of the node to render and the second is the id of the template to use when rendering the node.
This is probably much easier to build using xslt in umbraco. If you want to do something that is not possible in xslt, you can create a XSLT extension function (implemented in C#, called from XSLT) to do that (see http://en.wikibooks.org/wiki/Umbraco/Create_xslt_exstension_like_umbraco.Library_in_C for more info).
For a sample XSLT that list child pages, see BlogListPosts.xslt in the umbraco blog package:
http://blog4umbraco.codeplex.com/SourceControl/changeset/view/54177#916032

Make an ASP.NET Web service output an RSS Feed

I have been writing some Web services to be used by a few different client apps and i was trying to write a web service method that simply outputs an RSS XML Feed.
I can create the XML using an XmlTextWriter Object
Then i have tryed outputing to the Response (like i have done in the past when its an aspx page) but this only works it the return type is void (and still doesnt seem to output properly)
Then i tryed making the return type a string and using a StringWriter to output the xml from the XmlTextWriter but the output is then wrapped in a tag.
How can i do this?
Obviously create the interfaces and rest of the WCF service as normal.
Mark the class with the following attribute
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
And then this function
public Stream GetRSS()
{
string output;
//output = some_text;
MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(output));
WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
return ms;
}
I have some code for this, but it's more than will fit well in an SO post (about 1000 lines). It's really not that hard; the schema is simple enough you can do it yourself, but you don't have to: there are several components you can just plug in to create the xml for you.
You should see this question:
ASP.Net RSS feed
If you must use ASMX, then you can return an XmlDocument. Build the feed XML however you like, but then return the XmlDocument from your web method.

ASP.NET Localized web site -- updating on the fly

I think I have a solution to this, but is there a better way, or is this going to break on me?
I am constructing a localized web site using global/local resx files. It is a requirement that non-technical users can edit the strings and add new languages through the web app.
This seems easy enough -- I have a form to display strings and the changes are saved with code like this snippet:
string filename = MapPath("App_GlobalResources/strings.hu.resx");
XmlDocument xDoc = new XmlDocument();
XmlNode xNode;
xDoc.Load(filename);
xNode = xDoc.SelectSingleNode("//root/data[#name='PageTitle']/value");
xNode.InnerText = txtNewTitle.Text;
xDoc.Save(filename);
Is this going to cause problems on a busy site? If it causes a momentary delay for recompilation, that's no big deal. And realistically, this form won't see constant, heavy use. What does the community think?
I've used a similar method before for a very basic "CMS". The site wasn't massively used but it didn't cause me any problems.
I don't think changing a resx will cause a recycle.
We did something similar, but used a database to store the user modified values. We then provided a fallback mechanism to serve the overridden value of a localized key.
That said, I think your method should work fine.
Have you considered creating a Resource object? You would need to wrap your settings into a single object that all the client code would use. Something like:
public class GuiResources
{
public string PageTitle
{
get return _pageTitle;
}
// Fired once when the class is first created.
void LoadConfiguration()
{
// Load settings from config section
_pageTitle = // Value from config
}
}
You could make it a singleton or a provider, that way the object is loaded only one time. Also you could make it smart to look at the current thread to get the culture info so you know what language to return.
Then in your web.config file you can create a custom section and set restartOnExternalChanges="true". That way, your app will get the changed when they are made.

Resources