Stored procedures with WebMatrix/SQL Compact Edition - webmatrix

I am trying to create a simple application using the WebMatrix tool & Razor syntax. Hence learning a bit of Razor. I dont see a feature to create/call stored procedure's. Is this not supported?

SQL Compact (the default database for ASP.NET Web Pages) does not support Stored Procedures. If you have access to SQL Server, you can use Stored Procedures in it (and it's full supported in ASP.NET Web Pages).

First create a connection to SQL Server that supports Stored Procedures. See example below of entry in web.config file that WebMatrix can create for you.
<configuration>
<connectionStrings>
<add connectionString="trusted_connection=True;server=.\;database=YourDB" name="YourDB" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Second, connect to and run your Stored Procedure as in example below.
#{
var db = Database.Open("YourDB");
string YourSP = String.Format("EXEC dbo.YourSP");
db.Execute(YourSP);
}
Third, output results of YourSP to verify everything worked.
<table class="table-data">
<tbody>
#foreach(var row in db.Query(YourSP))
{
<tr>
<td>#row.YourQueryFieldName</td>
</tr>
}
</tbody>
</table>

Related

How to deploy Entity Framework with Oracle ODAC 12 on WS2012 just copying DLLs

I´ve searched the following links:
How to deploy Oracle with EF
Problems deploying Oracle with EF
And many other posts around regarding Oracle deployment.
Basically I have an C# simple test application to insert some rows into a database (this is a test application. The full application uses a lot of EF stuff):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
using MzDbLib.DataAccessObject;
using MzDbLib.DatabaseContext;
using MzDbLib.DatabaseModel;
namespace TestDbConnection
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("This program will generate 10 logs into SYSTEMDATALOG table");
///
/// Do a loop of 10 logs generated
///
for (int i = 0; i < 10; i++)
{
string msg = "TEST GENERATED LOG NUMBER " + i.ToString();
Console.Write("Generating log " + i.ToString() + "...");
//
// Connect to database and to the log table
//
Entities dbContext = new Entities();
SYSTEMDATALOG logTable = new SYSTEMDATALOG();
logTable.DATETIME = DateTime.Now;
logTable.TYPE = "INFO";
logTable.SEVERITY = 0;
logTable.SOURCE = "TESTDBCONNECTION";
logTable.USER = "SYSTEM";
logTable.MESSAGE = msg;
dbContext.SYSTEMDATALOG.Add(logTable);
dbContext.SaveChanges();
Console.WriteLine("Done.");
}
Console.WriteLine ("Data generated at the database. Press a key to end test.");
Console.ReadKey();
//
// Application exit
//
Environment.Exit(0);
}
}
}
The dbContext and SYSTEMDATALOG classes were generated though EF model-first from an Oracle database. I´m using Visual Studio 2012 and ODAC 12.1.0.1.0 with Oracle Developer Tools 32-bit installed on development machine. All fresh install and working pretty fine when developing.
All runs fine in DEVELOPMENT, but neve in production.
I´m using in production WINDOWS SERVER 2012. I have tried the following approaches:
a) Install WS2012 from schatch and install ODAC 32-bit version 12.1.0.1.0 fresh from Oracle site. I did run install
with ODAC 4 version.
I got "The provider is not compatible with the version of Oracle client". After some tries and some hours lost, with different approaches, I decided to go to a new method - non-installating Oracle
b) I fresh installed WS2012 and did no ORacle installation. Copied the DLLs stated in the above links and now I´m getting "Unable to find the requested .NET data provider". I´ve copied all the available Oracle DLLs from DEV machine to the WS2012 EXE directory of my application and still getting that error.
My connection string (auto-generated by VS2012) is:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="Entities" connectionString="metadata=res://*/DatabaseModel.DatabaseModel.csdl|res://*/DatabaseModel.DatabaseModel.ssdl|res://*/DatabaseModel.DatabaseModel.msl;provider=Oracle.DataAccess.Client;provider connection string="data source=//ORACLESERVER1:1521/MEZAMES;password=xxx;persist security info=True;user id=MZMESDB"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
This string is being generated into 2 files: TestDbConnection.exe.config and TestDbConnection.vshost.exe.config (I´m copying the bin/Debug folder to the server).
So, I need help to deploy my app to the new server. Some questions:
a) Which DLL is needed to go with the application for ODAC 12.1.0.1 ? Does that changed from ODAC 11 ?
b) Is that last error regarding EF or Oracle ?
c) Why does VS generated 2 config files ?
d) Does "providerName="System.Data.EntityClient" is the cause of the error ? If so, what DLL should be copied together.
e) Is there any tool/way to know what´s missing or with incompatible version, avoiding copying and trying methods ?
f) Is something missing on the config file ?
Thanks all for any kind of help. This is making me crazy as I´m stuck on that since the beggining of the week...
I'm not sure about the installation options for ODAC in a server environment. I know you need the Transaction module only if you're using TransactionScope in your code.
The problem you're seeing from not being able to find the provider is because Oracle changed the provider name from Oracle.DataAccess.Client to Oracle.ManagedDataAccess.Client with the 12c bits.
You need to change this in both the connection strings and in the SSDL section of the EDMX file: you will go from
<edmx:StorageModels>
<Schema Namespace="Model.Store" Alias="Self" Provider="Oracle.DataAccess.Client" (...)
to
<edmx:StorageModels>
<Schema Namespace="Model.Store" Alias="Self" Provider="Oracle.ManagedDataAccess.Client" (...)

