When I start my application, I get this error:
The ConnectionString property has not been initialized.
I am getting this exception while trying to connect to my SQL Server database.
Register.aspx.cs
protected void btnRegister_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = string.Format("insert into member
values('{0}','{1}','{2}','{3}','{4}','{5}','{6}')",
txtFullName.Text, rblGender.SelectedValue, ddlCountry.SelectedValue,
txtPhone.Text, txtEmail.Text, txtUsername.Text, txtPassword.Text);
try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
tblRegister.Visible = false;
Response.Write("Your account is created.");
}
catch(SqlException ex)
{
if (ex.Number == 2627)
lblMsg.Text = "Please Change The Username.";
else
lblMsg.Text = "An Error : " + ex.Message;
}
}
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.6.1"/>
<httpRuntime targetFramework="4.6.1"/>
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider,
Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider,
Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+"/>
</compilers>
</system.codedom>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
<connectionStrings>
<add name="MyDB"
connectionString="Data Source=.\sqlexpress;Initial Catalog=Company;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
You need to do it like this:
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=MSSQL1;Initial Catalog=AdventureWorks;Integrated Security=true;"";
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
With ConnectionString you specify which server to connect to and with what credentials, if not it won't know where you want to connect to and with what.
The example I gave is for SQL server and integrated security, depending on you database, server and your credentials you need to find the connection string you need
Related
I'm new to WebApi and the tutorial was going well. I got Get, Get with variables, Post, and Delete to work, but I can't seem to get Put to work. Well, if I remove all the variables from the method the in the controller, it actually goes into the method, but that's pretty useless. Has anyone come across this before that knows how to fix it?
PUT Url sent to Postman:
http://localhost:60679/api/incident/1234
Preview:
PUT /api/incident/1234 HTTP/1.1
Host: localhost:60679
Cache-Control: no-cache
Error Message:
{"Message":"No HTTP resource was found that matches the request URI
'http://localhost:60679/api/incident/1234'.","MessageDetail":"No action was found on the
controller 'Incident' that matches the request."}
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApiTest.AppLogic;
using WebApiTest.Data.Core;
namespace WebApiTest.WebApi.Controllers
{
public class IncidentController : ApiController
{
// GET api/values
public IEnumerable<Incident> Get()
{
using (EntityDemoEntities context = new EntityDemoEntities())
{
return context.Incidents.ToList<Incident>();
}
}
// GET api/values/5
public Incident Get(string id)
{
using (EntityDemoEntities context = new EntityDemoEntities())
{
Guid tempGuid = new Guid(id);
return context.Incidents.SingleOrDefault(i => i.IncidentId == tempGuid);
}
}
// PUT api/values/5
[HttpPut]
public void Put(string guid)
{
HttpResponseMessage result = new HttpResponseMessage();
try
{
if (ModelState.IsValid)
{
//Do something
}
else
{
result = Request.CreateResponse(HttpStatusCode.InternalServerError, "Invalid Model");
}
}
catch (Exception ex)
{
result = Request.CreateResponse(HttpStatusCode.InternalServerError, String.Format("{1}{0}{2}{0}{3}{0}{4}", Environment.NewLine, ex.Message, ex.StackTrace, ex.InnerException == null ? String.Empty : ex.InnerException.Message, ex.InnerException == null ? String.Empty : ex.InnerException.StackTrace));
}
}
}
}
WebApiConfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Web.config
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name ="WebDAVModule"/>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<modules runAllManagedModulesForAllRequests="true">
<remove name='WebDAVModule'/>
</modules>
Change your action to Put(string id) or Put([FromUri(Name="id")]string guid)
Store initialisation:
private static IDocumentStore CreateDocumentStore()
{
var store = (DocumentStore) new EmbeddableDocumentStore
{
ConnectionStringName = "RavenDb",
};
NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(8080);
store.Initialize();
store.Conventions.MaxNumberOfRequestsPerSession = 500;
return store;
}
Config:
</configSections>
<appSettings>
<add key="Raven/Port" value="8080"/>
<add key="Raven/DataDir" value="~\#App_Data"/>
<add key="Raven/AnonymousAccess" value="Get" />
</appSettings>
<connectionStrings>
<clear/>
<add name="RavenDb" connectionString="DataDir=~\#App_Data\Raven" />
</connectionStrings>
The application works and raven persists some of the data, I just can't get to the management studio
By default the studio isn't served. You have to enable RavenDB's embedded web server when constructing the store instance:
var store = (DocumentStore) new EmbeddableDocumentStore
{
ConnectionStringName = "RavenDb",
UseEmbeddedHttpServer = true
};
I am writing a simple program using nhibernate
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using System.Data.SqlServerCe;
using NHibernate.ByteCode.LinFu;
namespace FirstSolution
{
class Program
{
static void Main(string[] args)
{
Product p = new Product();
p.id = "padu";
p.name = "Sayan";
p.category = "Bogus";
Configuration cfg = new Configuration();
cfg.AddXmlFile("C:/Users/win7/Documents/Visual Studio 2008/Projects/FirstSolution/FirstSolution/Product.hbm.xml");
try
{
using (ISessionFactory factory = cfg.BuildSessionFactory())
{
using (ISession session = factory.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
// Tell NHibernate that this object should be saved
session.Save(p);
// commit all of the changes to the DB and close the ISession
session.Flush();
transaction.Commit();
session.Close();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
string s;
s = Console.ReadLine();
}
}
}
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="hibernate-configuration"
type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
</configSections>
<connectionStrings>
<add name="FirstSolution.Properties.Settings.Database1ConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory| \Database1.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="dialect">NHibernate.Dialect.MsSqlCeDialect</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="proxyfactory.factory_class">
NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu
</property>
<property name="connection.connection_string">Data Source=.\SQLEXPRESS; AttachDBFilename=|DataDirectory|Database1.mdf;Integrated Security=true;User Instance=true;</property>
<property name="show_sql">true</property>
<mapping assembly="FirstSolution"/>
</session-factory>
</hibernate-configuration>
</configuration>
Product.hbm.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="FirstSolution" assembly="FirstSolution">
<class name="Product" table="UserTable" lazy="false">
<id name="id" column="id" type="String" length="10">
<generator class="assigned"/>
</id>
<property name="name" column="name" type="String" length="10"/>
<property name="category" column="category" type="String" length="10"/>
</class>
</hibernate-mapping>
Product.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FirstSolution
{
public class Product
{
public String id { get; set; }
public String name { get; set; }
public String category { get; set; }
}
}
Program is running without any exception. Generated sql is showing on console. But no data is saved in UserTable of Database1.mdf
Database1.mdf is being copied to the /bin/Debug folder when the application is built and the data is saved there.
Hmm. I'm surprised that you don't get exceptions. The Product class must have virtual properties, otherwise it won't work.
Also, I see you're using the MsSqlCeDialect. I haven't used SqlExpress but SqlExpress != SqlCe. Trying using MsSql2005Dialect or MsSql2005Dialect.
I tried an example from NHibernate in Action book and when I try to run the app, it throws an exception saying "Could not compile the mapping document:
HelloNHibernate.Employee.hbm.xml"
Below is my code,
Employee.hbm.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true">
<class name="HelloNHibernate.Employee, HelloNHibernate" lazy="false" table="Employee">
<id name="id" access="field">
<generator class="native"/>
</id>
<property name="name" access="field" column="name"/>
<many-to-one access="field" name="manager" column="manager" cascade="all"/>
</class>
</hibernate-mapping>
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using System.Reflection;
using NHibernate.Cfg;
namespace HelloNHibernate
{
class Program
{
static void Main(string[] args)
{
CreateEmployeeAndSaveToDatabase();
UpdateTobinAndAssignPierreHenriAsManager();
LoadEmployeesFromDatabase();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
static void CreateEmployeeAndSaveToDatabase()
{
Employee tobin = new Employee();
tobin.name = "Tobin Harris";
using (ISession session = OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
session.Save(tobin);
transaction.Commit();
}
Console.WriteLine("Saved Tobin to the database");
}
}
static ISession OpenSession()
{
if (factory == null)
{
Configuration c = new Configuration();
c.AddAssembly(Assembly.GetCallingAssembly());
factory = c.BuildSessionFactory();
}
return factory.OpenSession();
}
static void LoadEmployeesFromDatabase()
{
using (ISession session = OpenSession())
{
IQuery query = session.CreateQuery("from Employee as emp order by emp.name asc");
IList<Employee> foundEmployees = query.List<Employee>();
Console.WriteLine("\n{0} employees found:", foundEmployees.Count);
foreach (Employee employee in foundEmployees)
Console.WriteLine(employee.SayHello());
}
}
static void UpdateTobinAndAssignPierreHenriAsManager()
{
using (ISession session = OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
IQuery q = session.CreateQuery("from Employee where name='Tobin Harris'");
Employee tobin = q.List<Employee>()[0];
tobin.name = "Tobin David Harris";
Employee pierreHenri = new Employee();
pierreHenri.name = "Pierre Henri Kuate";
tobin.manager = pierreHenri;
transaction.Commit();
Console.WriteLine("Updated Tobin and added Pierre Henri");
}
}
}
static ISessionFactory factory;
}
}
Employee.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HelloNHibernate
{
class Employee
{
public int id;
public string name;
public Employee manager;
public string SayHello()
{
return string.Format("'Hello World!', said {0}.", name);
}
}
}
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="nhibernate" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.3300.0, Culture=neutral
PublicKeyToken=b77a5c561934e089"/>
</configSections>
<nhibernate>
<add key="hibernate.show_sql" value="false"/>
<add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
<add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2005Dialect"/>
<add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver"/>
<add key="hibernate.connection.connection_string" value="Server=(local)\SQLEXPRESS; Database=HelloNHibernate;Integrated Security=SSPI;"/>
</nhibernate>
</configuration>
Let's open the Matryoshka doll a bit further, and solve the other problem:
In this line:
<section name="nhibernate" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.3300.0, Culture=neutral
PublicKeyToken=b77a5c561934e089"/>
you're missing a comma between "neutral" and "PublicKeyToken".
Give that a try.
Do you have a manager class and mapping defined? The
<many-to-one access="field" name="manager" column="manager" cascade="all"/>
line is looking for one. If the "manager" field is supposed to be an Employee, then you probably want:
<many-to-one access="field" name="manager" column="manager" class="HelloNHibernate.Employee, HelloNHibernate" cascade="all"/>
I think I see the problem now. The problem appears to be in this line:
<add key="hibernate.connection.connection_string" value="SQL2008EXPRESS" Database="HelloNHibernate;Integrated Security=SSPI;User Id=SQL2008"/>
The connection string is malformed, and it's throwing off the XML parser. Since the "value" attribute ends early, the XML parser thinks "Database=" is another XML attribute, but it's not one it recognizes, so it chokes. The solution is to fix the connection string.
The line should probably read:
<add key="hibernate.connection.connection_string" value="Server=(local)\SQLEXPRESS; Database=HelloNHibernate;Integrated Security=SSPI;"/>
This is assuming you're using Windows authentication; given that this is a learning project, that's probably the best way to go. If you're using SQL Server authentication, use this line instead:
<add key="hibernate.connection.connection_string" value="Server=(local)\SQLEXPRESS; Database=HelloNHibernate; User Id=theusername; Password=thepassword"/>
An aside: I don't think NHibernate 1.2.1GA has a SQL Server 2008 dialect. Instead, use NHibernate.Dialect.MsSql2005Dialect.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="HTTPBaseAddress"
value="http://localhost:8000/Derivatives/"/>
<add key="TCPBaseAddress"
value="net.tcp://localhost:8010/Derivatives/"/>
</appSettings>
<system.diagnostics>
<sources>
<source
name="System.ServiceModel.MessageLogging"
switchValue="Verbose">
<listeners>
<add
name="xml"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData="c:\logs\message.log" />
</listeners>
</source>
</sources>
<trace autoflush="true" />
</system.diagnostics>
<system.serviceModel>
<diagnostics>
<messageLogging logEntireMessage="true"
maxMessagesToLog="300"
logMessagesAtServiceLevel="false"
logMalformedMessages="true"
logMessagesAtTransportLevel="true" />
</diagnostics>
<services>
<service type=
"DerivativesCalculator.DerivativesCalculatorServiceType,DerivativesCalculatorService"
behaviorConfiguration="DerivativesCalculatorService">
<endpoint
address="Calculator"
binding="wsHttpBinding"
contract=
"DerivativesCalculator.IDerivativesCalculator,DerivativesCalculatorService"
/>
</service>
</services>
<behaviors>
<behavior name="DerivativesCalculatorService">
<serviceSecurityAudit auditLogLocation="Application" messageAuthenticationAuditLevel="SuccessOrFailure" serviceAuthorizationAuditLevel="SuccessOrFailure"/>
</behavior>
</behaviors>
</system.serviceModel>
</configuration>
This App.config is generating the following Exception:
Unrecognized attribute 'type'. Note that attribute names are case-sensitive.
My Source code is as follows:
using System;
using System.Collections.Generic;
using System.Text;
namespace DerivativesCalculator
{
public class Calculator
{
public decimal CalculateDerivative(
string[] symbols,
decimal[] parameters,
string[] functions)
{
return (decimal)(System.DateTime.Now.Millisecond);
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using DerivativesCalculatorService;
using DerivativesCalculator;
namespace DerivativesCalculator
{
public class DerivativesCalculatorServiceType : IDerivativesCalculator
{
decimal IDerivativesCalculator.CalculateDerivative(
string[] symbols,
decimal[] parameters,
string[] functions)
{
return new Calculator().CalculateDerivative(
symbols, parameters, functions);
}
void IDerivativesCalculator.DoNothing()
{
return;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
namespace DerivativesCalculatorService
{
[ServiceContract]
public interface IDerivativesCalculator
{
[OperationContract]
decimal CalculateDerivative(
string[] symbols,
decimal[] parameters,
string[] functions);
void DoNothing();
}
}
using System;
using System.Collections.Generic;
using System.Configuration;
using System.ServiceModel;
using System.Text;
namespace DerivativesCalculator
{
public class Program
{
public static void Main(string[] args)
{
Type serviceType = typeof(DerivativesCalculatorServiceType);
string httpBaseAddress = ConfigurationManager.AppSettings["HTTPBaseAddress"];
string tcpBaseAddress = ConfigurationManager.AppSettings["TCPBaseAddress"];
Uri httpBaseAddressUri = new Uri(httpBaseAddress);
Uri tcpBaseAddressUri = new Uri(tcpBaseAddress);
Uri[] baseAdresses = new Uri[] {
httpBaseAddressUri,
tcpBaseAddressUri};
using (ServiceHost host = new ServiceHost(
serviceType,
baseAdresses))
{
host.Open();
Console.WriteLine("The derivatives calculator service is available.");
Console.ReadKey();
host.Close();
}
}
}
}
How to solve this?
I believe that this line of your configuration file is incorrect:
<service
type="DerivativesCalculator.DerivativesCalculatorServiceType,DerivativesCalculatorService"
behaviorConfiguration="DerivativesCalculatorService">
I think instead the type="" should be name="".
<service
name="DerivativesCalculator.DerivativesCalculatorServiceType,DerivativesCalculatorService"
behaviorConfiguration="DerivativesCalculatorService">