i have a problem uploading an xlsx file to sharepoint on the deployed version. In my IIS Express in the local pc i can upload the document without any problem. When i deploy the application the server gives me an exception "No connection could be made because the target machine actively refused it. [::ffff:127.0.0.1]:9000 (127.0.0.1:9000)". The Server uses a proxy server in order to execute the web request. I tried many solutions on the internet but nothing worked. I also developed a console application, which was able to upload the file without any further configuration.
This brings me to the conclusion, that the blazor server for some reason doesn't use the systems default proxy when it does the web request.
Here is my code:
public Task<bool> UploadDocument(byte[] fileBinaryArray, string fileName, string sharePointLink)
{
try
{
Debug.WriteLine("-----------------------------------" + sharePointLink);
var preparedLink = PrepareSharePointLink(sharePointLink);
Debug.WriteLine("-----------------------------------" + preparedLink);
ClientContext ctx = new PnP.Framework.AuthenticationManager().GetACSAppOnlyContext(_siteUrl, _clientId, _clientSecret);
/*ctx.ExecutingWebRequest += (sen, args) =>
{
System.Net.WebProxy myProxy = new System.Net.WebProxy("proxyIp", 8080);
args.WebRequestExecutor.WebRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
args.WebRequestExecutor.WebRequest.Proxy = myProxy;
};*/
var folder = ctx.Web.GetFolderByServerRelativeUrl(preparedLink);
ctx.Load(folder);
ctx.ExecuteQuery();
folder.Files.Add(new FileCreationInformation
{
Overwrite = true,
Content = fileBinaryArray,
Url = fileName
});
ctx.ExecuteQuery();
return Task.FromResult(true);
}
catch(Exception e)
{
_eventlogService.LogError(e, _authenticationService?.UserName);
return Task.FromResult(false);
}
}
Related
My C# code is trying to pull some files from an Amazon S3 bucket. This code works fine on my development as well as on UAT server. However, when I run this on my production server, I get a certificate error.
One difference between the UAT and Production servers is that on UAT there is no restriction on outbound internet access. On Production servers free outbound internet access is not allowed. we open only selective URLs as per requirements.
We have already opened access to s3.amazonaws.com. We have also ensured that this access works fine using WinSCP tool. However, when my code tries to do the same, I get the following error:
WinSCP.SessionRemoteException: Server Certificate Verification Failed: Issuer is not trusted.
The source code is attached below:
s3HostName = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["s3HostName"]);
s3UserName = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["s3UserName"]);
s3Password = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["s3Password"]);
LocalFilePath = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["LocalFilePath"]);
s3Folder = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["s3Folder"]);
LocalFileFolder = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["LocalFileFolder"]);
LocalFolder = LocalFilePath + yesterday + "\\";
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.S3,
HostName = s3HostName,
UserName = s3UserName,
Password = s3Password,
};
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = WinSCP.TransferMode.Automatic;
transferOptions.FilePermissions = null;
transferOptions.PreserveTimestamp = false;
using (Session session = new Session())
{
log.Debug("Open session for s3");
session.Open(sessionOptions);
if (!Directory.Exists(LocalFolder))
{
Directory.CreateDirectory(LocalFolder);
}
//to download files
session.GetFiles(s3Folder + "*" + yesterday + ".csv", LocalFolder);
session.Close();
log.Debug("Closed session for s3");
return "Success";
}
Resolved the issue using the oldest trick in the book. Reinstalled WinSCP. Its all working fine now.
Trying to connect to an FTP server using a port just to see if it work.
If I use port 21 I get an error: 530 Not logged in and if I use port 22 I get an error the server committed a protocol violation.
I made sure my firewall is off, is there anything else to check or my code is wrong?
try
{
FtpWebRequest directoryListRequest = (FtpWebRequest)WebRequest.Create("ftp://ftp.fakeURL.com:22/");
directoryListRequest.Method = WebRequestMethods.Ftp.ListDirectory;
directoryListRequest.Credentials = new NetworkCredential("username", "password");
using (FtpWebResponse directoryListResponse = (FtpWebResponse)directoryListRequest.GetResponse())
{
using (StreamReader directoryListResponseReader = new StreamReader(directoryListResponse.GetResponseStream()))
{
string responseString = directoryListResponseReader.ReadToEnd();
string[] results = responseString.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
I was able to use Fluent FTP library to upload the file and it made my life way easier.
below an example of the code I used.
public static async Task UploadFileAsync() {
var token = new CancellationToken();
using (var ftp = new FtpClient("127.0.0.1", "ftptest", "ftptest")) {
await ftp.ConnectAsync(token);
// upload a file to an existing FTP directory
await ftp.UploadFileAsync(#"D:\Github\FluentFTP\README.md", "/public_html/temp/README.md");
// upload a file and ensure the FTP directory is created on the server
await ftp.UploadFileAsync(#"D:\Github\FluentFTP\README.md", "/public_html/temp/README.md", FtpRemoteExists.Overwrite, true);
// upload a file and ensure the FTP directory is created on the server, verify the file after upload
await ftp.UploadFileAsync(#"D:\Github\FluentFTP\README.md", "/public_html/temp/README.md", FtpRemoteExists.Overwrite, true, FtpVerify.Retry);
}
}
I am trying to use WinSCP in visual studio. I downloaded and installed WinSCP using the Managed NuGet package. I have used the below code in a web application to transfer one of the files to a remote Linux server. The code executes fine without any error, but the file is not transferred. I logged in using PuTTY to verify if the file has actually transferred, but could not locate the file. Below is the code used
public int Upload(String HostName, String UserName, String Password, String remotePath, String localFilePath)
{
int result = 0;
Session session = null;
try
{
// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = HostName,
UserName = UserName,
Password = Password,
Timeout = TimeSpan.FromDays(1),
};
using (session = new Session())
{
// Connect
session.Open(sessionOptions);
// upload files
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Ascii;
TransferOperationResult transferResult = null;
transferResult = session.PutFiles(localFilePath, remotePath, false, transferOptions);
// Throw on any error
transferResult.Check();
// Print results
foreach (TransferEventArgs transfer in transferResult.Transfers)
{
Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
}
session.GetFiles(#"\\remoteserver\folder1\folder_backups\test_files\test1.txt", #"d:\folder3\").Check();
}
result = 0;
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e);
result = 1;
}
finally
{
if (session != null)
{
session.Dispose();
}
}
return result;
}
The arguments are passed as below:
project1.Upload("remote host server", "username", "password", #"\\remote host server\folder1\folder_backups\test_files\", Fileupload1.PostedFile.FileName);
The code executes without any error, but no file is uploaded nor downloaded. How to fix this?
Thanks
After the login happens in GUI - it points to /home/UserId . But the folder which i want to move the files exist in /folder1
If remote path you want to use is /folder1/, use that for remotePath argument of your Upload method, instead of obviously wrong value #"\\remote host server\folder1\folder_backups\test_files\".
project1.Upload("host", "user", "password", "/folder1/", Fileupload1.PostedFile.FileName);
Not entirely sure but looks like you've set the protocol to FTP which may not be supported by the server. If you're able to login via putty then that means SSH connection is possible. Try setting the protocol to SFTP.
I have a web API2 application which is consumed by a third party application. When the application hits my end-point, my application send oAuth credentials for authentication and gets the results from the third party application.
Recently some of the transactions are failing and when i added some logs, i saw that the error: The remote server returned an error: (410) Gone is occurring for all failed transactions. Unfortunately I am unable to reproduce this issue when I am calling my application. The following is the code that I am using. What could be the issue that is causing this error?
public async Task<customerModel> SendSigned(string url)
{
customerModel customermodel = null;
try
{
OAuthBase oauthBase = new OAuthBase();
string oAuthKey = ConfigurationManager.AppSettings["oAuthKey"];
string oAuthSecret = ConfigurationManager.AppSettings["oAuthSecret"];
string timestamp = oauthBase.GenerateTimeStamp();
string nonce = oauthBase.GenerateNonce();
string normalizedUrl;
string normalizedRequestParameters;
string sig = HttpUtility.UrlEncode(oauthBase.GenerateSignature(
new Uri(url), oAuthKey, oAuthSecret, string.Empty, string.Empty,
"GET", timestamp, nonce, out normalizedUrl, out normalizedRequestParameters));
string requestUrl = String.Format("{0}?{1}&oauth_signature={2}", normalizedUrl, normalizedRequestParameters, sig);
HttpWebRequest request = null;
request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
myXMLDocument = new XmlDocument();
customermodel = GetCustomerInformation(response);
}
return await Task.Run(() => customermodel);
}
catch (Exception ex)
{
_logger.Error("Error in SendSigned method", ex.InnerException);
return customermodel;
}
}
The explanation of 410 is The target resource is no longer available at the origin server and that this condition is likely to be permanent based on
this link (similar to a 404)
I would suggest you to think about recent changes you made to your
API signatures
Folder restructure/reorganization of assets/resources
Routing changes
Rename of resources
I'm trying to build a C# SignalR app (console app on the server, winforms app on the client), and it works great (in Visual Studio) when both the client and server are on the same PC, but when I deploy the server and repoint the client to the server, I'm getting a "407 Proxy Authentication Required" exception when it tries to start.
This is my code...
var _connection = new HubConnection("http://www.redacted.com:8088/");
var _hub = _connection.CreateProxy("MyHub");
_connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
MessageBox.Show(string.Format("Could not connect - {0}", task.Exception.ToString()));
}).Wait();
I noticed that HubConnection has a Credentials property, and so I figured I'd try replacating some code I've used with WebServices when dealing with proxies (shown below, where I just make an HTTP request out and then pick up the proxy settings and credentials from that), but I get the same exception.
var _connection = new HubConnection("http://www.redacted.com:8088/");
var req = (HttpWebRequest)WebRequest.Create("http://www.google.com");
var proxy = new WebProxy(req.Proxy.GetProxy(req.RequestUri).AbsoluteUri) {UseDefaultCredentials = true};
_connection.Credentials = proxy.Credentials;
var _hub = _connection.CreateProxy("MyHub");
_connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
MessageBox.Show(string.Format("Could not connect - {0}", task.Exception.ToString()));
}).Wait();
This is required for some work I'm doing for a client where they want their local PCs to be able to receive messages from a remote system that's hosted outside the company.
Thanks!
Try to set the DefaultWebProxy:
WebProxy wproxy = new WebProxy("new proxy",true);
wproxy.Credentials = new NetworkCredential("user", "pass");
WebRequest.DefaultWebProxy = wproxy;