Sunday, March 27, 2016

Exploring Facade

Recently I have been working on surface on Amazon MWS API. So basically Amazon MWS API is for interacting with Amazon seller account. If we need to update products directly from your local system or database directly to Amazon that involves different operation on products, creation of reports and stuffs we need this API.

Amazon MWS API uses different types of separate feeds to update different sections of a products such as Product basic info on ProductFeed, its pricing on PricingFeed, Quantity on QuantityFeed and so on. As I was working on feeds, I felt there is some subsystem within and if Facade would match the things I was about to do, but wasn't sure if it was really needed there and might be too much for it, but then I also thought that the class would expand, might be hard later for modification while mixing everything on single class. So it went for Facade and felt later that it was a wiser choice. Here is some ripped of samples


public static class AmazonMwsFacade
{
    private static readonly PricingFeed PricingFeed = new PricingFeed();
    private static readonly ProductFeed ProductFeed = new ProductFeed();
    private static readonly ImageFeed ImageFeed = new ImageFeed();
    private static readonly InventoryFeed InventoryFeed = new InventoryFeed();
    private static readonly RelationshipFeed RelationshipFeed = new RelationshipFeed();

    public static IDictionary<string, string> CreateXml(string filterFeedType, string csvId)
    {
        #region Headers

        #endregion

        var count = 1;
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                if (reader["ProductBarCode"].ToString() != "0")
                {
                    if (filterFeedType.Contains("1"))
                        ProductFeed.CreateProductFeedXml(amazonProductXml, reader, ref count);
                    if (filterFeedType.Contains("2"))
                        PricingFeed.CreatePricingFeedXml(amazonPricingXml, reader, count);
                    if (filterFeedType.Contains("3"))
                        InventoryFeed.CreateInventoryFeedXml(amazonInventoryXml, reader, count);
                    if (filterFeedType.Contains("4"))
                        ImageFeed.CreateImageFeedXml(amazonImageXml, reader, count);
                    if (filterFeedType.Contains("5"))
                        RelationshipFeed.CreateRelationshipFeedXml(amazonRelationshipXml, reader, count);
                    ++count;
                }
            }
            if (filterFeedType.Contains("5"))
                RelationshipFeed.PostRelationshipFeedXml(amazonRelationshipXml);
        }

        IDictionary<string, string> dictXml = new Dictionary<string, string>();

        if (filterFeedType.Contains("1"))
            dictXml.Add("_POST_PRODUCT_DATA_", ProductFeed.SaveProductXml(amazonProductXml));
        if (filterFeedType.Contains("2"))
            dictXml.Add("_POST_PRODUCT_PRICING_DATA_", PricingFeed.SavePricingXml(amazonPricingXml));
        if (filterFeedType.Contains("3"))
            dictXml.Add("_POST_INVENTORY_AVAILABILITY_DATA_", InventoryFeed.SaveInventoryXml(amazonInventoryXml));
        if (filterFeedType.Contains("4"))
            dictXml.Add("_POST_PRODUCT_IMAGE_DATA_", ImageFeed.SaveImageXml(amazonImageXml));
        if (filterFeedType.Contains("5"))
            dictXml.Add("_POST_PRODUCT_RELATIONSHIP_DATA_", RelationshipFeed.SaveRelationshipXml(amazonRelationshipXml));
        return dictXml;
    }
}

Now for every feed type, I created a class, on Facade terms kind of subsystem.

internal class ProductFeed
{
    private readonly bool _hasRelation;
    public ProductFeed()
    {
                // Logic
    }

    public static XElement CreateSearchString(string searchString)
    {
                // Logic
    }

    public static string RemoveTroublesomeCharacters(string inString)
    {
                // Logic
    }

    public XElement CreateProductFeedXml(XElement amazonProductXml, SqlDataReader reader, ref int count)
    {
                // Logic
    }

    public string SaveProductXml(XElement amazonXml)
    {
                // Logic
    }

    private XElement RemoveDummyProductElement(XElement tempElement)
    {
                // Logic
    }

    private XElement RemoveDummyElement(XElement tempElement)
    {
                // Logic
    }

    private XElement RemoveDummySearchElement(XElement tempElement)
    {
                // Logic
    }
}

internal class PricingFeed
{
    public XElement CreatePricingFeedXml(XElement amazonPricingXml, SqlDataReader reader, int count)
    {
                // Logic
    }

