server-side file upload not saving my file - asp.net

on the server side, I've got these:
ASPX:
<form id="form1" runat="server" enctype="multipart/form-data">
<input type="file" id="myFile" name="myFile" />
<asp:Button runat="server" ID="btnUpload" OnClick="btnUploadClick" Text="Upload" />
</form>
CS:
protected void btnUploadClick(object sender, EventArgs e)
{
HttpPostedFile file = Request.Files["myFile"];
if (file != null && file.ContentLength > 0)
{
string fname = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath(Path.Combine("~/Files/", fname)));
}
}
Client Side app: it uses WebClient but I didn't think this was needed for any solution since webclient is pretty simple and straight forward. Anyways, here's the code
private void btnStart_Click(object sender, RoutedEventArgs e)
{
Uri uploadAddress = new Uri("http://localhost/WebUpload/default.aspx");
WebClient wc = new WebClient();
wc.UploadProgressChanged += new UploadProgressChangedEventHandler(wc_UploadProgressChanged);
wc.UploadFileCompleted += new UploadFileCompletedEventHandler(wc_UploadFileCompleted);
wc.Credentials = CredentialCache.DefaultCredentials;
wc.UploadFile(uploadAddress, "POST", m_filename);
}
void wc_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
{
if (e.Error != null)
txtProgress.Content = e.Error.Message;
else
txtProgress.Content = "Completed";
}
void wc_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
txtProgress.Content = String.Format("{0}% completed",
e.ProgressPercentage);
}
as for the client app: it's a simple webclient using uploadfileasync via HTTP POST to the aspx page.
Question: files gets saved normally using the aspx page but for the client app, the file gets uploaded and but doesn't get saved on the folder. What might be happening? I'm pretty sure this is a server side problem.
Update: added the client side code. The client app works on another (but asp classic) server so I'm doubting that the client is the one that needs fixing.

Reposting my comment since Jan never posted an answer.
Thanks to Jan for pointing me to the right direction. The file receiving code should have been in the page_load, that was careless of me. Another problem was the string name of the index of the file (Request.Files["myFile"]) which should be of the same id as the input control in the aspx page.

Related

How to do ASP.net website in english and Arabic

I can do the multilingual website in asp.net when language is similar ( dir=ltr for example English, Spanish, French). I would like to know how to do the same when one language dir=ltr (English) and other language dir=rtl (Arabic).
I would appreciate if some one can link to a resource which can show how to do this step by step as along with themes one for English and other for Arabic..
I am using ASP.Net 4.0 .
I would appreciate any help in this area and if someone can provide me with a two page example that would be great.
you can try like this ...
It is easy to develop multi language supported web site using ASP.NET . Just follw that step by step.
1.Take a new web site
2.Add “App_GlobalResources” from ASP.NET folders
3.Take a *.resx file (Strings.resx)
4.Enter Name and values
5.Make different *.resx file for different languages and name like that Strings.en-US.resx (for US english), Strings.fr-FR.resx (for
French). Make as many language file you needed
6.Now time for calling and using language from web page You website Solution Explorer will look like below image...
Default.aspx file will look like that
<asp:Label ID=”lblName” runat=”server” Text=”Label”></asp:Label>
<asp:Label ID=”lblDesc” runat=”server” Text=”Label”></asp:Label>
<asp:Label ID=”lblComments” runat=”server” Text=”Label”></asp:Label>
<asp:LinkButton ID=”lnkEnglish” runat=”server” OnClick=”lnkEnglish_Click”>English</asp:LinkButton>
<asp:LinkButton ID=”lnkFrench” runat=”server” OnClick=”lnkFrench_Click”>French</asp:LinkButton>
Codes of Default.aspx.cs
private ResourceManager rm;
protected void Page_Load(object sender, EventArgs e)
{
CultureInfo ci;
if (!IsPostBack)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo(“en-US”);
rm = new ResourceManager(“Resources.Strings”, Assembly.Load(“App_GlobalResources”));
ci = Thread.CurrentThread.CurrentCulture;LoadData(ci);
}
else
{
rm = new ResourceManager(“Resources.Strings”,Assembly.Load(“App_GlobalResources”));
ci = Thread.CurrentThread.CurrentCulture;LoadData(ci);
}
}
protected void lnkEnglish_Click(object sender, EventArgs e)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo(“en-US”);
LoadData(Thread.CurrentThread.CurrentCulture);
}
protected void lnkFrench_Click(object sender, EventArgs e)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo(“fr-FR”);
LoadData(Thread.CurrentThread.CurrentCulture);
}
public void LoadData(CultureInfo ci)
{
lblName.Text = rm.GetString(“EventName”, ci);
lblDesc.Text = rm.GetString(“EventDescription”, ci);
lblComments.Text = rm.GetString(“EventComments”,ci);
}

How to indicate create user control if user already exists

