I am using Ext.Net library along with ASP.net routing.
The following page
~/Admin/Dashboard.aspx
is routed as
administrator/fr/dashboard/
or
administrator/en/dashboard/
I am using Ext.Net FileUpload control.
The following code (on a direct event)
HttpContext.Current.Request.Files[0].SaveAs(fileName);
produces the following exception
System.Web.HttpException (0x80004005): The file
'/administrator/en/dashboarddefault.aspx' does not exist. at
Ext.Net.HandlerMethods.GetHandlerMethods(HttpContext context, String
requestPath) at Ext.Net.HandlerMethods.GetHandlerMethods(HttpContext
context, String requestPath) at
Ext.Net.DirectRequestModule.ProcessRequest(HttpApplication app,
HttpRequest request)
with Status Code: 200, Status Text: OK.
If I do the same thing from
~/Admin/Dashboard.aspx
There is no problem.
Please help.
Try to use Generic handlers.
upload.ashx :
<%# WebHandler Language="C#" Class="upload" %>
using System;
using System.Web;
using System.IO;
using System.Web.Script.Serialization;
public class upload : IHttpHandler {
public void ProcessRequest (HttpContext context) {
try
{
HttpPostedFile postedFile = context.Request.Files[0];
byte[] b = new byte[postedFile.ContentLength];
postedFile.InputStream.Read(b, 0, postedFile.ContentLength);
File.WriteAllBytes(Path.GetTempPath() + postedFile.FileName, b);
context.Response.Write((new JavaScriptSerializer()).Serialize(new { success = true }));
}
catch (Exception ex)
{
context.Response.Write((new JavaScriptSerializer()).Serialize(new { success = false, error = ex.Message }));
}
}
public bool IsReusable {
get {
return false;
}
}
}
js code (you can adapt him to Ext.Net or use CustomConfig), put this code to form items array:
{
xtype: 'fileuploadfield',
listeners: {
change: function () {
var fp = this.findParentByType('panel');
if (fp.getForm().isValid()) {
fp.getForm().submit({
url: 'Handlers/upload.ashx',
success: function (me, o) {
if (o.result.success) {
// some code
} else {
Ext.Msg.alert('Error', o.result.error);
}
}
});
}
}
}
}
Related
I am creating a web server through asp.net.
The source works well in debug mode.
However, after posting to iis, if you go through the source, you will get the error 'HTTP Error 503. The service is unavailable' after about 20 seconds.
I am confident that there is an error in the OpenFileDialog section.
In the past, this code worked well after posting. I do not know what has been modified since then.
Thanks in advance for your help.
.js code
action: function (e, dt, node, config) {
$.ajax({
"url": "/api/Member/ExcelRead",
"type": "POST",
"datatype": 'json',
success: function (data) {
if (data === 'OK') {
alert("성공");
}
},
error: function (response, state, errorCode) {
alert("실패");
}
});
.cs
public class MemberController : ApiController
{
[HttpPost]
public string ExcelRead()
{
ExcelHelper helper = new ExcelHelper();
Thread th = new Thread(helper.ReadExcelData);
th.SetApartmentState(ApartmentState.STA);
th.Start();
th.Join();
if (helper.data == null)
return ("NO");
return ("OK");
}
}
public void ReadExcelData()
{
IsRun = false;
OpenFileDialog openFile = new OpenFileDialog();
openFile.DefaultExt = "xlsx";
openFile.Filter = "Excel Files(*.xlsx)|*.xlsx";
DialogResult dresult = openFile.ShowDialog();
if (dresult != DialogResult.OK)
{
return;
}
if (openFile.FileNames.Length > 0)
{
foreach (string filename in openFile.FileNames)
{
//this.textBox1.Text = filename;
}
}
}
In ASP.NET, Unable to invoke delIt web service method in Defaults.aspx.cs from ActionComplete method. But am able to invoke AddIt and UpdateIt web methods in Defaults.aspx.cs
My code:
In Default.aspx:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True" />
function ActionComplete(args) {
var ganttRecord = args.data;
if (args.requestType === 'save' && args._cAddedRecord) {
PageMethods.AddIt(ganttRecord);
}
else if (args.requestType === 'save') {
PageMethods.UpdateIt(ganttRecord);
}
else if (args.requestType === 'delete') {
PageMethods.delIt(ganttRecord);
}
}
In Default.aspx.cs:
[WebMethod]
public static void AddIt(TaskData record)
{
Default sample = new Default();
sample.Add(record);
}
[WebMethod]
public static void UpdateIt(TaskData record)
{
Default sample1 = new Default();
sample1.Update(record);
}
[WebMethod]
public static void delIt(TaskData record)
{
Default sample2 = new Default();
sample2.Delete(record);
}
The "ganttRecord" Json object which i passed to delIt method has some extra undefined variables and boolean variables. So only I think so Pagemethods unable to call that delIt method in the Defaults.aspx.cs
public class MessageHelper : System.Web.UI.MasterPage
{
public MessageHelper()
{
}
public string Message
{
set { Session["Message"] = value; }
get
{
if (Session["Message"] != null)
{
var msg = Session["Message"] as string;
Session["Message"] = "";
return msg;
}
return "";
}
}
public string ErrorMsg
{
set { Session["Error"] = value; }
get
{
if (Session["Error"] != null)
{
var err = Session["Error"] as string;
Session["Error"] = "";
return err;
}
return "";
}
}
}
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.UI.UserControl.get_Session() +15
WebApplication1.MessageHelper.get_ErrorMsg() in ..file.master.cs:71
where line 71 is: if (Session["Error"] != null)
what am I doing wrong here?!
EDIT (transcribed from original author):
#David,
here is AdminMaster.master.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.SessionState;
namespace WebApplication1
{
public partial class AdminMaster : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
MessageHelper msg = new MessageHelper();
if (msg.ErrorMsg != "")
{
// do something
}
if (msg.ErrorMsg != "")
{
// do something
}
}
}
public class MessageHelper : System.Web.UI.MasterPage
{
public MessageHelper()
{
}
public string Message
{
set { System.Web.HttpContext.Current.Session["Message"] = value; }
get
{
if (System.Web.HttpContext.Current.Session["Message"] != null)
{
var msg = System.Web.HttpContext.Current.Session["Message"] as string;
System.Web.HttpContext.Current.Session["Message"] = "";
return msg;
}
return "";
}
}
public string ErrorMsg
{
set { System.Web.HttpContext.Current.Session["Error"] = value; }
get
{
if (System.Web.HttpContext.Current.Session["Error"] != null)
{
var err = System.Web.HttpContext.Current.Session["Error"] as string;
System.Web.HttpContext.Current.Session["Error"] = "";
return err;
}
return "";
}
}
}
}
so it does inherit from System.Web.UI.MasterPage, my bad.
i want the MessageHelper to be accessed from different pages on the site. all of my pages use the Master file, that's why i put the MessageHelper in the master file.
what is wrong here?
During debugging, can you confirm that Session is not null? Try referencing it fully-qualified as System.Web.HttpContext.Current.Session within this class and see if that helps any.
Edit: In response to the non-answer answer that you posted...
It's not recommended to put that helper class in the same file as your master page. Put it in its own file named for the class. (There's probably debate over whether every class should have its own file, but in this particular case it's clear that the two classes in this one file are very much unrelated and shouldn't be together.)
The class can have its own namespace, such as WebApplication1.Helpers (though I recommend in the future using something more descriptive than WebApplication1, but don't try to change it here because it'll cause errors elsewhere in the project), and other class files can reference that namespace with using WebApplication1.Helpers in order to use that class.
Separating classes into an intuitive structure in the project (or multiple projects, as things grow in complexity) will make it easier to support in the future.
And, seeing the whole file, the helper class definitely should not inherit from MasterPage. It doesn't need to, and doing so adds things to that class that shouldn't be there.
I'm a bit confused by what you're trying to achieve with the MessageHelper class.
If it is code common to your master pages then you should surely be inheriting AdminMaster from MessageHelper.
eg.
public partial class AdminMaster : MessageHelper
If not, I don't understand why MessageHelper needs to inherit from MasterPage?
I've been using my own Error reporting module which was combination of simple c# and jQueryUI Dialog. Problem is that once error or success occurs i do write it's value to session. It does work pretty good on pages with Responce.Redirect on error but not on pages where i catch an error and then return to same form.
My question is why does session which added pre-postback fails to load in pages where i have return statement on some condition.
And if there another way to save errors and success message except in session ? Maybe global variables or something like that ...
CODE EXAMPLES
this is Error class
public static string getMessage()
{
HttpContext c = HttpContext.Current;
string messageType = "";
if (c.Session["errorMessage"] != null)
{
messageType = "errorMessage";
}
else if (c.Session["successMessage"] != null)
{
messageType = "successMessage";
}
if (!string.IsNullOrEmpty(messageType))
{
string[] messageBody = c.Session[messageType].ToString().Split('|');
StringBuilder userMessageSb = new StringBuilder();
userMessageSb.Append(string.Format("<div id=\"{0}\" title=\"{1}\">{2}</div>", messageType, messageBody[0], messageBody[1]));
// fix so message will not re-appear
c.Session.Remove(messageType);
messageType = userMessageSb.ToString();
}
return messageType;
}
public static void setSuccess(string successMessage)
{
HttpContext.Current.Session["successMessage"] = setMessage("success", successMessage);
}
public static void setError(string errorMessage)
{
HttpContext.Current.Session["errorMessage"] = setMessage("error", errorMessage);
}
private static string setMessage(string messageTitle, string messageBody)
{
return string.Format("{0}|{1}", messageTitle, messageBody);
}
i set message like this prior to redirect or return
Errors.setError(my error is");
i get error on bottom of my masterpage like this
<%= Errors.getMessage() %>
and this is JS
$(function () {
$("#errorMessage").dialog("destroy");
$("#successMessage").dialog("destroy");
if ($("#errorMessage").length != 0) {
$("#errorMessage").dialog({
modal: true,
height: 300,
width: 400,
buttons: {
Ok: function () {
$(this).dialog('close');
}
}
});
}
if ($("#successMessage").length != 0) {
$("#successMessage").dialog({
modal: true,
height: 300,
width: 400,
buttons: {
Ok: function () {
$(this).dialog('close');
}
}
});
}
});
There is a possibility that <%= Errors.getMessage() %> executes before you call Errors.setError(my error is") in case when you are not redirecting.
Hope below answer helps.
Create a property in your master page code behind
public string MessagePlaceholder
{
get { return messagePlaceholder.InnerHtml; }
set { messagePlaceholder.InnerHtml = value; }
}
Replace <%= Errors.getMessage() %> with a div place holder like below
<div id="messagePlaceholder" runat="server"></div>
And here is your setError method
public static void setError(string errorMessage, bool redirecting)
{
HttpContext.Current.Session["errorMessage"] = setMessage("error", errorMessage);
if (!redirecting)
{
((HttpContext.Current.Handler as System.Web.UI.Page).Master as YourMasterPageType).MessagePlaceholder = getMessage();
}
}
EDIT
Sorry I forgot this
In Page_Load event of your master page
if(!IsPostBack)
{
messagePlaceholder.InnerHtml = Errors.getMessage();
}
I know this is a dumb question. For some reason my mind is blank on this. Any ideas?
Sorry should have been more clear.
Using a HtmlGenericControl to pull in link description as well as image.
private void InternalCreateChildControls()
{
if (this.DataItem != null && this.Relationships.Count > 0)
{
HtmlGenericControl fieldset = new HtmlGenericControl("fieldset");
this.Controls.Add(fieldset);
HtmlGenericControl legend = new HtmlGenericControl("legend");
legend.InnerText = this.Caption;
fieldset.Controls.Add(legend);
HtmlGenericControl listControl = new HtmlGenericControl("ul");
fieldset.Controls.Add(listControl);
for (int i = 0; i < this.Relationships.Count; i++)
{
CatalogRelationshipsDataSet.CatalogRelationship relationship =
this.Relationships[i];
HtmlGenericControl listItem = new HtmlGenericControl("li");
listControl.Controls.Add(listItem);
RelatedItemsContainer container = new RelatedItemsContainer(relationship);
listItem.Controls.Add(container);
Image Image = new Image();
Image.ImageUrl = relationship.DisplayName;
LinkButton link = new LinkButton();
link.Text = relationship.DisplayName;
///ToDO Add Image or Image and description
link.CommandName = "Redirect";
container.Controls.Add(link);
}
}
}
Not asking anyone to do this for me just a reference or an idea.
Thanks -overly frustrated and feeling humbled.
I'm assuming you want to generate an image dynamicly based upon an url.
What I typically do is a create a very lightweight HTTPHandler to serve the images:
using System;
using System.Web;
namespace Example
{
public class GetImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString("id") != null)
{
// Code that uses System.Drawing to construct the image
// ...
context.Response.ContentType = "image/pjpeg";
context.Response.BinaryWrite(Image);
context.Response.End();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
You can reference this directly in your img tag:
<img src="GetImage.ashx?id=111"/>
Or, you could even create a server control that does it for you:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Example.WebControl
{
[ToolboxData("<{0}:DynamicImageCreator runat=server></{0}:DynamicImageCreator>")]
public class DynamicImageCreator : Control
{
public int Id
{
get
{
if (ViewState["Id" + this.ID] == null)
return 0;
else
return ViewState["Id"];
}
set
{
ViewState["Id" + this.ID] = value;
}
}
protected override void RenderContents(HtmlTextWriter output)
{
output.Write("<img src='getImage.ashx?id=" + this.Id + "'/>");
base.RenderContents(output);
}
}
}
This could be used like
<cc:DDynamicImageCreator id="db1" Id="123" runat="server/>
Check out the new DynamicImage control released in CodePlex by the ASP.NET team.
This is kind of a horrible question. I mean, .NET has an image control where you can set the source to anything you want. I'm not sure what you're wanting to be discussed.