    public string SavePricingXml(XElement amazonXml)
    {
                // Logic
    }
}


internal class ImageFeed
{
    public XElement CreateImageFeedXml(XElement amazonImageXml, SqlDataReader reader, int count)
    {
                // Logic
    }

    public string SaveImageXml(XElement amazonXml)
    {
                // Logic
    }
}

internal class RelationshipFeed
{
    private string _parentSku = String.Empty;
    private int _count;
    private XElement _listElement;
    private bool _hasFooter;
    private string _groupId;

    public RelationshipFeed()
    {
        _listElement = new XElement("DummyElement");
    }

    public XElement CreateRelationshipFeedXml(XElement amazonRelationshipXml, SqlDataReader reader,
        int count)
    {
                // Logic
    }

    public XElement PostRelationshipFeedXml(XElement amazonRelationshipXml)
    {
                // Logic
    }

    private XElement RemoveDummyElement(XElement tempElement)
    {
                // Logic
    }

    public string SaveRelationshipXml(XElement amazonXml)
    {
                // Logic
    }
}

internal class InventoryFeed
{
    public XElement CreateInventoryFeedXml(XElement amazonInventoryXml, SqlDataReader reader, int count)
    {
                // Logic
    }

    public string SaveInventoryXml(XElement amazonXml)
    {
        // Logic
    }
}


Didn't think those subsystem class would expand and get dirty but if I now imagine myself without subsytem approach I am sure it will get dirtier than its now. Further common operations or methods are inside AmazonMWSFacade class and only distinct operation are on respective subsystem regardless of similar signature.

Monday, September 21, 2015

Really Singleton

Here is a piece of code I took from dofactory.com

using System;
using System.Collections.Generic;
class MainApp
{
    static void Main()
    {
        LoadBalancer oldbalancer = null;
        for (int i = 0; i < 15; i++)
        {
            LoadBalancer balancerNew = LoadBalancer.GetLoadBalancer();

            if (oldbalancer == balancerNew && oldbalancer != null)
            {
                Console.WriteLine("{0} SameInstance {1}", oldbalancer.Server, balancerNew.Server);
            }
            oldbalancer = balancerNew;
        }
        Console.ReadKey();
    }
}

class LoadBalancer
{
    private static LoadBalancer _instance;
    private List<string> _servers = new List<string>();
    private Random _random = new Random();

    private static object syncLock = new object();

    private LoadBalancer()
    {
        _servers.Add("ServerI");
        _servers.Add("ServerII");
        _servers.Add("ServerIII");
        _servers.Add("ServerIV");
        _servers.Add("ServerV");
    }

    public static LoadBalancer GetLoadBalancer()
    {
        if (_instance == null)
        {
            lock (syncLock)
            {
                if (_instance == null)
                {
                    _instance = new LoadBalancer();
                }
            }
        }

        return _instance;
    }

    public string Server
    {
        get
        {
            int r = _random.Next(_servers.Count);
            return _servers[r].ToString();
        }
    }
}

I took code from dofactory.com, nothing so fancy but I find this far good than examples with Foo and Bar additionally book from Judith Bishop on C# 3.0 Design Patterns has example about active application in mac dock.
If you look at code we are actually building new objects on for loop, so that creates new object but reuses instance as a result of which the oldbalancer and newbalancer has same instance, How? its due to static keyword used on function GetLoadBalancer(), despite of having different server value which is random list, static on GetLoadBalancer() belongs to the type itself rather than to a specific object.
Additionally there is double check locking here

if (_instance == null)
            {
                lock (syncLock)
                {
                    if (_instance == null)
since from MSDN
The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.
so every-time mutual-exclusion lock is issued, even if it don't need to which is unnecessary so we have null check.
Hopefully it helps in clearing more.

Wednesday, February 25, 2015

Implementing Interface in C#


I have been programming for my living for quite few years, programming is more like hobby and sometime one of the way to past time, like gaming. Uncle Bob forwarded something called SOLID for good object oriented design and sometime we do blindly follow it sometime we really need it. Today I have something for Interface Segregation.
Interface has been around for quite a while from java to now typescript. Yes its basically a contract as defined on papers about interface but why do we need a contract? how do we implement it in real world application? There are enough Foo and Bar around, knowing technical part of it, knowing syntax is the most easiest part of anything along with how to do :-), but actually getting your finger to write code along with interface takes time.

Let us assume I have class FoodEstablishment, now I want to do simple CRUD operation, so how do I do it?
I define an interface for service, but why? wait :-)