I am using Create User control with my own sql server database, I am not sure what event is there which can indicate the create user control to show its Duplicate UserName Error Message if there is an existing Username or email.
Please let me know.
thanks,
If you were using aspnet membership then CreateUser Control would have done the work itself. But from your question I guess you are not using so. In this case you will have to use logic to check for existing username. You can use Custom Validator and create a server side validation with it.
Example:
.aspx
<asp:TextBox ID="txtUserName" runat="server" MaxLength="150"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" OnServerValidate="CustomValidator1_ServerValidate"
ControlToValidate="txtUserName" Display="Dynamic"
ErrorMessage="UserName Already Exists"
ToolTip="Please select a different UserName" ValidationGroup="Register">
</asp:CustomValidator>
The code behind can have:
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
SqlCommand objcmd = new SqlCommand("Select * from Login_Table where UserName='" + args.Value + "'",con);
SqlDataReader objReader;
con.Open();
objReader = objcmd.ExecuteReader();
if (objReader.HasRows)
{
args.IsValid = false;
}
else {
args.IsValid = true;
}
con.Close();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
{
return;
}
// your registration code
}
Remember to keep the submit button under the same Validation Group as the Custom Validator i.e. "Register" in this case. You can have the control inside ajax update panel further. Hope this helps :)

Best way to inject HTML into a page (server-side) in ASP.NET

