I'm working with a Visual WebPart and I want to upload a image from my FileUpload control to a SharePoint list. This is the code I'm using but I can't get it to work, (Title, prodnum, color, etc is working, but not image). I've also installed SparQube.
This is my ListView:
.
protected void Button_Save_Click(object sender, EventArgs e)
{
SPSite currentSite = SPContext.Current.Site;
SPList myList = currentSite.RootWeb.Lists.TryGetList("SharePointDatabase");
try
{
if (myList != null && FileUpload_Pic.PostedFile != null && FileUpload_Pic.HasFile)
{
SPListItem listItem = myList.Items.Add();
listItem["Title"] = TextBox_Name.Text;
listItem["ProductNumber"] = TextBox_ProdNum.Text;
listItem["Color"] = TextBox_Color.Text;
listItem["ListPrice"] = TextBox_ListPrice.Text;
listItem["MoreInformation"] = TextBox_MoreInfo.Text;
string fileName = Path.GetFileName(FileUpload_Pic.PostedFile.FileName);
listItem["Image"] = fileName;
listItem.Update();
TextBox_Search.Text = string.Empty;
TextBox_Name.Text = string.Empty;
TextBox_MoreInfo.Text = string.Empty;
TextBox_ProdNum.Text = string.Empty;
TextBox_Color.Text = string.Empty;
TextBox_ListPrice.Text = string.Empty;
Label_Exception.Text = "Saved to Database list.";
Dispose();
}
}
catch (Exception x)
{
Label_Exception.Text = x.Message;
}
}
You can add file as stream directly from File Upload to specific web using following method and then add the file path to the list as shown in below example,
SPContext.Current.Web.Files.Add(String.Concat(SPContext.Current.Web.Site.RootWeb.Url, path), stream, true);
path is relative path for the image. in user case file name.
stream can get using FileUpload.FileContent in file upload control
Then add this path to the list as below.
listItem["Image"] = path;
This is work for all the browsers.
Are you sure the SPList has Atachment Upload enabled?
I had made the expierience that the normal ribbon button isn't greyed out although the list is not able to hold itemattachments.
SPList list = new SPList(); // Sample
list.EnableAttachments = false; //set
bool attachmentsAllowed = list.EnableAttachments; //get
What Type of field is "Image"? It's not the attachments folder...
An other way to save your Image is to upload it to a library and use a "Hyperlink" field.
Use this as help: http://www.sharepoint-tips.com/2007/10/code-practices-gettingsetting-values.html
Check out this question: https://sharepoint.stackexchange.com/questions/49481/exception-when-adding-attachment/49485
There are some problems, when you are using FileUpload control in standard edit/add pages.
Related
I have an app in which the user needs to access certain files in a user set and selected folder.
The folder and files paths need to be easily accessed (short simple path).
I use the Properties Settings to hold the Folder and File paths, but for some reason each time I re-start the program the Folder and File paths are lost.
I have followed and checked the program and all seems to be OK (except something I am missing, apparently).
I attach here the program snippet in two parts: The search for path and the setting in case path / file not found. (removed exception handling to save on lines)
public Main() //part of Main, stripped off exception handling)
{
//..........
dataFolder = Properties.Settings.Default.dataFolder;
if (!Directory.Exists(dataFolder))
{
SetDataFolder();
}
configFile = Properties.Settings.Default.configFile;
if (!File.Exists(configFile))
{
SetConfigFile();
}
dataFile = Properties.Settings.Default.dataFile;
if (!File.Exists(dataFile))
{
SetDataFile();
}
loadParamsFromFile(configFile); //Load the previously saved controls.
public String SetDataFolder()
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
DialogResult folder = dialog.ShowDialog();
if (folder == DialogResult.OK)
{
dataFolder = dialog.SelectedPath;
Directory.CreateDirectory(dataFolder);
dataFolder = Path.GetFullPath(dataFolder);
Properties.Settings.Default.dataFolder = dataFolder;
Properties.Settings.Default.Save();
return dataFolder;
}
else return null;
}
private string SetDataFile()
{
dataFile = $"{dataFolder}\\{textBoxSampleID.Text.Replace("/r", "").Trim()}.txt";
File.Create(dataFile).Close();
Properties.Settings.Default.dataFile = dataFile;
Properties.Settings.Default.Save();
return dataFile;
}
private string SetConfigFile()
{
configFile = $"{dataFolder}\\electroplating.cfg";
File.Create(configFile).Close();
Properties.Settings.Default.configFile = configFile;
Properties.Settings.Default.Save();
return configFile;
}
Check out this question:
How to change application settings (Settings) while app is open?
I would suggest using Path.Combine() for the construction of the file paths.
If it still doesn't work, you could also try using the registry for storing the values.
string dataFilePath = Path.Combine(dataFolder, textBoxSampleID.Text.Replace("/r", "").Trim());
RegistryKey key = Registry.LocalMachine.CreateSubKey(#"SOFTWARE\Company");
if (key != null)
{
key.SetValue("dataFilePath", dataFilePath);
}
You could then use string dataFilePath = (string)key.GetValue("dataFilePath") to get the value out of the registry.
I am trying to create a torrent file with monotorrent package using C#.
I already created the torrent file with the torrent creator but I want to add some other options that I can't find in the torrent creator methods or properties.
Options that I am looking for :
adding tracking url(S),
Web seed URL(S),
Source,
Optimize alignment.
Here is a snippet of my code:
string filepath = ofd.FileName;
PathDirectoryTxt.Text = filepath;
MonoTorrent.Common.TorrentCreator torrentcreaotr = new MonoTorrent.Common.TorrentCreator();
ITorrentFileSource fileSource = new TorrentFileSource(filepath);
torrentcreaotr.Comment = CommentsRichTxt.Text;
torrentcreaotr.CreatedBy = "Google using " + VersionInfo.ClientVersion;
torrentcreaotr.Publisher = "www.itsitus.com";
if ((PrivateTorrentCheckbox.Checked))
{
torrentcreaotr.Private = true;
}
else if (!PrivateTorrentCheckbox.Checked)
{
torrentcreaotr.Private = false;
}
string savepath = sfd.FileName;
torrentcreaotr.Create(fileSource, savepath);
MessageBox.Show("torrent file has been created successfully !");
Have you tried setting the 'Announce' property with the URL for your tracker, or setting the 'Announces' if you have tracker tiers/fallbacks? Similarly, Webseeds are set using the GetrightHttpSeed property.
Well, I'm making a simple winform to create a text file containing paths to various songs. It's just a simplistic playlist for a visualizer/audio player that I've been working on (using XNA, C#, and Bass.Net). I'd like to use TagLib access and display song titles, artists, and to sort playlists.
This is the code that I've been using:
private void button1_Click(object sender, EventArgs e)
{
selectPlaylist.ShowDialog();
string filePath = string.Empty;
if (selectPlaylist.FileName.EndsWith(".txt"))
{
StreamReader fInput = new StreamReader(selectPlaylist.FileName);
playlistName = fInput.ReadLine();
playlistNameTextBox.Text = playlistName;
while (!fInput.EndOfStream)
{
filePath = fInput.ReadLine();
if (!filePath.Contains(":\\")) continue;
songInfo.Add(TagLib.File.Create(filePath).Tag); //List<TagLib.Tag>
songs.Add(filePath); //List<string>
}
songNamesComboBox.DataSource = songs;
fInput.Close();
fInput = null; //don't even know if I need this
}
}
Regardless of what files I use, all of the Tag properties/attributes are empty. I created a console application and did the same thing (creating a file and saving its Tag to a variable) and was able to correctly access tag information.
TagLib.Tag tag = TabLib.File.Create("D:\\Music\\Electronic Music\\" +
"Instrumental Core\\The Angels Among Demons.mp3").Tag;
Console.WriteLine(tag.Title);
I'm a bit new to C#, but I cannot figure what I've done wrong. Why would the latter (console application) work, but not my winform?
so I have a script that essentially iterates through a bunch of delimited text files and uploads the images from said files to a SharePoint site. It works great, expect with one minor problem, I have a couple of images that are >4MB in size and these give me a (400) Bad Request error when the script attempts to upload them.
Code below:
class spImageUpload()
{
private static System.Collections.Generic.List<string> keywords;
private static NetworkCredential credentials = new NetworkCredential(username, password, domain);
private static ClientContext clientContext = new ClientContext(site name);
private static Web site = clientContext.Web;
private static List list = site.Lists.GetByTitle(listName);
private static FileCreationInformation newFile = new FileCreationInformation();
private static Image image = new Image();
private static FileIO fo = new FileIO();
public SharePointAccess()
{
sharepointLogin();
uploadImage();
}
private static void updateFields()
{
//Loads the site list
clientContext.Load(list);
//Creates a ListItemCollection object from list
ListItemCollection listItems = list.GetItems(CamlQuery.CreateAllItemsQuery());
//Loads the listItems
clientContext.Load(listItems);
//Executes the previous queries on the server
clientContext.ExecuteQuery();
//For each listItem...
foreach (var listItem in listItems)
{
//Writes out the item ID and Title
//Console.WriteLine("Id: {0} Title: {1}", listItem.Id, listItem["Title"]);
//Loads the files from the listItem
clientContext.Load(listItem.File);
//Executes the previous query
clientContext.ExecuteQuery();
//Writes out the listItem File Name
//Console.WriteLine("listItem File Name: {0}", listItem.File.Name);
//Looks for the most recently uploaded file, if found...
if (listItem.File.Name.Contains(fileName))
{
title = fileName;
//Changes the Title field value
listItem["Title"] = title;
//Changes the Keywords field value using the keywords list
foreach (var keyword in keywords)
{
listItem["Keywords"] += keyword;
//Writes out the item ID, Title, and Keywords
//Console.WriteLine("Id: {0} Title: {1} Keywords: {2}", listItem.Id, listItem["Title"], listItem["Keywords"]);
}
}
//Remember changes...
listItem.Update();
}
//Executes the previous query and ensures changes are committed to the server
clientContext.ExecuteQuery();
}
private static void uploadImage()
{
try
{
fo.loadFile();
foreach (var img in fo.lImageSet)
{
Console.WriteLine("Image Name: {0}", img.getName());
}
foreach (var img in fo.lImageSet)
{
DateTime start;
DateTime end;
start = DateTime.Now;
//Sets file path equal to the path value stored in the current image of lImageSet
filePath = img.getPath();
//Writes out to the console indicating what's been stored in filePath
Console.WriteLine("Image Path: {0}", filePath);
//Reads in the contents of the file
newFile.Content = System.IO.File.ReadAllBytes(filePath);
//Sets the file name equal to the name value stored in the current image of lImageSet
fileName = img.getName() + ".jpeg";
//Sets the URL path for the file
newFile.Url = fileName;
//Creates a List object of type String
keywords = new System.Collections.Generic.List<string>();
//For each keyword in the current image stored in lImageSet...
foreach (var keyword in img.lTags)
{
//...add that keyword to the newly created list
keywords.Add(keyword);
}
//Uploads the file to the picture library
Microsoft.SharePoint.Client.File uploadFile = list.RootFolder.Files.Add(newFile);
//Loads uploadFile method
clientContext.Load(uploadFile);
//Executes previous query
clientContext.ExecuteQuery();
//Calls the updateFields method to update the associated fields of the most recently uploaded image
updateFields();
end = DateTime.Now;
TimeSpan span = end.Subtract(start);
//Writes out to the console to indicate the file has finished being uploaded
Console.WriteLine("Uploaded: {0}", fileName + " Done!");
Console.WriteLine("Time Elapsed: {0}", span.Seconds + "seconds");
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void sharepointLogin()
{
try
{
//Loads credentials needed for authentication
clientContext.Credentials = credentials;
//Loads the site
clientContext.Load(site);
//Loads the site list
clientContext.Load(list);
//Executes the previous queries on the server
clientContext.ExecuteQuery();
//Writes out the title of the SharePoint site to the console
Console.WriteLine("Title: {0}", site.Title);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
Right now, I have to do everything remotely using the client-object model. I can't use SharePoint.Administration to change the max upload size. So does anyone know how, using the client-object model I can get past this problem of not being able to upload files greater than 4MB? Thank you in advance for any help!
This is because of the WCF limit for the client object model. You need to run this on the server from a SharePoint management shell with admin rights:
SPWebService contentService = SPWebService.ContentService;
contentService.ClientRequestServiceSettings.MaxReceivedMessageSize = int.MaxValue; // 2GB
contentService.Update();
More info here
Try to use the SaveBinaryDirect method. The SaveBinaryDirect method use Web Based Distributed Authoring and Versioning (WebDAV) for uploading and downloading files. Without building your own custom WCF service, WebDAV
is the most efficient way to upload and download files.
using (FileStream lp_fs = new FileStream(is_FileToImport, FileMode.OpenOrCreate))
{
Microsoft.SharePoint.Client.File.SaveBinaryDirect(lp_context, lp_uri.LocalPath, lp_fs, true);
}
Microsoft.SharePoint.Client.File lp_newFile = lp_web.GetFileByServerRelativeUrl(lp_uri.LocalPath);
lp_context.Load(lp_newFile);
lp_context.ExecuteQuery();
//check out to make sure not to create multiple versions
lp_newFile.CheckOut();
ListItem lp_item = lp_newFile.ListItemAllFields;
listItem["Created"] = info.SourceFile.CreationTime;
listItem["Modified"] = info.SourceFile.LastWriteTime;
listItem.Update();
// use OverwriteCheckIn type to make sure not to create multiple versions
lp_newFile.CheckIn(string.Empty, CheckinType.OverwriteCheckIn);
I need to upload a file in a website using watin. The problem is that setting the direction of the file, like this:
browser.FileUpload(Find.ById("ctl00_cpContent_FileUpload1")).Set(DIRECCION_XML + "plantilla.txt");
doesnt work. Because this, I need to handle the windows popup that appear and fill the direction of the file to upload. I dont know how to do it... I were searching info of FileUploadHandler, but i cant get it.
There is more option than that? Pls, help me with a possible code to do it.
Really thanks
The FileUploadHandler works great. I have it running in production mode with thousands of files being uploaded every day and I haven't had any issues with it so far.
This is the way it needs to be implemented:
EDIT: (I forgot to include the uploadDialog object)
IntPtr hwndTmp = (IntPtr)FindWindow("#32770","Select file(s) to upload"); // or whatever the window text says when you are opening that upload window)
Window uploadDialog = new Window(hwndTmp);
UploadFileDialogHandler uploadFile = new UploadFileDialogHandler(_toBeSent.FileToSent);
_browser.AddDialogHandler(uploadFile);
uploadFile.HandleDialog(uploadDialog);
uploadFile = null;
That will take care of the upload process. when you need to upload the file just those lines will take care of everything (loop thru all open dialogs, find the right one, find the text field, enter the name for you and click the Ok button. On top of that you need to create another class that will be the UploadFileDialogHandler:
public class UploadFileDialogHandler : BaseDialogHandler
{
private const int WmSettext = 0x000C;
private string fileName;
private bool _processed = false;
public override bool HandleDialog(Window window)
{
var button = GetOpenButton(window);
if (button != null)
{
if (_processed == false)
{
var fileNameHandle = NativeMethods.GetChildWindowHwnd(window.Hwnd, "Edit");
var fileNameHwnd = new Hwnd(fileNameHandle);
fileNameHwnd.SetFocus();
_processed = true;
//MessageBox.Show("About to send " + fileName);
fileNameHwnd.SendString(fileName);
button.Click();
}
return true;
}
else
{
return false;
}
}
public UploadFileDialogHandler(string file)
{
fileName = "";
fileName = file;
//MessageBox.Show("Setting filename: " + fileName);
}
public override bool CanHandleDialog(Window window)
{
return GetOpenButton(window) != null;
}
private WinButton GetOpenButton(Window window)
{
var windowButton = new WindowsEnumerator().GetChildWindows(window.Hwnd, w => w.ClassName == "Button" && new WinButton(w.Hwnd).Title == "&Open").FirstOrDefault();
if (windowButton == null)
return null;
else
return new WinButton(windowButton.Hwnd);
}
}
}
You can just copy and paste that class inside your program and with the 4 lines of code above it will take care of the rest for you. In case you need more information there's a good amount of information on the WatIn file source code but it could be a little bit challenging to follow if you don't understand the Windows API.
Hope this helps.
This command work for me fine: browser.FileUpload(Find.ById("FormImage")).Set("C:\\Pictures\\11.PNG");
Try it