Pick a random url from list and display as URL - asp.net

Im using Visual Studio 2012 and creating a web page using "ASP.NET Web Site (Razor v2)"
Im using Java to generate a random link;
<script>
var random = new Array();
random[0] = "example1.com";
random[1] = "pattern1.com";
random[2] = "specimen1.com";
</script>
<script>
function randomlink() {
window.location = random[Math.floor(Math.random() * random.length)];
}
</script>
A Random URL
When I click the A Random URL link it opens a random page from the list in the script above. I'ts all good, but because its a verry big list I need a way to do the same without having it in HTML because its slowing the loading of the page since its in the _SiteLayout.cshtml. Thanks.

Among your choices are the following options:
Send all the URLs to the client and have the client pick a random choice.
Have the server pre-pick the random URL and send only that one to the client (it can just be put directly into the <a> link. No need for javascript at all.
Make an ajax call to the server to request a random link and when that is returned, go to it.
Make a get request to the server and have the server return a redirect to a randomly chosen URL.
It sounds like you don't want to implement the first option if you have a zillion URLs.
The second option is probably the easiest as it requires only slightly modifying the generation of the page and requires no new server APIs. You just have to figure out how to select a random URL in your server-side environment.
The third and fourth options are the least efficient as they require a call to the server, a response from the server with the new URL and then a client redirect to the actual URL.

I would pass the random url with the page when it renders from the server. You can generate the url on the server using c#'s Random class.
A Random URL
Just pass a model that you reference in your view.

Related

Is it possible to return HTTP code 200, but give a "better" url without using 3xx?

Consider StackOverflow, where each question has a unique ID, but URLs are often overridden to include a stub in the URL. For readability and other reasons the stub helps users know they are at the right place.
I have a site that returns 200 when calling a URL like:
http://stackoverflow.com/questions/28057406/
But want the URL to update to:
http://stackoverflow.com/questions/28057406/is-it-possible-to-return-http-code-200-but-give-a-better-url-without-using-3x
The first call is technically valid and the code can retrieve the object and render it perfectly fine, but I'd like to update the URL to use the stubified one.
I'd prefer to do this without a redirect as just getting the ID causes a database call to get the object. Which would mean with a redirect the process would be:
Call http://stackoverflow.com/questions/28057406/
Retrieve item 25257999 from the database to get the name to make the stub
Redirect to http://stackoverflow.com/questions/28057406/is-it-possible-to-return-http-code-200-but-give-a-better-url-without-using-3x
New HTTP Call, so retrieve item 25257999 from the database to render the final page.
If possible I'd like to not use Javascript either.
So, is it possible to return Location as part of a HTTP header with a status code of 200 and the actual page, or am I stuck using 3xx calls or Javascript?
If you are just doing HTTP, you can either choose to redirect, or not choose to redirect... You can also (with Content-Location) tell the client that the canonical address is actually somewhere else... but no browser will respond to that.
To avoid the database-call, you could of course just cache the result.
If you are in a browser however, you can dynamically update the current address without forcing a refresh, with window.history.pushState.
For more information about that call, see this other SO answer:
Modify the URL without reloading the page

PDF creation tool that can handle Client-side view changes

I am trying to find a tool that can be used to create PDFs from websites. These websites all have Bootstrap based client side view settings, such as tabs, toggles, and paging. As such, there is no post-back to the server. I need to be able to create a pdf that is in the same state as the user sees it.
In my research, I have only been able to find tools that can create PDFs if given a URL, or if given a HTML string. Examples of these tools include ActivePDF's Webgrabber, and EVO PDF. However, they are not able to generate the PDF's with the client-specific settings, but instead only see the default selections of a given page. It is not possible for me to do a post-back to the server, so I am looking for a tool that can create PDFs on the fly, with the dynamic settings intact. I am working in ASP.NET, and so I would like a tool that is .NET friendly as well. Lastly, I would prefer the tool to not be open-sourced.
It sounds like a proper solution here would be to take data from your client side, post it via AJAX (not an ASP.NET postback!) and then process it on the server side to generate the PDF. Since you haven't given much detail, I'm going to assume we don't need to send over all the HTML, but rather values that were entered via a form.
<script>
function postDataToServer(){
var itemId = $("#ItemIdTB").val();
var quantityOrdered = $("#QuantityTB").val();
$.ajax({
url : "GeneratePdfFromForm?itemId="+itemId+"&quantityOrdered="+quantityOrdered
})
.done(function(){alert("Success!");})
.fail(function(){alert("Failure!");});
}
</script>
My answer is using jQuery, which is a JavaScript library that simplifies AJAX and DOM manipulation. However, this technique is doable with other JavaScript libraries (or even without a library).
On the server side, let's have an ASP.NET Web API function that can handle that AJAX Post.
[Route("GeneratePdfFromForm")]
public static void GeneratePdfFromForm(string itemId, int quantityOrdered)
{
Debug.WriteLine("Received itemId {0} and quantity {1}", itemId, quantityOrdered);
byte[] pdf = GeneratePDF(itemId, quantityOdered); //you'll need a function called GeneratePDF that can generate your PDF based on the parameters, probably using a library like iTextSharp.
//now do you want with the PDF byte array
}
So that's how you'd generate the PDF. You could return it from the GeneratePdfFromForm() function back to the client. But since that's potentially a long running task, you should probably implement it in the background using something like Hangfire, then when the PDF is ready you'd present it to the client for download (perhaps using SignalR or jQuery AJAX polling to alert the client of when the PDF is ready).
I was passing data from the client side to the server side via query string. You could instead create a class to represent the parameters for your PDF generation, then pass that form the client side to the server side via jQuery AJAX's data parameter.
If you really want to post the entire HTML from the client side to the server, you could so something like this:
var html=$("html").html();
$.ajax({
url: <your url here>,
data: html,
contentType: "text/html"
});
However, I'm willing to bet the actual HTML isn't what you care about for generating the PDF, but rather the selected values from some client side form. The actual HTML would include everything on the client side, including navigation menus, scripts etc. You could post a subset of the HTML using a different selector (ex: $("#OrderDiv").html()), which is a technique some people use to generate PDF's. But I think it's much cleaner to decouple your HTML intended for the browser from the way the PDF is generated, so that changes to your site don't mess up the PDF. You can then use the PDF creating library's capabilities to build the PDF rather than using HTML.

How to add parameters to SSRS URL in report viewer?

In reference to this article:
http://msdn.microsoft.com/en-us/library/ms252072(VS.80).aspx
I can access my SSRS report from my Web Application but the problem is it does not accept the parameters in the URL.
here is the format that it accepts
Report Server URL:
http://ABCD.com/reportserver
Report Path:
/Company works/Sales report/ABC
Can anyone help me?
I want to pass parameters in the SSRS url through report viewer.
You can not pass parameters via the URL since the control is expecting on the URL to the actual reportserver and nothing more.
Example:
serverReport.ReportServerUrl = new Uri("http://ABCS.com/reportserver");
serverReport.ReportPath = "/AdventureWorks Sample Reports/My Report";
You can pass these parameters in your code behind though by using the ReportViewer.ServerReport.SetParameters() function. Here is a snippet of code I used for this purpose:
var parametersCollection = new List<ReportParameter>();
//add generic parameters that every report needs
parametersCollection.Add(new ReportParameter("RandomizerString", new Random().Next().ToString(), false));
parametersCollection.Add(new ReportParameter("MachineName", Request.UserHostAddress.ToString(), false));
ERDashboard.ServerReport.SetParameters(parametersCollection);
can't seem to add a comment to Sam's answer so I'll post another:
The ReportViewerControl ReportServerURL property is a lot different than formatting a general URL to access a report. You could use the logic that sam has provided to navigate a web browser control to that URL which would also render the report within your web app. It's another to try if you want.
As a note there are various reasons that you may choose a webbrowser control vs a reportviewer control. The reportviewer control is a lot easier to manage in the code-behind, but there is a memory issue when refreshing a report for extended periods of time (lots of information through google about memory leaks). This is the scenario where I have instead used the webbrowser and manually formatted URLs to pass parameters instead.

Single Page Applications using ASP Web Forms

I need to implement single page applications using ASP Web Forms. I faced with a navigation problem. I need to use a navigation pattern like this:
http:// web site url / ... / page.aspx? {query string} # {ListId} / {ItemId}
When a user request a data from the server, the request on the server doesn't contain hash # (because this is a client-side feature). And it looks like this:
http:// web site url / ... / page.aspx? {query string}
So, actually I need two requests:
to get a page without hash and load javascript;
to handle hash data using javascript and async call required data from the server.
Is it possible to implement this logic with only one request?
Are there any best practices?
You can append ListId/ItemId to query string before sending request and read it regularly on a server.
var url = 'http://example.com?param1=10&param2=20#1000';
var beforeHash = url.split('#')[0];
var itemId= url.split('#')[1];
var processedUrl = beforeHash + '&itemId=' + itemId;
If your request is not already fired from JavaScript, you will have to hook into link's click event...
Or maybe you can get rid of # entirely and scroll content via JavaScript (my guess is that you use # because of local anchors to jump to different places in document)?
BTW There is window.location.hash property.
Update:
Based on your comment the flow is like this:
User types URL with #ItemId
Server returns the page
JavaScript reads #ItemId from window.location, puts it into QueryString and makes a request
Server returns the page based on modified QueryString
In this situation the two-requests pattern seems to be the only viable option. By design server does not get #Item part (called fragment). So there is no way to guess ItemId upon initial request. If after second (ajax) request, you refresh #ItemId dependant parts of the page through JavaScirpt, user experience will not be hindered much.

Help submitting an asp.net form with jquery

I'm trying to post the entire asp.net form to a certain url.
I have tried:
$.post("http://www.someaddress.com", $("form").serialize());
I have also tried:
$.ajax({
type:"POST",
url:"http://www.someaddress.com",
data: $('form').serialize(),
success: function(){
alert('yay');
}
});
In both cases the submit is fine but no data is passed along with it.
When i test the form.serialize() in firebug console, this shows my form serialized just fine. When i view the submit in fiddler, i can see that the data part is not set. Maybe im not understanding the data part, but every single tutorial shows this as the way to go -> serialize the form and set that as data. What must i do to get my serialized form as the data in my request?
What am i missing? Also - why does the NET tab in firebug show all these requests as method OPTIONS?
is this
url:"http://www.someaddress.com"
just an example or do you try to access a foreign domain? (which would explain the problem).
Based on your comment, the ajax same origin policy does not allow to access a foreign domain.
You cannot do a Ajax request to a foreign domain. As this is not allowed (against security) in javascript to access a foreign page ( not on your domain )

Resources