private DxStoreStateMachine CreateStateMachine(Round <string>?leaderHint, PaxosBasicInfo referencePaxos)
        {
            Policy policy = new Policy
            {
                DebugName = this.GroupConfig.Self
            };
            bool flag = false;

            string[] array = (from m in this.GroupConfig.Members
                              select m.Name).ToArray <string>();
            if (referencePaxos != null && referencePaxos.IsMember(this.GroupConfig.Self))
            {
                array = referencePaxos.Members;
                flag  = true;
            }
            IDxStoreEventLogger eventLogger = this.EventLogger;
            DxEventSeverity     severity    = DxEventSeverity.Info;
            int    id           = 0;
            string formatString = "{0}: Creating state machine with membership '{1}' (IsUsingReferencePaxos: {2}, IsReferencePaxosLeader: {3}, GroupConfig.Members: {4}";

            object[] array2 = new object[5];
            array2[0] = this.GroupConfig.Identity;
            array2[1] = array.JoinWithComma("<null>");
            array2[2] = flag;
            array2[3] = (flag ? referencePaxos.IsLeader.ToString() : "<unknown>");
            array2[4] = (from m in this.GroupConfig.Members
                         select m.Name).JoinWithComma("<null>");
            eventLogger.Log(severity, id, formatString, array2);
            Dictionary <string, ServiceEndpoint> membersInstanceClientEndPoints = this.GetMembersInstanceClientEndPoints(array);
            NodeEndPointsBase <ServiceEndpoint>  nodeEndPointsBase = new NodeEndPointsBase <ServiceEndpoint>(this.GroupConfig.Self, membersInstanceClientEndPoints);

            this.PerfCounters = new Counters(this.GroupConfig.Identity);
            Configuration <string> configuration = new Configuration <string>(nodeEndPointsBase.Nodes, nodeEndPointsBase.Nodes, nodeEndPointsBase.Nodes, null);
            GroupMembersMesh       mesh          = new GroupMembersMesh(this.Identity, nodeEndPointsBase, this.GroupConfig);
            EsentStorage <string, DxStoreCommand> esentStorage = new EsentStorage <string, DxStoreCommand>(this.GroupConfig.Settings.PaxosStorageDir, this.PerfCounters, null, null, true);

            esentStorage.TryInitialize(configuration);
            return(new DxStoreStateMachine(policy, this, nodeEndPointsBase, esentStorage, mesh, this.PerfCounters, leaderHint));
        }
        public static ProxyStateMachine New(string location, string serviceName)
        {
            ProxyStateMachine stateMachine;
            var nodeConfig      = RoleEnvironment.GetConfigurationSettingValue(serviceName + ".Nodes");
            var nodeDescriptors = nodeConfig.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            var nodes           = new Dictionary <string, Uri>();

            foreach (var d in nodeDescriptors)
            {
                var n = d.Split('=');
                try
                {
                    nodes.Add(n[0], new UriBuilder()
                    {
                        Host = n[1]
                    }.Uri);
                }
                catch (Exception x)
                {
                    Trace.TraceError(x.ToString());
                }
            }
            Uri host;

            if (nodes.TryGetValue(location, out host))
            {
                var preferedLeaders = RoleEnvironment.GetConfigurationSettingValue(serviceName + ".PreferedActiveMembers").Split(';');
                var localStorage    = RoleEnvironment.GetLocalResource("LocalStorage").RootPath;
                var storagePath     = Path.Combine(localStorage, serviceName);

                if (!Directory.Exists(storagePath))
                {
                    Directory.CreateDirectory(storagePath);
                }
                var storage       = new EsentStorage <string, SerialilzableWebRequest>(storagePath, new Counters(location));
                var configuration = new Configuration <string>(preferedLeaders, preferedLeaders, nodes.Keys);
                storage.TryInitialize(configuration);
                Trace.WriteLine("Local Storage Initialized");

                var meshPath = serviceName + "Mesh.ashx";
                var uri      = new UriBuilder(host)
                {
                    Path = meshPath
                }.Uri;
                X509Certificate2 cert = Utility.GetCert();
                var mesh = new MeshHandler <Message>(uri, null, cert);
                RouteTable.Routes.Add(new Route(meshPath, new FuncRouteHandler(_ => mesh)));

                FUSE.Weld.Azure.Configuration.SetConfigurationSettingPublisher();
                var s2        = Utility.GetStorageAccount(true);
                var container = s2.CreateCloudBlobClient().GetContainerReference("root");
                container.CreateIfNotExist();

                Trace.Write("Remote Storage Loaded");

                stateMachine = new ProxyStateMachine(location, nodes, mesh, storage, serviceName, preferedLeaders);

                stateMachine.Paxos.WhenDiverged.Subscribe(d =>
                {
                    Utility.DisableService(stateMachine.ServiceName);
                });

                Global.lastMessages[serviceName]  = new Queue <Timestamped <Tuple <string, Message, string> > >();
                Global.stateMachines[serviceName] = stateMachine;

                var o = stateMachine.Mesh
                        .Where(m => Interesting(m.Item2))
                        .Where(m => stateMachine.EndpointUrisToNames.ContainsKey(m.Item1))
                        .Select(m => Tuple.Create(stateMachine.EndpointUrisToNames[m.Item1], m.Item2, "To"))
                        .Timestamp();

                var i = mesh
                        .Where(m => Interesting(m.Item2))
                        .Where(m => stateMachine.EndpointUrisToNames.ContainsKey(m.Item1))
                        .Select(m => Tuple.Create(stateMachine.EndpointUrisToNames[m.Item1], m.Item2, "From"))
                        .Timestamp();

                i
                .Merge(o)
                .Subscribe(m =>
                {
                    try
                    {
                        lock (Global.lastMessages)
                        {
                            var lastMessages = Global.lastMessages[serviceName];
                            lastMessages.Enqueue(m);
                            while (lastMessages.Count > 1000)
                            {
                                lastMessages.Dequeue();
                            }
                        }
                    }
                    catch
                    {
                    }
                });
                var enabled      = false;
                var enabledState = container.GetBlobReference(serviceName + "EnabledState.txt");
                try
                {
                    enabled = Boolean.Parse(enabledState.DownloadText());
                }
                catch
                {
                }

                mesh.enabled = enabled;
                return(stateMachine);
            }
            else
            {
                throw new ArgumentException("Location not found");
            }
        }