Entity Framework 6.x from 4.x DbExtensions is not declared. It maybe inaccessible due to its protection level.

After upgrade from Entity Framework 4.x to 6.x get various errors:

Error

DbExtensions.Load(context.myItems)
myBindingSource.DataSource = DbExtensions.ToBindingList(context.myItems)

Solution

context.myItems.Load()
me.myDataGridView.DataSource = context.myItems.Local.ToBindingList

 

End.

 

Windows Forms DataGridView Formatting

Time Formatting

To format Null set the Null Value in designer, or code for empty string.

Found when binding to a POCO class with TimeSpan that had some errors with some formats. hh\:mm seems to work.

http://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx

To format 00:00 as blank then:

    Private Sub TimeDataGridView_CellFormatting(sender As System.Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles TimeDataGridView.CellFormatting

        If e.ColumnIndex <> myColumn.Index Then
            Exit Sub
        End If
        If e.Value = New TimeSpan(0, 0, 0) Then
            e.Value = ""
            e.FormattingApplied = True
        End If

    End Sub

End

NuGet

This is well documented elsewhere. The purpose of this post is to collate links and pull out for my own notes those features and commands that I most use, and may not recall.

NuGet Package Manager Console

Finding and Installing a NuGet Package Using the Package Manager Console and removing and updating a package

http://docs.nuget.org/docs/start-here/Using-the-Package-Manager-Console

Key commands:

  1. get-help Install-Package
  2. Install-Package EntityFramework
  3. Unistall-Package EntityFramework
  4. Get-Package EntityFramework -updates to see if there are newer versions available
  5. Update-Pacakge EntityFramework

NuGet Package Explorer – Including Create Package

I have always had work to do to copy my own assemblies into common locations. NuGet offers the possibility of hosting your own NuGet feeds, which may be local.  If I understand this correctly, this looks very interesting and might solve my issue and save me some time.

http://docs.nuget.org/docs/creating-packages/creating-and-publishing-a-package#api-key

http://docs.nuget.org/docs/Creating-Packages/Hosting-Your-Own-NuGet-Feeds

This requires the NuGet Package Explorer:  http://npe.codeplex.com/

I found this would not install because I did not have .NET Framework 4.5 installed, as I am only on Visual Studio 2010. I installed 4.5 as my belief was that this would not break VS 2010. Creating the package then became easy with a few notes:

Use Tools > Analyze package to see if there are any issues.

It does like to have the target .Net Framework:

lib > net40 > myAssembly.dll

Creating your own package – Dependencies on your own packages

  1. Edit Metadata
  2. Edit dependencies
  3. Groups + Gave me [no target framework]
  4. Properties
  5. Package Source *** Put in here the location of your LocalNuGetFeed *** Reload
  6. Select your required package
  7. open

 

Creating your own online NuGet package feed

TODO

http://haacked.com/archive/2011/03/31/hosting-simple-nuget-package-feed.aspx/

 

My favourite Nuget packages

  1. Entity Framework
  2. Data connection – for connection dialog box for my tool kit software

 

 

End

Programming against Sharepoint (Online) Client Side Object Model CSOM

References

Add References to:

  1. C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll
  2. C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll

Problem 1

The referenced assembly “Microsoft.SharePoint.Client, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL” could not be resolved because it has a dependency on “System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” which is not in the currently targeted framework “.NETFramework,Version=v4.0,Profile=Client”. Please remove references to assemblies not in the targeted framework or consider retargeting your project. SharepointWinFormsCSharp

Solution 1

Ensure that the project targets .Net Framework 4 and not Client Profile

Project > Properties > Application > Target Framework

Problem 2

The type or namespace name ‘SharepointOnlineCredentials’ does not exist in the namespace ‘Microsoft.SharePoint.Client’ (are you missing an assembly reference?)

Solution 2A – use this

First check that the spelling is precise including casing

Second, odd, but I copied the references to the bin folder and re-directed the reference to there and it started working. Odd thing was when I then pointed the reference back it continued to work.

Solution 2B – just creates a new problem

  1. Select Reference Microsoft.Sharepoint.Client
  2. Right-Click > Properties
  3. Embed Interop Types change from False to True
  4. Build

This returns new problem

  1. Cannot embed interop types from assembly ‘c:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.Sharepoint.Client.dll” because it is missing either the ‘ImportedFromTypeLibAttribute’ attribute or the ‘PrimaryInteropAssemblyAsstribute’ attribute
  2. Cannot embed interop types from assembly ‘c:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.Sharepoint.Client.dll” because it is missing the ‘GuidAttribute’ attribute

How to use CSOM

After the above each of the use cases in the following demonstrations then worked.

How to: Complete basic operations using SharePoint 2013 client library code

            using (var context = new ClientContext("https://xxx.sharepoint.com"))
            {
                var web = context.Web;
                var login = "xx@xx";
                var password = "xxxx";
                var securePassword = new System.Security.SecureString();
                foreach (char c in password)
                {
                    securePassword.AppendChar(c);
                }
                context.Credentials = new SharePointOnlineCredentials(login, securePassword);
                context.Load(web);
                context.ExecuteQuery();
                ResusltsListBox.Items.Add(web.Title);
            }

The end

Where is “Add Web Reference” in Visual Studio?

With thanks to:

http://blogs.msdn.com/b/kaevans/archive/2008/03/18/where-the-heck-is-add-web-reference-in-visual-studio-2008.aspx

Steps:

  1. Add service reference
  2. Advanced ( bottom LHS )
  3. Add Web Reference … ( bottom LHS )

 

 

How to create a WCF Service Web Role and publish to Azure and consume it

Create the Project

Visual Studio > New Project > Visual Basic or Visual C# > Cloud > Windows Azure Cloud Service
> Select WCFServiceWebRole
If this is missing then Install “Windows Azure SDK for .Net”

Code quick start: Create and deploy a WCF service in Windows Azure
http://msdn.microsoft.com/en-us/library/windowsazure/gg651130.aspx

Code Quick Start: Create a client application that uses a WCF service deployed to Windows Azure
http://msdn.microsoft.com/en-us/library/windowsazure/gg651126.aspx

Also see:

http://rickrainey.com/2013/08/30/hosting-a-wcf-service-in-an-azure-web-role-with-http-tcp-endpoints/

Code the Project

Follow the instructions above.

You cannot overload a method. So I had GetMakes and GetMakes(VehicleTypeID) this will mean the service cannot be activated.

Deployment to Azure

Points to watch are:

  1. In ServiceConfiguration.Cloud.cscfg
    <Instances count=”2″ />
  2. In the role, e.g. WCFServiceWebRole1 on Configuration specify the storage account credentials for the Diagnostics results:
    Use the eclipse and pick existing Azure account

Change the name of a service

MyService.svc is actually 2 files, with a linked code behind file.
Using right-click MyService.svc may be opened for code or for markup. If opened for markup then the service name is exposed. If you change the name of the project then you need to change the name here to the fully qualified name.

Consume the service

Mostly fine by following the example. Notable point here.

  1. Add service reference to a project in Visual Studio
  2. Right-click and Configure Service Reference
  3. Under Data Type > Tick On the “Always generate message contracts”

Otherwise the Get..Request() or Get..Response() may not be visible.

Troubleshooting

You could remote desktop to the Azure instance and then use:

  1. the Event Viewer – Application to view errors.
  2. IIS > Management > Configuration Editor
    If this will not open, then it may display what error was found in the Web.Config file. Correct this.

For debugging In Web.confg you may add the following section so that actual errors appear on web inspection:

  <system.web>
    <customErrors mode="Off"/>
  </system.web>

but configSections must be first and there should be only one open and close tag for configuration.

 

Error 1

If debugging then it would crash OnStart when calling AzureLocalStorageTraceListener.GetLogDirectory. Issue here was in ServiceDefinition.csdef there was no log defined.

Error 1 Solution

    <LocalResources>
       <LocalStorage name="WCFServiceWebRole1.svclog" sizeInMB="1000" cleanOnRoleRecycle="false" />
     </LocalResources>

Error 2

Metadata contains a reference that cannot be resolved: ‘http://<ip address>:<port no>/CatalogueService.svc?wsdl’.
The document format is not recognized (the content type is ‘text/html; charset=UTF-8’).
Metadata contains a reference that cannot be resolved: ‘http://<ip address:<port no>/CatalogueService.svc’.
There was no endpoint listening at http://<ip address>:<port no>/CatalogueService.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
The remote server returned an error: (404) Not Found.
If the service is defined in the current solution, try building the solution and adding the service reference again.

Error 2 Solution

I had inadvertently commented out the [ServiceContract] from the IService
Also make sure that the markup of the service is correct.

Error 3

“The remote server returned an error (500) Internal Server Error”

Error 3 Solution

Unfortunately this just means there has been an error. I changed a number of things and then it started again, i do not know which fixed the issue for me:

  1. Added an [OperationContract] to the ICatalogueService and did not explicity implement it.
  2. An issue with remote desktop publish
  3. Overloaded a method with the same name
  4. Remmed out next line
    //[ServiceContract(ProtectionLevel=ProtectionLevel.EncryptAndSign)
    [ServiceContract]
    public interface ICatalogueService

Error 4

I had a test fail possibly when returning a lot of data.

System.ServiceModel.CommunicationException: The maximum message size quota for incoming messages (65536) has been exceeded. To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding element. —> System.ServiceModel.QuotaExceededException: The maximum message size quota for incoming messages (65536) has been exceeded. To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding element.

Error 4 Solution

Surprisingly I didn’t change anything on the outgoing service.
Instead on the calling application in the app.config file there are some settings for the bindings.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IMyService" closeTimeout="00:01:00"
...
                    maxBufferSize="6553600" maxBufferPoolSize="524288" maxReceivedMessageSize="6553600"
...
                </binding>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://xxx.xx/MyService.svc"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IMyService"
                contract="CatalogueCloudService.IMyService" name="BasicHttpBinding_IMyService" />
        </client>
    </system.serviceModel>
</configuration>

Error 5 – The type or namespace ‘..’ could not be found (are you missing a using directive or an assembly reference?) in  – …\..\Reference.cs

Solution 5

I tried removing [Serializable][DataContract] from class and remove [DataMember] from properties and then re-deployed the web service and the error went away.

Error 6 – Web.Config errors

Resulted in Internal Server Erorr 500

Solution 6

See top of troubleshooting. Use IIS and try and use the Configuration Editor. This may display your error. Possible errors include:

  1. You should have only 1 configuration open and close tag
  2. configSections should be the first element

 

Error 7 Busy (Starting role… Unhandled Exception: Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironmentException

Does not progress beyond this. You have to delete that deployment for now.

Solution to Error 7

This is similar to error 2 above.

The Web Role project in AzureLocalStorageTraceListener the name of the path must be the same as the service

publicclassAzureLocalStorageTraceListener : XmlWriterTraceListener

{
public AzureLocalStorageTraceListener() : base(Path.Combine(AzureLocalStorageTraceListener.GetLogDirectory().Path, “WCFServiceWebRole2.svclog”)) {}

publicstaticDirectoryConfiguration GetLogDirectory()
{
DirectoryConfiguration directory = newDirectoryConfiguration();
directory.Container = “wad-tracefiles”;
directory.DirectoryQuotaInMB = 10;
directory.Path = RoleEnvironment.GetLocalResource(“WCFServiceWebRole2.svclog”).RootPath;
return directory;
}
}

Error 8

The type ‘WCFServiceWebRole.VRMService’, provided as the Service attribute value in the ServiceHost directive, or provided in the configuration element system.serviceModel/serviceHostingEnvironment/serviceActivations could not be found.

Solution to Error 8

Right-Click on the service with the bug and use View Markup. The Service name may have got out of sync with the project name

<%@ServiceHostLanguage=”C#”Debug=”true”Service=”WCFServiceWebRole.MyService”CodeBehind=”MyService.svc.cs” %>

 

The name in the Azure Service Project > Roles > Your Role > Properties > Local Storage > must have the same name

 

 

Using SSL on the WCF WebRole

Links to:

If you have a subscription then see Pluralsight course: Windows Azure fundementals > Windows Azure Roles

http://rickrainey.com/2013/09/18/securing-a-wcf-service-in-an-azure-web-role-with-http-tcp-endpoints-2/

End.

Publish ASP.Net to Azure ‘freezes’

Steps to reproduce freeze when publishing a website to Azure

This assumes you have previously published a site

  1. Visual Studio
  2. Right-click on ASP.Net project that you wish to publish
  3. Publish
  4. Preview
  5. Start Preview
  6. Publish
  7. Freezes after build

How to resolve

If your solution has multiple projects, make sure that the ASP.Net project is the “Start up project”

Writing C# as a VB.Net programmer

Comparisons have been written before.

http://www.harding.edu/fmccown/vbnet_csharp_comparison.html

Differences

VB.Net C# Notes
OrElse || .
Public public Note casing
If public is excluded VB.Net assumes Public. In C# assumes private.
Property MyString As String string MyString;
Property MyString As String var MyString = “Hello World”; In c# var is used to infer
Sub Main static void Main(string[] args)
int + double = double

The model backing the ‘FilmContext’ context has changed since the database was created. Consider using Code First Migrations to update the database

This happened when the database connection string had not been setup in the App.config, so Code First went ahead and created a new database, which I then deleted and set up the connection string to my existing database. I then started getting this error.

Workaround by adding Entity.Database.SetInitializer in the context:

Protected Overrides Sub OnModelCreating(modelBuilder As System.Data.Entity.DbModelBuilder)
Entity.Database.SetInitializer(Of FilmContext)(Nothing) ‘To not initialise the database
modelBuilder.Configurations.Add(New FilmsMap)
End Sub

Entity Framework connection error: System.Data.ProviderIncompatibleException

For me this occurred when I used Entity Framework Power Tools Beta 3, and then used the “Entity Framework > View Entity Data Model (Read-Only)” functionality. The error was:

System.Data.ProviderIncompatibleException: An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct. —> System.Data.ProviderIncompatibleException: The provider did not return a ProviderManifestToken string. —> System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 – Could not open a connection to SQL Server)

This was because the Project containing the context was a class library and was not the startup project. I changed the App.config in the class library but this had no effect. To resolve you change the App.config file in the project marked as the startup project.

Might also be that a reference to the project containing the context is missing.

Solved.