I m trying to save the file throw SFTP.Its working when i deployed on our company server but when i deployed on production server it give me error.Here is the code
string host = "https://xyz.in";
int port = 22;
string username = "abc";
string password = "xyz"
string SftpfolderName = "Images"
using (var client = new SftpClient(host, port, username, password))
{
client.Connect();
}
using(var client = new sftpClient(host,port,username,password) throwing exception.
below are the exception details
Web Application$|MethodName$|3017$|$|{"ClassName":"System.ArgumentException","Message":"host","Data":null,"InnerException":null,"HelpURL":null,"StackTraceString":" at Renci.SshNet.ConnectionInfo..ctor(String host, Int32 port, String username, ProxyTypes proxyType, String proxyHost, Int32 proxyPort, String proxyUsername, String proxyPassword, AuthenticationMethod[] authenticationMethods)\r\n at Renci.SshNet.PasswordConnectionInfo..ctor(String host, Int32 port, String username, Byte[] password, ProxyTypes proxyType, String proxyHost, Int32 proxyPort, String proxyUsername, String proxyPassword)\r\n at Renci.SshNet.SftpClient..ctor(String host, Int32 port, String username, String password)\r\n Renci.SshNet.AuthenticationMethod[])","HResult":-2147024809,"Source":"Renci.SshNet","WatsonBuckets":null,"ParamName":null}1/25/2017 11:54:24 AM
i found the cause of this error..in my case the issue was, i added the "https://" in the host name when i removed "https://" from host name its working.
now the code look like this
string host = "xyz.in";
int port = 22;
string username = "abc";
string password = "xyz"
string SftpfolderName = "Images";
using (var client = new SftpClient(host, port, username, password))
{
client.Connect();
}
Related
Under 389 DS we have setup as password policy to save last 5 password in history, so that those can not be used.
We have java application under which password is changed as LDAP administrator. But when password is changed instead of adding new password in password history, it replaces old password with new password. This enables user to change password to the password used in past.
Eg.
User sets password to abc, then history is {abc}.
User changes password to efg, then history is { abc, efg }
Administrator changes password to xyz, then history is expected to be {xyz, abc, efg} but it is {xyz, efg}.
private static void changePasswordAsAdmin(String userDn, String sNewPassword) throws Exception {
System.out.println("Setting Password:" + sNewPassword);
LDAPConnection connection = new LDAPConnection(new MySSLSocketFactory(), "Ldap host", 636, "adminCN", "adminPwd" );
final List mods = new ArrayList();
final Modification item = new Modification(ModificationType.REPLACE, "userPassword", sNewPassword);
mods.add(item);
final ModifyRequest request = new ModifyRequest(userDn, mods);
try {
LDAPResult result = connection.modify(request);
System.out.println(result.getResultString());
}
catch(Exception e) {
System.out.println(e.getMessage());
throw e;
}
}
private static void changePasswordAsUser(String userDn, String oldPassword, String newPassword) throws Exception {
System.out.println("Setting Password, old password: " + oldPassword + ", new password: " + newPassword);
LDAPConnection connection = new LDAPConnection(new MySSLSocketFactory(), "ldapHost", 636, "userDn", "oldPassword");
final List mods = new ArrayList();
final Modification item = new Modification(ModificationType.REPLACE, "userPassword", newPassword);
mods.add(item);
final ModifyRequest request = new ModifyRequest(userDn, mods);
try {
LDAPResult result = connection.modify(request);
System.out.println(result.getResultString());
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
This is a known bug which should be fixed according to : https://pagure.io/389-ds-base/issue/48813
Try to update you version of 389DS
I have been working on SQL Server Reporting Services 2008, and i am connecting to report server from asp.net using below code:
ReportExecutionService rs = new ReportExecutionService();
System.Net.CredentialCache.DefaultNetworkCredentials.Domain = ConfigurationManager.AppSettings["Domain"].ToString();
System.Net.CredentialCache.DefaultNetworkCredentials.UserName = ConfigurationManager.AppSettings["UserName"].ToString();
System.Net.CredentialCache.DefaultNetworkCredentials.Password = ConfigurationManager.AppSettings["Password"].ToString();
rs.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
// Render arguments
byte[] result = null;
string reportpath = reportPath;
string format = "PDF";
string historyID = null;
string devInfo = #"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
string encoding;
string mimeType;
string extension;
ParameterValue[] parameters = new ParameterValue[1];
parameters[0] = new ParameterValue();
parameters[0].Name = reportParameterBidName.Trim();
parameters[0].Value = reportParameterBidValue.Trim();
Warning[] warnings = null;
string[] streamIDs = null;
ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();
rs.ExecutionHeaderValue = execHeader;
execInfo = rs.LoadReport(reportpath, historyID);
rs.SetExecutionParameters(parameters, "en-us");
String SessionId = rs.ExecutionHeaderValue.ExecutionID;
try
{
result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
return result;
}
catch (SoapException e)
{
return null;
}
Now it works well with my local server, when i upload it to final server it does not work and throws unable to connect error. If i use VPN and use same credentials then too it is working.
Please advise on this.
I just code 4 methods for API REST, but the last I need is not working. This is deleting the message queue. I have this code:
public static string DeleteMessage(String queueName, string account, byte[] key, string endpoint, string popreceipt,string messageid)
{
string requestMethod = "DELETE";
String urlPath = String.Format("{0}/messages/{1}?popreceipt={2}", queueName,Uri.EscapeDataString(messageid),Uri.EscapeDataString(popreceipt));
String storageServiceVersion = "2009-09-19";
String dateInRfc1123Format = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
String canonicalizedHeaders = String.Format(
"x-ms-date:{0}\nx-ms-version:{1}",
dateInRfc1123Format,
storageServiceVersion);
String canonicalizedResource = String.Format("/{0}/{1}", account, urlPath);
//String canonicalizedResource = String.Format("/{0}/{1}\npopreceipt:{2}", account, urlPath, popreceipt);
String stringToSign = String.Format(
"{0}\n\n\n\n\n\n\n\n\n\n\n\n{1}\n{2}",
requestMethod,
canonicalizedHeaders,
canonicalizedResource);
String authorizationHeader = CreateAuthorizationHeader(stringToSign, account, key);
Uri uri = new Uri(endpoint + urlPath);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = requestMethod;
request.Headers.Add("x-ms-date", dateInRfc1123Format);
request.Headers.Add("x-ms-version", storageServiceVersion);
request.Headers.Add("Authorization", authorizationHeader);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
return response.StatusCode.ToString();
}
}
public static string GetMessage(String queueName,string account, byte[] key,string endpoint)
{
string requestMethod = "GET";
String urlPath = String.Format("{0}/messages", queueName);
String storageServiceVersion = "2009-09-19";
String dateInRfc1123Format = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
String canonicalizedHeaders = String.Format(
"x-ms-date:{0}\nx-ms-version:{1}",
dateInRfc1123Format,
storageServiceVersion );
String canonicalizedResource = String.Format("/{0}/{1}", account, urlPath);
String stringToSign = String.Format(
"{0}\n\n\n\n\n\n\n\n\n\n\n\n{1}\n{2}",
requestMethod,
canonicalizedHeaders,
canonicalizedResource);
String authorizationHeader = CreateAuthorizationHeader(stringToSign,account,key);
Uri uri = new Uri(endpoint + urlPath);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = requestMethod;
request.Headers.Add("x-ms-date", dateInRfc1123Format);
request.Headers.Add("x-ms-version", storageServiceVersion );
request.Headers.Add("Authorization", authorizationHeader);
request.Accept = "application/atom+xml,application/xml";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
using (StreamReader reader = new StreamReader(dataStream))
{
String responseFromServer = reader.ReadToEnd();
return responseFromServer;
}
}
}
GetMessage is just working and DeleteMessage is not working, the CreateAuthorithation Headers Code is :
private static String CreateAuthorizationHeader(String canonicalizedString, string account, byte[] key)
{
String signature = string.Empty;
using (HMACSHA256 hmacSha256 = new HMACSHA256(key))
{
Byte[] dataToHmac = System.Text.Encoding.UTF8.GetBytes(canonicalizedString);
signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
}
String authorizationHeader = String.Format(
CultureInfo.InvariantCulture,
"{0} {1}:{2}",
"SharedKey",
account,
signature);
return authorizationHeader;
}
I pass the KEY using "Convert.FromBase64String(AccountSharedKey)", that works for GetMessage (and also another method for put message), but this is not working for DELETING THE MESSAGE.
I see the API in MSDN and DELETE and GET message use the same parameters, except the parameters passed by the query string.
SOLVED
The problem was that I dinĀ“t use UriEscape for the parameters in the Uri string, and sometimes the URL was valid and sometimes not.
I believe there's an issue with the way you're constructing "canonicalizedResource" string. Based on the documentation here: http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx (scroll down to the section titled "Constructing the Canonicalized Resource String"), you should not be passing the Query String parameters as part of the main canonicalized resource string. They should be appended separately.
Can you see if using the following works:
string canonicalizedResource = string.Format("/{0}/{1}/messages/{2}\npopreceipt:{3}", account, queueName, messageid, popreceipt);
Hope this helps.
I tried the following code and it worked fine for me. I created a queue, inserted a message did a "GET" message on that to get the pop receipt and then deleted the message. Only thing I modified in your code is the canonicalizedResource string based on my answer above:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web;
using System.IO;
using System.Security.Cryptography;
using System.Globalization;
namespace ConsoleApplication15
{
class Program
{
static void Main(string[] args)
{
string messageId = "<message id e.g. ba9bdbe6-cd10-465d-ab32-90756ea0471d>";
string queueName = "<queue name e.g. abc>";
string accountName = "<your account name>";
string accountKey = "<you account key base64 encoded string>";
string endpoint = "http://accountname.queue.core.windows.net/";
string popreceipt = "<pop receipt e.g. AgAAAAEAAAAAAAAACuMLtGTIzQE=>";
var result = DeleteMessage(queueName, accountName, Convert.FromBase64String(accountKey), endpoint,
popreceipt, messageId);
}
public static string DeleteMessage(String queueName, string account, byte[] key, string endpoint, string popreceipt, string messageid)
{
string requestMethod = "DELETE";
String urlPath = String.Format("{0}/messages/{1}?popreceipt={2}", queueName, Uri.EscapeDataString(messageid), Uri.EscapeDataString(popreceipt));
String storageServiceVersion = "2009-09-19";
String dateInRfc1123Format = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
String canonicalizedHeaders = String.Format(
"x-ms-date:{0}\nx-ms-version:{1}",
dateInRfc1123Format,
storageServiceVersion);
String canonicalizedResource = string.Format("/{0}/{1}/messages/{2}\npopreceipt:{3}", account, queueName, messageid, popreceipt);
String stringToSign = String.Format(
"{0}\n\n\n\n\n\n\n\n\n\n\n\n{1}\n{2}",
requestMethod,
canonicalizedHeaders,
canonicalizedResource);
String authorizationHeader = CreateAuthorizationHeader(stringToSign, account, key);
Uri uri = new Uri(endpoint + urlPath);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = requestMethod;
request.Headers.Add("x-ms-date", dateInRfc1123Format);
request.Headers.Add("x-ms-version", storageServiceVersion);
request.Headers.Add("Authorization", authorizationHeader);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
return response.StatusCode.ToString();
}
}
private static String CreateAuthorizationHeader(String canonicalizedString, string account, byte[] key)
{
String signature = string.Empty;
using (HMACSHA256 hmacSha256 = new HMACSHA256(key))
{
Byte[] dataToHmac = System.Text.Encoding.UTF8.GetBytes(canonicalizedString);
signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
}
String authorizationHeader = String.Format(
CultureInfo.InvariantCulture,
"{0} {1}:{2}",
"SharedKey",
account,
signature);
return authorizationHeader;
}
}
}
receiving the error:
"Property or indexer
'Microsoft.Reporting.WebForms.IReportServerCredentials.NetworkCredentials'
cannot be assigned to-- it is read only"
within this line:
reportviewer1.ServerReport.ReportServerCredentials.NetworkCredentials
= new System.Net.NetworkCredential("someaccount",
"somepassword");
When I hover the cursor on NetworkCredentials, it says: "Gets or sets the network credentials that are used for authentication with report server"..
what the heck is going on here?
thanks
this.rpv.ServerReport.ReportServerCredentials is not read-only. Read this post:
http://www.visualstudiodev.com/visual-studio-report-controls/reportviewerserverreportreportservercredentialsnetworkcredentials-readonly-24629.shtml
it is still read only, that ReportServerCredentials field is still read only, it has only getter but not a setter !
add this class to the same namespace:
public class CustomReportCredentials : IReportServerCredentials
{
private string _UserName;
private string _PassWord;
private string _DomainName;
public CustomReportCredentials(string UserName, string PassWord, string DomainName)
{
_UserName = UserName;
_PassWord = PassWord;
_DomainName = DomainName;
}
public System.Security.Principal.WindowsIdentity ImpersonationUser
{
get { return null; }
}
public ICredentials NetworkCredentials
{
get { return new NetworkCredential(_UserName, _PassWord, _DomainName); }
}
public bool GetFormsCredentials(out Cookie authCookie, out string user,
out string password, out string authority)
{
authCookie = null;
user = password = authority = null;
return false;
}
}
Then set your credentials like this:
IReportServerCredentials Creds = new CustomReportCredentials("Administrator", "password", "domain"); //to actual values
myReportViewer.ServerReport.ReportServerCredentials = Creds;
in .NET core as well in .NET 5.0 replace "reportViewer.ServerReport.ReportServerCredentials" with "reportViewer.ServerReport.ReportServerCredentials.NetworkCredentials = new System.Net.NetworkCredential(Username,Password,Domain);"
also you Should install "Microsoft.Reporting.WinForms" NuGet
I have a method that sets a property
public void SetNetworkCredential(string userName, string password, string domain)
{
_reportExecutionService.Credentials = new NetworkCredential(userName, password, domain);
}
how do I verify that Credentials was called with a valid NetworkCredential?
I tried this TestMethod but it fails because the NetworkCredential objects are different references
[TestMethod]
public void TestTest()
{
const string userName = "userName";
const string password = "password";
const string domain = "domain";
var mock = MockRepository.GenerateMock<IReportExecutionService>();
var rptService= new ReportService(mock);
rptService.SetNetworkCredential(userName, password, domain);
mock.AssertWasCalled(x => x.Credentials = new System.Net.NetworkCredential(userName, password, domain));
}
Is there a way to validate that the setter was called with an object of type NetworkCredential and with the correct parameters?
I fixed it by making the ReportService accept a Network Credential instead of the username, password, domain
public void SetNetworkCredential(NetworkCredential networkCredential)
{
_reportExecutionService.Credentials = networkCredential;
}
so my test was much easier
[TestMethod]
public void TestTest()
{
const string userName = "userName";
const string password = "password";
const string domain = "domain";
var mock = MockRepository.GenerateMock<IReportExecutionService>();
var rptService= new ReportService(mock);
var networkCredential = new System.Net.NetworkCredential(userName, password, domain);
rptService.SetNetworkCredential(networkCredential);
mock.AssertWasCalled(x => x.Credentials = networkCredential);
}
Edit: Rethinking this problem, my previous suggested answer would probably not work. Here's why:
Essentially, you are attempting to verify that the dependency of a dependency has been set up correctly. That is probably why you are having problems writing a unit test for this. You probably want to consider whether it would make sense for you to move the SetNetworkCredential method into the class that implements IReportExecutionService instead.
And if you do, the unit test for that method would be simple enough:
[Test]
public void TestSetNetworkCredential()
{
const string userName = "userName";
const string password = "password";
const string domain = "domain";
var rptService= new ReportExecutionService();
rptService.SetNetworkCredential(userName, password, domain);
Assert.AreEqual(userName, rptService.Credentials.UserName);
Assert.AreEqual(password, rptService.Credentials.Password);
Assert.AreEqual(domain, rptService.Credentials.Domain);
}