fileupload control causing server error - c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
String fn = FileUpload1.FileName;
string fp = Server.MapPath("images");
if (fp.EndsWith("\\") == false)
{
fp = fp + "\\";
}
fp = fp + fn;
FileUpload1.PostedFile.SaveAs(fp);
}
}
on runnning this code, i receive the following error:
Server Error in '/WebSite11' Application
HTTP Error 400 - Bad Request.
Version Information:
ASP.NET Development Server 10.0.0.0

If the images folder is located at the root of your site then path should be this
string fp = Server.MapPath(~"/images");
and also try to run the site on a different brwose bcz few days ago i saw the same issue but when he rans the code on a different browse it works fine.
see the following post
HTTP Error 400 - Bad Request due to FileUpload control in vb.net

Related

C# Retrieve Document List From SharePoint 2013 Document Library

I want to make this really simple. I have a fresh, brand new asp.net C# web form with the code behind showing as below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
I have a SharePoint 2013 site with a document library that has a few documents in it with a few columns of metadata.
How do I make it show on the web page, a link to each document and the metadata from the columns for each document from the library. I'm super new to any work with integrating SharePoint and ASP.Net.
Please help.
Andy
Sharepoint has 3 APIs that you could use. Have a look here: https://msdn.microsoft.com/en-us/library/office/jj164060.aspx
You probably want to use the client.svc service via the CSOM Library (Microsoft.SharePoint.Client) just because it is the easiest to get up and running on. Don't use the older asmx api because it is deprecated. There's a third option - REST - but it doesn't provide all the functionality that CSOM does.
Here's some rough code showing the basics. There are a lot of nuances that aren't covered in the code (SharePoint is complicated) so you you'll also want to find some additional information online.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Client;
public partial class _Default : System.Web.UI.Page
{
protected string SiteUrl = "http://mysite.mydomain.com/site";
protected string LibraryName = "MyList";
protected void Page_Load(object sender, EventArgs e)
{
var context = new ClientContext(SiteUrl);
context.Load(context.Site);
context.ExecuteQuery();
var list = context.Web.Lists.GetByTitle(LibraryName);
if (list == null)
{
throw new ArgumentException(string.Format("List with name '{0}' not found on site '{1}'", LibraryName, SiteUrl));
}
context.Load(list, l => l.RootFolder.ServerRelativeUrl);
context.ExecuteQuery();
// Empty query. You probably want to filter on something so
// do a search on "CAML Query". Also watch out for SharePoint
// List View Threshold which limits # of items that can be retrieved
var camlQuery = #"<View Scope='All'><Query></Query></View>";
var items = list.GetItems(camlQuery);
context.Load(items, l => l.IncludeWithDefaultProperties(i => i.Folder, i => i.File, i => i.DisplayName));
context.ExecuteQuery();
// Url for first item
var url = SiteUrl + "/" + LibraryName + "/" + items[0]["Title"]
}
}

Can't get Request.QueryString or similar methods to work

To my shame, because I can barely C#, I cannot manage to read the parameters from the URL.
I run a C# cgi executable on my IIS 7 as an application. The url that calls the executable is as below:
https://server/cgi/showEmail/showEmail.exe?email=john#gmail.com
The code starts as below:
using System;
using System.Web; // <---- isn't this for Request.QueryString ?
using System.Web.UI;
using System.Collections;
using System.Collections.Specialized;
using System.Data.SqlClient;
class showEmail
{
static void Main(string[] args)
{
Console.WriteLine("\r\n\r\n");
Console.WriteLine("<h1>Test</h1>");
try
{
Now, if I use the code below, the program compiles, but gives this a null exception when executed in the browser:
string email = HttpContext.Current.Request.QueryString["email"];
System.NullReferenceException: Object reference not set to an instance of an object. at showEmail.Main(String[] args)
and if I use this code below, the fun stops already at the compiler, who gives a "current context" exception:
string email = Request.QueryString["email"];
error CS0103: The name 'Request' does not exist in the current context
...
Am I missing something elementary that is required for the executable to see the url parameters?
Edit: I have looked through sof and many other places, but so far have not been able to connect the dots on this issue.
HttpContext.Current.Request is not available in console appliaction.
Use args parameter to receive query string parameter, like I am doing below.
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine("parameter[{0}] is [{1}]", i, args[i]);
}
You might need to use below code to extract parameters from url received in args.
var url=args[0];
var queryString = url.Substring(url.IndexOf('?')).Split('#')[0]
System.Web.HttpUtility.ParseQueryString(queryString)
This is how I got it to work finally, please keep in mind this is not professionally validated code, more of try and try and try...
using System;
using System.Data;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string email = Request.QueryString["email"] ?? "null";
if (email != "null") {

Can any one tell me how to upload an image from asp.net to godaddy server

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
namespace GodaddyImages
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[] filePaths = Directory.GetFiles(Server.MapPath("~\\Images\\"));
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
string fileName = Path.GetFileName(filePath);
files.Add(new ListItem(fileName, "~\\Images\\" + fileName));
}
GridView1.DataSource = files;
GridView1.DataBind();
}
}
protected void Upload(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.PostedFile.SaveAs(Server.MapPath("~\\Images\\") + fileName);
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
}
Can any one tell me how to upload an image from asp.net to godaddy server.
I can upload images to local folders but found difficult in uploading into godaddy server
Typically in local system you will be having permissions to writing files(Images in this case). But when you are using server( or shared hosting) typically for security purposes they will give you read-only access to the folder that you deploy. But you can go ahead and still change the permissions of it when you are admin for that domain which you have hosted.The code required for uploading from asp.net is as straight forward as :
fileUpload.SaveAs(Server.MapPath("~/Images/") + fileUpload.FileName);
But, still for it work you need to have appropriate write permission for that particular folder.
Hope, it helps.

