We are showing reports in our Azure web application using ReportViewer (rdlc) control in VS2010 which is working perfectly. Recently my client asked me to capture the the Print event for ReportViewer and log an entry on the server. I've hooked the with the print button.. This works perfectly when I run the web application on a local environment. However, on Azure, the Ajax method never gets called from client side. Please suggest what to do? Is there a limitation for Ajax in Azure Environment?
I'm registering the Page on Page_Load in code behind
protected void Page_Load(object sender, EventArgs e)
{
Ajax.Utility.RegisterTypeForAjax(typeof(Pages.Report));
ImageButton btnPrint = new ImageButton();
btnPrint = ((ImageButton)(this.FindControl("ctl00$" + ReportViewer1.ClientID.Replace("_","$") + "$ctl06$ctl06$ctl00$ctl00$ctl00")));
btnPrint.Attributes["onclick"] += "attachEventForPrint();";
}
[AjaxMethod(Ajax.HttpSessionStateRequirement.ReadWrite)]
public static void LogEvent(int pLoggingEvent)
{
// Addded logic to log event
}
And in ASPX file following function was added in JS
function attachEventForPrint() {
if (typeof (Report) != "undefined") {
Report.LogEvent(4);
}
}
The good news is that I don't think there's any limitation with using ajax controls - I've used a few and they just worked.
Some things to check might be:
can you use Fiddler to view the HTTP trace - is a request being sent to the server when you click on the the print button?
can you use a javascript debugger to check that there are no errors being reported when attachEventForPrint occurs?
are there any issues here with "State" - especially with Session storage?
One other thing to check is whether there is a more maintainable way to access the print button - the "$ctl06$ctl06$ctl00$ctl00$ctl00" just looks like it is asking for trouble either now or at some point in the future
Related
I have a asp.net webform page who uses 2 google charts, I'm using Jquery Ajax to retrieve information from database to populate the charts, the query to retrieve the chart data takes a long time, in this time user can make a click in a link to redirect to another page, the redirect is very slow because wait querys return from database to do the redirect, how can I avoid this behavior?
I'm using Jquery Datatable plugin, when user click one row an javascript event is called
function redirectToCampaignCreator(campaignID) {
try {
$.xhrPool.abortAll();
redirecting = true;
$('#multiCampID').val(campaignID);
//window.location.href = "campaigncreator.aspx?Edit=True&CampaignId=" + campaignID;
DoPartialPostBack("<%=btnCampaignEdit.UniqueID%>");
} catch (e) {
}
}
In this function I cancel the Ajax calls and do a __doPostBack(control, ""); to ejecute some code to save session values and then redirect
protected void Page_PreInit(object sender, Even`enter code here`tArgs e)
{
if (IsPostBack)
{
if (Request.Form["multiCampID"] != null)
{
View();
Context.Response.Redirect("CampaignCreator.aspx?Edit=True", true);
}
}
}
The redirect is slow because it's waiting querys return from DB
Can you make your link client side instead of linking via redirect in the code behind?
Link to other page
I am not sure how you are using the code structure to manage such kind of tasks but if you want that your responsiveness to be free you can use async your c# functions.
https://msdn.microsoft.com/en-us/library/hh191443.aspx
How can I inject a JavaScript code from asp.net page into html page in another domain e.g http://www.codeproject.com/ . how to inject a JavaScript into this html page from my application
I am currently working on making a plugin just like Pinterest when the html page opens from my application it shows a bookmarklet just like Pinterest automatically on the page.
Below is the code I am using to inject JavaScript
public partial class ViewPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string script = "javascript:(function(){var jsdom = document.createElement('script');jsdom.src = 'http://localhost:15064/Script/delete.js';document.body.appendChild(jsdom);})();";
Response.Redirect(Server.UrlEncode(script));
}
}
Below is the Error I get After the execution of above code
Same Original Policy will not allow you to run scripts in someone else's domain.If this did not exist anyone could run scripts in any domain which would be a major security risk.
There are a couple *legal exceptions to this rule which you can read below
https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
The only other way to accomplish outside of an agreement with both sides would be a violation of Same Origin and probably illegal.
Xss attacks are pretty common and do what you are describing.
The closest you will probably be able to get is a bookmarklet:
http://www.mattcutts.com/blog/javascript-bookmarklet-basics/
which is basically a shortcut to inline javascript.
An example in the wild is the X-Ray Goggles bookmarklet. You can add it by creating a new bookmark and pasting the location as:
javascript:(function(){var script=document.createElement('script');script.src='https://goggles.webmaker.org/en-US/webxray.js';script.className='webxray';script.setAttribute('data-lang','en-US');script.setAttribute('data-baseuri','https://goggles.webmaker.org/en-US');document.body.appendChild(script);})();
This won't let you inject from your application but it is a way of injecting into a doc from your browser.
I need to redirect a user to a different page if they visit a certain set of pages in a web. There is one condition: I'm not allowed to touch the IIS. I have googled around and found a thing called the custom HttpHandler for WSS 3.0. It sounded like something that I can use to capture the URL the user enters (the most malicious way to get to a page that should really be redirected) and redirect them to another page/web. But having not have the chance to use it yet, I was wondering am I on the right track by using a Custom HttpHandler to redirect a user to a different page in Sharepoint using C#?
Many thanks.
HttpHandlers are used by IIS to "handle" different document types, for instance you have separate .asmx handle, .aspx handler, .ascx handler, etc.
Look into SPUtility.Redirect
You can use the SPUtility.Redirect method whenever you want to direct the user to a different page. For example, you might create a landing page that determines the user's role membership, and based on that information you can redirect them to an appropriate page. Or, based on the contents of a query string issued by the user's browser, you might redirect them to a page that can process the query string, such as the Search Center results page.
Alternatively, you can look into Using Disposable Windows SharePoint Services Objects.
--EDIT--
This is in response to your comment; you are thinking in the right direction
Create a custom HttpHandler; Example 1, Example 2
Whenever a user requests a url, your custom HttpHandler is going to process that.
Redirect() if you like the url, else otherwise.
But for your Custom HttpHandler to work, it should be called first - so in your config file you will have to provide the value in path. Usually an extension is added here. But you can replace that with a * to work for all request. I believe that would work.
<httpHandlers>
<add verb="*" path="*.aspx" type="MyNameSpace.MyHttpHandler, MyAssemblyName" />
</httpHandlers>
--EDIT--
This is in response to your comment. Assuming that you have "access" to pages so that you can write javascript in it, you can use the javascript in following way.
<script language=JavaScript>
function RedirectIfUnAuthorized()
{
//Get the location of the current page.
var currentUrl = new String( document.location.href )
//See if it belongs to the urls you are looking for; redirect if so.
if (currentUrl == "http://www.thisUrl.com/page1.aspx") {Response.Redirect("http://www.GOOGLE.com")}
if (currentUrl == "http://www.thisUrl.com/page2.aspx") {Response.Redirect("http://www.BING.com")}
if (currentUrl == "http://www.thisUrl.com/page3.aspx") {Response.Redirect("http://www.someother.com")}
}
</script>
You may call the above javascript in the page's OnLoad event.
Are you allowed to deploy code on the server? Or is that touching IIS too?
(SharePoint makes changes to web.config too. If you're allowed to deploy code, so could you. If you don't tell your admins they probably wouldnt even notice.)
You can 'deploy' your web.config changes through an SPWebConfigModification and deploy any web.config redirections or httphandlers that way.
HTTP handlers are the end point
objects in ASP.NET pipeline and an
HTTP Handler essentially processes the
request and produces the response. For
example an ASP.NET Page is an HTTP
Handler.
HTTP Modules are objects which also
participate the pipeline but they work
before and after the HTTP Handler does
its job, and produce additional
services within the pipeline (for
example associating session within a
request before HTTP handler executes,
and saving the session state after
HTTP handler has done its job, is
basically done by an HTTP module,
SessionStateModule)
In your case, HTTPModule will require to redirect the another web page.
using System;
using System.Web;
using System.Web.UI;
using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data;
namespace CustomHttpModule
{
public class HttpModuleImplementation : IHttpModule
{
#region IHttpModule Members
public void Dispose()
{
}
public void Init(HttpApplication context)
{
if (context == null)
throw new ArgumentNullException("Context == null");
context.AuthorizeRequest += new EventHandler(this.ProcessRequestHandler);
}
#endregion
private void DummpRequest(object sender, EventArgs e)
{
}
//first check that user.identity record exist in database
//If not then forward user to User registration page
private void ProcessRequestHandler(object sender, EventArgs e)
{
try
{
HttpApplication context = (HttpApplication)sender;
string strAbsoluteUri = context.Request.Url.AbsoluteUri.ToLower();
//check if request is accessing aspx page
if (strAbsoluteUri.Substring(strAbsoluteUri.Length - 5, 5).Contains(".aspx"))
{
string userName = context.User.Identity.Name;
//replace Test Module with DB call to validate user data
if (!CheckUserInDb(userName))
{
if (!strAbsoluteUri.Contains("mypage.aspx"))
redirectToRegistrationPage(context);
}
}
}
catch (Exception ex)
{
}
}
private void redirectToRegistrationPage(HttpApplication context)
{
context.Response.Redirect("http://" + context.Request.ServerVariables["HTTP_HOST"].ToString() + "Regpage.aspx", false);
}
private bool CheckUserInDb(string userName)
{
return true;
}
}
}
In SharePoint virtual directory web.config file you have to enter the following entry under section httpModules :
<add name="CustomHttpModule" type="CustomHttpModule.HttpModuleImplementation, CustomHttpModule" />
Monitoring my global exception logs this error seems to be impossible to remove no matter what I do, I thought I finally got rid of it but it's back again. You can see a strack trace of the error on a similar post here.
Notes about the environment:
IIS 6.0, .NET 3.5 SP1 single server ASP.NET application
Steps already taken:
<system.web>
<machineKey validationKey="big encryption key"
decryptionKey="big decryption key"
validation="SHA1" decryption="AES" />
In my Page Base for all of my pages
protected override void OnInit(EventArgs e)
{
const string viewStateKey = "big key value";
Page.ViewStateUserKey = viewStateKey;
}
Also in the source of the page I can see that all of the ASP.NET generated hidden fields are correctly at the top of the page.
First of all lets start from the fact, that this error of view state happens on PostBack.
Also I must say that I have done all the things that every one suggest to do to avoid this problem. And I have single machine, but 2 pools that run the same Pages.
So someone do an action, ether a man, ether some other search machine by 'clicking' on your pages, or some hacker try to check your system for problems...
I have similar problems (rare but existing ones), and I finally found that people try to hack-test my pages. (from the same IP I have and dos attacks)
I modify the function LoadPageStateFromPersistenceMedium() that translate the viewstate, and see by logging what exactly was the input, and from what IPs... then I started monitor these results and see that the view state was changed by hand - or was totally empty.
On error I just redirect him to the same page...
Here is what I did...
public abstract class BasePage : System.Web.UI.Page
{
protected override object LoadPageStateFromPersistenceMedium()
{
try
{
.. return the base, or make here your decompress, or what ever...
return base.LoadPageStateFromPersistenceMedium();
}
catch (Exception x)
{
string vsString = Request.Form[__VIEWSTATE];
string cThePage = Request.RawUrl;
...log the x.ToString() error...
...log the vsString...
...log the ip coming from...
...log the cThePage...
// check by your self for local errors
Debug.Fail("Fail to load view state ! Reason:" + x.ToString());
}
// if reach here, then have fail, so I reload the page - maybe here you
// can place somthing like ?rnd=RandomNumber&ErrorId=1 and show a message
Responce.Redirect(Request.RawUrl, true);
// the return is not used after the redirect
return string.Empty;
}
}
Second Reason
Now there is one more reason why this can happen, and the reason is because some one click on your page before the __EVENTVALIDATION is loaded.
This eventValidation is placed on the last button-even that asp.net found, and if you have some of them on many place on the page, or near the button, then this go to the end of the page.
So even if you see the viewstate on the top of the page, where is the Validation ??? maybe this never loaded - page corrupt ?, too fast user click on page ?
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" ... >
To avoid this kind of problem I made a simple javascript that I do not let it press the button unless this input have been loaded !!!.
One more comment, the __EVENTVALIDATION is not always presents ! so is maybe safer not to search for this field if you make a general solution, but to make a javascript trick to just check if the full page is loaded, or something else that you think.
Here is my final solution with jQuery: (note that I check on PageLoad if eventvalidation exist !). I have this placed on my MasterPages.
<script language="javascript" type="text/javascript">
function AllowFormToRun()
{
var MyEventValidation = $("#__EVENTVALIDATION");
if(MyEventValidation.length == 0 || MyEventValidation.val() == ""){
alert("Please wait for the page to fully loaded.");
return false;
}
return true;
}
</script>
protected void Page_Load(object sender, EventArgs e)
{
// I do not know if Page can be null - just in case I place it.
if (Page != null && Page.EnableEventValidation)
{
Form.Attributes["onsubmit"] = "return AllowFormToRun();";
}
}
You can test by placing near the button of your page a delay.
<% System.Threading.Thread.Sleep(5000); %>
Update
Today I see in log this message again for WebResource and what I discover is that a bot getting the pages and make all the character on the links in lower case, including the parameters, so this was one more reason to not getting the correct encoded string, and throw a message like Padding is invalid and cannot be removed.
Hope this help you more.
A survey of the web pages found with several of the keywords from the error message indicate that this type of error is relatively common, usually random (at least in appearance) and unfortunately rarely inclusive of an explicit work-around or explanation...
The existence of many similar-yet-different situations is probably tied to the very many different architectures and underlying configurations which can somehow lead to the inability of the crypto layer to assert the authenticity of the MAC (Message Authentication Codes) in the request pages:
Server farm setup
Cross domain / syndicated pages
third party widget libraries and such
Actual ASP program logic (of course)
One relatively frequent "marker" around these bug reports is the mention of resource requests (eg. WebResource.axd).
Note that such requests are often not logged (lest they inflate the log files size with event of relative little interest). This absence from the log file and the fact they are often cached (and hence the relative random and infrequent occurrence of the bug) may explain how this possible origin of the bug go "under the radar". This also suggests that in trying to recreate the bug, (while tracking in the logs, in real time etc) it may be useful to prevent the web browser from caching (or for the least to clear it cache initially).
In short, here are a few ideas and things to look for:
start logging the *.axd requests
try and co-relate such axd requests with the error events in the exception log
look for pages with resource references
if in a Farm setting, ensure that all instances use the same key (apparently the snippet provided in the question hint at multiple IIS servers)
Be suspicious of pages with 3rd party tie-ins (search services, affiliate programs...)
Hope this helps ;-)
Are you sure your problem is cryptography related, and not caused by oversized ViewState?
If ViewState is the problem, you can chunk it - change the value of pages / MaxPageStateFieldLength in web.config
I've made a little game in silverlight that records users scores whilst they play.
I decided it would be a lot better if I could implement a leaderboard, so I created a database in mySQL to store all the high scores along with names and dates. I have created some communications to the database in ASP.net. This works and I can simply insert and get data within the code.
It's now time to link the silverlight project with the ASP.net database communications, so I can send the users name and score as variables to my ASP.net code and then it will upload it to the database. That's all I need. Surely there must be an easy way of doing this, I just can't seem to find any ways when researching.
Thanks in advance,
Lloyd
At first you need add Generic Handler to your ASP.Net project.
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string userName = context.Request["user"];
int score = int.Parse(context.Request["score"]);
//And store it in DB
}
}
After you need call this handler from SilverLight app:
string uri = HtmlPage.Document.DocumentUri.ToString();
// Remove the web page from the current URI to get the root URI.
string rootUri = uri.Remove(uri.LastIndexOf('/'),
uri.Length - uri.LastIndexOf('/'));
string diggUrl = String.Format(rootUri + "/" + "test.ashx?user={0}&score={1}", "testuser", "234");
// Initiate Async Network call to Digg
WebClient diggService = new WebClient();
diggService.DownloadStringAsync(new Uri(diggUrl));
here i used Uri Class to send parameter to asp.net, but you can send string format only.
// this code written on Silverlight Button Click Event.
Uri myURI = new Uri(HtmlPage.Document.DocumentUri,String.Format("Report.aspx?brcd={0}&acc={1}&user={2}", Brcd, Acc, User)); HtmlPage.Window.Navigate(myURI, "_blank");
below code is written on Asp.net page_load or page init event
Brcd = Request.QueryString["brcd"];// brcd value accept here.
acc= Request.QueryString["ACC"];`
user= Request.QueryString["User"];
in above code we accept the silverlight parameter in asp.net but in [] bracket put name as it is use in silverlight page because it case sensitive.
By ASP.NET, do you mean an ASP.NET Webforms app?
If so, an ASP.NET Webforms app is a method of building a UI. What you need is an API, for your Silverlight app to use programatically. For this purpose you may want to consider building an ASP.NET Webservice instead, which provides an API over HTTP.
What do you need its to send data to web server from a Silverlight application, right?
You can:
Call Javascript functions from Silverlight and, there, do a postback
Call web services with Silverlight, but make sure its in same server which your SL application came from, or you will face some XSS issues.
An easy way to do this is to have your Silverlight code create a REST URL by encoding the information into the query string, and invoking an .aspx page on the server. The page wouldn't need to return any markup; it would just handle the back-end stuff and return.
Alternatively, you could make a web service call from Silverlight to your back end.
I prefer the latter approach. It's a little more work the first time through, but it's also more general purpose and makes for generally better code in the long run.
Although technically you could use JavaScript, I wouldn't suggest it; why go backwards in tech if you don't have to?