Add file header to new class/other items automatically on creation in Visual Studio

Hi,

This post shows how we can make little changes to the Class template in visual studio so that we can add a file header to a newly created class. It’s generally a good practice to add a file header to any class/file in a solution but it’s equally a pain when we have to copy-paste a file header from a different file and remember to change the name at the top. Instead you can just follow the below steps to make Visual Studio add it automatically for you with the right filename when you create a new class.

Note: I’ve done this for Visual Studio 2015. But it is pretty much the same for other versions

  1. Navigate to the below folder
    C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class\
  2. Open the Class.cs file in notepad or any editor you find comfortable. Edit it as shown below. Basically just add the file header you wish to add to every class. But edit the filename to $safeitemrootname$.cs. This will ensure that the name of the file you’ve provided is replaced here.
  3. Make any more changes as required. Save.
  4. Go back to visual studio to check if it is actually working.
  5. Modify other templates like for Interface or any other file type if required. Note :  you might want to check the folders at the 1033 level in the above path.

Hope this helps!

[Update]

The below post by Abhijit Jana shows very clearly how the same can be achieved with more controls using Macros. Do have a look.

Add document header for files automatically in Visual Studio

 

Posted in General, visual studio | Tagged , , , | 4 Comments

Creating WCF Service hosted in Azure Service Fabric over Https with Basic Authentication

Hi,

This post will show how we can create a WCF Service in Azure Service Fabric and how to configure Basic authentication to it using simple username and password validation.

Follow the below steps in the given order:

  1. Create Service fabric service.
    Create a service fabric stateless service in Visual studio.
  2. Add a sample contract and implementation with a sample method. In this case it just returns a random guid.

  3. Create a communication listener for the Wcf Service. Read next steps which would be part of the communication listener
  4. In our example, we’re going to expose the WCF Service over HTTPS on the port 44000. As part of the communication listener, we’ll create a BasicHttpsBinding and set the security mode to Transport and CredentialType to Basic.
  5. Next create the listener object which is of type WcfCommunicationListener<ContractType>. This type is in the namespace Microsoft.ServiceFabric.Services.Communication.Wcf.Runtime. You will have to add the NuGet package Microsoft.ServiceFabric.Services.Wcf. See sample code below.
  6. Next, set the Credentials for the service host listener. Since, we’re using custom Username authentication, we will set the UserNamePasswordValidationMode to Custom and we would also specify the custom validator class object which would override the UserNamePasswordValidator class. This is an abstract class that provides a Validate method that takes in 2 parameters, the username and password.
  7. The Custom validator class implementation is as shown below.
  8. Coming back to the listener creation part. Now we also want to add a service metadata behavior so that clients can access the service metadata. Also we have to make sure that we set the httpsGetEnabled to true so that metadata is available over https. See sample code below.
  9. Now return the above created listener. The complete Listener creation method is given below.
  10. This method is called from the CreateServiceInstanceListener method provided by Service Fabric.
  11. Run the service and check that it is healthy in the service fabric explorer. Make a note of the URL.
  12. If you click on the URL, you would see something like below.

    This is because the specified port doesn’t have any certificate bound to it. We need to bind a certificate to the specified port, in this case port 44000. In your dev machine, you can create a self-signed certificate using the New-SelfSignedCertificate powershell cmdlet. Next run the below command in command prompt in admin mode to bind the certificate to the port.

     netsh http add sslcert ipport=0.0.0.0:44000 certhash=<cert_thumbprint> appid={someguid}

    See sample below.

  13. Now run the service again and try opening the URL. You would be able to see the service wsdl as seen below.
  14. As you can see in the wsdl above, there are references to other files (see wsdl:import tag). If you want everything in a single wsdl, we can add a endpoint behavior for that. I’ve added it in the sample application code uploaded with this post (refer link at the end of post). I thank the author of this post for explaining it clearly.
  15. Now for the client side. Create a wcf client. I’m creating a sample console application here.
  16. Add a service reference and put the URL you copied above. After clicking on Go, it shows a popup that certificate is not trusted, which is ok in our case as we’ve created it locally. Then it prompts for username and password. Enter the username and password that your WCF service expects. Now service reference is added.

  17. In the code, make sure that you’ve provided the credentials (username and password) as shown in below sample.
  18. As mentioned above, make sure that small piece of code marked with comment doesn’t go into production. That is meant for local dev purposes only.
  19. When we run the client, if we’re passing correct username and password, we will get a guid response as shown below.

