Wednesday 22 April 2015

Generic Repository to do transactions with Azure Document DB

Following is a generic repository we can use in order to do data manipulations in Azure document DB. This can be used to save and retrieve POCO objects and generic streamed objects in Azure Document DB.

I have used MEF to do the dependency injections. This repository is used only to deal with one collection. More generic implementation is on its way and will update soon.

 public interface IDocumentDb
        {
            dynamic GetRecord(string id);

            IEnumerable<object> GetRecords();
            
             Task Add(object entity);

            Task Update(object entity,string id);

            Task Delete(string id);

            void Dispose();
        }
The implementation class is as follows.
   [Export(typeof(IDocumentDb))]
    [PartCreationPolicy(CreationPolicy.NonShared)]
   public class DocumentDb : IDocumentDb
    {
        private static DocumentClient _client;
        private Database _database;
        private DocumentCollection _collection;

        private static readonly string DadatabaseId = ConfigurationManager.AppSettings["DatabaseId"];


        private static readonly string EndpointUrl = ConfigurationManager.AppSettings["EndPointUrl"];
        private static readonly string AuthorizationKey = ConfigurationManager.AppSettings["AuthorizationKey"];
        private static readonly string CollectionId = ConfigurationManager.AppSettings["CollectionId"];

    
        public DocumentDb()
        {
            
           Init();
        }

        private async Task Init()
        {
            _client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey);
            try
            {
                this._database = _client.CreateDatabaseQuery().Where(db => db.Id == DadatabaseId).ToArray().FirstOrDefault();
                if (_database == null)
                {
                    this._database = await _client.CreateDatabaseAsync(new Database { Id = DadatabaseId });
                }

                this._collection = _client.CreateDocumentCollectionQuery(_database.SelfLink).Where(c => c.Id == CollectionId).ToArray().FirstOrDefault();
                if (_collection == null)
                {
                    _collection = await _client.CreateDocumentCollectionAsync(_database.SelfLink, new DocumentCollection { Id = CollectionId });
                }
            }
            catch (Exception ex)
            {
                
                throw;
            }
          

          
        }

        public async Task Add(object entity)
        {
            try
            {
                await _client.CreateDocumentAsync(_collection.SelfLink, entity);
            }
            catch (Exception ex)
            {
                
                throw;
            }
        }

        public async Task Update(object entity,string id)
        {
            try
            {
                var doc =
                   _client.CreateDocumentQuery(_collection.SelfLink).Where(d => d.Id == id).AsEnumerable().FirstOrDefault();

                if (doc != null)
                    await _client.ReplaceDocumentAsync(doc.SelfLink, entity);

            }
            catch (Exception ex)
            {
                
                throw;
            }
        }

        public dynamic GetRecord(string id)
        {
            try
            {
                dynamic doc =
                    _client.CreateDocumentQuery(_collection.SelfLink).Where(d => d.Id == id).AsEnumerable().FirstOrDefault();
                return doc;
            }
            catch (Exception ex)
            {
                throw;
            }
           
        }

        public IEnumerable<object> GetRecords()
        {
            try
            {
                var obj = _client.CreateDocumentQuery(_collection.SelfLink, "SELECT * FROM " + CollectionId).AsEnumerable().ToList();
                return obj;
            }
            catch (Exception ex)
            {
                throw;
            }
        }


        public async Task  Delete(string id)
        {
            try
            {

                var doc =
                    _client.CreateDocumentQuery(_collection.SelfLink)
                        .Where(d => d.Id == id)
                        .AsEnumerable()
                        .FirstOrDefault();

                if (doc != null)
                {
                    var resourceResponse = await _client.DeleteDocumentAsync(doc.SelfLink);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        public void Dispose()
        {
            if (_client == null)
            {
                return;
            }

           _client.Dispose();
        }

    }
Following is the consumer class.
public class Consumer
{
      [Import(typeof(IDocumentDb))]
      public IDocumentDb DocumentDb { get; set; }

      public Consumer()
      {
      }

      public void TempAdd()
      {
                  DocDbCustomFieldViewModel docDbEntity = new DocDbCustomFieldViewModel();
                  docDbEntity.Id = model.ID;
                  docDbEntity.ClientId = CurrentClientID;
                  docDbEntity.ProjectId = CurrentProjectID;

                List lCusFields = new List();
                foreach (var cusField in cusFields)
                {
                    CustomFieldViewModel newCusField = CustomFieldProvider.Get(cusField.CustomFieldID);
                    CustomFieldViewViewModel tmpModel = new CustomFieldViewViewModel();
                    tmpModel.DisplayName = newCusField.DisplayName;
                    tmpModel.FieldName = newCusField.FieldName;
                    tmpModel.Value = string.Empty;
                    lCusFields.Add(tmpModel);

                }
                docDbEntity.CustomFields = lCusFields;     

                 DocumentDb.Add(docDbEntity);
       }

       public void TempSearch(string id)

}

Tuesday 7 April 2015

Dynamically Importing multiple functionality using MEF (Managed Extensibility Framework)

Using Managed Extensibility Framework (MEF) we can create lightweight, extensible applications without much of a fuzz.  It is a pretty good tools for IoC and can be easily use as a good DI component as well.

Following is a very simple example of using MEF create simple message service which include many variations.

First of all you need to import the assembly System.ComponentModel. This is the assembly that contains all the beauty of MEF.

We would be creating a very simple console application just to demonstrate the  principle.

The Program class is looks as follows.

    class Program
    {
        static void Main(string[] args)
        {
           DynamicLoad();
        }

        private static void DynamicLoad()
        {
            var testDynamicMessaging = new DynamicMessaging();
            testDynamicMessaging.Run();

            Console.ReadLine();
        }
      
    }

This class is very simple. Just invoking the method Run in the DynamicMessaging class.
DynamicMessaging looks as follows.
 internal class DynamicMessaging
    {
        [ImportMany]
        public IEnumerable Messages { get; set; }
        public void Run()
        {
          Compose();
          foreach (var messenger in Messages)
          {
              messenger.Send("Hi");
          }

        }
        
        private void Compose()
        {
          var assemblyCatalog = new AssemblyCatalog(GetType().Assembly);
          var container = new CompositionContainer(assemblyCatalog);

          container.ComposeParts(this);

        }
    }
There are few important points in this class as follows. 1. ImportMany attribute enables importing many interfaces to the enumerable property Messages. 2. We are creating an assembly catalog and using that when creating the CompositionContainer. 3. When composing parts, we are just passing the current object only. (this) . But if we are not going to load multiple interfaces , the code would looks as follows. ie: only the object type we need.
 var container = new CompositionContainer();
 container.ComposeParts(this, new SpecificMessenger());
Finally the implemented messenger classes are looks like follows.
[Export(typeof(IMessenger))]
    class EMailMessenger : IMessenger
    {
        public void Send(string message)
        {
            Console.WriteLine("This is from the email Messenger " + message  );
        }
    }

 [Export(typeof(IMessenger))]
    class TextMessenger : IMessenger
    {
        public void Send(string message )
        {
            Console.WriteLine("This is from the text messenger " +  message);
        }
    }

Re sharper r - Re-factoring failed - Files still read-only' error message - Issue Fixed


Just got this error in Re sharper re-factoring.



I am using GIT as my source control and this is caused by that. So in VS2013 , Just Select the plugin as None in Source Control as follows. 

Bingo ! This solves the issue.