Ajax toolkit file upload is not called - c#

I have two ajaxtoolkit file ulopads on the same page like
<ajaxToolkit:AjaxFileUpload
id="AjaxFileUpload1"
AllowedFileTypes="jpg,jpeg,gif,png"
OnUploadComplete="ajaxUpload2_OnUploadComplete"
runat="server" />
<ajaxToolkit:AjaxFileUpload
id="ajaxUpload1"
AllowedFileTypes="jpg,jpeg,gif,png"
OnUploadComplete="ajaxUpload1_OnUploadComplete"
runat="server" />
and code behind
protected void ajaxUpload2_OnUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
string filePath = "~/Images/" + e.FileName;
filePath = filePath.Split('\\').Last();
Session["img2"] = filePath.ToString();
AjaxFileUpload1.SaveAs(MapPath(filePath));
}
protected void ajaxUpload1_OnUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
string filePath = "~/Images/" + e.FileName;
filePath = filePath.Split('\\').Last();
Session["img1"] = filePath.ToString();
ajaxUpload1.SaveAs(MapPath(filePath));
}
The question is whenever I use upload AjaxFileUpload1 it works on and calls void ajaxUpload2_OnUploadComplete method but if I use ajaxUpload1 the method ajaxUpload2_OnUploadComplete is called again but the method ajaxUpload1 is not called
Why??
Thanks.

We got the same problem yesterday and we found out that you cannot have more than one instance of AjaxFileUpload on the same page.
If you look at the source code, you'll see that this control use a constant GUID to identify its events. Since the GUID is a constant, all instances of AjaxFileUpload use the same GUID...
Result :
the first instance swallow all the events...
Here is the GUID in action :
private const string ContextKey = "{DA8BEDC8-B952-4d5d-8CC2-59FE922E2923}";
(...)
if (this.Page.Request.QueryString["contextkey"] == ContextKey && this.Page.Request.Files.Count > 0)

We customized the September 2012 toolkit as follows - hope this is a temporary workaround and that this is fixed in a future release:
OLD
private const string ContextKey = "{DA8BEDC8-B952-4d5d-8CC2-59FE922E2923}";
NEW
private string ContextKey = "";
OLD
public AjaxFileUpload()
: base(true, HtmlTextWriterTag.Div)
{
}
NEW
public AjaxFileUpload()
: base(true, HtmlTextWriterTag.Div)
{
if (HttpContext.Current.Items["lastAjaxFileUploadContextKey"] == null)
{
HttpContext.Current.Items["lastAjaxFileUploadContextKey"] = 1;
}
else
{
HttpContext.Current.Items["lastAjaxFileUploadContextKey"] = (int)HttpContext.Current.Items["lastAjaxFileUploadContextKey"] + 1;
}
ContextKey = HttpContext.Current.Items["lastAjaxFileUploadContextKey"].ToString();
}

