Alert show when extension of FileUpLoads are not allowed - c#

I have a asp FileUpload control in my aspx page.
And the code behind to check file's extension and then insert them into database:
private string Write(HttpPostedFile file, string table)
{
string fileNameMain = Path.GetFileName(file.FileName);
// check for the valid file extension
string fileExtension = Path.GetExtension(fileNameMain).ToLower();
if (fileExtension.Equals(".pdf") || fileExtension.Equals(".doc"))
{
...insert fileupload into database
}
else
{
LabelError.Text = "Extension of files are not allowed.";
return null;
}
}
With the code above, it checks the extension and then show the message "Extension of files are not allowed." in a LabelError if the fileupload is not allowed.
Now, I'm required to do the "check-extension" in the other way: at the moment the client click and choose FileUpload, an alert show "Extension of files are not allowed.".
I need a way to make an alert show at the momment the FileUpload choosed in browser. Help!!!!

Hi but if you want an Alert (JavaScript) but first you need an postback action to execute code vb and the alert for example you could use a button to execute this method. You can show alert with this code
string script = "alert('Extension of files are not allowed');";
ScriptManager.RegisterStartupScript(this, typeof(Page), "alert", script , true);

Related

C# Unable to login with WebBrowser

I am newbie to C#. I need help to be able to login the webpage and read some data.
After googling, I tried to find below code and other resources but in all cases, I can only get the html source of the login page but not other pages source data.
I need to traverse to the homepage first.
Then, I need to traverse
to "Port Status" and read some useful data. To inform data is stored in the
frames. How can I read data from the frames ?
Adding more info
1) view-source:http://192.168.0.239/homepage.html, which calls script as shown below
getSubTree('Management');
2) The above call hits the content in java script file (http://192.168.0.239/frame.js)
case "Management":
str += OneNodeLink("lv1", "Switch Information", "/iss/specific/sysInfo.html?Gambit="+GAMBIT);
str += OneNodeLink("lv1", "Port Status", "/iss/specific/port_settings.html?Gambit="+GAMBIT);
document.getElementById("treeFrame").innerHTML = str;
3) The above code executes this file "view-source:http://192.168.0.239/iss/specific/port_settings.html?Gambit=pisfgagehesfhjikojngqcabdfkjeeffmpkhfckm" and gets "Port Status"
My requirement is to read the "Port Status" received which is from the frames data. Hope I am able to make it clear. Let me know if you need more info to help.
Link has screenshots and html source files : https://www.dropbox.com/sh/oml3tk75tf1lu5c/AADuGtbZci3gnyOQ2AE8IYwua?dl=0
Thanks a lot in advance
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WebBrowserWithoutAForm
{
class Program
{
private static bool completed = false;
private static WebBrowser wb;
[STAThread]
static void Main(string[] args)
{
wb = new WebBrowser();
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
string postData = string.Format("LoginPassword={0}&login=Login", "password");
ASCIIEncoding enc = new ASCIIEncoding();
wb.Navigate("http://192.168.0.239", "", enc.GetBytes(postData), "Content-Type: application/x-www-form-urlencoded\r\n");
//wb.Navigate("http://192.168.0.239");
while (!completed)
{
Application.DoEvents();
Thread.Sleep(100);
}
Console.Write("\n\nDone with it!\n\n");
Console.ReadLine();
}
static void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//Console.WriteLine(wb.Document.Body.InnerHtml);
completed = true;
Thread.Sleep(1000);
//*******HERE I NEED TO TRAVERSE TO THE HOME PAGE AND GET ITS SOURCE ******
wb.Navigate("http://192.168.0.239/homepage.html");
Console.WriteLine(wb.DocumentText);
}
}
}
I suggest you use selenium - my sample code of using Selenium to login facebook
I'm not gonna code for you but you could copy some part of my code though.
For the login page, I would do a GetElementById on the input for the login, and then set the value attribute. Then for the login button, if it's actually a button, I would trigger the click() event, otherwise if it is a form, then I would do a submit.
For port Status, you would again need to know the html of the home page and do a GetElementById on it and then trigger a click() event.
To put some code to these words it would look something like this:
var portStatus = this.webBrowser1.Document.GetElementById("portStatus");
portStatus.InvokeMember("click");
//this should give you access to DOM of the first frame on the page.
//if you have more than 1 then you will need to know which one.
var frameDoc= this.webBrowser1.Document.Window.Frames[0].Document;
//or
var frameDoc= this.webBrowser1.Document.Window.Frames["iframeid"].Document;;
var login = this.webBrowser1.Document.GetElementById("Login");
login.SetAttribute("Value", "password");
var loginButton = this.webBrowser1.Document.GetElementById("LoginButton");
loginButton.InvokeMember("click");
//or if the login button is a form then submit the form
HtmlElement form = webBrowser1.Document.GetElementById("FormID");
if (form != null)
form.InvokeMember("submit");
Since you didn't provide the HTML of the homepage, The Id's used here would have to be replaced by the actual Ids of the page. And you would replace "password" with whatever your actual password is here.
I hope this helps, if you need some explanation let me know.
Also see this for working with frames