I’ve uploaded the complete sample application here. Alternatively, you can clone the repo using this git url directly.

https://github.com/amoghnatu/WcfWithBasicAuthDemo.git

Hope this helps!

Posted in .NET | Tagged , , , , , , , , | Leave a comment

Entity Framework not saving data to database on context.SaveAsync() while using Autofac

Hi,

Recently I was using Entity Framework with a DB first approach in an application and using the Repository pattern with Unit of Work to have easy management of DB operations.

So my repository constructor accepted an IDataContext object (IDataContext is a custom interface I had written which encapsulates the DbContext generated after adding Entity Data model. Refer sample code below.

RepositoryBase:

public class RepositoryBase<TEntity> : IRepositoryBase<TEntity>
where TEntity : class

{

        public RepositoryBase(IDataContext context)

        {

        }

}

The UnitOfWork class had a constructor that accepted the ILifetimeScope object and using this object, I was resolving the context in the constructor. I also had a couple of repositories specified as properties in this class. Refer sample code below.

UnitOfWork.cs

public class UnitOfWork : IUnitOfWork

{

    public UnitOfWork(ILifetimeScope scope)

    {
        this.scope = scope.
        this.Context = this.scope.Resolve<IDataContext>();

    }

    public Task<int> SaveAsync()

    {

        return this.Context.SaveAsync();

    }

   // Repositories

    public IRepositoryBase<SampleClass> SampleRepository

    {

        get
        {
            if(this.sampleClassRepository == null) this.sampleClassRepository = this.scope.Resolve<IRespositoryBase<SampleClass>>();    // Observe above line later
             return this.sampleClassRepository;
        }

    }

}

The code that was using this repository was something like

using(var uow = this.scope.Resolve<IUnitOfWork>())
{

    uow.SampleRepository.Insert(newEntity);
    uow.SaveAsync();    // This should actually save above new entity into DB but it wasn't saving anything.
}

The problem with this approach was that When I was working with the repository, Autofac initially sees that the repository object has not been created and so creates a new object by resolution by injecting a NEW CONTEXT object as it sees that repository constructor requires an IDataContext object.

So because of this issue, we end up with 2 different contexts, one which just got created while trying to access the repository and this also has the change (insert), and the other which got created while creation of UnitOfWork object. And what happens is insert action goes into repository context object and Save action works upon the UnitOfWork’s context object. Hence, nothing fails but nothing happens in DB as well.

To make sure that repositories are also using the same context as UnitOfWork, what we can do is to pass the unitOfWork’s context to the Resolve method of ILifetimeScope as shown below.

if(this.sampleClassRepository == null) 
    this.sampleClassRepository = 
    this.scope.Resolve<IRespositoryBase<SampleClass>>
        (new TypedParameter(typeof(IDataContext), this.Context));

This is present in the UnitOfWork class. And this.Context refers to unitOfWork’s context. This statement ensures that when repository instance is being created, instead of creating a new context, we’re going to reuse the context of unitOfWork and so any Save operations performed would thus perform the operations on the database as well.

Hope this helps!

Reference : http://docs.autofac.org/en/latest/resolve/parameters.html

Posted in .NET, General | Tagged , , , , , , , | Leave a comment

Resolving Azure Data Lake Authorization Issue

Hi,

While trying to access Azure Data Lake Store from my application, I encountered the below exception.

The client 'guid' with object id 'guid' does not have authorization 
to perform action 'Microsoft.Authorization/permissions/read' 
over scope '/subscriptions/guid....

Resolution :

I realized that I had not given permission to the Active directory application in the Data Explorer tab in ADLS. To give permission, open Data Explorer –> Access –> Add –> Search for your AD application, Give Read, Write, Execute permission –> Save.

This should resolve the issue.

Hope this helps!

Posted in .NET, General | Tagged , , , , , | Leave a comment

Resolving IContainer in Constructor when using Autofac

Hi,

While using Unity as an Inversion of Control and Dependency Injection container, there is an option to directly inject the container into a class’s constructor by placing the IUnityContainer interface as a constructor parameter. This container can then be used by the class members for further resolution.

This option is not directly available in Autofac. If we put a parameter of IContainer type in a class’s constructor, then we get the below exception.

None of the constructors found with 
'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' 
on type 'your_class' can be invoked with the 
available services and parameters:

Cannot resolve parameter 'Autofac.IContainer container' 
of constructor 'Void .ctor(Autofac.IContainer)'.

Instead, you can inject the IComponentContext or the ILifetimeScope interfaces in the constructor of your class and use the injected instance of either of these for resolving further dependencies.

Example:

public class SampleClass
{
    public SampleClass(ILifetimeScope lifetimeScope)
    {
        // basically using the lifetimescope parameter 
        // as a container for resolving other dependencies.

        var someOtherDependency = 
             lifetimeScope.Resolve<ISomeOtherInterface>();

    }
}

Hope this helps!

 

Posted in General | Tagged , , , , | Leave a comment

Resolving “Value does not fall within the expected range” ArgumentException while reporting custom health events in Azure service fabric

Hi,

If you’re working with Azure Service Fabric, there are chances you might be using the cluster Health Management APIs provided by SF SDK. And if you’re using those, then you would obviously be posting some custom health events at either your service level, application level or instance level with a source Id, health property and a human-readable description.

Solution :  The one thing to note here is that the Description field of HealthInformation class has a limit of 4095 characters. This is nowhere mentioned in the documentation but it’s there. And if the description is more than that, while reporting you would get the below exception.

Exception Type : System.Argument Exception
Message : Value does not fall within the expected range.
Inner Exception :  null
Stack Trace : 
   at System.Fabric.Interop.NativeClient.IFabricHealthClient3.ReportHealth(IntPtr healthReport)
   at System.Fabric.FabricClient.HealthClient.ReportHealthHelper(HealthReport healthReport)
   at System.Fabric.Interop.Utility.<>c__DisplayClass13.<WrapNativeSyncInvoke>b__12()
   at System.Fabric.Interop.Utility.WrapNativeSyncInvoke[TResult](Func`1 func, String functionTag, String functionArgs)
   at System.Fabric.Interop.Utility.RunInMTA(Action action)
   at System.Fabric.FabricClient.HealthClient.ReportHealth(HealthReport healthReport)
   at ….. your file.

So, in case you run into this exception at the point of reporting, make sure you double-check the description length and in-general all the data that you’ve added to the health report object.

Hope this helps!

Posted in .NET, General | Tagged , , , , , , , , | Leave a comment

Check if service bus topic/subscription/queue exists with SAS key not having Manage permission

Hi,

Consider a scenario where you’ve developed an application health monitoring type system which validates your application at application startup/periodically. Now as part of that if your application uses Azure service bus queues, topics, subscriptions, then it would be good to verify that they all exist before your application actually starts its work.

So your initial thought would be to use NamespaceManager class from the Microsoft.ServiceBus assembly. This class provides <entity>Exists() methods for all the above. However, one point to note here is that NamespaceManager class requires Manage permission to be present to the SAS key from the connection string.

As a security measure, the general advise is to NOT use a SAS key with manage permission and to use one with Send/Listen permissions.

1

So for checking if the entities exist, we can use the TopicClient, SubscriptionClient, QueueClient classes from Microsoft.ServiceBus.Messaging assembly. Check below code. Click for full size image.

2_updated

 

In the above snippet, each of the .Peek() (Or PeekAsync()) methods will throw an exception (Entity not found) if the corresponding entity doesn’t exist and passes if they exist. This check can be used to determine if the entities exist or not.

P.S: There are other ways too but this is relevant if you do not want to send/receive from these service bus entities.

Hope this helps!

Posted in .NET, C#, General | Tagged , , , , , , , , , , , | Leave a comment