Error in Early Bound Class in Dynamics CRM 2015 - c#

We are using CRM 2015 on-premise, we are trying to build customer portal, for that we generated Early Bound class
It is successfully generated and added to VS 2012. Now the problem is when i build the project in VS it goes fine and when i run the project it throws error in the Auto generated code
The code is below
public XrmServiceContext()
{
}
Below is my web.config code
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="Microsoft.Xrm.Client" type="Microsoft.Xrm.Client.Configuration.CrmSection, Microsoft.Xrm.Client"/>
</configSections>
<connectionStrings>
<add name="Xrm" connectionString="ServiceUri=http://Contoso/XRMServices/2011/OrganizationData.svc/; Domain=MyDomain; Username=vsaravanakumar; Password=Password#5"/>
</connectionStrings>
<Microsoft.Xrm.Client>
<contexts>
<add name="Xrm" type="Xrm.XrmServiceContext, WebAppWalkthrough"/>
</contexts>
</Microsoft.Xrm.Client>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<pages controlRenderingCompatibilityVersion="4.0" clientIDMode="AutoID">
<controls>
<add tagPrefix="crm" namespace="Microsoft.Xrm.Portal.Web.UI.WebControls" assembly="Microsoft.Xrm.Portal"/>
</controls>
</pages>
<authentication mode="None"/>
</system.web>
</configuration>
The exception im getting is "Unable to find connection string with name".
I got this error during debugging of my code
I followed each and every steps what MSDN website is mentioned in the website portal development, if i missed anything please help me to resolve this error
Below is my Web.config Code

You need to define the CRM connection string in your app.config/web.config files. If you don't specify a connection string the Client DLL defaults to using the Config file.

The CRMSvcUtil.exe is used to generate a set of classes that you can include in your project and then use to read and manipulate CRM data. But they don't "do" anything until you create a connection and then instantiate and use them. The simplified connection string method is covered here...
https://msdn.microsoft.com/en-us/library/gg695810.aspx
Essentially you put a conn string in web.config section like this...
<add connectionString="Url=http://crm.contoso.com/xrmContoso; Domain=CONTOSO; Username=jsmith; Password=passcode" name="Crm" />
Then somewhere before you use early or late bound objects, you do this...
//Use the Microsoft Dynamics CRM Online connection string from the web.config (or app.config) file named "CRM".
var connection = new CrmConnection("CRM");
var service = new OrganizationService(connection);
var context = new CrmOrganizationServiceContext(connection);
With early bound you then can do a LINQ query against the generated code objects or {entity}Sets of the context like this...
var contacts = (from c in context.ContactSet
where c.LastName == "Smith"
select c);
This will return a collection of records matching your criteria that you could enumerate through with a foreach loop, or bind to a control, or send as a jSON array, or whatever you'd like.

Related

Custom app.config section fails to cast to NameValueCollection

This tutorial makes what I'm trying to do look dead easy. All I want to do is read a custom attribute out of my web.config. Here's the relevant part:
<configSections>
<section name="Authentication.WSFedShell" type="System.Configuration.DictionarySectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<Authentication.WSFedShell>
<add key="Authentication.PrincipalType" value="ClientCertificate" />
</Authentication.WSFedShell>
In the immediate window I can execute:
System.Configuration.ConfigurationManager.GetSection("Authentication.WSFedShell")
which returns the string
["Authentication.PrincipalType"]: "ClientCertificate"
However, when I try to cast it (with as NameValueCollection), as this tutorial says to do, I get null returned and my code blows up. There's gotta be a cleaner way to get the value "ClientCertificate" than manually parsing the string result.
How do I read "ClientCertificate" from app.config?
Why can't you use AppSetting like
<configuration>
<appSettings>
<add key="Authentication.PrincipalType" value="ClientCertificate"/>
</appSettings>
</configuration>
System.Configuration.ConfigurationManager.AppSettings["Authentication.PrincipalType"]
Most probably the issue with your section is the Type attribute. But anyways, you need to cast the result of GetSection() to your type defined for section like
System.Configuration.DictionarySectionHandler config = (System.Configuration.DictionarySectionHandler)System.Configuration.ConfigurationManager.GetSection("Authentication.WSFedShell");

