I am developing a WebService in C # however I am facing an error.
This is the error :
System.Security.Authentication.AuthenticationException: A call to SSPI failed, see inner exception. ---> System.ComponentModel.Win32Exception: The message or signature supplied for verification has been altered
So I sometimes get this error when I open my MySQL connection in my WebService.
I had this error by launching my webService twice at the same time then I tried again and no more errors.
My web service is on a Windows server 2012 R2 and i'm using .NET Framework 4.7.2 (It is called by the website php).
I did quite a bit of internet research and came across this in C# :
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
But it doesn't work, Do you have any idea so that I do not face this problem again ?
There is my MySQL open connection method :
public MySqlConnection OpenConnectionDB(string clientId)
{
listVerifs = new List<string>();
int iConn = 0;
try
{
MySqlConnection sqlCo = new MySqlConnection("server=MyServer;database=" + this.db + ";username=MyUID;password=MyPwd;AllowLoadLocalInfile=true");
if (sqlCo.State != ConnectionState.Open)
{
sqlCo.Open();
}
listVerifs.Add("CO SQL");
dataSourceDBF = #"//ntserver/Winbooks_Data/winbooks/data/" + clientId + "/";
dbfCo = new AdsConnection(#"data Source=//ntserver/Winbooks_Data/winbooks/data/" + clientId + "/" + clientId + ".add;User ID=mYUID;Password=;ServerType=local;ReadOnly=true;pooling=true;TrimTrailingSpaces=true;TableType=CDX;LockMode=COMPATIBLE");
if (dbfCo.State == ConnectionState.Closed)
{
dbfCo.Open();
}
listVerifs.Add("CO DBF");
Console.WriteLine("Databases connections open succesfull");
return sqlCo;
}
catch (Exception e)
{
dbfCo = null;
Console.WriteLine("Error connection " + e.Message);
test = e.Message;
log.AddLog("Erreur Fonction OpenConnectionDB : " + e.ToString(), 3, "WebServiceMySQL");
return null;
}
Thank's in advance !
Related
I am working on an application that connects to Dynamics 365 and creates contacts there, for example.
My question now is how to configure the login.
For testing, multi-factor authentication is disabled and it works so far. However, in the production system, MFA will be active.
I want to avoid users using an app password.
Is there a way to pop up the standard O365 login popup window from within a WinForms application?
Unfortunately I couldn't find anything about it.
What would make the most sense here?
Thats my code so far:
public CrmServiceClient connect_crm()
{
string ConnectionString = "AuthType = OAuth; " +
"Username= " + textBox1.Text + ";" +
"Password=" + textBox2.Text + ";" +
"Url=https://company.dynamics.com;" +
"RedirectUri=app://;" +
"AppId=XXXXXXXX-XXXXX-XXXX-XXXX-XXXXXXXXXXXXX;" +
"LoginPrompt=Auto";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
svc = new CrmServiceClient(ConnectionString);
try
{
if (svc != null && svc.IsReady)
{
label4.BackColor = Color.LightGreen;
label4.Text = "Connected";
CreateContact2(svc);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return svc;
}
I've got the solution!
You need to use the client secret from the app, you registered in azure.
And you have to create an application user in dynamics. (via power platform admin ceter)
See here: https://softchief.com/2021/08/03/connect-dynamics-365-from-console-c-application-in-mfa-enabled-access-using-client-secret-and-azure-client-id/
public CrmServiceClient connect_crm()
{
string ConnectionString = "AuthType = ClientSecret; " +
"Url=https://company.dynamics.com;" +
"ClientId=XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX;" + //AppID
"ClientSecret=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; //ClientKey
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
svc = new CrmServiceClient(ConnectionString);
try
{
if (svc != null && svc.IsReady)
{
label4.BackColor = Color.LightGreen;
label4.Text = "Connected!";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return svc;
}
I am trying to execute a piece of Azure script to check if the user object is synced from on-prem AD to Azure as below.
username follows the pattern of a UPN. example: john.Smith#ed.com
//Check Azure to see if user is synced to office 365
private static bool IsAccountSyncedToOffice365(string username)
{
StringBuilder cmd = CreateAzureConnectScript();
//cmd.AppendLine("Get-MsolUser -UserPrincipalName " + username + " -ErrorAction SilentlyContinue");
cmd.AppendLine("$global:res = \"false\"");
cmd.AppendLine("$global:user = \"false\"");
cmd.AppendLine("try{ if(($global:user=Get-MsolUser -UserPrincipalName " + username + " -ErrorAction Stop).ImmutableId -ne $null) { $global:res = \"true\"} } Catch { $global:errorMessage = $_.Exception.Message}");
try
{
Collection<PSObject> results;
string output, error, errorMessageAzureCnn = "";
do
{
results = null;
output = "";
error = "";
var rs = CreateAzureRunspace();
var pipe = rs.CreatePipeline();
pipe.Commands.AddScript(cmd.ToString());
results = pipe.Invoke();
output = (rs.SessionStateProxy.PSVariable.GetValue("res")) != null ? rs.SessionStateProxy.PSVariable.GetValue("res").ToString() : "false";
error = (rs.SessionStateProxy.PSVariable.GetValue("errorMessage")) != null ? rs.SessionStateProxy.PSVariable.GetValue("errorMessage").ToString() : "null";
errorMessageAzureCnn = (rs.SessionStateProxy.PSVariable.GetValue("errorMessageAzureCnn")) != null ? rs.SessionStateProxy.PSVariable.GetValue("errorMessageAzureCnn").ToString() : "null";
ExceptionManager.Publish(new Exception("LOG: Queried Azure at:" + DateTime.Now + " for user:" + username + " Result: " + output + " Error: " + error + " errorMessageAzureCnn: " + errorMessageAzureCnn));
Thread.Sleep(60000); //sleep for 60 seconds
pipe.Dispose();
rs.Close();
rs.Dispose();
} while (output.Trim().ToLower() != "true");
ExceptionManager.Publish(new Exception("LOG: " + username + " is found synced to Azure at: " + DateTime.Now));
cmd.Clear();
return true;
}
catch (Exception ex)
{
ExceptionManager.Publish(new Exception("Error checking Azure to see if the user is synced to office 365 or not.. " + ex.Message));
throw ex;
}
}
private static StringBuilder CreateAzureConnectScript()
{
StringBuilder ss = new StringBuilder();
MSCredential cred = new MSCredential();
var username = cred.username;
var pwd = cred.password;
try
{
ss.AppendLine("try {");
ss.AppendLine("$password = ConvertTo-SecureString \"" + pwd + "\" -AsPlainText –Force");
ss.AppendLine("$credential = New-Object System.Management.Automation.PsCredential(\"" + username + "\",$password)");
ss.AppendLine("$cred = Get-Credential -cred $credential");
ss.AppendLine("Import-Module MSOnline");
ss.AppendLine("Start-Sleep -s 10");
ss.AppendLine("Connect-Msolservice -cred $cred");
ss.AppendLine("} Catch { $global:errorMessageAzureCnn = $_.Exception.Message }");
//ExceptionManager.Publish(new Exception("LOG:pwd: " + pwd + " uname:" + username));
return ss;
}
catch (Exception ex)
{
ExceptionManager.Publish(new Exception("Error enabling the remote mailbox.. " + ex.Message));
throw ex;
}
}
While the script executes successfully through Powershell Window on the same server having got all the latest versions of the modules installed. When trying to execute the same command from C# code it throws the below exception collected from the powershell exception handling $global:errorMessage = $_.Exception.Message.
Show Details Exception (0): [] LOG: Queried Azure at:7/30/2015 12:00:55 PM for user:testuser0385#xxx.com Result: false Error: You must call the Connect-MsolService cmdlet before calling any other cmdlets. errorMessageAzureCnn: null
Worth mentioning that I have got the same code as below working in one server but it is throwing the below error on a production server (Windows Server 2008 R2 Datacenter) and only via the code it is happening. via the powershell window it works perfectly fine.
Good to know your thoughts about what looks wrong or needed to be looked into.
Thanks!
It suggests that the sign in is failing, but you're pushing on with the Get-MsolUser anyway. The Connect-MsolService cmdlet fails if it cannot communicate to the Microsoft Online Services Sign-In Assistant. Ref: https://community.office365.com/en-us/f/156/t/252201
Has the production server got all the pre-requisites installed: Microsoft Online Services Sign-In Assistant and .NET 3.5? We had a problem in production (Azure PAAS) where the guest OS image was automatically updated and was missing .NET 3.5, which broke our Azure AD PowerShell processes.
I am building an application which has a database on the server machine and I am using this method for database access:
public static string GetDefaultConnectionString()
{
//get my db info from ini file
dbinfo DatabaseInfo = new dbinfo();
DatabaseInfo = GetDatabaseInfo();
if (DatabaseInfo.dbName == "" || DatabaseInfo.Password == "" || DatabaseInfo.Server == "" || DatabaseInfo.UserId == "")
{
throw new Exception("Database config file is not valid");
}
else
{
MessageBox.Show("Db name " + DatabaseInfo.dbName);
MessageBox.Show("User " + DatabaseInfo.UserId);
MessageBox.Show("Db Pass " + DatabaseInfo.Password);
MessageBox.Show("Db Server " + DatabaseInfo.Server);
}
string conStrIntegratedSecurity = new System.Data.EntityClient.EntityConnectionStringBuilder
{
Metadata = "res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl",
Provider = "System.Data.SqlClient",
ProviderConnectionString = new System.Data.SqlClient.SqlConnectionStringBuilder
{
InitialCatalog = DatabaseInfo.dbName,
DataSource = DatabaseInfo.Server,
IntegratedSecurity = true,
UserID = DatabaseInfo.UserId,
Password = DatabaseInfo.Password,
MultipleActiveResultSets = true,
ConnectTimeout = 0,
MaxPoolSize = 500,
}.ConnectionString
}.ConnectionString;
//MessageBox.Show(conStrIntegratedSecurity);
return conStrIntegratedSecurity;
}
and it works fine in server pc.
But, when I install this application on any client machine, it cannot open a connection and it gives the following error message:
System.Data.EntityException: The underlying provider failed on Open. --->
System.Data.SqlClient.SqlException: Cannot open database "dbName" requested by the login. The login failed.
Login failed for user 'ServerName\User'.
Does anyone know why this is happening?
I just use
IntegratedSecurity = true,
to
IntegratedSecurity = false,
and it works!
I am trying to connect to my companies Exchange 2003 server using RDO & MAPI which I've never done before. I have found a pretty good site that uses Outlook's Redemption (http://www.dimastr.com/redemption/home.htm) but with all of the examples on the site using VB.NET and me not being great at programming it's a bit difficult to get this working.
So far I have this code
static void ConnectToExchange()
{
object oItems;
//string outLookUser = "My Profile Name";
string outLookUser = "username#xxx.xxxx";
string ToEmailAddress = "username#xxxx.com";
string FromEmailAddress = "username#xxx.com";
string outLookServer = "xxservernamexx";
string sMessageBody =
"\n outLookUser: " + outLookUser +
"\n outLookServer: " + outLookServer +
"\n\n";
RDOSession Session = new RDOSession();
try
{
Session.LogonExchangeMailbox(outLookUser,outLookServer);
int mailboxCount = Session.Stores.Count;
string defaultStore = Session.Stores.DefaultStore.Name;
RDOFolder TestTaxCert = Session.GetFolderFromPath(#"\\Public Folders\All Public Folders\TestTaxCert");
}
catch (Exception ex)
{
Session = null;
//System.Web.Mail.SmtpMail.Send(ToEmailAddress, FromEmailAddress, "Error", sMessageBody + " " + ex.Message);
}
finally
{
if ((Session != null))
{
if (Session.LoggedOn)
{
Session.Logoff();
}
}
}
}
}
My problem is that once the program hits the Session.LogonExchangeMailbox(outLookUser,outLookServer); line, a prompt appears asking for my credentials (username, domain, password) and no matter what information I fed the prompt it denied permission.
SO if someone can help me with that and then also with connecting to the public folders...that'd be greaaat
Make sure your code is running as the domain user specified in the call to LogonExchangeMailbox.
Did you really mean 2003, or is it Exchange 2013?
I have the following code, just to test connection:
public void Test()
{
SqlCeConnection conn = new SqlCeConnection(#"Data Source=/Application/Database.sdf;");
try
{
conn.Open();
label1.text = "Connection!";
}
catch (Exception ee)
{
label1.text = "No connection!";
}
}
When trying to connect to this database, the application throws an exception at conn.Open() saying
SqlCeException was unhandled
and nothing more. The exception message is blank, so I'm having a hard time figuring out what went wrong.
The database file is there, and the application returns true with
File.Exist(#"/Application/Database.sdf");
so it does have access to the file.
I'm probably doing something really wrong here, can anyone help me out with this?
I'm using Compact Framework 2.0 on Windows CE 5, and the application in question is an existing one. I'm trying to add a database to it so I can load large amounts of data much more easier.
What Erik is saying is change your code to this:
public void Test()
{
SqlCeConnection conn = new SqlCeConnection(#"Data Source=/Application/Database.sdf;");
try
{
conn.Open();
label1.text = "Connection!";
}
catch (SqlCeException ee) // <- Notice the use of SqlCeException to read your errors
{
SqlCeErrorCollection errorCollection = ee.Errors;
StringBuilder bld = new StringBuilder();
Exception inner = ee.InnerException;
if (null != inner)
{
MessageBox.Show("Inner Exception: " + inner.ToString());
}
// Enumerate the errors to a message box.
foreach (SqlCeError err in errorCollection)
{
bld.Append("\n Error Code: " + err.HResult.ToString("X"));
bld.Append("\n Message : " + err.Message);
bld.Append("\n Minor Err.: " + err.NativeError);
bld.Append("\n Source : " + err.Source);
// Enumerate each numeric parameter for the error.
foreach (int numPar in err.NumericErrorParameters)
{
if (0 != numPar) bld.Append("\n Num. Par. : " + numPar);
}
// Enumerate each string parameter for the error.
foreach (string errPar in err.ErrorParameters)
{
if (String.Empty != errPar) bld.Append("\n Err. Par. : " + errPar);
}
}
label1.text = bld.ToString();
bld.Remove(0, bld.Length);
}
}
The generic Exception you are catching right now can not give you the details of the SqlCeException.