Currently I have an application that receives an uploaded file from my web application. I now need to transfer that file to a file server which happens to be located on the same network (however this might not always be the case).
I was attempting to use the webclient class in C# .NET.
string filePath = "C:\\test\\564.flv";
try
{
WebClient client = new WebClient();
NetworkCredential nc = new NetworkCredential(uName, password);
Uri addy = new Uri("\\\\192.168.1.28\\Files\\test.flv");
client.Credentials = nc;
byte[] arrReturn = client.UploadFile(addy, filePath);
Console.WriteLine(arrReturn.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
The machine located at 192.168.1.28 is a file server and has a share c:\Files.
As of right now I am receiving an error of Login failed bad user name or password, but I can open explorer and type in that path login successfully. I can also login using remote desktop, so I know the user account works.
Any ideas on this error?
Is it possible to transfer a file directly like that? With the webclient class or maybe some other class?
Just use
File.Copy(filepath, "\\\\192.168.1.28\\Files");
A windows fileshare exposed via a UNC path is treated as part of the file system, and has nothing to do with the web.
The credentials used will be that of the ASP.NET worker process, or any impersonation you've enabled. If you can tweak those to get it right, this can be done.
You may run into problems because you are using the IP address instead of the server name (windows trust settings prevent leaving the domain - by using IP you are hiding any domain details). If at all possible, use the server name!
If this is not on the same windows domain, and you are trying to use a different domain account, you will need to specify the username as "[domain_or_machine]\[username]"
If you need to specify explicit credentials, you'll need to look into coding an impersonation solution.
namespace FileUpload
{
public partial class Form1 : Form
{
string fileName = "";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string path = "";
OpenFileDialog fDialog = new OpenFileDialog();
fDialog.Title = "Attach customer proposal document";
fDialog.Filter = "Doc Files|*.doc|Docx File|*.docx|PDF doc|*.pdf";
fDialog.InitialDirectory = #"C:\";
if (fDialog.ShowDialog() == DialogResult.OK)
{
fileName = System.IO.Path.GetFileName(fDialog.FileName);
path = Path.GetDirectoryName(fDialog.FileName);
textBox1.Text = path + "\\" + fileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
WebClient client = new WebClient();
NetworkCredential nc = new NetworkCredential("erandika1986", "123");
Uri addy = new Uri(#"\\192.168.2.4\UploadDocs\"+fileName);
client.Credentials = nc;
byte[] arrReturn = client.UploadFile(addy, textBox1.Text);
MessageBox.Show(arrReturn.ToString());
}
catch (Exception ex1)
{
MessageBox.Show(ex1.Message);
}
}
}
}
when you manually open the IP address (via the RUN command or mapping a network drive), your PC will send your credentials over the pipe and the file server will receive authorization from the DC.
When ASP.Net tries, then it is going to try to use the IIS worker user (unless impersonation is turned on which will list a few other issues). Traditionally, the IIS worker user does not have authorization to work across servers (or even in other folders on the web server).
Related
I am attempting to open an Imanage document, in MS Word, within a temporary test application (for debugging) to later copy over into an ActiveX control project. The error that is popping up is:
Exception thrown at 0x7618851A (msvcrt.dll) in w3wp.exe: 0xC0000005: Access >violation reading location 0x09801000.
If there is a handler for this exception, the program may be safely continued.
The error occurs when running the cmd.Execute line and I am unsure as to why I am getting the error.
using IManage;
using IMANEXTLib;
using System;
namespace WebApplication3
{
public partial class WebForm2 : System.Web.UI.Page
{
IManDatabase imanagedatabase;
IManDMS myDMS = new ManDMSClass();
protected void Page_Load(object sender, EventArgs e)
{
openImanageDoc("docNumber", "versionNumber", "server", "database", ReadOnly);
}
public void imanageLogin(string server, string database)
{
try
{
IManSession session = myDMS.Sessions.Add(server);
IManWorkArea oWorkArea = session.WorkArea;
session.TrustedLogin();
foreach (IManDatabase dbase in session.Databases)
{
if (dbase.Name == database)
{
imanagedatabase = dbase;
}
}
}
catch (Exception ex)
{
throw ex;
}
}
public void openImanageDoc(string docNo, string versionNo, string server, string database, bool isReadOnly = true)
{
IManDocument doc;
try
{
imanageLogin(server, database);
int iDocNo = int.Parse(docNo);
int iVersion = int.Parse(versionNo);
doc = imanagedatabase.GetDocument(iDocNo, iVersion);
openNRTDocument(ref doc, isReadOnly);
imanagedatabase.Session.Logout();
myDMS.Close();
}
catch (Exception Ex)
{
imanagedatabase.Session.Logout();
throw Ex;
}
finally
{
imanagedatabase = null;
myDMS = null;
}
}
public void openNRTDocument(ref IManDocument nrtDocument, Boolean isReadonly)
{
OpenCmd cmd = new OpenCmd();
ContextItems objContextItems = new ContextItems();
objContextItems.Add("NRTDMS", myDMS);
objContextItems.Add("SelectedNRTDocuments", new[] { (NRTDocument)nrtDocument.LatestVersion });
objContextItems.Add("IManExt.OpenCmd.Integration", false);
objContextItems.Add("IManExt.OpenCmd.NoCmdUI", true);
cmd.Initialize(objContextItems);
cmd.Update();
cmd.Execute();
}
}
}
Due to the nature of the error, I am presuming it is a configuration issue rather than a code error although I could be completely wrong as I am very new to programming.
I have found out that w3wp.exe is an IIS worker process created by the app pool but other than that I have no idea what the numeric code represents. Any help or advice is greatly appreciated.
The error is being raised by the OpenCmd instance because it is most likely trying to access resources such as local registry settings. It's not possible to do that in a web application, unless you host your code in a proprietary technology like ActiveX (which is specific to Internet Explorer)
Actually, it is not appropriate for you to use OpenCmd here. Those type of commands (iManage "ICommand" implementations) are intended to be used in regular Windows applications that have either the iManage FileSite or DeskSite client installed. These commands are all part of the so-called Extensibility COM libraries (iManExt.dll, iManExt2.dll, etc) and should not be used in web applications, or at least used with caution as they may inappropriately attempt to access the registry, as you've discovered, or perhaps even display input Win32 dialogs.
For a web app you should instead just limit yourself to the low-level iManage COM library (IManage.dll). This is in fact what iManage themselves do with their own WorkSite Web application
Probably what you should do is replace your openNRTDocument method with something like this:
// create a temporary file on your web server..
var filePath = Path.GetTempFileName();
// fetch a copy of the iManage document and save to the temporary file location
doc.GetCopy(filePath, imGetCopyOptions.imNativeFormat);
In an MVC web application you would then just return a FileContentResult, something like this:
// read entire document as a byte array
var docContent = File.ReadAllBytes(filePath);
// delete temporary copy of file
File.Delete(filePath);
// return byte stream to web client
return File(stream, MediaTypeNames.Application.Octet, fileName);
In a Web Forms application you could do something like this:
// set content disposition as appropriate - here example is for Word DOCX files
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
// write file to HTTP content output stream
Response.WriteFile(filePath);
Response.End();
I am really new to this share point stuffs.We have a share point server with admin account in it and i was connecting it from my local machine through ip and share point port manually.
Nut i need to write a program which needs to upload the files into the share point server from the local machine to server. Is it possible in using winforms ? or only possible in web services.?
using (SPSite oSite = new SPSite(sharePointSite))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
if (!System.IO.File.Exists(fileToUpload))
throw new FileNotFoundException("File not found.", fileToUpload);
SPFolder myLibrary = oWeb.Folders[documentLibraryName];
// Prepare to upload
Boolean replaceExistingFiles = true;
String fileName = System.IO.Path.GetFileName(fileToUpload);
FileStream fileStream = File.OpenRead(fileToUpload);
// Upload document
SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);
// Commit
myLibrary.Update();
}
}
tried using the above code and i getting error from the following line
using (SPSite oSite = new SPSite(sharePointSite))
and the error was
"The Web application at http://server:port/ 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"
and am not able to upload the file.
But if i copied and paste the same URL in my local machine i can able to access the sharepoint deployed in server and i can even upload files manually from my local machine.
How to upload a file in sharepoint server from the local machine connected with LAN..??
siteURL = Main URl of the sharepoint (eg) "http://10.0.0.14:48487/";
documentListName = any of the folders in shrepoint (eg) Shared Documents
documentName = name of the file (eg)sampleword.docx , readme.txt etc
documentStream = the byte format of the file which we going to upload.
(eg)byte[] bytefile = System.IO.File.ReadAllBytes(filepath+filename);
public static void UploadDocument(string siteURL, string documentListName, string documentListURL,string documentName, byte[] documentStream = null)
{
try
{
using (SP.ClientContext clientContext = new SP.ClientContext(siteURL))
{
#region"Only if you have credentials"
NetworkCredential Cred = new NetworkCredential("username", "password");
clientContext.Credentials = Cred;
#endregion
SP.List documentsList = clientContext.Web.Lists.GetByTitle(documentListName);
var fileCreationInformation = new SP.FileCreationInformation();
//Assign to content byte[] i.e. documentStream
fileCreationInformation.Content = documentStream;
//Allow owerwrite of document
fileCreationInformation.Overwrite = true;
//Upload URL
fileCreationInformation.Url = documentName;
Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add(
fileCreationInformation);
uploadFile.ListItemAllFields.Update();
clientContext.ExecuteQuery();
}
}
catch (Exception ex)
{
}
}
}
This works perfect for me :) :)
make sure your connecting to an existing site collection. the error you have received is quite self explainitory, it cannot find the site collection you have pointed it at. check your string sharePointSite to make sure there isn't a typo and that it's accessing the correct root site collection. Remember with SharePoint SPSite = Site Collection SPWeb = a website in a site collection.
i can't see any glaring errors in your code without running something up myself except to make sure that when you are calling oSite.openweb() it's for a single site within the site collection.
Platform is Windows 7 and above.
I am having problems with BITS.
I don't even know if this is feasible to do.
I would like to initiate a BITS job under the System account running as a service. I would like to pass in credentials such as NT domain creds domain\Username. I would like the job to transfer (download) from a network share but not while that user is logged on.
So just to re-iterate, Service to download from a network share using BITS but the will need to domain cred to access the share.
I have tried so many different things from impersonating the NT domain account (user isn't logged on and therefore the Job wont start).
Pass credentials into the BITS job but that has little success.
Attempted to add the network share in Credential manager but fails with error 1312
Update
Some code here for you - I am using the SharpBits as the BITS wrapper. http://sharpbits.codeplex.com/
I have tried to minimise the class to make it as simple as possible. Apologies on posting the code its not as simple as I expected.
using SharpBits.Base;
public class BitsFetchFiles : IDisposable
{
BitsCredentials _BitsCredentials;
BitsManager mManager = new BitsManager();
List<string> _JobIds = new List<string>();
DirectoryInfo _Source; //Set by constructor
DirectoryInfo _Cache; //Set by constructor
//Impersonation class to wrap credentials in
InfoDllImpersonation _Impersonation = null;
public void GetJob(string Domain, string Username, string Password)
{
_BitsCredentials = new BitsCredentials();
_BitsCredentials.UserName = Domain + "\\" + Username;
_BitsCredentials.Password = Password;
_BitsCredentials.AuthenticationTarget = AuthenticationTarget.Server;
_BitsCredentials.AuthenticationScheme = AuthenticationScheme.Negotiate;
_Impersonation = new InfoDllImpersonation(Username, Password, Domain);
//Just a method to the impersonated user access to the destination directory
GiveAllUserAccessToTheFolder(DirectoryDestination);
BitsJob Bjob = mManager.CreateJob("Service Download", JobType.Download);
Bjob.OnJobError += Bjob_OnJobError;
Bjob.OnJobTransferred += Bjob_OnJobTransferred;
Bjob.Priority = JobPriorityForDownload;
Bjob.OnJobModified += Bjob_OnJobModified;
_JobIds.Add(Bjob.JobId.ToString());
JobInformation.JobId = Bjob.JobId.ToString();
Bjob.TakeOwnership();
using (_Impersonation.ImpersonatedUser)
{
using (new NetworkConnection(_Source.FullName, new System.Net.NetworkCredential(
_Impersonation.UserName, _Impersonation.Password, _Impersonation.Domain)))
{
Bjob.AddCredentials(_BitsCredentials);
StartIncludingSubs(remoteFiles, Bjob, ref totalFileBytes);
}
}
//Enumerate all jobs listed and resume - e.g Bjob.Resume();
StartAllJobs();
}
void StartIncludingSubs(FileInfo[] remoteFiles, BitsJob Bjob, ref long totalFileBytes)
{
_LogFile.Log(string.Format("Using network credentials user : {0}",
_Impersonation.UserName), LogFile.LogLevel.Debug);
remoteFiles = _Source.GetFiles("*.*", SearchOption.AllDirectories);
JobInformation.TotalNumberOfFiles = remoteFiles.Length;
//Collected all remote files...
JobInformation.StatusInformation =
"Source Files have been collected and read with a total of "
+ remoteFiles.Length.ToString() + " files";
foreach (var fi in remoteFiles)
{
string newCacheFile = _Cache + fi.FullName.
Substring(_Source.FullName.Length);
string direct = newCacheFile.Substring(0, newCacheFile.LastIndexOf("\\"));
Directory.CreateDirectory(direct);
Bjob.AddFile(fi.FullName, newCacheFile);
if (_CancelTheJobAddingFiles)
{
return;
}
//Console.WriteLine("remote file {0} and Local is {1}", _Source.FullName + "\\" + fi.Name, newCacheFile);
totalFileBytes += fi.Length;
}
}
}
I have a simple website in ASP.NET where I have loaded a DLL. I have published the site via IIS and I only want to show on the user side his Machine Name, logged in user and IP. I have tried the following:
My DLL:
namespace ClassLibrary1
{
public class Class1
{
public string getInfo()
{
IPAddress[] ips;
ips = Dns.GetHostAddresses(Dns.GetHostName());
string returns = null;
returns = Environment.MachineName + Convert.ToChar(9) + Environment.UserName;
foreach (IPAddress ip in ips)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
returns += Convert.ToChar(9) + ip.ToString();
}
return returns;
}
}
}
And in the website:
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
ClassLibrary1.Class1 cl = new ClassLibrary1.Class1();
Label2.Text = cl.getInfo();
}
}
The output is not what I expected. In my machine, when I access the site i get
MyMachineName Classic .NET AppPool MyIp
And when anyone else opens it, they also get those informations, not their machinename, logged in user and IP.
So my question is how to retrieve their info?
Thanks in advance.
You are pulling the stats from the machine that is serving the website, not the visitor's machine. You should probably take a look at the HttpRequest.ServerVariables NameValueCollection instead.
Some of those "variables", particularly the ones you are interested in, are derived from the headers in each web request from the client. Keep in mind that you aren't actually talking to the client's machine, these are sent to you from the client. Consequently, there's no guarantee that they will be accurate (proxy, etc.), if they're even there at all.
That said, the ones you are probably interested in are:
var ip = HttpRequest.ServerVariables["REMOTE_ADDR"];
var user = HttpRequest.ServerVariables["REMOTE_USER"]; // Windows auth
var user = HttpRequest.ServerVariables["LOGON_USER"]; // Non-Windows auth
var machine = HttpRequest.ServerVariables["REMOTE_HOST"];
Here's the list of variables to pick from.
I'm trying to load data into my Silverlight app. However, when it launches, I get a TargetInvocationException as soon as I hit e.Result:
public MainPage() {
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenReadAsync(new Uri("http://www.google.com"));
}
void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) {
Stream st = e.Result;
StreamReader sr = new StreamReader(st);
String result = sr.ReadToEnd();
}
Why does this fail, and what should I do to make it work?
PS, I'm afraid I cannot make a local proxy, because the app is going to be deployed as part of an app on an Apache Tomcat server, not an IIS.
Cheers
Nik
Silverlight cannot make cross-domain requests without a cross-domain policy file on the target domain. If you can't set up a proxy, you won't be able to get data from any domain other than the one hosting your application.