Invalid authorization specification and Invalid connection string attribute - c#

I am getting the following error "Invalid authorization specification, Invalid connection string attribute"
//namespaces
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Data.OleDb;
namespace Database1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public bool IsValidConnectionForPrinting()
{
//string declaration
string str = #" Provider = SQLOLEDB; Data Source = sekhar; Database = DMS; UserId = sa; Password = 123";
//Oledbconnection to database
OleDbConnection oleDbcon = new OleDbConnection(str);
try
{
oleDbcon.Open();
MessageBox.Show("hai");
oleDbcon.Close();
}
//Exception
catch (Exception ex)
{
if (ex.Message.StartsWith("Invalid object name"))
{
MessageBox.Show(ex.Message.Replace("Invalid object name", "Table or view not found"), "Connection Test");
}
//Connection
private void btnConnTest_Click(object sender, EventArgs e)
{
if (IsValidConnectionForPrinting())
{
MessageBox.Show("Connection succeeded", "Connection Test");
}
}
}
}

I would recommend using a connection string that does not include Database or Initial Catalog, and then calling something like:
oleDbcon.ChangeDatabase("DMS");
This is because, as you have already experienced, different database drivers use different syntax for referring to the database in the connection string.

I had this error and it turned out the code path had not connected to the database.
Worth checking.

Related

Xamarin forms with firebase user registration error

i am developing an app using xamarin forms and firebase authentication
with xamarin.firebase.auth and xamarin.firebase.core
when i want to create a new user the code works fine but it gives me the exception
Java.Lang.IllegalStateException: 'Task is not yet complete'
when i trace the code line by line every thing works just fine and i get no errors but when running the app after creating user it gives me the exception.
this is my code:
inerface in pcl:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace XamarinFirebaseAuth
{
public interface IAuth
{
Task<string> LoginWithEmailPassword(string email, string password);
bool SignUpWithEmailPassword(string email, string password);
}
}
android implementation:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Foundation;
using UIKit;
using XamarinFirebaseAuth;
using XamarinFirebaseAuth.iOS;
using Firebase.Auth;
using System.Threading.Tasks;
using Xamarin.Forms;
[assembly: Dependency(typeof(AuthIOS))]
namespace XamarinFirebaseAuth.iOS
{
public class AuthIOS : IAuth
{
public async Task<string> LoginWithEmailPassword(string email, string password)
{
try
{
var user = await Auth.DefaultInstance.SignInWithPasswordAsync(email, password);
var token = user.User.GetIdTokenAsync();
return token.ToString();
}
catch(Exception e)
{
return "";
}
}
public bool SignUpWithEmailPassword(string email, string password)
{
try
{
var signUpTask = Auth.DefaultInstance.CreateUserAsync(email, password);
return true;
}
catch (Exception e)
{
throw;
//return false;
}
}
}
}
and this is my sign up page :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace XamarinFirebaseAuth
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SignUpPage : ContentPage
{
IAuth auth;
public SignUpPage()
{
InitializeComponent();
auth = DependencyService.Get<IAuth>();
}
private async void btnRegister_Clicked(object sender, EventArgs e)
{
try
{
bool created = auth.SignUpWithEmailPassword(EmailInput.Text, PasswordInput.Text);
if (created)
{
await DisplayAlert("Success", "Your account created successfully", "OK");
await Navigation.PopAsync();
}
else
{
await DisplayAlert("Error", "Something went wrong. Try again later!", "OK");
}
}
catch
{
throw;
}
}
}
}
I think you should await the CreateUserAsync method to know whether the account is created successfully or not:
AuthDataResult signUpTask = await Auth.DefaultInstance.CreateUserAsync(email, password);
Then you can get the user info:
await signUpTask.User.GetIdTokenAsync();

Error downloading metadata from ASMX-webservice C#