I've got a HTTPHandler which returns a lump of HTML. What's the best way to inject this into a control on the server?
I've got it mostly working by using an asp:literal and using WebClient.downloadString() to grab the text from the handler
<asp:Literal runat="server" ID="Text_Page1" Visible="false"></asp:Literal>
<asp:Literal runat="server" ID="Text_Page2" Visible="false"></asp:Literal>
and then in the server-side methods:
Text_Page1.Text = new WebClient().DownloadString("http://localhost:666/" +sPage1URL);
Text_Page2.Text = new WebClient().DownloadString("http://localhost:666/" +sPage2URL);
The hardcoded web-address is just there for testing at the moment. Previously I tried just using "~/" +URL to try and build it up but the WebClient library threw an exception saying that the URL was too long (which is not true I don't think)
Any ideas on the best way to do this from the server-side?
Edit : When I say "Best" I mean most efficient and adhering to "best practices". My method doesn't work so well when it's put onto an authenticated IIS. I'm having trouble authenticating. I thought that doing
WebClient oClient = new WebClient();
oClient.Credentials = CredentialCache.DefaultCredentials;
oClient.UseDefaultCredentials = true;
String sData = oClient.DownloadString(sURL);
would work but i get a 401 error. Does anybody have any alternatives?
Cheers
Gordon
Without asking any questions about the reasoning behind fetching html via a webrequest from the same application serving the contents of the include, i would wrap the functionality in a WebUserControl. Something along the lines of:
using System;
using System.Net;
using System.Web.UI;
public partial class HtmlFetcher : UserControl
{
//configure this somewhere else in the real world, web.config maybe
private const string ServiceUrl = "http://localhost:666/";
public string HtmlPath { get; set; }
protected override void Render(HtmlTextWriter output)
{
string outputText = String.Empty;
try
{
outputText = new WebClient().DownloadString(string.Format("{0}{1}", ServiceUrl, HtmlPath));
} catch (Exception e)
{
//Handle that error;
}
output.Write(outputText);
}
}
This is how you would add it to your page:
<%# Register src="HtmlFetcher.ascx" tagname="HtmlFetcher" tagprefix="uc1" %>
<uc1:HtmlFetcher ID="HtmlFetcher1" HtmlPath="some-test-file.html" runat="server" />
you will get the data in the string lcHtml then use it as you want
// *** Establish the request
string lcUrl = "http://yourURL";
HttpWebRequest loHttp =
(HttpWebRequest) WebRequest.Create(lcUrl);
// *** Set properties
loHttp.Timeout = 10000; // 10 secs
loHttp.UserAgent = "Code Sample Web Client";
// *** Retrieve request info headers
HttpWebResponse loWebResponse = (HttpWebResponse) loHttp.GetResponse();
Encoding enc = Encoding.GetEncoding(1252); // Windows default Code Page
StreamReader loResponseStream =
new StreamReader(loWebResponse.GetResponseStream(),enc);
string lcHtml = loResponseStream.ReadToEnd();
loWebResponse.Close();
loResponseStream.Close();
You can use server side code blocks into your aspx with <% %>.
Try this:
<% new WebClient().DownloadString("http://localhost:666/" +sPage1URL) %>

cannot modify asp login in page_load or page_init

So I have an asp:Login field on my login page.
However, I want to use a path for the create account url and the forgot password url. So I have to do it in Page_Load or maybe Page_Init. Regardless, neither option works, it simply refuses to modify the login form.
protected void Page_Load(object sender, EventArgs e)
{
string accountpath = Request.Url.AbsoluteUri + "/user/RequestAccount.aspx";
string forgotpath = Request.Url.AbsoluteUri + "/user/ForgotPassword.aspx";
lgnMain.CreateUserUrl = accountpath;
lgnMain.PasswordRecoveryUrl = forgotpath;
lgnMain.InstructionText = "test";
lgnMain.Focus();
}
protected void Page_Init(object sender, EventArgs e)
{
string accountpath = Request.Url.AbsoluteUri + "/user/RequestAccount.aspx";
string forgotpath = Request.Url.AbsoluteUri + "/user/ForgotPassword.aspx";
lgnMain.CreateUserUrl = accountpath;
lgnMain.UserName = "test";
lgnMain.InstructionText = "test";
lgnMain.PasswordRecoveryUrl = forgotpath;
}
The CreateUserUrl and the PasswordRecoveryUrl are ignored if you haven't set the CreateUserText and PasswordRecoveryText properties respectively. Since the Text properties probably don't need to be dynamic, just set them in the ASPX (although you could still set them in the code behind if required), and then the dynamic setting of the URL properties (in the Page_Load event) should work without problem.
Documentation here: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.login_members(v=vs.85).aspx
From the Documentation above:
If the CreateUserText property is
empty, the link to the registration
page is unavailable to the user.
If the PasswordRecoveryText property
is empty, the link to the password
recovery page is not available to the
user.
have you tried setting it in the markup?
<asp:Login id="lgnMain" runat="server"
CreateUserText="Register"
CreateUserUrl="~/user/RequestAccount.aspx"
PasswordRecoveryText = "Forgot Password"
PasswordRecoveryUrl = "~/user/ForgotPassword.aspx" >
</asp:Login>

ASP.NET Web Page Not Available

It's pretty difficult to show code for ASP.NET here, so I will try my best to describe my problem.
I have a FileUploadControl and a Button that calls a function when it's clicked. It seems that the Button function works when there is nothing chosen for my FileUploadControl. However, when there is something chosen in the FileUploadControl (I have selected a file to upload), there is a problem when I click the button. It completely does not matter what the function does (it could just be writing to a label, even when it has nothing to do with the FileUploadControl). The error I get is:
This webpage is not available.
The webpage at http://localhost:2134/UploadMedia/Default.aspx might be temporarily down or it may have moved permanently to a new web address.
I have searched on Google, and people seem to have had problems with this, but different causes from me. They have said that their ASP.NET Development Server port is actually different from their port in the address bar. This is not the case for me.
Also, another problem people have had is with Use Dynamic Ports. I have tried both true and false. I have also tried different ports, and I have always gotten the same error.
This is really driving me crazy because it doesn't matter what the code in the buttonFunction is, it doesn't work as long as there is something in the FileUploadControl. If there is nothing, it seems to work fine.
Here is the code for the ASP.NET Controls:
<asp:FileUpload id="FileUploadControl" runat="server" />
<asp:Button runat="server" id="UploadButton" text="Upload" OnClick="uploadClicked" />
<br /><br />
<asp:Label runat="server" id="StatusLabel" text="Upload status: " />
And this is the code for the button function:
protected void uploadClicked(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
string filename = Path.GetFileName(FileUploadControl.FileName);
//Check if the entered username already exists in the database.
String sqlDupStmt = "Select songPath from Songs where songPath ='" + Server.MapPath("~/Uploads/") + filename + "'";
SqlConnection sqlDupConn = new SqlConnection(#"Data Source = .\SQLEXPRESS; AttachDbFilename = |DataDirectory|\Database.mdf; Integrated Security = True; User Instance = True;");
SqlCommand sqlDupCmd = new SqlCommand(sqlDupStmt, sqlDupConn);
sqlDupCmd.Connection.Open();
SqlDataReader sqlDupReader = sqlDupCmd.ExecuteReader(CommandBehavior.CloseConnection);
if (sqlDupReader.Read())
{
StatusLabel.Text = "Upload status: The file already exists.";
sqlDupReader.Close();
}
else
{
sqlDupReader.Close();
//See "How To Use DPAPI (Machine Store) from ASP.NET" for information about securely storing connection strings.
String sqlStmt = "Insert into Songs values (#songpath);";
SqlConnection sqlConn = new SqlConnection(#"Data Source = .\SQLEXPRESS; AttachDbFilename = |DataDirectory|\Database.mdf; Integrated Security = True; User Instance = True; uid=sa; pwd=password;");
SqlCommand cmd = new SqlCommand(sqlStmt, sqlConn);
SqlParameter sqlParam = null;
//Usage of Sql parameters also helps avoid SQL Injection attacks.
sqlParam = cmd.Parameters.Add("#userName", SqlDbType.VarChar, 150);
sqlParam.Value = Server.MapPath("~/Uploads/") + filename;
//Attempt to add the song to the database.
try
{
sqlConn.Open();
cmd.ExecuteNonQuery();
FileUploadControl.SaveAs(Server.MapPath("~/Uploads/") + filename);
songList.Items.Add(filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
finally
{
sqlConn.Close();
}
}
}
}
But this buttonfunction provides the same results:
protected void uploadClicked(object sender, EventArgs e)
{
StatusLabel.Text = "FooBar";
}
Has anyone had this problem before, or might know what the cause is?
Thanks!
My friend helped me figure it out. It was because ASP.NET only allowed uploads of 4MB sizes. I had to go into the web.config or the machine.config file and change the value of MaxRequestLength to be larger than 4096. This solved it.

Resources