SQL Server CE database upgrade 3.5 to 4.0 C#

I'm totally new. I'm following a book and teaching my self C#. I'm reading one of the HEAD FIRST books. I just created a contact data base program. I made the SQL database placed it on a form did all the steps. And when I go to run the program I get this view source print?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void pictureBox1_Click(object sender, EventArgs e) {
MessageBox.Show("Contact List 1.0. \nWritten by: Greg Amero", "About");
}
private void peopleBindingNavigatorSaveItem_Click(object sender, EventArgs e) {
this.Validate();
this.peopleBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.contactDBDataSet);
}
private void Form1_Load(object sender, EventArgs e) {
// TODO: This line of code loads data into the 'contactDBDataSet.People' table. You can move, or remove it, as needed.
this.peopleTableAdapter.Fill(this.contactDBDataSet.People);
}
}
}
At the this.peopleTableAdapter.Fill(this.contactDBDataSet.People); I get an error msg saying
SqlCelnvaliddatabase format exception was unhandled.
The database file has been created by an earlier version of SQL Server Compact. Please upgrade using SqlCeEngine.Upgrade() method.
I get the above error using visual 2010
If I use Visual 2012 express it works fine and I'm thinking it has something to do with the SQL Server CE versions they run off of. I've installed SQL Server CE 3.5, 4.0 , etc but still not work.. Please help..
Greg
Use following code to upgrade SQL Server Compact version 3.5 files to 4.0.
public static void Upgrade(string fileName, string password)
{
if (String.IsNullOrEmpty(fileName) || password == null)
throw new Exception("Unable to create connection string because filename or password was not defined");
try
{
var connectionString = string.Format(#"Data source={0};Password={1}", fileName, password);
var engine = new SqlCeEngine(connectionString);
engine.Upgrade();
}
catch (Exception ex)
{
throw (ex);
}
}

Getting (The name 'file' does not exist in the current context) message

UPDATE 1:
Here is the full code behind from the downloaded example, unedited:
using System;
using System.IO;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String UpPath;
UpPath = "C:\\UploadedUserFiles";
if (!Directory.Exists(UpPath))
{
Directory.CreateDirectory("C:\\UploadedUserFiles\\");
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
HttpFileCollection uploads = HttpContext.Current.Request.Files;
for (int i = 0; i < uploads.Count; i++)
{
HttpPostedFile upload = file;
if (upload.ContentLength == 0)
continue;
string c = System.IO.Path.GetFileName(upload.FileName); // We don't need the path, just the name.
try
{
upload.SaveAs("C:\\UploadedUserFiles\\" + c);
Span1.InnerHtml = "Upload(s) Successful.";
}
catch(Exception Exp)
{
Span1.InnerHtml = "Upload(s) FAILED.";
}
}
}
}
ORIGINAL QUESTION:
I've just downloaded a "file uploading" example from www.asp.net:
Link to tutorial: http://www.asp.net/web-forms/videos/how-do-i/how-do-i-multiple-file-uploads-in-aspnet-2
Link to download: http://download.microsoft.com/download/8/6/9/869ff08a-1e39-4bab-a303-f7dcedc52427/CS-ASP-MultiFileUpload-CS.zip
and copied the files to my webserver after extracting them.
When I navigate to http://server/uploader/Default.aspx
It creates the folder in the servers c drive successfully, but on the web browser I get the following error:
Server Error in '/' Application.
--------------------------------------------------------------------------------
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0103: The name 'file' does not exist in the current context
Source Error:
Line 29: for (int i = 0; i < uploads.Count; i++)
Line 30: {
Line 31: HttpPostedFile upload = file;
Line 32:
Line 33: if (upload.ContentLength == 0)
Source File: c:\Inetpub\wwwroot\uploader\Default.aspx.cs Line: 31
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.3623; ASP.NET Version:2.0.50727.3618
Anyone know why this is happening?
You are addressing an undeclared local variable file, you should be retrieving the HttpPostedFile from the uploads "Items" collection using the Item index;
HttpPostedFile upload = uploads[i];
It seems a bug on the sample code. Try replacing this
HttpPostedFile upload = file
by
HttpPostedFile upload = uploads[i]
Along with "Default.aspx" and "Default.aspx.cs", you need "Default.aspx.Designer.cs" File.
As all the controls are defined with its style in "Designer" file.

Categories