public interface IFoodEstablishmentService
{
    Task<int> AddAsync(FoodEstablishment oFoodEstablishment);
    FoodEstablishment SelectByFoodEstablishmentId(long id);
    Task<int> UpdateAsync(FoodEstablishment oFoodEstablishment);
    Task<int> DeleteAsync(FoodEstablishment oFoodEstablishment);
}

Then I will implement that contract or interface for that particular service

public class FoodEstablishmentService : IFoodEstablishmentService
{
    public async Task<int> AddAsync(FoodEstablishment oFoodEstablishment)
    {
       // Insert Operation
        return result;
    }

    public FoodEstablishment SelectByFoodEstablishmentId(long id)
    {
        // Select Logic
        return oFoodEstablishment;
    }

    public async Task<int> UpdateAsync(FoodEstablishment oFoodEstablishment)
    {
        // Update Logic
        return result;
    }

    public async Task<int> DeleteAsync(FoodEstablishment oFoodEstablishment)
    {
        // Delete Logic
        return result;
    }
}

So in my main program or where I wish to use Service, I will do

IFoodEstablishmentService oFoodEstablishmentService =  new FoodEstablishmentService();
FoodEstablishment oFoodEstablishment = // Input might be from views;
oFoodEstablishmentService.AddAsync(oFoodEstablishment);

So till now it seems like an extra step, when we could have directly done

FoodEstablishmentService oFoodEstablishmentService =  new FoodEstablishmentService();
FoodEstablishment oFoodEstablishment = // Input might be from views;
oFoodEstablishmentService.AddAsync(oFoodEstablishment);

But wait what if I might need to pass my insert logic through queue rather than directly to server, wait for insert operation to complete and then return result, rather pass on queue and then the queue worker handles those operation, might not be best idea to queue insert but yes definitely good for interface example :-). So now what I do is, create another class FoodEstablishment implementing same contract IFoodEstablishment.

public class FoodEstablishmentQueueService : IFoodEstablishmentService
{
    public async Task<int> AddAsync(FoodEstablishment oFoodEstablishment)
    {
       // Insert Queue Operation
        return result;
    }

    public FoodEstablishment SelectByFoodEstablishmentId(long id)
    {
        // Select Queue Logic
        return oFoodEstablishment;
    }

    public async Task<int> UpdateAsync(FoodEstablishment oFoodEstablishment)
    {
        // Update Queue Logic
        return result;
    }

    public async Task<int> DeleteAsync(FoodEstablishment oFoodEstablishment)
    {
        // Delete Queue Logic
        return result;
    }
}

So now if I want to use the queue version, I would just do

IFoodEstablishmentService oFoodEstablishmentService =  new FoodEstablishmentQueueService();
FoodEstablishment oFoodEstablishment = // Input might be from views;
oFoodEstablishmentService.AddAsync(oFoodEstablishment);

We could do that with the older way using class but that bounds the class instantiation with a particular class which is kind of rigid to extension, now FoodEstablishmentQueueService can do other things too, create another method until the contract is valid so interface is contact for consistency, Imaging one guy doing the normal version and other doing the queue version or someone doing cache version, there might be problems regarding signature unless its pre-specified about the working contract and people don't end up cross checking everything.

Similarly, let consider other simple example of using predefined types like IEnumerable. Suppose I pass a list of FoodEstablishment collection and return custom sorted list

public FoodEstablishment[] SortFoodEstablishment(FoodEstablishment[] list)
{
    foreach(var oFoodEstablishment in list)
    {
    // some logic
    }
    return sortedList;
}

So we will use it this way

FoodEstablishment[] list = new FoodEstablishment[]{ //some values }
var listSorted = oFoodEstablishmentService.SortFoodEstablishment(list);

But what if we send list instead of array

List<FoodEstablishment> list = //some values;
var listSorted = oFoodEstablishmentService.SortFoodEstablishment(list);

We will get error, because its strict implementation using class so instead we use IEnumerable<> which is implemented by List and that basically removes dependency from List to Interface

public IEnumerable<FoodEstablishment> SortFoodEstablishment(IEnumerable<FoodEstablishment> list)
{
    foreach(var oFoodEstablishment in list)
    {
    // some logic
    }
    return sortedList;
}

So usually implementation hugely depends on situation, its not like I woke up suddenly and start writing everywhere :-)