Castle Windsor / ActiveRecord / NHibernate: How to intercept/modify connection string

I have consolidated the connection string information for a number of C# .NET solutions that are in my possession. Previously, each project was storing its connection string in its own format, requiring me to modify several files for each installation of the software.
Only one remaining solution is giving me trouble. This particular solution uses Castle Windsor 2.0, ActiveRecord 2.0 and NHibernate 2.1. The code reads its configuration from an XML file. I wish to remove the connection string from the config file and set it programmatically in the code.
Here is the relevant section of code that initiates Windsor:
windsorContainer = new WindsorContainer(new XmlInterpreter(xmlFileName));
windsorContainer.Resolve<IWindsorConfigurator>().Configure(windsorContainer);
logger = windsorContainer.Resolve<ILogger>();
Here are the contents of the XML file:
<?xml version="1.0"?>
<configuration>
<properties>
<connectionString>Server=*****;Database=*****;User Id=*****;Password=*****</connectionString>
</properties>
<facilities>
<facility id="logging" type="Castle.Facilities.Logging.LoggingFacility, Castle.Facilities.Logging" loggingApi="log4net" configFile="Configs/log4net.config" />
<facility id="atm" type="Castle.Facilities.AutomaticTransactionManagement.TransactionFacility, Castle.Facilities.AutomaticTransactionManagement" />
<facility id="arfacility" type="Castle.Facilities.ActiveRecordIntegration.ActiveRecordFacility, Castle.Facilities.ActiveRecordIntegration" isDebug="false" isWeb="false">
<!-- Configure the namespaces for the models using Active Record Integration -->
<assemblies>
<item>ChronoSteril.Application</item>
</assemblies>
<config>
<add key="connection.driver_class" value="NHibernate.Driver.SqlClientDriver" />
<add key="dialect" value="NHibernate.Dialect.MsSql2005Dialect" />
<add key="connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
<add key="connection.connection_string" value="#{connectionString}" />
<add key="hibernate.cache.provider_class" value="NHibernate.Caches.SysCache.SysCacheProvider, NHibernate.Caches.SysCache" />
<add key="proxyfactory.factory_class" value="NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle" />
<add key="hibernate.expiration" value="60" />
</config>
</facility>
</facilities>
<components>
<component id="windsorConfigurator" service="ChronoSteril.Application.IWindsorConfigurator, ChronoSteril.Application" type="ChronoSteril.WinApp.ClarionIntegrationWindsorConfigurator, ChronoSteril.WinApp" />
</components>
I am not familiar with Windsor. During my Google tour, I did see some code that adds facilities programmatically, but those examples were not valid for my version of Windsor (I assume).
Question: Can anyone guide me in removing the connection string information from the XML file and allow me to set it in the code?
Thank you!
I managed to accomplish my intention. It is not ideal, but will work until the code base is rewritten. (I cannot wait to drop the existing code like a bad dream.)
Patrick's comment, under my initial question, let me to refine my search criteria, which yielded the thread located here.
My XML file remains the same, except that I use bogus values for the connection string information. I will never need to modify these, and they do not reveal any valid connection information. This was my intention. I still have not discovered how to successfully remove the ActiveRecord configuration from the XML file and configure using code.
I now call a method that contains the following code:
ISessionFactoryHolder sessionFactoryHolder = ActiveRecordMediator.GetSessionFactoryHolder();
NHibernate.Cfg.Configuration configuration = sessionFactoryHolder.GetConfiguration(typeof(ActiveRecordBase));
connectionString = ReadConnectionString();
configuration.SetProperty("connection.connection_string", connectionString);
This works for me. I hope that it can also help someone else who is in the same position as I was.

Unable to read app.config settings during unit testing - again