Umbraco - First run - connection string failed

I just downloaded Umraco (via Web Platform Installer).
It takes me to this web page:
How can I just select 'integrated security'?
That connection string is set to a blank database that exists. I have added 'IIS AppPool\DefaultAppPool' and 'IIS APPPOOL\UmbracoTest' as database owner. The next screen is like this Database configuration is invalid for connection string Data Source=.;Integrated Security=True;Initial Catalog=UmbracoTest:
That connection string is fine, I've used '.' datasource elsewhere with no problems (SQL Express).
Is there any way to get useful error messages?
How can I get this working?
Thanks.
I just ran into the same issue during an Umbraco 6.1.5 installation. My issue was the providerName being empty as suggested, so when I added:
providerName="System.Data.SqlClient"
I was able to install and upgrade my Umbraco 6.1.3 database. My full connection string is:
<add name="umbracoDbDSN" connectionString="server=72.18.**.***,1533;database=mydatabase;user id=emma;password=******" providerName="System.Data.SqlClient" />
The connection string is wrong, trust me :)
Instead of DataSource=. try DataSource=.\sqlexpress
Also ensure that the initial catalog=UmbracoTest is actually the correct name of the database.
Finally, since you are using an Umbraco 6.x version, the log files will be at ~App_Data/Logs but in this case they will just tell you much the same as the install screen, that an SqlException has occurred.
Edit:
Looking at the Umbraco source, the error you see is raised by the following code:
if (_configured == false ||
(string.IsNullOrEmpty(_connectionString) ||
string.IsNullOrEmpty(ProviderName)))
{
return new Result
{
Message =
"Database configuration is invalid. Please check
that the entered database exists and that the provided
username and password has write access to the
database.",
Success = false,
Percentage = "10"
};
}
So my assumption is that you are missing the Provider from your connection string. In your web.config file your connection should look like this:
I had the same issue. I fixed it by adding the IIS_IUSRS user to the Umbraco site directory with "Modify" rights as the setup process is trying to write to the web.config with your connection string. Hope this helps.

Entity Framework, ASP.NET, and SQL Server CE

With VS 2010 SP1 I created an ASP.NET MVC4 project from the "internet" template. I then created a connection string for SQL Server CE 4.0:
<add name="DefaultConnection"
connectionString="Data Source=|DataDirectory|MyDatabase.sdf;Password=123456"
providerName="System.Data.SqlServerCe" />
With the web application successfully debug-launched in cassini, I choose the "Register" user option. Immediately this causes the InitializeSimpleMembershipAttribute filter to execute. The filter crashes the site when it reaches this code:
Database.SetInitializer<UsersContext>(null);
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
//This line never executes. It is meant to configure my custom user table.
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "Users", "ID", "UserName", true);
The Exists() check throws an ArgumentException stating:
Unable to find the requested .Net Framework Data Provider. It may not be installed.
Now I wanted to be sure that (1) there was nothing wrong with my connection string and (2) there was nothing wrong with my provider. To do that, I inserted a snippet of code before the Exists() check. The snippet used a new SqlCeEngine to create the database, and Dapper calls to setup user tables. That code worked just fine, just before exploding on the Exists() check again.
I then considered that EF might need some additional setup help. I tried replacing the EF defaultConnectionFactory in my web.config:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
<parameters>
<parameter value="System.Data.SqlServerCe.4.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
Still the exception I received did not change.
I'm now wondering if EF needs a "special" connection string to work with SQL Server CE. I will be checking here and here. But at first glance I'm not sure that is the issue.
Thoughts?
EF requires the providers to be installed.
Use one the connect to DB options to check. eg ADD Entity DAta Model to Project. Just to the providers available to it. Do you see your preferred connection Client ?
Seems Compact edition should work with some restrictions...
http://technet.microsoft.com/en-us/library/cc835494.aspx
So then I think its The "DEFAULT CONNECTION" issue
See the Context constructor. EF looks for a connection by that name unless you pass an alternative in.
try...
<connectionStrings>
<add name="MyContextName" connectionString="bla";App=EntityFramework"
providerName="System.Data.SqlServerCe.4.0" />
You need to install Sql Server Compact edition. You can download it from here.