I've been working on a small MVC-project which since I converted to more of an MVC-approach has stopped working.
The program consuming the web-service is a simple console-application with its own controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication.ServiceReference1;
namespace ConsoleApplication
{
class ConsoleController
{
ServiceReference1.WebService2SoapClient webservice = new ServiceReference1.WebService2SoapClient();
public List<Employee> GetEmployees()
{
return webservice.GetEmployees().ToList();
}
}
}
The web-service consists of a Employee-class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace webservice
{
public class Employee
{
public string _socialSN { get; set; }
public string _lastName { get; set; }
public string _firstName { get; set; }
public Employee(string socialSN, string firstName, string lastName)
{
this._firstName = firstName;
this._lastName = lastName;
this._socialSN = socialSN;
}
}
}
A data access layer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace webservice
{
public class DAL
{
private SqlConnection con;
private SqlCommand cmd;
public void GetConnection()
{
con = new SqlConnection("Data Source=****;Initial Catalog=DB2015;Persist Security Info=True;User ID=****;Password=***********");
}
public List<Employee> GetEmployees()
{
GetConnection();
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = "SELECT SocialSN, Name, Surname FROM Employee";
SqlDataReader reader = cmd.ExecuteReader();
List<Employee> employeeList = new List<Employee>();
if (reader.HasRows)
{
while (reader.Read())
{
employeeList.Add(new Employee(reader.GetString(0), reader.GetString(1), reader.GetString(2)));
}
}
else
{
employeeList = null;
}
reader.Close();
con.Close();
reader.Dispose();
con.Dispose();
return employeeList;
}
}
}
A BackController:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace webservice
{
class BackController
{
DAL dal = new DAL();
public List<Employee> GetEmployees()
{
return dal.GetEmployees();
}
}
}
And finally the webservice-code itself:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
namespace webservice
{
/// <summary>
/// Summary description for WebService2
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService2 : System.Web.Services.WebService
{
BackController bcontroller = new BackController();
[WebMethod]
public List<Employee> GetEmployees()
{
return bcontroller.GetEmployees();
}
}
}
Whenever I try to add a new service-reference to my console-application I get this error:
Error part 1 http://i.imgur.com/UVw1cAO.png
Error part 2 http://i.imgur.com/N0dF159.png
I cannot figure out what is wrong. It worked fine before I changed to MVC. I've tried to clean the projects, rebuild them and create them all from scratch again and just simply won't work.
Please let me know if you've got any ideas what could be wrong or if you need additional information.
Thanks!
It sounds like you've upgraded some components but the code is still trying to latch onto the old version. Essentially something in your code is looking for say version 1.1.0.1 and you've got version 2.1.0.1. or something like that. You'll need to either redirect to the correct assembly in your web config or find another way to get your application to accept the newer version.
Here are some links you can check out for some tips but these can be elusive bugs to sort out.
From stackoverflow:
The located assembly's manifest definition does not match the assembly reference.
that link has this one inside it:
http://blogs.msdn.com/b/junfeng/archive/2004/03/25/95826.aspx
And here is an independent blogger's take on it:
http://www.codingdefined.com/2014/10/error-located-assemblys-manifest.html

I am trying to connect to SQL Server by using the using(){} .. but my Visual Studio shows the following error :

Error
Invalid token 'using' in class, struct, or interface member declaration
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace BusinessLayer
{
class EmployeeBusinessLayer
{
String Connectionstring = ConfigurationManager.ConnectionStrings["DBConStr"].ConnectionString;
using(SqlConnection con = new SqlConnection()){
}
}
}
You're attempting to use the using statement at the class scope, which is invalid. Try the following:
public void YourMethod() {
string connStr = ConfigurationManager.ConnectionStrings["DBConStr"].ConnectionString.ToString();
using(SqlConnection connection = new SqlConnection()) {
//do something
}
}

Project Server Console Application Error: The type name 'LoginWindows' does not exist in the type 'ProjectServer.WebSvcLoginWindows'

