I am new at this. I am doing an ASP.NET tutorial, but I can't I connect to SQL Server 2016 Express from VS. I get the error below:
An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code
Additional information: Instance failure.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace tree_view_control_tutorial_2
{
public partial class WebForm4 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetData(null);
}
}
private void GetData(string searchTerm)
{
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spSearchStudents", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter searchParameter = new SqlParameter("#SearchTerm", searchTerm);
cmd.Parameters.Add(searchParameter);
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
}
}
}
How do I fix this? Thanks!
Your connection string in web.config should be like below one.
<connectionStrings>
<add name="DBCS"
connectionString="Data Source=.\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
Since you are getting instance failure,it is problem with the creation of instance of SQL server,just check whether the SQL server is up and running when you execute your application.
To check the services,just type services.msc in your run dialogue window.
Figured it out! My connection string is on the Web.config page which is XML, not C#, so the Data Source should have been ".\SQLEXPRESS" (one \ only!)
Related
I have an asp.net web form and when a button event is clicked i would like to have one of my database table columns called quantity subtract from its already stored integer number.
I am aware some sort of SQL statement will be needed to minus the quantity column by 1 but am unsure of how to achieve this.
any feedback would be appreciated.
Create a stored procedure as an update query.
USE [MyDB]
GO
Create Procedure [dbo].[myproc]
(
#SomeID bigint,
)
as
set nocount on
update MyTable set
MyField=SomeMath-SomeMath,
where SomeID=#SomeID
Then need to link it on the web page (aspx.cs)
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _MyPage : System.Web.UI.Page
{
DataSet ds = new DataSet();
SqlConnection con;
//Here we declare the parameter which we have to use in our application
SqlCommand cmd = new SqlCommand();
SqlParameter Id = new SqlParameter();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
con = new SqlConnection("server=(local); database=mydb;uid=myuser;pwd=Mypass");
cmd = new SqlCommand("myproc", con);
cmd.Parameters.Add("#ID", SqlDbType.BigInt);
cmd.Parameters["#ID"].Value = MyValue;
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect("ThanksPage.aspx");
}
}
I study NHibernate and try to repeat the creating an application from the video course,
I created database, model, XML-file and then I wrote this code
using System;
using System.Reflection;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;
namespace NHibernateDemo
{
internal class Program
{
static void Main(string[] args)
{
var cfg = new Configuration();
cfg.DataBaseIntegration(x =>
{
x.ConnectionString = "Server=localhost; Database=NHibernateDemo; Integrated Security = SSPI";
x.Driver<SqlClientDriver>();
x.Dialect<MsSql2008Dialect>();
});
cfg.AddAssembly(Assembly.GetExecutingAssembly());
var sessionFactory = cfg.BuildSessionFactory();
using (var session = sessionFactory.OpenSession())
using (var tx = session.BeginTransaction())
{
var customers = session.CreateCriteria<Customer>()
.List<Customer>();
foreach (var customer in customers)
{
Console.WriteLine("{0} {1}", customer.FirstName, customer.LastName);
}
tx.Commit();
Console.WriteLine("Enter any key to exit...");
Console.ReadKey();
}
}
}
}
but when I tried to debug it I got SqlExeption was unhandled
I suppose I need to add login and password in my code, but can someone explain me how to do it?
You are using integrated securty, the user which is running your code has to have access:
Server=localhost; Database=NHibernateDemo; Integrated Security = SSPI
You can change your connection string to use a sql account or give the user access to your database.
Configure connectionstrings: connectionstrings
How can I replace and extend this code to use password and username in authentication credentials. I was trying to solve this by analyzing examples in mscrm sdk but without luck since I`m not c# programmer.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk.Client;
using System.Net;
using Microsoft.Xrm.Sdk;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void id_Click(object sender, EventArgs e)
{
AuthenticationCredentials authCredentials = new AuthenticationCredentials();
//Authenticate using credentials of the logged in user;
ClientCredentials Credentials = new ClientCredentials();
Uri OrganizationUri = new Uri("http://Crm/Contoso/XRMServices/2011/Organization.svc");
Uri HomeRealmUri = null;
//OrganizationServiceProxy serviceProxy;
using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, Credentials, null))
{
IOrganizationService service = (IOrganizationService)serviceProxy;
//Instantiate the contact object and populate the attributes.
Entity contact = new Entity("contact");
contact["firstname"] = txtFirstName.Text.ToString();
contact["lastname"] = txtLastName.Text.ToString();
Guid newContactId = service.Create(contact);
}
}
}
Thanks!
I'm going to assume you are using Active Directory authentication here. There is a rather long winded example on the MSDN which shows how to create a connection for all authentication methods.
I believe you only have to change:
ClientCredentials Credentials = new ClientCredentials();
To:
ClientCredentials Credentials = new ClientCredentials();
Credentials.UserName.UserName = "domain\username";
Credentials.UserName.Password = "password";
I would recommend using default credentials if at all possible, if not possible then we use something like this:
ClientCredentials creds = new ClientCredentials();
creds.Windows.ClientCredential = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["username"], ConfigurationManager.AppSettings["password"], ConfigurationManager.AppSettings["domain"]);
Obvious downside of this method is that the password is in cleartext, but the upside is that you don't need to recompile to change password or user.
I am new to Telerik reporting. I have been trying to follow this KB article, more or less.
The approach described there bypasses the Wizard. I need to bypass the Wizard because the database is SQL Server 2000 and the Wizard demands 2005 or later.
I drag and drop a sqlDataAdapter to the report from the Toolbox. The adapter is configured in the report's constructor.
When I add a text field to my report and go to its properties page and click on the ellipsis [...] button for Value and the click "Fields" in the lower left section of the dialog, the pane to the right says "No Data Source".
How to get the datasource to be recognized at design-time? What am I missing? Thanks
namespace EventsReportingClassLibrary
{
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using Telerik.Reporting;
using Telerik.Reporting.Drawing;
/// <summary>
/// Summary description for Report1.
/// </summary>
public partial class Report1 : Telerik.Reporting.Report
{
private SqlConnection CNN;
private SqlDataAdapter DA
{
get { return sqlDataAdapter1; // dropped from the toolbox onto report}
}
private string ConnectionString
{
get { return "server=server5\\SQL2K;Initial Catalog=foo;User Id=foo2;Password=foo3;Pooling=yes"; }
}
public Report1()
{
InitializeComponent();
CNN = new SqlConnection(ConnectionString);
DA.SelectCommand = new SqlCommand("select * from myView",CNN);
DA.SelectCommand.CommandType = CommandType.Text;
this.DataSource = DA;
}
private void Report1_NeedDataSource(object sender, System.EventArgs e)
{
// fires at run-time if datasource of this report is null
}
}
}
I am trying to build a small WCF service and wanted to utilize it in a test application.
PFB service code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace HelloIndigo
{
[ServiceContract(Namespace="http://www.thatindigoirl.com/samples/2006/06")]
public interface IHelloIndigoService
{
[OperationContract]
string HelloIndigo();
}
public class HelloIndigoService : IHelloIndigoService
{
public string HelloIndigo()
{
return "Hello indigo";
}
}
}
Host Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace Host
{
class Program
{
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(HelloIndigo.HelloIndigoService), new Uri("http://localhost:8000/HelloIndigo")))
{
host.AddServiceEndpoint(typeof(HelloIndigo.IHelloIndigoService), new BasicHttpBinding(), #"HelloIndigoService");
host.Open();
Console.WriteLine("Press <ENTER> to terminate the service hosy");
Console.ReadLine();
}
}
}
}
Whenever I am trying to run Host I am getting below mentioned error in host.Open() statement.
HTTP could not register URL
http://+:8000/HelloIndigo/. Your
process does not have access rights to
this namespace (see
http://go.microsoft.com/fwlink/?LinkId=70353
for details).
Can anyone help me with this
You need to run the host app with elevated privileges (i.e., "As Administrator"). Under Vista/Win7, only administrative accounts have the permission to register socket listeners.