How to create a certificate – for Azure

Using MakeCert

http://msdn.microsoft.com/en-us/library/bfsktky3.aspx

After using makecert, it may say Succeeded, but you may not be able to find the certificate.
If you started from c:\Windows\system32 then It may be in c:\Windows\SysWOW64

To create your own self-signed management certificates which will be valid for Azure, open a Visual Studio command prompt as an administrator, and then run the following command:

http://msdn.microsoft.com/en-us/library/windowsazure/gg551722.aspx

makecert -sky exchange -r -n “CN=<CertificateName>” -pe -a sha1 -len 2048 -ss My “<CertificateName>.cer”

The CN may need to be abc.cloudapp.net

NOTE: If you get:
Error: CryptCertStrToNameW failed => 0x80092023 (-2146885597)
Failed

Then try manually deleting each ” and re-typing

 

Export from MMC

http://social.technet.microsoft.com/wiki/contents/articles/2167.how-to-use-the-certificates-console.aspx

Not sure still learning, but current notes are

  1. Windows start type mmc.exe
  2. Probably current user for self-signed
  3. Select certificate
  4. Right-click All Tasks – Export
  5. Export with Private Key and Password
  6. Upload to the Service – Certificates in Azure

 

 

Configuring SSL for an application in Windows Azure

http://www.windowsazure.com/en-us/develop/net/common-tasks/enable-ssl/

http://msdn.microsoft.com/en-us/library/ms731074.aspx

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.

Dreyfus model of skill acquisition

http://en.wikipedia.org/wiki/Dreyfus_model_of_skill_acquisition

Instead the original Dreyfus model is based on four binary qualities:
Recollection (non-situational or situational)
Recognition (decomposed or holistic)
Decision (analytical or intuitive)
Awareness (monitoring or absorbed)

This leads to five roles:
1. Novice non-situational recollection, decomposed recognition, analytical decision, monitoring awareness
2. Competence situational recollection, decomposed recognition, analytical decision, monitoring awareness
3. Proficiency situational recollection, holistic recognition, analytical decision, monitoring awareness
4. Expertise situational recollection, holistic recognition, intuitive decision, monitoring awareness
5. Mastery situational recollection, holistic recognition, intuitive decision, absorbed awareness

Get DbContext entities and properties at runtime

The modelbuilder will first build all DbSets specified.
It will then build from any class objects that these DbSets refer to. This is more than you might think. Furthermore on some actions one of these other classes may have not been mapped correctly and cause the main program to crash, even if you were never interested in these classes.

To discover what classes and properties have been built at run-time use the following code:

    _
    Public Sub ProductsContextEntitiesBuiltList()
        Using context As New ProductsContext(ConnectionString.CurrentConnectionString)
            ContextEntitiesBuiltList(context)
        End Using
    End Sub

    Private Sub ContextEntitiesBuiltList(context As Entity.DbContext)
        Dim objContext = CType(context, IObjectContextAdapter).ObjectContext
        Dim workspace As MetadataWorkspace = objContext.MetadataWorkspace
        Dim tables As IEnumerable(Of EntityType) = workspace.GetItems(Of EntityType)(DataSpace.CSpace)
        For Each table In tables
            Debug.WriteLine(table.FullName)

            For Each p In table.Properties
                Debug.WriteLine("   " + p.Name)
            Next
        Next

        Debug.WriteLine("")

        'Or
        'For Each myEntity In objContext.MetadataWorkspace.GetItems(Of EntityType)(DataSpace.CSpace).ToList
        '    Debug.WriteLine(myEntity.FullName)
        'Next
    End Sub

Use modelBuilder.Ignore(Of <entity) 'to stop building those not required.

Entity Framework Error “The property ‘id’ is part of the object’s key information and cannot be modified”

If you load an entity then change its key you may get this message.

If you really must change the key, for instance on an entity which does not use identity, then you may set the entity’s state to Added then change the key, then change the state to Unchanged.

To change state you could use

    Sub SetEntityState(myObject As Object, myState As System.Data.Entity.EntityState)
        context.Entry(myObject).State = myState
    End Sub

— Original 8-Jul-2013 —

In my case this was because I was using context.Products.Find(123) and then manipulating the item, perhaps adding it again. So the Find method will cache it the first time. So if you want to do a subsequent Add/Modify then perhaps best to clear that store. You can do this with.

For each p as product in context.products
   context.enty(p).state = detached
next

It was not that the key was wrong.

 

Error setting up SQL Server CDC – Change Data Capture

Error when using:
EXECUTE sys.sp_cdc_enable_db

Msg 22830, Level 16, State 1, Procedure sp_cdc_enable_db_internal, Line 193
Could not update the metadata that indicates database <dbname> is enabled for Change Data Capture. The failure occurred when executing the command ‘SetCDCTracked(Value = 1)’. The error returned was 15517: ‘Cannot execute as the database principal because the principal “dbo” does not exist, this type of principal cannot be impersonated, or you do not have permission.’. Use the action and error to determine the cause of the failure and resubmit the request.

Solution:

Database > Properties > Files >
Check that the databse has an owner

For me this went wrong because ‘dbo’ existed on the server (pc) where this database was created, but did not exist on this server (pc) (SQL Server Developer Edition)