I am getting really hungry and more foolish than ever :D

Sunday, February 8, 2015

Factory Pattern with Azure Blobs


I have been playing with Windows Azure quite a bit these days in my own noob ways :-). In Azure we have blobs which stores files on storage account rather than on the websites itself.

Practically in our part of world we store images and files on folder inside websites with different folder structure such as Uploads -> Images -> Company, its easy and its good but what if we want to transfer the same file to production? we commit same file to production right, but why do you want to commit same test file to production? yes might not be dynamic but for system specific files such as image we need to. So here blobs acts as another layering which is makes it independent. Further serving huge files which is what blobs stands for (big objects) from the server where websites hosts does not exhaust webserver feeding huge static content. And its easy with AzureCDN too. I actually tried free CDN with CloudFront too but its point of presence is far than AzureCDNs, so the network latency was relatively high with CloudFront resulting in poor performance so it was better without CDN then actually forcing to have one :-).

I have been through factory pattern on the web and some pdfs too, I find it good and easily implementable. Which describes the way the object are created with subclasses deciding type of class to be instantiate, so basically we instantiate classes based on parameter here. I am not too much on copy pasting with diagram and sorts of thing but have simple approach which can atleast convince us to use those. Here is how I implement basic of pattern on instantiating Azure Blobs

public class BlobCore
    {
        private readonly CloudBlockBlob _blockBlob;
 
        public CloudBlockBlob CloudBlockBlob
        {
            get { return _blockBlob; }
        }
 
        public BlobCore(string referenceType, string name)
        {
            // Can use Azure Cloud Service but for this used the traditional Web.Config
            CloudStorageAccount storageAccount =
                CloudStorageAccount.Parse(
                    ConfigurationManager.AppSettings["StorageConnectionString"]
            );
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container = blobClient.GetContainerReference(referenceType);
 
            container.CreateIfNotExistsAsync();
 
            // Giving the blobs Public Access
            container.SetPermissions(new BlobContainerPermissions() {
                PublicAccess = BlobContainerPublicAccessType.Blob
            });
 
            _blockBlob = container.GetBlockBlobReference(name);
        }
 
        public static BlobCore ProductContainer(string name)
        {
            return new BlobCore("Product", name);
        }
 
        public static BlobCore CompanyContainer(string name)
        {
            return new BlobCore("Company", name);
        }
 
        public int Upload(HttpPostedFileBase file)
        {
            CloudBlockBlob.UploadFromStream(file.InputStream);
            return 1;
        }
 
        public int Delete()
        {
            CloudBlockBlob.Delete();
            return 1;
        }
    }

So inorder to instantiate I would do something like this

var oBlobCore = BlobCore.ProductContainer('imageName');
oBlobCore.Upload(file);


So this gives me clear idea if I am using this as client not knowing the detail which clearly states that I am using ProudContainer with name of image that I wish to operate to. But here instead of using multiple classes my solution was best using single class. So implementation of patterns varies with need and someday if I come accross through the full detail factory pattern will love to post some codes here.

Staying very hungry and doing things foolishly

Friday, June 27, 2014

Google IO

I don't know how I got so much interested in technological stuffs, I know it was subconsciously inside me but I cannot remember what triggered me over technology. Recently we got over WWDC by Apple and now its Google time with Google IO.

Either through tech blogs or feeds or Facebook page or posts people are more or less into technology and know more or less about technology, so people are slowly and unknowingly building expectations within themselves about the future of technology. With every dev focused conference like WWDC or even Google IO at the end of the day people are like with Okay feeling rather than getting excited over the development, one of the main reason to being Okay from a Wow is its mostly for devs and not all the people watching are devs, most of them are watching keynote and off, but overall its good coz more people are getting engaged.