There actually is a way to use multiple AjaxFileUpload controls on a single page, with each control firing its own event. The solution is very simple; it involves overriding one of Microsoft's client-side functions for the AjaxFileUpload control to inject information on the control that actually caused the upload complete event, then using a single event handler for all of the AjaxFileUpload controls as a "switchboard", which will subsequently fire the correct event handler for the control which created the event server-side.
Here's how to do it:
Add this script block somewhere after the head element of your page. If you're using master pages, put this in a placeholder for HTML content:
<script type="text/javascript">
Sys.Extended.UI.AjaxFileUpload.Control.prototype.doneAndUploadNextFile = function (c) {
var a = new XMLHttpRequest, b = this;
a.open("POST", "?contextKey=" + this._contextKey + "&done=1&guid=" + c._id + "&uplCtrlID=" + b.get_id(), true);
a.onreadystatechange = function () {
if (a.readyState == 4) if (a.status == 200) {
b.raiseUploadComplete(Sys.Serialization.JavaScriptSerializer.deserialize(a.responseText));
b._processor.startUpload()
}
else {
b.setFileStatus(c, "error", Sys.Extended.UI.Resources.AjaxFileUpload_error);
b.raiseUploadError(a);
throw "error raising upload complete event and start new upload";
}
};
a.send(null);
}
</script>
This code is the same function being used to call your page and trigger the UploadComplete event, only modified to add an extra parameter - uplCtrlID - which will contain the ID of the control that REALLY caused the event.
Set up your server side code as follows:
//set the OnUploadComplete property on all of your AjaxFileUpload controls to this method
protected void anyUploader_UploadComplete(object sender, AjaxFileUploadEventArgs e)
{
//call the correct upload complete handler if possible
if (Request.QueryString["uplCtrlID"] != null)
{
//uplCtrlID (the query string param we injected with the overriden JS function)
//contains the ID of the uploader.
//We'll use that to fire the appropriate event handler...
if (Request.QueryString["uplCtrlID"] == FileUploaderA.ClientID)
FileUploaderA_UploadComplete(FileUploaderA, e);
else if (Request.QueryString["uplCtrlID"] == FileUploaderB.ClientID)
FileUploaderB_UploadComplete(FileUploaderB, e);
//etc (or use a switch block - whatever suits you)
}
}
protected void FileUploaderA_UploadComplete(AjaxFileUpload sender, AjaxFileUploadEventArgs e)
{
//logic here
}
protected void FileUploaderB_UploadComplete(AjaxFileUpload sender, AjaxFileUploadEventArgs e)
{
//logic here
}
You're all set. Multiple AjaxFileUpload controls on the same page, no problems.

Related

Page_Load fires infinity times

I have problem with my iframe asp.net page.
Browser url containst parameter which I need to use in my iframe page.
Obviously I can't get access via .NET so I came up with the idea that at the end of the Page_Load method add sth like that :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bool isReloaded = Request.QueryString.GetValue<bool>("reloaded");
ContentId = Request.QueryString.GetValue<int>("contentId"); //I need this value
if (!isReloaded)
{
StringBuilder js = new StringBuilder("<script language='javascript'>");
js.Append("var last = window.top.location.href.substring(window.top.location.href.lastIndexOf('/') + 1, window.top.location.href.length); ");
js.Append("window.location.href = window.location.href + '?reloaded=true&contentId=' + last;");
js.Append("if(window.location.href.indexOf('reloaded=true') == -1) window.location.reload();");
js.Append("<" + "/script>");
Response.Write(js.ToString());
}
}
}
In shortcut I use Javascript to get value I need and fire reload() but with changed QueryString.
Page_Load is firing again and now I have bool isReloaded filled with true.
The condition (!isReloaded) blocks that this time javascript will not be added to Response.
I don't know why, but Page_Load fires again, this time without added parameters so it's the same situation as at the beginning and again is adding JS etc.
Result is that Page_load fires endlessly.
What did I do wrong ? What is the reason ?
if you have a look at your code, you have this line:
js.Append("if(window.location.href.indexOf('reloaded=true') == -1) window.location.reload();");
you are checking the location.href for the 'reloaded' var, but note that your page is reloaded as soon as you change the location, and your script keeps executing before it is done, so it results in reloading of the page over an over again without the query string.
remove this line and it should work fine.
another thing though, i changed your code a little bit to register the script on page instead of response.write it,
it shouldnt make any difference, but if your code still doesnt work then try my version:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bool isReloaded;
int ContentId;
bool.TryParse(Request.QueryString["reloaded"],out isReloaded);
int.TryParse(Request.QueryString["contentId"],out ContentId); //I need this value
if (!isReloaded)
{
StringBuilder js = new StringBuilder();
js.Append("var last = window.top.location.href.substring(window.top.location.href.lastIndexOf('/') + 1, window.top.location.href.length); ");
js.Append("window.location.href = window.location.href + '?reloaded=true&contentId=' + last;");
ExecScript(js.ToString());
}
}
}
void ExecScript(string script)
{
Page page = HttpContext.Current.CurrentHandler as Page;
if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("AttachedScript"))
{
page.ClientScript.RegisterClientScriptBlock(page.GetType(), "AttachedScript", script, true);
}
}
Thanks for help.
Now I have sth like that and it's ok.
StringBuilder js = new StringBuilder("<script language='javascript'>");
js.Append("var last = window.top.location.href.substring(window.top.location.href.lastIndexOf('/') + 1, window.top.location.href.length); ");
js.Append("if(window.location.href.indexOf('reloaded=true') == -1) window.location.href = window.location.href + '?reloaded=true&contentId=' + last;");
js.Append("<" + "/script>");
I didn't know that editing location executes reload automatically ;)
Thanks again

