I basically want to transfer a file from the client to the file storage server without actual login to the server so that the client cannot access the storage location on the server directly. I can do this only if i manually login to the storage server through windows login. I dont want to do that. This is a Web-Based Application.
Using the link below, I wrote a code for my application. I am not able to get it right though, Please refer the link and help me ot with it...
Uploading files to file server using webclient class
The following is my code:-
protected void Button1_Click(object sender, EventArgs e)
{
filePath = FileUpload1.FileName;
try
{
WebClient client = new WebClient();
NetworkCredential nc = new NetworkCredential(uName, password);
Uri addy = new Uri("\\\\192.168.1.3\\upload\\");
client.Credentials = nc;
byte[] arrReturn = client.UploadFile(addy, filePath);
Console.WriteLine(arrReturn.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
The following line doesn't execute...
byte[] arrReturn = client.UploadFile(addy, filePath);
This is the error I get:
An exception occurred during a
WebClient request
Ah, it seems (and with good reason), the FileUpload can only save files to the web server and its drives. So my first thought won't work.
But: if you have the necessary permissions, couldn't you just save the file that you get in the FileUpload to that UNC path using standard System.IO calls?? Something like :
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string completeFileName =
Path.Combine(#"\\192.168.1.3\upload", FileUpload1.FileName);
BinaryReader br = new BinaryReader(FileUpload1.PostedFile.InputStream);
FileStream fstm = new FileStream(completeFileName, FileMode.Create, FileAccess.ReadWrite);
BinaryWriter bw = new BinaryWriter(fstm);
byte[] buffer = br.ReadBytes(FileUpload1.PostedFile.ContentLength);
br.Close();
bw.Write(buffer);
bw.Flush();
bw.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
If you expect very large files to be uploaded, you might want to transfer the data from the BinaryReader to the BinaryWriter in chunks - instead of allocating just a single buffer - but that's just an implementation detail, really.
I had the same issue a few days ago, I solved it by creating a user on the Web server and on the storage server with the same user name and password, I then impersonated the user in the web.config file.
NB: The user should have RW permissions in the directory where you want to store the files.
Related
I am using below code in service file for auto downloading. It works in my system and our network drive, but when i installed it client pc not working but it download in all folders except server shared location.
try
{
filename = #"N:\Shared\tna related\tna (for processing)\TNA DATA\Timesuite\LOC" + filename + ".csv";
StreamWriter file = new StreamWriter(filename);
file.WriteLine(sb.ToString());
file.Close();
TraceImplogs.TraceLTService("Download Completed");
}
catch (Exception es)
{
TraceImplogs.TraceLTService("error 2"+es.Message);
}
Error Shows in client pc:
Could not find a part of the path 'N:\Shared\tna related\tna (for processing)\TNA DATA\DXB2018-05-12.csv'.
Hello in my app I download ".mp3" file into isolated storage and user should be able to listen this ".mp3" file but it seems i cant reach ".mp3" file in play click event
here is my code
private IsolatedStorageFile isoStore;
public mp3kuran()
{
InitializeComponent();
using ( isoStore= IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoStore.DirectoryExists("/shared/transfers"))
{
isoStore.CreateDirectory("/shared/transfers");
}
}
}
string link= "https://dl.dropboxusercontent.com/u/75638865/001.mp3";
private BackgroundTransferRequest transferRequest;
here is my download button action it downloads the mp3 file
private void download_Click(object sender, RoutedEventArgs e)
{
Uri transferuri = new Uri(Uri.EscapeUriString(link), UriKind.RelativeOrAbsolute);
// Create the new transfer request, passing in the URI of the file to
// be transferred.
transferRequest = new BackgroundTransferRequest(transferuri);
// Set the transfer method. GET and POST are supported.
transferRequest.Method = "GET";
string downloadFile = link.Substring(link.LastIndexOf("/") + 1);
Uri downloadUri = new Uri("shared/transfers/" + downloadFile, UriKind.RelativeOrAbsolute);
transferRequest.DownloadLocation = downloadUri;
transferRequest.Tag = downloadFile;
// Add the transfer request using the BackgroundTransferService. Do this in
// a try block in case an exception is thrown.
try
{
BackgroundTransferService.Add(transferRequest);
}
catch (InvalidOperationException ex)
{
MessageBox.Show("Unable to add background transfer request. " + ex.Message);
}
catch (Exception)
{
MessageBox.Show("Unable to add background transfer request.");
}
}
here play button click event
private void play_Click(object sender, RoutedEventArgs e)
{
string fileName = transferRequest.Tag;
MessageBox.Show(fileName);
using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoStore.FileExists(fileName))
{MessageBox.Show("here");
using (var isoStream = isoStore.OpenFile(fileName, FileMode.Open, FileAccess.Read))
{
mediaSound.Stop();
mediaSound.SetSource(isoStream);
mediaSound.Position = System.TimeSpan.FromSeconds(0);
mediaSound.Volume = 20;
mediaSound.Play();
}
}
}
}
in play_clic event i try to reach mp3 from isolated storage but i couldnt solve what is wrong because when I click button ,it does nothing
Some ideas...
Are you checking the BackgroundTransferRequest has completed before allowing the play button to be clicked?
Are you sure the complete file has been successfully downloaded by checking for the presence of a physical file, the same size as the original? You can use a tool like Windows Phone Toolkit to check this.
It does the Tag property on your BackgroundTransferRequest maintain the correct value after the download is complete?
Normally you'd check the status of the BackgroundTransferRequest and copy the file out of "/shared/transfers" to your own location. You'd then play the file from that location.
I have build an app with a webbrowser in it. It's working fine but when I try to navigate to an adress like bla.pdf the webbrowser shows nothing.
I solved this problem with automatically open the Internet Explorer if the adress is linking to a pdf file.
Is there a better solution? I want to open that PDF file in my own app and I dont want to open the Internet Explorer everytime. Any suggestions?
If you've got a locally downloaded PDF that is in Isolated Storage you can launch the PDF Reader application (or any other applications registered to open PDF files) using LaunchFileAsync.
private async void LaunchFileButton_Click(object sender, RoutedEventArgs rea)
{
// Access isolated storage.
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
// Access the PDF.
StorageFile pdfFile = await local.GetFileAsync("file1.pdf");
// Launch the bug query file.
Windows.System.Launcher.LaunchFileAsync(pdfFile);
}
(adapted from MSDN, see section on "launching a file").
If it's a remote URL then you can use LaunchUriAsync (which will use IE to download the file first).
You will need to try this on a device with the PDF Reader application installed - it won't work on the Emulator.
You should read following article if you are not familiar with Async: MSDN Asynchronous Programming with Async and Await
I couldn't test my app because my WP8 Phone is currently not available and I can't install an PDF reader on the emulator.
Call following method to start the download
WebClient pdfDownloader = null;
string LastFileName = ""; //To save the filename of the last created pdf
private void StartPDFDownload(string URL)
{
pdfDownloader = new WebClient(); //prevents that the OpenReadCompleted-Event is called multiple times
pdfDownloader.OpenReadCompleted += DownloadPDF; //Create an event handler
pdfDownloader.OpenReadAsync(new Uri(URL)); //Start to read the website
}
async void DownloadPDF(object sender, OpenReadCompletedEventArgs e)
{
byte[] buffer = new byte[e.Result.Length]; //Gets the byte length of the pdf file
await e.Result.ReadAsync(buffer, 0, buffer.Length); //Waits until the rad is completed (Async doesn't block the GUI Thread)
using (IsolatedStorageFile ISFile = IsolatedStorageFile.GetUserStoreForApplication())
{
try
{
LastFileName = "tempPDF" + DateTime.Now.Ticks + ".pdf";
using (IsolatedStorageFileStream ISFileStream = ISFile.CreateFile(LastFileName))
{
await ISFileStream.WriteAsync(buffer, 0, buffer.Length);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.HResult,
ex.Source, MessageBoxButton.OK);
//Catch errors regarding the creation of file
}
}
OpenPDFFile();
}
private async void OpenPDFFile()
{
StorageFolder ISFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
try
{
IStorageFile ISFile = await ISFolder.GetFileAsync(LastFileName);
await Windows.System.Launcher.LaunchFileAsync(ISFile);
//http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206987%28v=vs.105%29.aspx
}
catch (Exception ex)
{
//Catch unknown errors while getting the file
//or opening the app to display it
}
}
To call these methods from your WebBrowser-Control you need to catch the navigating event.
YourWebBrowserControl.Navigating += YourWebBrowserControl_Navigating;
void YourWebBrowserControl_Navigating(object sender, NavigatingEventArgs e)
{
if(e.Uri.AbsolutPath.EndsWith("pdf"))
{
StartPDFDownload(e.Uri.ToString());
}
}
Don't forget that you'll have to delete the files created someday.
Try this to open a PDF from a WebControl:
void MyWebBrowserControl_Navigating(object sender, NavigatingEventArgs e)
{
if (e.Uri.AbsolutPath.ToLower().EndsWith(".pdf"))
{
var success = Windows.System.Launcher.LaunchUriAsync(e.Uri);
}
}
The code below, is an attempt to get (download) files from a sharepoint.
If I try this on my local version, it works like a charm. I can select all items in the document library.
There are several methods I've tried, and I could post some of them here if you like. I can download corrupt files, but even when the link is wrong.
If I try this on the TeamSite in Office 365, I get an exception that my link is wrong. But I'm referring to the same site (instead of localhost/dev/ im referring to http://mysite.com/TeamSite/dev/). Any idea what the difference can be? Does Microsoft block something so external connections aren't allowed?
private void btnDownload_Click(object sender, EventArgs e)
{
if (comboBox1.Items.Count > 0 && comboBox1.SelectedIndex != -1)
{
SaveFileDialog dialog = new SaveFileDialog();
dialog.ShowDialog();
using (SPSite site = new SPSite("http://localhost/dev/"))
{
using (SPWeb web = site.OpenWeb())
{
SPFolder myLibrary = web.Folders["Management"];
foreach (SPFile file in myLibrary.Files)
{
if (file.Name == comboBox1.SelectedItem.ToString())
{
byte[] bytes = file.OpenBinary();
try
{
FileStream fs = new FileStream(dialog.FileName, FileMode.Create, FileAccess.ReadWrite);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(bytes);
bw.Close();
MessageBox.Show("File downloaded to: " + dialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
}
}
else
{
MessageBox.Show("Select file to download");
}
}
This is the Exception message:
The Web application at http://www.gtest.nl/TeamSite/ could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application.
You can not connect to sharepoint site, deployed on another computer like this.
You should use Client Context
for example:
string siteUrl = "http://MyServer/sites/MySiteCollection";
ClientContext clientContext = new ClientContext(siteUrl);
Web oWebsite = clientContext.Web;
ListCollection collList = oWebsite.Lists;
clientContext.Load(collList);
clientContext.ExecuteQuery();
foreach (SP.List oList in collList)
{
Console.WriteLine("Title: {0} Created: {1}", oList.Title, oList.Created.ToString());
}
you could find more examples on Client Context here
There is allready an example of file download from sharepoint through clientContext.
I need a method which will take an *.jpg image file and upload it to a user profile in the Active Directory of Windows AD 2003.
Also a method to retrieve the photo as stream or expose it as secure web service to be called by cross platform apps in java etc (Damn! am I asking too much!!!)
The file being uploaded will be a *.jpg which is basically a visual signature file created by a user.
Does anyone having any experience working with Active Directory in C# provide some information as to how this can be done with minimum implication related to security.
From the point of view of the Windows Active Directory Administrator what does he have to
do to make this possible.Changes/provisions to schema of user profile etc.
The image is being uploaded so that it can be later retrieved from the AD to be inserted into PDF document for signature purposes.
Can this be done in C#? Or is there any done libraries etc?
Here's a series of blog postings with code that shows how to do it:
(The first shows how to get a photo in, the second shows how to get it out)
Using the jpegPhoto attribute in AD - Part I
Using the jpegPhoto attribute in AD - Part II
EDIT: Here's a generic function implementing the code from Part I:
void AddPictureToUser(
string strDN, // User Distinguished Name, in the form "CN=Joe User,OU=Employees,DC=company,DC=local"
string strDCName, // Domain Controller, ie: "DC-01"
string strFileName // Picture file to open and import into AD
)
{
// Open file
System.IO.FileStream inFile = new System.IO.FileStream(strFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
// Retrive Data into a byte array variable
byte[] binaryData = new byte[inFile.Length];
int bytesRead = inFile.Read(binaryData, 0, (int)inFile.Length);
inFile.Close();
// Connect to AD
System.DirectoryServices.DirectoryEntry myUser = new System.DirectoryServices.DirectoryEntry(#"LDAP://" + strDCName + #"/" + strDN);
// Clear existing picture if exists
myUser.Properties["jpegPhoto"].Clear();
// Update attribute with binary data from file
myUser.Properties["jpegPhoto"].Add(binaryData);
myUser.CommitChanges();
}
EDIT: I found that in my organisation, the correct attribute to set was "thumbnailPhoto" like this:
myUser.Properties["thumbnailPhoto"].Add(binaryData);
This also seems to tbe the one that the commercial product Exclaimer is setting (but it might be only doing that in my organization)
The common AD attribute for a user photo is jpegPhoto but you can use what ever name you want
This sample shows the basic AD way to get and set an image stream. You need to flesh these methods out to be a useful class
Consider making your web service to just return the URL of the image. The request handler for that URL should then return the image with the correct content type etc. Much more useful in a web environment
using System;
using System.DirectoryServices;
using System.Collections;
using System.IO;
public class ADPhoto {
public void Set() {
try {
var de = new DirectoryEntry("LDAP://cn=username,cn=users,DC=domain, DC=com");
de.Username = "username";
de.Password = "password";
var forceAuth = de.NativeObject;
var fs = new FileStream("path\\photo.jpg", FileMode.Open);
var br = new BinaryReader(fs);
br.BaseStream.Seek(0, SeekOrigin.Begin);
byte[] ba = new byte[br.BaseStream.Length];
ba = br.ReadBytes((int)br.BaseStream.Length);
de.Properties["jpegPhoto"].Insert(0, ba);
de.CommitChanges();
}
catch(Exception ex) {
Console.WriteLine(ex.Message);
}
}
public Stream Get() {
var fs = new MemoryStream();
try {
var de = new DirectoryEntry("LDAP://cn=username,cn=users,DC=domain, DC=com");
de.Username = "username";
de.Password = "password";
var forceAuth = de.NativeObject;
var wr = new BinaryWriter(fs);
byte[] bb = (byte[])de.Properties["jpegPhoto"][0];
wr.Write(bb);
wr.Close();
}
catch (Exception e) {
Console.WriteLine(e.Message);
}
return fs;
}
}
Found an article that describes how to upload pictures to Active Directory and how to get them to show on the end-users computers.
http://blog.jocha.se/tech/ad-user-pictures-in-windows-10
Each Active Directory User Profile will have a home folder.
If you are not sure about this please checkout the below article
http://support.microsoft.com/kb/816313
I believe that you have to upload the image file to this directory.
Also if this doesn't solve your problem, please update if you find something else.
MNK...