With WWDC, I am excited over Yosemite i.e. new version of the Apple's OS X coming soon and with the Google IO with Android L which I have preview installed. The future of search by Ray Kurzweil is something to look forward with time but for now its being materialistic over material design :-). I don't know about others but I am using it as regular OS on my regular phone and its smooth as far as I have used. Its more like adding retouch on both iOS and legacy Android. I had earlier used dev preview of Windows 8 even the consumer preview but didn't find anything so to worry about on the Preview versions and same is for the Android L. Moving to android L, as addressed so much on Keynote, the experience is good with more depth and animation thing going on, and the animation is more like sliding underneath the other layout which is similar to the multi tab of chrome thing but is highly polished, even the recent window are multi tabbed, they have worked in details and design for this version, touch are responsive with ripple effect, the notification are on the lock screen with a fixed line grid layout but when its slightly lower down notification expands which is good detailing but needs more days to get used to it, the dialer more colourful, overall the feel this time is definitely like installing a UPDATE rather than just incrementing the version number beneath, so its now the UX thats slowly taking on Android. Now its ART all the way, which was optional for the earlier version of Nexus 5.

When I saw news about android L on preview mode regardless of warning I jumped straight into it and got it done and I am happy that I am using it without breaking anything beneath of my hard earned Nexus 5 :-)

Happy Technology

  








Monday, May 19, 2014

Something X

We all know google right :-)

I remember when I knew google, might be around 7-8 years from now, I knew it not in a good way. I kind of heard it that its a company by young group of people which might not exist for long as people would expect to. But as years passed we are google all the way. Its been so part of our life that we can’t even imagine life without it. How can search engine make money out of it? It did and did in a grand style.

Recently I have been reading about Google X, a kind of secretive lab for moonshot thinking, saw interview of Astro Teller captain of Google X and its like really good. Imagine someone comes to you and ask you about if you can increase the maximum speed of a might be a F1 car from 400 kmph to 500 kmph, so what would you do?? you will start to know about the engine and start tweaking the bottlenecks and you will somehow achieve it or even achieve it like 550kmph and might be the reason of applaud but what if anyone or no-one comes and ask you if you can increase the speed to like crazy 1500kmph or even more?? Now you are thinking on the X's way. Why ?? coz you now cannot tweak that system, you have to think beyond iteration and think beyond sky (coz sky is limit) now you will have to work on small details and rebuild those details to art, shattering all those laws of defining something. Even getting this thing known made me feel wow. How could possibly someone think these things ?? So its Google X way of doing things. Everything they do like the Google Glass brings huge possibilities to us, imagine reading menus of restaurant with google glass of language that you don't know, even knowing the history or price tag of any product you are seeing, even heath related concern with that particular object. So the possibility is widening up with technology and its evolution. So Google has a research division but how is Google X different?? its not something that is in the name, its on the approach that they take. So basically what a research is? its like digging into something that no-one knows till making it like nothing but google X is like digging into everything if they can get something for everyone so the approach is one liner but different, different enough to make it something like X. They like to create non-iterative things, once done is done, the leftover is like for the weaker ones :-). Some defines X like roman X i.e. 10 it does work 10 years ahead, some says its like they do 10 folds of a particular thing but whatever it may be, its bringing foundational change for tomorrow. I remember google buying Boston Dynamics and when I saw that video there is noway that you will say its made, it seems like a bull running in iron clad armour, its real and its now Google. 

To add to X, I am so much excited to about Oculus VR being acquired by Facebook. I have read somewhere that it might be the platform for Facebook and I wish it is. I am highly optimistic about Oculus being the platform coz when we see the big companies like Microsoft its platform is Windows OS, Google's Android, Apple's OS X but what about Facebook?? It has no platform, instead it depends on android or window or OS X or .... but what if it could have something that you can interact differently that you normally do so is it Oculus VR?? its certainly has huge possibility but if its Facebook platform that surely its good.

So there are so much of things that are happening out there, somewhere so this rejunevates life and help me try to do things that I usually don't, so its like staying informed but still staying foolish. 

Friday, April 18, 2014

Struck with details



Came up with a new from TechCrunch about www.canva.com:

“Macintosh democratized computers; Google democratized information; and eBay democratized commerce. In the same way, Canva democratizes design,” Kawasaki said in a statement. “You don’t get many chances to democratize an industry, so I seized the opportunity to work for Canva.”

 So I just seized the opportunity and just created a blog cover in wrong place I guess, Its beautiful a kind of app thing, details are huge on this especially loved loading part. Wow so much excited to see what is next for Canva, huge thanks to canva for getting me excited :-)