How to exit from a method manually?

I have a query which returns a DataSet. After that I check whether records are available or not. If no records available I want to display error message, exit from the process and redirect to another page. Methods available in below the exiting method should not execute.
Here is the code I have so far.
ds = dba.loadEmpInfo(number, searchType, department);
string appNumber = "";
if (ds.Tables[0].Rows.Count > 0)
{
appNumber = ds.Tables[0].Rows[0]["Ref_no"].ToString();
workDS = dba.workExp(appNumber, searchType);
}
else
{
WebMsgBox.Show("No Record relevant to this app number are available");
}
If you want to show Alert message from code behind use below syntax,
ScriptManager.RegisterStartupScript(Control control, Type type,string key, string script,bool addScriptTags);
i.e, in the else part
{
ScriptManager.RegisterStartupScript(this, GetType(), "Alert",
"alert('No Record relevant to this app number are available!');", true);
// Now Re-direct to the next page as you wish
Response.Redirect("yourPage.aspx");
}

Add script block after workbook save in C#

I have the below code which will create an aspose excel file to pop up. I need a script block to execute from the javascript immediately after the download happens. The registerstartupscript is not firing in the below code.
what is wrong in this?
workbook.Save(HttpContext.Current.Response, "Template.xls", ContentDisposition.Attachment, new XlsSaveOptions(SaveFormat.Excel97To2003));
Page.RegisterStartupScript("alert", "<script>parent.downloadcomplete()</script>");
Use an instance of ClientScriptManager.
workbook.Save(HttpContext.Current.Response, "Template.xls", ContentDisposition.Attachment, new XlsSaveOptions(SaveFormat.Excel97To2003));
// Page.RegisterStartupScript("alert", "<script>parent.downloadcomplete()</script>");
ClientScriptManager cScript = Page.ClientScript;
if (!cScript.IsStartupScriptRegistered(this.GetType(), "alert"))
{
// Register if not done already
string javascriptCode = "<script type='text/javascript'> alert('Download complete'); </script>";
cScript.RegisterStartupScript(this.GetType(), "alert", javascriptCode);
}

Issue while changing the profile picture after deploying the code in server