Continue executing an event after validations on modal or radwindow

I have the following scenario: A user makes a click on a button inside an asp page. Because of security reasons, during the click event execution the system determines that it is necessary to apply some validations before continuing with the execution of the fired event.
Those validations are shown in a window (in this case a Telerik RadWindow). Inside this RadWindow, there is a web user control (WUC) containg validations like a Captcha, or security code, secret questions, etc. After the user writes the captcha text or the necessary validations (it implies postbacks inside the WUC), the WUC should continue with the execution of the fired event from the botton which opened the RadWindow.
How can I do this? Any idea? Is it possible?
When you call your RadWindow, make sure the set the OnClientClose event. If you are creating your RadWindow from code-behind:
RadWindow newWindow = new RadWindow();
newWindow.OnClientClose = "onRadWindowClosed";
...
If you are opening your RadWindow through javascript, you can use the add_close() method:
...
getRadWindow().add_close('onRadWindowClosed');
...
In either case, you need to create a new event handler script on your calling page for the OnClientClose event:
function onRadWindowClosed(sender, eventArgs) {
var returnValue = eventArgs.get_argument();
if (returnValue != null) {
if (returnValue == "continue") {
// Continue doing work
}
else {
// Throw an error
}
}
}
On your WUC, in the btnContinue click event:
protected void btnContinue_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptBlock(GetType(), "closeScript", "getRadWindow().close('continue');", true);
}
This function is used on both pages:
function getRadWindow() {
var oWindow = null;
if (window.radWindow)
oWindow = window.radWindow;
else if (window.frameElement.radWindow)
oWindow = window.frameElement.radWindow;
return oWindow;
}
UPDATE TO THE EXISTING ANSWER
On your calling page, add a function to get the RadAjaxManager (assuming you already have on the page. If not, you'll need one):
function get_ajaxManager() {
return $find("<%= Telerik.Web.UI.RadAjaxManager.GetCurrent(this.Page).ClientID %>");
}
Modify your OnClosed javascript function (from the calling page):
function onRadWindowClosed(sender, eventArgs) {
var returnValue = eventArgs.get_argument();
if (returnValue != null) {
if (returnValue == "continue") {
// This call will invoke a server side event
get_ajaxManager().ajaxRequest("continue~");
}
}
}
In your code-behind, handle the server-side event that gets called:
protected void RadAjaxManager1_Request(object source, Telerik.Web.UI.AjaxRequestEventArgs e)
{
try
{
if (e.Argument.Trim().Length == 0)
{
// Show a message when debugging, otherwise return
return;
}
string argument = (e.Argument);
String[] stringArray = argument.Split('~');
switch (stringArray[0])
{
case "continue":
// Continue performing your action or call a specific method
ServerSideMethodCall();
break;
}
}
catch (Exception ex)
{
RadAjaxManager.GetCurrent(this.Page).Alert("Unable to complete operation at this time: " + ex.Message);
}
}
As previously mentioned, you'll need a RadAjaxManager on the page if you don't already have one, and you'll need to tie the AjaxRequest handler to it.
<telerik:RadAjaxManager runat="server" ID="RadAjaxManager1" OnAjaxRequest="RadAjaxManager1_Request"></telerik:RadAjaxManager>
Sorry for the long-winded answer. Let me know if that gets you what you need.

How to detect page refresh in .net

I have a Button_click event. While refreshing the page the previous Postback event is triggering again. How do I identify the page refresh event to prevent the Postback action?
I tried the below code to solve it. Actually, I am adding a visual webpart in a SharePoint page. Adding webpart is a post back event so !postback is always false each time I'm adding the webpart to page, and I'm getting an error at the else loop because the object reference is null.
if (!IsPostBack){
ViewState["postids"] = System.Guid.NewGuid().ToString();
Cache["postid"] = ViewState["postids"].ToString();
}
else{
if (ViewState["postids"].ToString() != Cache["postid"].ToString()){
IsPageRefresh = true;
}
Cache["postid"] = System.Guid.NewGuid().ToString();
ViewState["postids"] = Cache["postid"].ToString();
}
How do I solve this problem?
using the viewstate worked a lot better for me as detailed here. Basically:
bool IsPageRefresh = false;
//this section of code checks if the page postback is due to genuine submit by user or by pressing "refresh"
if (!IsPostBack)
{
ViewState["ViewStateId"] = System.Guid.NewGuid().ToString();
Session["SessionId"] = ViewState["ViewStateId"].ToString();
}
else
{
if (ViewState["ViewStateId"].ToString() != Session["SessionId"].ToString())
{
IsPageRefresh = true;
}
Session["SessionId"] = System.Guid.NewGuid().ToString();
ViewState["ViewStateId"] = Session["SessionId"].ToString();
}
This article could be of help to you
http://www.codeproject.com/Articles/68371/Detecting-Refresh-or-Postback-in-ASP-NET
you are adding a Guid to your view state to uniquely identify each page. This mechanism works fine when you are in the Page class itself. If you need to identify requests before you reach the page handler, you need to use a different mechanism (since view state is not yet restored).
The Page.LoadComplete event is a reasonable place to check if a Guid is associated with the page, and if not, create one.
check this
http://shawpnendu.blogspot.in/2009/12/how-to-detect-page-refresh-using-aspnet.html
This worked fine for me..
bool isPageRefreshed = false;
protected void Page_Load(object sender, EventArgs args)
{
if (!IsPostBack)
{
ViewState["ViewStateId"] = System.Guid.NewGuid().ToString();
Session["SessionId"] = ViewState["ViewStateId"].ToString();
}
else
{
if (ViewState["ViewStateId"].ToString() != Session["SessionId"].ToString())
{
isPageRefreshed = true;
}
Session["SessionId"] = System.Guid.NewGuid().ToString();
ViewState["ViewStateId"] = Session["SessionId"].ToString();
}
}
Simple Solution
Thought I'd post this simple 3 line solution in case it helps someone. On post the session and viewstate IsPageRefresh values will be equal, but they become out of sync on a page refresh. And that triggers a redirect which resets the page. You'll need to modify the redirect slightly if you want to keep query string parameters.
protected void Page_Load(object sender, EventArgs e)
{
var id = "IsPageRefresh";
if (IsPostBack && (Guid)ViewState[id] != (Guid)Session[id]) Response.Redirect(HttpContext.Current.Request.Url.AbsolutePath);
Session[id] = ViewState[id] = Guid.NewGuid();
// do something
}
If you want to detect a refresh on an HTTP GET rather than only POSTs, here's a hacky work-around that, in modern browsers, mostly works.
Javascript:
window.onload = function () {
// regex for finding "loaded" query string parameter
var qsRegex = /^(\?|.+&)loaded=\d/ig;
if (!qsRegex.test(location.search)) {
var loc = window.location.href + (window.location.search.length ? '&' : '?') + 'loaded=1';
window.history.replaceState(null, document.title, loc);
}
};
C#:
public bool IsPageRefresh
{
get
{
return !string.IsNullOrEmpty(Request.QueryString["loaded"]);
}
}
When the page loads, it will change add a QueryString parameter of loaded=1 without reloading the page (again, this--window.history.replaceState--only works in post-archaic browsers). Then, when the user refreshes the page, the server can check for the presence of the loaded parameter of the query string.
Caveat: mostly works
The case where this doesn't work is when the user clicks the Address Bar and presses enter. That is, the server will produce a false-positive, detecting a refresh, when odds are, the user actually meant to reload the page fresh.
Depending on your purposes, maybe this is desirable, but as a user, it would drive me crazy if I expected it to reset the page.
I haven't put too much thought into it, but it might be possible to write some magic in order to distinguish a refresh from a reset via the address bar using any/all of:
SessionState (assuming SessionState is enabled) and the value of the loaded QueryString parameter
the window.onbeforeunload event listener
keyboard events (detecting F5 and Ctrl + R to quickly change the URL back to removing the loaded QueryString parameter--though this would have a false-negative for clicking the browser's refresh button)
cookies
If someone does come up with a solution, I'd love to hear it.
Another way to check page refresh. I have written custom code without java script or any client side.
Not sure, it's the best way but I feel good work around.
protected void Page_Load(object sender, EventArgs e)
{
if ((Boolean)Session["CheckRefresh"] is true)
{
Session["CheckRefresh"] = null;
Response.Write("Page was refreshed");
}
else
{ }
}
protected void Page_PreInit(object sender, EventArgs e)
{
Session["CheckRefresh"] = Session["CheckRefresh"] is null ? false : true;
}

Get data from user control since Webpage

I have a simple question in asp.net.
I want to know if it is possible to get data from controls in my user control directly . I want to do it without using Session variable,Viewstate ...
EDIT: I now use the method of declaring public variables in the UC.
Here is a part of Page_load from my parent page:
this.plan_action = (UCPlan)Page.LoadControl("~/Association/UCPlan.ascx");
PlaceHolder1.Controls.Add(this.plan_action);
if (this.plan_action.Validate == true)
{
CheckBox1.Checked = true;
//String référence = Session["liste_action"].ToString();
for (int i = 0; i < this.plan_action.List1.Count; i++)
{
Label8.Text += this.plan_action.List1[i].Référence + "/";
//Label8.Text += "/";
}
}
but my variable validate stay to false.
Here is the code where I change the value of the validate variable with it declaration:
private bool validate;
public bool Validate
{
get { return validate; }
set { validate = value; }
}
protected void Button2_Click(object sender, EventArgs e)
{
//myCommand.Connection = myConnection;
//Session["liste_action"] = this.List;
this.Validate = true;
//Response.Redirect("../Risques_folder/AjouterRisque.aspx");
}
Thank you for your help,
Quentin
UPDATE due to new information
You need to learn about the sequence of events in ASP.NET.
The Load of the page happens a long time before the Click handler of Button2 in your UserControl... so the Validate property is always going to be set to false.
You have two obvious options (as I see it)...
Keep the creation of the UserControl in your Page_Load (or preferably, move it to your Page_Init, as this is normally the most appropriate place for it). Then place your check for the Validate property in a Page_PreRender.
Or, create an Event in your UserControl, Raise that event on the click of Button2, and handle the event in the Page.
ANOTHER UPDATE
For the 2nd of the two options above, in your UserControl class have the following...
public delegate void ButtonClickedDelegate(object sender, EventArgs e);
public event ButtonClickedDelegate ButtonClicked;
In the Button2_Click method of the UserControl (after setting the this.Validate = true;) call...
ButtonClickedDelegate(sender, e);
In the Page_Init of the Page, put something like...
ctrl1.ButtonClicked += new UCPlan.ButtonClickedDelegate(ctrl1_ButtonClicked);
And then have a new method called something like
void ctrl1_ButtonClicked(object sender, EventArgs e)
{
if (ctrl1.Validate)
{
...
}
}
Remember, as you control the delegate you can pass whatever information you want, including an entire class. So instead of calling the Validate property, create a new instance of the class you want, and pass that as a delegate parameter.
You can find more information on delegates and events on MSDN.
ORIGINAL ANSWER
Unless I've missed something, this is a very simple ASP.NET concept...
You can create properties and/or methods.
For example, as a property...
public string MyProperty
{
get { return "My Property Value"; }
}
Or as a method
public string MyMethod()
{
return "My Method Value";
}
If you're talking about passing the values between the UserControl and the ASP.NET Page that contains it, then in your Page, you can simply call the property or method. If your control was called (for example) myCtrl, then you can something like...
string prop = myCtrl.MyProperty;
string meth = myCtrl.MyMethod();
(On the back of the great comment from AHMED EL-HAROUNY)
If you're talking about passing the values to the client side page, then you can use the same properties / methods directly in the HTML markup. However, in this case, the properties / method can be declared as protected rather than public
For instance, to display the value...
<%=MyProperty%>
Or
<%=MyMethod()%>
Or if you're going to use the value in javascript, something like...
var myProp = "<%=MyProperty%>";
Yes That is possible, But exposing the controls in the UserControl as Public.

HttpModule - get HTML content or controls for modifications

Tried something like this:
HttpApplication app = s as HttpApplication; //s is sender of the OnBeginRequest event
System.Web.UI.Page p = (System.Web.UI.Page)app.Context.Handler;
System.Web.UI.WebControls.Label lbl = new System.Web.UI.WebControls.Label();
lbl.Text = "TEST TEST TEST";
p.Controls.Add(lbl);
when running this I get "Object reference not set to an instance of an object." for the last line...
How do I get to insert two lines of text (asp.net/html) at specific loactions in the original file?
And how do I figure out the extension of the file (I only want to apply this on aspx files...?
Its simplier than you think:
public void Init(HttpApplication app)
{
app.PreRequestHandlerExecute += OnPreRequestHandlerExecute;
}
private void OnPreRequestHandlerExecute(object sender, EventArgs args)
{
HttpApplication app = sender as HttpApplication;
if (app != null)
{
Page page = app.Context.Handler as Page;
if (page != null)
{
page.PreRender += OnPreRender;
}
}
}
private void OnPreRender(object sender, EventArgs args)
{
Page page = sender as Page;
if (page != null)
{
page.Controls.Clear(); // Or do whatever u want with ur page...
}
}
If the PreRender Event isn't sufficient u can add whatever Event u need in the PreRequestHandlerExecute EventHandler...
I'm not sure, but I don't think you can use an HttpModule to alter the Page's control tree (please correct me if I'm wrong). You CAN modify the HTML markup however, you'll have to write a "response filter" for this. For an example, see http://aspnetresources.com/articles/HttpFilters.aspx, or google for "httpmodule response filter".
It seems like the HttpFilter solution is doing the trick here :o)
If I had used MOSS/.net 2.x+ I could have used Runes version or just added my tags in a master page...
Super suggestions and after my test of the solution, I'll accept miies.myopenid.com's solution as it seems to solve thar actual issue
There have been some changes in how you write HttpModules in IIS7 as compared to IIS6 or 5, so it might be that my suggestion is not valid if you are using IIS7.
If you use the Current static property of the HttpContext you can get a reference to the current context. The HttpContext class has properties for both the Request (HttpRequest type) and the Response (HttpResponse) and depending on where which event you are handling (Application.EndRequest maybe?) you can perform various actions on these objects.
If you want to change the content of the page being delivered you will probably want to do this as late as possible so responding to the EndRequest event is probably the best place to do this.
Checking which file type that was requested can be done by checking the Request.Url property, maybe together with the System.IO.Path class. Try something like this:
string requestPath = HttpContext.Current.Request.Url.AbsolutePath;
string extension = System.IO.Path.GetExtension(requestPath);
bool isAspx = extension.Equals(".aspx");
Modifying the content is harder. You may be able to do it in one of the events of the Context object, but I am not sure.
One possible approach could be to write your own cusom Page derived class that would check for a value in the Context.Items collection. If this value was found you could add a Label to a PlaceHolder object and set the text of the label to whatever you wanted.
Something like this should work:
Add the following code to a HttpModule derived class:
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(BeginRequest);
}
void BeginRequest(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
HttpRequest request = context.Request;
string requestPath = HttpContext.Current.Request.Url.AbsolutePath;
string extension = System.IO.Path.GetExtension(requestPath);
bool isAspx = extension.Equals(".aspx");
if (isAspx)
{
// Add whatever you need of custom logic for adding the content here
context.Items["custom"] = "anything here";
}
}
Then you add the following class to the App_Code folder:
public class CustomPage : System.Web.UI.Page
{
public CustomPage()
{ }
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (Context.Items["custom"] == null)
{
return;
}
PlaceHolder placeHolder = this.FindControl("pp") as PlaceHolder;
if (placeHolder == null)
{
return;
}
Label addedContent = new Label();
addedContent.Text = Context.Items["custom"].ToString();
placeHolder .Controls.Add(addedContent);
}
}
Then you you modify your pages like this:
public partial class _Default : CustomPage
Note that the inheritance is changed from System.Web.UI.Page to CustomPage.
And finally you add PlaceHolder objects to your aspx files wherever you want you custom content.

Categories