I can't figure out how to get rid of this error. I'm very new to C#, but please give any assistance you can. Thanks
Error: The type name 'LoginWindows' does not exist in the type 'ProjectServer.WebSvcLoginWindows'
Source Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using ProjectServer.LoginForms;
using ProjectServer.Statusing;
using ProjectServer;
using System.Net;
using System.Threading;
using PSLibrary = Microsoft.Office.Project.Server.Library;
using System.Windows.Forms.MessageBox;
using System.Windows.Forms;
namespace ProjectServer
{
public partial class LogonProjectServer : Form
{
public static WebSvcLoginWindows.LoginWindows loginWindows =
new WebSvcLoginWindows.LoginWindows();
public static CookieContainer cookies = new CookieContainer();
public static WebSvcProject.LoginForms loginForms =
new SyprisProjectServer.WebSvcProject.LoginForms();
private const string LOGINFORMSWEBSERVICE = "/PWA/_vti_bin/PSI/LoginForms.asmx?wsdl";
private const string LOGINWINDOWSWEBSERVICE = "/PWA/_vti_bin/PSI/LoginWindows.asmx?wsdl";
private string baseUrl; // Example: http://ServerName/ProjectServer/
public bool LogonPS(bool useWinLogon, string baseUrl,
string userName, string password)
{
const string LOGINWINDOWS = "PWA/_vti_bin/PSI/LoginWindows.asmx?wsdl";
const string LOGINFORMS = "PWA/_vti_bin/PSI/LoginForms.asmx?wsdl";
bool logonSucceeded = false;
try
{
if (useWinLogon)
{
loginWindows.Url = baseUrl + LOGINWINDOWS;
loginWindows.Credentials = CredentialCache.DefaultCredentials;
if (loginWindows.Login()) logonSucceeded = true;
}
}
// Catch statements
catch (System.Web.Services.Protocols.SoapException ex)
{
MessageBox.Show(ex.Message.ToString(), "Logon Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (System.Net.WebException ex)
{
MessageBox.Show(ex.Message.ToString(), "Logon Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return logonSucceeded;
}
}
}
The problem is likely due to either the class name (LoginWindows) or the namespace (WebSvcLoginWindows) being incorrect when you create the loginWindows variable:
public static WebSvcLoginWindows.LoginWindows loginWindows = new WebSvcLoginWindows.LoginWindows();
Make sure the namespace and class name are spelled correctly and have the correct capitalisation.
If the class is contained in a separate asssembly, make sure your winforms project has a reference to the other assembly.
Hope that helps.
Check your build configuration and make sure all referenced projects are being built and being built for the correct configuration (64 vs 32 bit). Also, ensure you are using the correct version of any referenced dlls.

Connecting to a SQL server using ADODB from a C# dll

I am writing a custom Connection class in C# for Excel to be able to connect to a SQL Server.
When I use SQLConnection from System.Data.SqlClient library I am able to establish a connection. The working code I've got:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Runtime.InteropServices;
namespace Test
{
[InterfaceType(ComInterfaceType.InterfaceIsDual),
Guid("6E8B9F68-FB6C-422F-9619-3BA6D5C24E84")]
public interface IConnection
{
bool Status { get; }
bool Open();
}
[ClassInterface(ClassInterfaceType.None)]
[Guid("B280EAA4-CE11-43AD-BACD-723783BB3CF2")]
[ProgId("Test.Connection")]
public class Connection : IConnection
{
private bool status;
private SqlConnection conn;
private string connString = "Data Source=[server]; Initial Catalog=[initial]; User ID=[username]; Password=[password]";
public Connection()
{
}
public bool Status
{
get
{
return status;
}
}
public bool Open()
{
try
{
conn = new SqlConnection(connString);
conn.Open();
status = true;
return true;
}
catch(Exception e)
{
e.ToString();
return false;
}
}
}
}
And after adding the reference to Excel I am able to test the connection using a simple VBA code like this:
Sub TestConnection()
Dim conn As Test.Connection
Set conn = New Test.Connection
Debug.Print conn.Status
conn.Open
Debug.Print conn.Status
End Sub
It outputs:
False
True
So everything is fine. Now I would like to create custom Recordset class in my C# library so I decided to use an ADODB library and its RecordSetinstead of SqlDataReader as I am planning to work with some big chunks of data. So, I have modified my code to this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Runtime.InteropServices;
namespace Test
{
[InterfaceType(ComInterfaceType.InterfaceIsDual),
Guid("6E8B9F68-FB6C-422F-9619-3BA6D5C24E84")]
public interface IConnection
{
bool Status { get; }
bool Open();
}
[ClassInterface(ClassInterfaceType.None)]
[Guid("B280EAA4-CE11-43AD-BACD-723783BB3CF2")]
[ProgId("Test.Connection")]
public class Connection : IConnection
{
private bool status;
private ADODB.Connection conn = new ADODB.Connection();
private string connString = "Data Source=[server]; Initial Catalog=[initial]; User ID=[username]; Password=[password]";
public Connection()
{
}
public bool Status
{
get
{
return status;
}
}
public bool Open()
{
try
{
conn.ConnectionString = connString;
conn.Open();
// conn.Open(connString, ["username"], ["password"], 0)
// what else can I try? is this where it actually fails?
status = true;
return true;
}
catch (Exception e)
{
e.ToString();
return false;
}
}
}
}
I also have added references to Microsoft ActiveX Data Objects 6.1 Library.
Now, when I am executing the VBA code it outputs:
0
0
But I was expecting 0 and 1. It seems to me like I am not properly connecting to the server ( credentials are the same i have just removed actual data from this code ).
I have tried to use different variations of the connection string, however it always returns 0 and 0. I have tried creating a new project with new GUIDs and also tried renaming the projects, classes, etc. nothing has worked. I am suspecting its the establishment of the connection but I am unsure how to debug a dll.
I have used link1, link2, link3, link4 for reference
Update:
I have wrote the exception to the file as TheKingDave suggested. This is the exception error message
System.Runtime.InteropServices.COMException (0x80004005):
[Microsoft][ODBC Driver Manager] Data source name not found and no
default driver specified at ADODB._Connection.Open(String
ConnectionString, String UserID, String Password, Int32 Options) at
TestADODB.Connection.Open() in c:\Users\administrator\Documents\Visual
Studio 2012\Projects\Test\Test\Connection.cs:line 49
The connection string is missing Provider=SQLOLEDB.
The ADODB.Connection needs to know what type of database it is connecting to.

Categories