I've been trying to read an app.config file during unit testing following the instructions in this Using a Configuration File to Define a Data Source using Visual Studio 2010. I've read numerous posts here in the forum as well, but I'm still getting a null value when trying to read the app.config values. Below are snippets of my app.config and unit test code.
App.config
<configuration>
<configSections>
<section name="microsoft.visualstudio.testtools" type="Microsoft.VisualStudio.TestTools.UnitTesting.TestConfigurationSection, Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</configSections>
<connectionStrings>
<add name="DatabaseConnectionString" connectionString="Data Source=***;User Id=***;Password=***;Integrated Security=no" providerName="Oracle"/>
</connectionStrings>
<microsoft.visualstudio.testtools>
<dataSources>
<add name="MyOracleConnection" connectionString="DatabaseConnectionString" dataTableName="***" dataAccessMethod="Sequential"/>
</dataSources>
</microsoft.visualstudio.testtools>
</configuration>
Unit Test:
[TestMethod()]
[DeploymentItem("app.config")]
public void S_ConstructorTest(){
myObject m = new myObject();
...}
In my object code I'm attempting to read the config file via:
public static readonly string sConnectionString = System.Web.Configuration.WebConfigurationManager.AppSettings["sConnectionString"];
Based on what I've read in other posts here, MSDN seems to add more than is necessary for this to work, however I still keep getting null values when reading the config file. I know that there's a debate as to whether or not unit testing should access a real DB but for now I just need to get it to read the config file.
Any help would be appreciated.

How can I access web.config from an ASP.NET Custom Control?

Inside my web.config file I've got code like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
...
<section name="UninstallSurveySettings" type="dashboard.UninstallSurveyConfig" />
</configSections>
...
<UninstallSurveySettings>
<add key="fileLocation" value="C:\inetpub\wwwroot\output\" />
</UninstallSurveySettings>
...
</configuration>
I need to be able to access this field from my custom control. The control can be dropped into any website and needs to check that site's web.config for the fileLocation value in UninstallSurveySetting.
I've tried a couple different approaches with no luck. Any help on this would be greatly appreciated.
Much easier to use AppSettings.
Web.config:
<configuration>
<appSettings>
<add key="fileLocation" value="C:\inetpub\wwwroot\output\" />
</appSettings>
</configuration>
Code:
string location = System.Configuration.ConfigurationManager.AppSettings["fileLocation"];
If your section will become more complex, then:
var section = (NameValueFileSectionHandler)ConfigurationManager.GetSection("UninstallSurveySettings");
if (section != null)
{
// access section members
}
P.S.
Maybe you want to use ConfigurationSection class instead of handler.
In ASP.NET MVC 3 the tag cannot be a direct child of (it results in a configuration error).
How about adding your key to the section. Then you can easily access it via the ConfigurationManager.AppSettings collection.
using System.Configuration.ConfigurationManager and you will be able to get what you want from the web.config
I was able to solve this by creating a configuration class for it and placing this code in the web.config:
<section name="UninstallSurveyConfig" type="dashboard.UninstallSurveyConfig" />
..
<UninstallSurveyConfig dirFileLocation="C:\inetpub\wwwroot\build\output" webFileLocation="~/output" />

Getting BLToolkit to work with MySQL

Heya, I'm currently trying to get bltoolkit working in my project.
I've added the BLToolkit.3 project to my solution and am referencing it appropriately.
The code in question is really simple.
public List<Account> LoadAccounts()
{
using (DbManager db = new DbManager("MySql"))
{
var query = new SqlQuery<Account>();
return query.SelectAll(db);
}
}
With an app.config of
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="bltoolkit" type="BLToolkit.Configuration.BLToolkitSection, BLToolkit.3"/>
</configSections>
<bltoolkit>
<dataProviders>
<add type="BLToolkit.Data.DataProvider.MySqlDataProvider" />
</dataProviders>
</bltoolkit>
<connectionStrings>
<add name="MySql" connectionString="Server=localhost;Port=3306;Database=BLT;Uid=root;" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
</configuration>
When I try to run that, I get the following exception: "The type initializer for 'BLToolkit.Data.DbManager' threw an exception."
Upon closer inspection it seems to be line 261 in DbManager.Config.cs
Type dataProviderType = Type.GetType(provider.TypeName, true);
Which basically fails to get the MySQL providers type. I've tried putting the MySQL.data.dll in my applications run path, with no luck.
Any ideas?
By default, MySqlDataProvider is not included in build. You'll have to download source code and add MySqlDataProvider.cs as "Existing Item" to your project (and modify assembly-qualified type name appropriately). Or, if you're fine with recompiling BLTooklit, you can include it in BLToolkit project itself.

Categories