Web.config not being read (VS 2010)?

I have a ASP.Net Web Application which connects to a SQL Server. The web.config has <connectionStrings/>. It appears web.config is not being read at runtime, and it's causing data bound controls to fail at runtime with "The ConnectionString property has not been initialized"
My connection string uses a System DSN, and appears to follow connectionStrings Element. The DSN tests properly, and when I use the connection string from web.config on a control's property, all works well.
EDIT: Its blowing up on the Visual Studio generated line grvSysStatus.DataBind()
. Here's the code:
<asp:GridView ID="grvSysStatus" runat="server" GridLines="None" AutoGenerateColumns="False" Width="95%" showHeader="False">
<Columns>
<asp:BoundField DataField="message_text" />
</Columns>
</asp:GridView>
Any ideas?
Thanks,
Jeff
<configuration>
<connectionStrings>
<add name="MasterTraq_Dev"
connectionString="Dsn=MasterTraq_Dev;uid=xxxxx;pwd=yyyyy;trusted_connection=No;app=Microsoft® Visual Studio® 2010;wsid=zzzzz;database=MasterTraq_Dev"
providerName="System.Data.Odbc"
/>
</connectionStrings>
...
</configuration>
That connection string looks so wrong.
I've not used a DSN since classic ASP days but I'm pretty sure it didn't allow a 'registered trademark' character in it.
Have a look at connectionstring.com perhaps?

Update a CRM 2011 record using LINQ example

Can someone please post a confirmed example using linq to retrieve and update a record in CRM Dynamics 2011.
Microsoft claims this is "unsupported" but I have a suspicion it is possible.
I use the "early bound" approach where you generate C# entity classes using the CrmSvcUtil.exe tool, but make sure you use the /codecustomization switch that you'll find in various examples. You'll need the latest version of the CRM 2011 SDK, and must run CrmSvcUtil.exe from the \bin folder of that (don't use the version that installs with CRM).
Your project will need to reference Microsoft.Xrm.Client, Microsoft.Xrm.Sdk and Microsoft.Crm.Sdk.Proxy plus a few others from the .Net framework (look at the build errors to see what you're missing, then add them until it builds).
Here is a basic code snippet that retrieves a Contact entity, updates one of its fields, then saves it back to CRM:
CrmDataContext dc = new CrmDataContext("Xrm");
Contact contact = (from c in dc.ContactSet
where ...whatever...
select c).FirstOrDefault();
contact.FirstName = "Jo";
dc.SaveChanges();
(Note that CrmDataContext is the name of my data context. You can set this name using one of the CrmSvcUtil command line switches).
You'll also need to add a few things to your web.config:
<configSections>
<section name="microsoft.xrm.client" type="Microsoft.Xrm.Client.Configuration.CrmSection, Microsoft.Xrm.Client" />
</configSections>
<connectionStrings>
<add name="Xrm" connectionString="Server=http://<your crm url>; Domain=<your domain>; Username=<a crm user id>; Password=<their password>" />
</connectionStrings>
<microsoft.xrm.client>
<contexts>
<add name="Xrm" type="" />
</contexts>
</microsoft.xrm.client>
This is assuming you are running CRM on your corporate network, so the account and domain specified in the connection string would be an AD account, who is set up as a CRM user with relevant permissions to retrieve and update entities.
This is a rough example of using the ODATA provider connected to the online provider
var serverConfig = GetServerConfig(sessionKey);
// Connect to the Organization service.
// The using statement ensures that the service proxy will be properly disposed.
using (var serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
{
// This statement is required to enable early-bound type support.
serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
using (var orgContext = new CrmServiceContext(serviceProxy))
{
return orgContext.AccountSet.Where(item => item.Id == id).Select().Single();
}
}
there's also a good example in the SDK:
CRM2011Sdk\sdk\samplecode\cs\wsdlbasedproxies\online

Resources