I'm using twitter bootstrap. I'm changing the profile picture. I'm just saving the picture in a folder and retrieving it again. It works fine in local system but it is not working after deploying the code in the server. But picture is getting saved in the folder and not getting Changed in .aspx page. When i log out and log in again,its getting refreshed.
Here is my code :
<img runat="server" id="ImgPic" />
<input type="file" id="fileUpload" runat="server"/>
Change
<asp:Button ID="btnChangeUserPic" runat="server" OnClick="btnChangeUserPic_Click"
class="hidden" />
function ChangePicture(){
$('#btnChangeUserPic').click();
}
protected void btnChangeUserPic_Click(object sender, EventArgs e)
{
try
{
string filePath = Server.MapPath("~/Upload/Images/");
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
string file = fileUpload.PostedFile.FileName.ToLower();
HttpPostedFile hpfFile = fileUpload.PostedFile;
if (file != "")
{
string fileExtn = Path.GetExtension(hpfFile.FileName).ToLower();
if (fileExtn == ".jpg")
{
string filename = filePath +System.IO.Path.GetFileName(hpfFile.FileName);
if (File.Exists(filename))
{
File.Delete(filename);
}
hpfFile.SaveAs(filename);
ImgPic.src= filename;
}
}
}
catch (Exception ex)
{
}
}
The Picture should get updated in master page also.
Thank you all in advance for your response.
I'm not 100% sure what you mean by 'getting refreshed' but.. the filepath on your server is not going to be the same as on you local machine. Use Server.MapPath instead of a simple string;
http://msdn.microsoft.com/en-us/library/ms524632(v=vs.90).aspx
Also check you permissions to the folder and show us the code in whatever UI page that actually displays the picture, how is that getting set?
My guess (there's not enough info) is that ImgPic.src is holding the URL for the img tag. This would explain why it works locally but not on the server, because you've set
ImgPic.src= filename;
it should be set to the URL, not the mapped path.
If it's not that please post info on where the img is getting it's src set.

How to display Javascript alert instead of yellow-page error

I'm trying to restrict how large a file a user can upload on a particular page. I've done this using web.config like this:
<location path="SubSection/TestPage">
<system.web>
<httpRuntime maxRequestLength="2048" />
</system.web>
</location>
However, when this errors, it takes the user to one of those ASP.NET yellow-error pages. Now I know it is possible to create custom error pages, and I've looked into this, but they still involve redirecting the browser.
This is simply for trying inform the user that they are trying to upload a file that is too large, without navigating them away from the page they are currently on. Is it possible to prevent this TestPage from redirecting to the yellow-error page, and instead display a JavaScript popup of some kind?
I have tried to handle the error in the Application_Error() method in the global.asax file, but unfortunately it always seems to redirect after this method finishes, regardless of what I do in it. My attempts to display a JavaScript popup through this page were also not successful, although my understanding is that this is actually possible in the global.asax file, so I would assume I'm simply doing something wrong there.
This is my code for handling Application_Error(), based on the accepted answer from here, with the JavaScript part based on this.
void Application_Error(object sender, EventArgs e)
{
int TimedOutExceptionCode = -2147467259;
Exception mainEx;
Exception lastEx = Server.GetLastError();
HttpUnhandledException unhandledEx = lastEx as HttpUnhandledException;
if (unhandledEx != null && unhandledEx.ErrorCode == TimedOutExceptionCode)
{
mainEx = unhandledEx.InnerException;
}
else
mainEx = lastEx;
HttpException httpEx = mainEx as HttpException;
if (httpEx != null && httpEx.ErrorCode == TimedOutExceptionCode)
{
if(httpEx.StackTrace.Contains("GetEntireRawContent"))
{
System.Web.UI.Page myPage = (System.Web.UI.Page)HttpContext.Current.Handler;
myPage.RegisterStartupScript("alert","<script language=javascript>alert('The file you attempted to upload was too large. Please try another.');</script" + ">");
Server.ClearError();
}
}
}
Finally, I have also tried the following code in the user control itself (which is in VB.NET), based on the accepted answer from this:
Private Sub Page_Error(ByVal sender As Object, ByVal e As EventArgs)
Dim err As Exception = Server.GetLastError()
Dim cs As ClientScriptManager = Page.ClientScript
If (cs.IsStartupScriptRegistered(Me.GetType(), "testJS") = False)
Dim cstext1 As String = "alert('" & err.Message & "');"
cs.RegisterStartupScript(Me.GetType(), "testJS", cstext1, True)
End If
End Sub
Unfortunately, this code did not seem to get called at all.
To reiterate, this is just for handling, say, a simple user mistake in uploading a file that is slightly too large. I don't want to redirect and lose what else the user may have done on the original page, I just want to display a simple JavaScript alert box. Can this be done?
you can get the file size in java script like follow.
var fileSize = document.getElementById("myfileUploader").files[0].size; //gives size in bytes.
if(fileSize > 2097152) //2038Kb = 2038*1024 bytes
{
alert("File size exceded");
return false;
}
You can send the request using AJAX and handle an error response as an indication that the files are too large. For example, using jQuery:
$.ajax("/my/upload/action",
{
type: "POST",
data-type: "xml",
data: serializeFilesAsXML();
success: function() {
alert("Your files were uploaded!");
}
error: function(jqXHR, textStatus, errorThrown) {
if(errorThrown == "Files Too Large") {
alert("Your files were too large.");
} else {
alert("There was an error uploading your files. Please try again.");
}
}
}
);
You may need to rewrite your action for uploading files so that it responds to AJAX requests and can send appropriate failure messages.

Categories

Resources