Tuesday, August 4, 2015

Select specific columns from Entity Framework

This helped:
http://stackoverflow.com/questions/19536064/entity-framework-select-multiple-columns


My code:
     private void buttonRefresh_Click(object sender, EventArgs e)
        {

            try
            {
                EnterpriseConfigurationRegistryEntities model = new EnterpriseConfigurationRegistryEntities();

                var p = model.ProductLists
                    .Include("Name")
                    .Select(x => new { x.Name }).ToList();


                BindingSource bi = new BindingSource();
                bi.DataSource = p;
                dataGridView1.DataSource = bi;
                dataGridView1.Columns[0].HeaderText = "Products";

            }
            catch (Exception ex)
            {
               
                throw;

            }

Thursday, May 21, 2015

Code snippet for throwing a sensible message instead of a Entity framweork validation exception (DbEntityValidationException)

When entity framework throws exceptions for data validation it does not clearly expose all the exceptions. This is what you must do to make get to them:


               


            catch(DbEntityValidationException ex)

            {

                IEnumerable<string> errorMessages = ex.EntityValidationErrors

                                   .SelectMany(x => x.ValidationErrors)

                                   .Select(x => x.ErrorMessage);

 

                throw new Exception(string.Join("; ", errorMessages))

            }




This is my code snippet to make it happen. Thanks to http://blogs.infosupport.com/improving-dbentityvalidationexception/ for the c# code.


<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
 <CodeSnippet Format="1.0.0">
  <Header>
   <Title>EntityFrameworkValidationCatch</Title>
   <Shortcut>JCEntityFrameworkValidationCatch</Shortcut>
   <Description>Catch for entity framwork validation errors</Description>
   <Author>James Cooke</Author>
   <SnippetTypes>
    <SnippetType>Expansion</SnippetType>
   </SnippetTypes>
  </Header>
  <Snippet>
   <Code Language="csharp">
   <![CDATA[catch(DbEntityValidationException ex)
            {
                IEnumerable<string> errorMessages = ex.EntityValidationErrors
                                   .SelectMany(x => x.ValidationErrors)
                                   .Select(x => x.ErrorMessage);
                throw new Exception(string.Join("; ", errorMessages))
            }$end$]]>
   </Code>
  </Snippet>
 </CodeSnippet>
</CodeSnippets>

Friday, October 31, 2014

C# web.Config Transformation with Visual Studio 2013 - endpoint configuration

I uninstalled slow cheetah and use the basic VS one.
This is my config: Yes, its a dog. Paste it in to A page to make it legible.

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="Enviroment" value="Develop" />
    <add key="IsDebug" value="NO"/>
    <add key="AssociationLibrary" value="DATZT19"/>
    <add key="ServiceLocatorUrl" value="http://APPDEVCS.develop.fcbt/Services/DataServices/ServiceLocator/ServiceLocator.svc" />
    <add key="AS400Mode" value="GLOBAL" />
    <add key="AS400IP" value="10.10.1.55" />
    <add key="AS400Connection" value="Driver={{iSeries Access ODBC Driver}};System={0};Uid=UCQUERY;Pwd=fcbquery1;Database=SYPLIB;"/>
    <!--<add key="AS400SecureConnectionString" value="JtQqRYitKAyxOm+bW7T9KFHBvzrPBLx3/5SsrNE+bmr/g9XZwK8piq3B7hPFMv795rrnHe24QQ41e7D854qbg8FhzbZZCHk/AwVvmkky/qYioF29B5PJq2+OHHN4gSBCusXKoq1f+917SPaKfHpFoA=="/>-->
    <!--  Enterprise Logging Settings -->
    <add key="loggingIsUseWCFService" value="false" />
    <add key="loggingIsUseTextFile" value="true" />
    <add key="LogWriterServiceConnectionString" value="LogWriterService,1,Develop,basicHttpBinding" />
    <add key="LoggingAutoRetryAttempts" value="5" />
    <add key="LoggingSecondsBetweenRetryAttempts" value="60" />
    <add key="loggingFolderName" value="C:\Temp\Logs\Services\DataServices\LendingSystemService" />
    <add key="loggingApplicationName" value="LendingSystemService" />
    <add key="loggingEnvironmentName" value="test" />
    <add key="loggingMinimumSeverityLevel" value="Verbose" />
    <add key="loggingExcludeClasses" value="" />
    <add key="loggingIsAddHeaders" value="false" />
    <add key="loggingMaxFileAgeDays" value="30"/>
    <add key="loggingMaxFileCount" value="100"/>

    <!--LoanIq Db2 Database Settings
    NOTE THAT THESE LINES ARE FOR QUICK COPY/PASTE
    <add key="TESTLoanIqServer" value="LQtestBE.DEVELOP.FCBT"/>
    <add key="TESTLoanIqDatabase" value="LQtest"/>
    <add key="DEVLoanIqServer" value="LQSTD1BE.DEVELOP.FCBT"/>
    <add key="DEVLoanIqDatabase" value="LQRPTF"/>
    -->
    <add key="LoanIqServer" value="lqstd1be.develop.fcbt"/>
    <add key="LoanIqDatabase" value="lqrptf"/>

    <add key="LoanIqPort" value="50000"/>
    <add key="LoanIqSchema" value="LS2USER"/>
    <add key="LoanIqConnectFormatString" value="Driver={{IBM DB2 ODBC DRIVER}};Database={0};Hostname={1};Protocol=TCPIP;Port={2};Uid={3};Pwd={4};"/>
    <add key="EmptyDb2CacheOnStartup" value="true"/>
    <add key="CacheDb2Data" value="false"/>

    <!-- Robot database key -->
    <add key="RobotSecurityEnvironment" value="BillStat"/>
    <!-- We have separate values because CRM on develop.fcbt does not always trust nterprise credentials -->
    <add key="RobotSecurityEnvironmentXrm" value="BillStat_X"/>


    <!--This is the root folder location where saved LoanIqInquiryApi (read), LoanIqApi(write) and Cardinal Spot  scripts are saved.
    LoanIq scriptfiles reside in that folder at /LoanIq and  must end with .xml
    Cardinal scriptfiles reside in that folder at /Cardinal and  must end with .txt
    -->
   
    <add key="ScriptFolderPath" value="c:\Projects\Services\DataServices\LendingSystemService\Scripts"/>

   
    <!--
    Address translation table for different Environments. Used with the SubEnvironment parameter.
    Tells this service which LoanIq server to use for each of the respective AS/400 environments.
    This Cardinal environment value (i.e DATO) gets passed in via the request envelope to this service,
    and the ExecuteScriptCommand reads this translation list to determine which LoanIq server to run
    the LiqReadWriteDataService service against. Pretty nifty. Note that some of these currently point
    to LQDEV because I dont have API permission against loanIq against all the respective servers.
    This HAS to change in production.
    -->
    <add key="Environment:DATO" value="LQDATOMT.DEVELOP.FCBT"/>
    <add key="Environment:DATX" value="LQDATXMT.DEVELOP.FCBT"/>
    <add key="Environment:RPTF" value="LQRPTFMT.DEVELOP.FCBT"/>
    <add key="Environment:BETA" value="LQBETAMT.DEVELOP.FCBT"/>
    <add key="Environment:DATF" value="LQDATFMT.DEVELOP.FCBT"/>
    <add key="Environment:DATL" value="LQDATLMT.DEVELOP.FCBT"/>
    <add key="Environment:DATN" value="LQDATNMT.DEVELOP.FCBT"/>
    <add key="Environment:DEV" value="LQDEVMT.DEVELOP.FCBT"/>
    <add key="Environment:DATZ" value="LQDATZMT.DEVELOP.FCBT"/>
    <add key="Environment:TEST" value="LQTESTMT.DEVELOP.FCBT"/>
    <add key="Environment:PROD" value="LQPRODMT.NTERPRISE.WET"/> <!--this mis-spelling is done on purpose to prevent silly mistakes.-->
    <add key="Environment:DAT" value="LQPRODMT.NTERPRISE.WET"/> <!--this mis-spelling is done on purpose to prevent silly mistakes.-->
   
  </appSettings>

  <connectionStrings>
    <add name="RobotConfig" connectionString="Server=lqdatoapi.develop.fcbt;Database=FCBRobot;Initial Catalog=FCBRobot;Trusted_Connection=True;"/>
  </connectionStrings>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IServiceLocator" closeTimeout="00:01:00"
          openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
          allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
          maxBufferPoolSize="524288" maxBufferSize="65536" maxReceivedMessageSize="65536"
          textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true"
          messageEncoding="Text">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
            maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None"
              realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>
        <binding name="BasicHttpBinding_ILiqReadWriteDataService" maxBufferSize="20000000" maxReceivedMessageSize="20000000" />
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://appdevcs.develop.fcbt/Services/DataServices/ServiceLocator/ServiceLocator.svc"
        binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IServiceLocator"
        contract="ServiceLocator.IServiceLocator" name="BasicHttpBinding_IServiceLocator" />
     
      <!--http://localhost:42614/LiqReadWriteDataService.svc-->
      <!--http://appdevcs.develop.fcbt/Services/DataServices/LiqReadWriteDataService/LiqReadWriteDataService.svc-->
      <endpoint address="http://localhost:42614/LiqReadWriteDataService.svc"
        binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ILiqReadWriteDataService"
        contract="LiqReadWriteDataServiceReference.ILiqReadWriteDataService"
        name="BasicHttpBinding_ILiqReadWriteDataService" />
    </client>
    <behaviors>
      <serviceBehaviors>
        <behavior name="Throttling">
          <serviceThrottling maxConcurrentInstances="50"/>
        </behavior>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
    <standardEndpoints>
      <webScriptEndpoint>
        <standardEndpoint name="" crossDomainScriptAccessEnabled="true" />
      </webScriptEndpoint>
    </standardEndpoints>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>



NOW HERE IS THE CONFIG TRANSFORMATION, IT WORKS

<?xml version="1.0" encoding="utf-8"?>

<!-- For more information on using web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 -->

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <appSettings>
    <add key="Enviroment" value="TEST" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
    <add key="ServiceLocatorUrl" value="http://appTESTcs.develop.fcbt/Services/DataServices/ServiceLocator/ServiceLocator.svc" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
    <add key="LogWriterServiceConnectionString" value="LogWriterService,1,TEST,basicHttpBinding" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
    <add key="LoanIqServer" value="LQSTD1BE.DEVELOP.FCBT" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
    <add key="LoanIqDatabase" value="LQRPTF" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
    <add key="ScriptFolderPath" value="C:\inetpub\HTTP_Site\Services\DataServices\LendingSystemService\Scripts" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
    <add key="loggingEnvironmentName" value="TEST" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
  </appSettings>


  <connectionStrings>
    <add name="RobotConfig" connectionString="Server=lqdatoapi.develop.fcbt;Database=FCBRobot;Initial Catalog=FCBRobot;Trusted_Connection=True;"  xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
  </connectionStrings>


  <system.serviceModel>
    <client>
      <endpoint address="http://appTESTcs.develop.fcbt/Services/DataServices/ServiceLocator/ServiceLocator.svc" xdt:Transform="SetAttributes(address)" xdt:Locator="Condition(@name='BasicHttpBinding_IServiceLocator')"/>
      <endpoint address="http://appTESTcs.develop.fcbt/Services/DataServices/LiqReadWriteDataService/LiqReadWriteDataService.svc" xdt:Transform="SetAttributes(address)" xdt:Locator="Condition(@name='BasicHttpBinding_ILiqReadWriteDataService')"/>
    </client>
  </system.serviceModel>
    

</configuration>