private void CreateConfigurationClientForTest()
        {
            var testLogger = new TestLogger();
            var client     = new ConfigurationServiceClient(testLogger.Log, "CQRS_TEST_CONFIGURATION_MANAGER", stubEnvironment);

            cleanup = ConfigurationServiceClient.OverrideInstanceForUnitTesting(client);
        }
예제 #2
0
        public static ConfigurationServiceClient GetConfigurationServiceClient(string hostName, string port)
        {
            if (!string.IsNullOrEmpty(port) &&
                !port.StartsWith(":"))
            {
                port = ":" + port;
            }

            string endPointUri = string.Format("http://{0}{1}/", hostName, port);

            if (configurationServiceClients == null)
            {
                configurationServiceClients = new Dictionary <string, ConfigurationServiceClient>();
            }

            if (configurationServiceClients.ContainsKey(endPointUri))
            {
                return(configurationServiceClients[endPointUri]);
            }

            WSHttpBinding binding = GetBinding();

            ConfigurationServiceClient retVal = new ConfigurationServiceClient(binding, new EndpointAddress(endPointUri));

            if (!configurationServiceClients.ContainsKey(endPointUri))
            {
                configurationServiceClients.Add(endPointUri, retVal);
            }

            return(retVal);
        }
 private void CreateStandardSut()
 {
     sut = new ConfigurationServiceClient(
         (s, b, ex) => Console.WriteLine(s),
         "TEST",
         new StandardEnvironment());
 }
 private async Task EnsureValidConfigurationServiceWcfConnection()
 {
     await
     WcfCommunicationHelper.StartWcfClient <ConfigurationServiceClient, ConfigurationFault, ConfigurationService.IConfigurationService>(this, _configurationServiceClient,
                                                                                                                                        c => new ConfigurationServiceClient(), async c =>
     {
         _configurationServiceClient = c;
         try
         {
             if (_keepAliveConfigurationService != null)
             {
                 _keepAliveConfigurationService.Dispose();
             }
             if (!await c.get_IsInitializedAsync())
             {
                 IsEnabled = false;
                 return;
             }
             _keepAliveConfigurationService = WcfCommunicationHelper.KeepAlive <ConfigurationFault>(c.KeepAliveAsync, _logger);
             IsEnabled = true;
         }
         catch (Exception ex)
         {
             _logger.Error("Error connecting to configuration service.", ex);
             IsEnabled = false;
         }
     });
 }
예제 #5
0
파일: Helper.cs 프로젝트: rid50/ActiveX
        static Helper()
        {
            //System.Diagnostics.Debug.Listeners.Add(new System.Diagnostics.TextWriterTraceListener(@"c:\temp\debug.log"));
            //System.Diagnostics.Debug.WriteLine("kuku", "Helper1::");

            //configurationServiceClient = new ConfigurationServiceClient();

            //BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
            //binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
            //binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;

            BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);

            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;

            binding.Name            = "BasicHttpBinding_IConfigurationService";
            binding.MessageEncoding = WSMessageEncoding.Mtom;

            //EndpointAddress endpointAddress = new EndpointAddress("http://pscservice/CommonService/ConfigurationService.svc");
            var             assemly         = System.Reflection.Assembly.GetExecutingAssembly();
            var             configuration   = ConfigurationManager.OpenExeConfiguration(assemly.Location);
            string          url             = configuration.AppSettings.Settings["siteConfigurationServiceUrl"].Value;
            EndpointAddress endpointAddress = new EndpointAddress(url);

            configurationServiceClient = new ConfigurationServiceClient(binding, endpointAddress);
        }
예제 #6
0
        public static void Init(ClientConfig config)
        {
            if (appSettings == null)
            {
                appSettings = new Dictionary <string, string>();
            }

            client = ClientFactory.GetConfigurationServiceClient(config.ConfigurationServer, config.ConfigurationServerPort);
            if (GetServerKey() == null)
            {
                throw new InvalidOperationException("Unable to retrieve server key");
            }

            //masterEncryptedAppHash = serverKey.EncryptWithPublicKey(config.ApplicationHash);

            if (clientKey == null)
            {
                string     masterEncryptedAppHash = serverKey.EncryptWithPublicKey(config.ApplicationHash);
                RSAKeyPair tempKey = new RSAKeyPair();
                clientKey = GetClientKey(masterEncryptedAppHash, tempKey);
            }

            // if the clientKey is still null
            // we were unable to get it from the service
            if (clientKey == null)
            {
                throw new InvalidOperationException("Unable to retrieve client key.  Make sure that you are using the correct application hash");
            }
        }
예제 #7
0
 public static void AbandonSettings()
 {
     client       = null;
     config       = null;
     appSettings  = null;
     lastResponse = null;
     serverKey    = null;
     clientKey    = null;
 }
 private void CreateSutWithDefault(FileInfo defaultConfig, FileInfo defaultParametersConfig)
 {
     sut = new ConfigurationServiceClient(
         (s, b, ex) => Console.WriteLine(s),
         "TEST",
         new StandardEnvironment(),
         defaultConfig,
         defaultParametersConfig);
 }
예제 #9
0
 public static void AbandonSettings()
 {
     client = null;
     config = null;
     appSettings = null;
     lastResponse = null;
     serverKey = null;
     clientKey = null;
 }
        private void BootstrapConfigurationServiceClient()
        {
            var defaultParameterFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "defaultParameters.config");

            ConfigurationServiceClient.AppDomainInitializer(
                LoggerFunction,
                "JARVIS_CONFIG_SERVICE",
                defaultParameterFile: new FileInfo(defaultParameterFileName),
                missingParametersAction: ConfigurationManagerMissingParametersAction.Blank
                );
        }
        static void Main(string[] args)
        {
            ConfigurationServiceClient.AppDomainInitializer(
                (message, isError, exception) =>
            {
                if (isError)
                {
                    Console.Error.WriteLine(message + "\n" + exception);
                }
                else
                {
                    Console.WriteLine(message);
                }
            },
                "JARVIS_CONFIG_SERVICE",
                null,
                new FileInfo("defaultParameters.config"),
                missingParametersAction: ConfigurationManagerMissingParametersAction.Blank);

            lastErrorFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "_lastError.txt");
            if (args.Length == 1)
            {
                if (args[0] == "install" || args[0] == "uninstall")
                {
                    var runAsSystem = "true".Equals(
                        ConfigurationManager.AppSettings["runs-as-system"],
                        StringComparison.OrdinalIgnoreCase);
                    var dependencies = ConfigurationManager.AppSettings["depends-on-services"] ?? "";

                    ServiceInstallHelper.StartForInstallOrUninstall(
                        runAsSystem, dependencies, ServiceDescriptiveName, ServiceName);
                }
                else if (args[0] == "restore")
                {
                    Bootstrapper bs = new Bootstrapper();
                    bs.Start(false);
                    var restoreJob = bs.GetRestoreJob();
                    restoreJob.Start();
                }
            }
            else
            {
                var exitcode = StandardStart();
                if (Environment.UserInteractive)
                {
                    if (exitcode != TopshelfExitCode.Ok && Environment.UserInteractive)
                    {
                        Console.WriteLine("Failure exit code: {0} press a key to continue", exitcode.ToString());
                        Console.ReadKey();
                    }
                }
            }
        }
예제 #12
0
        internal async Task CreateNode(params string[] nodes)
        {
            using (ConfigurationServiceClient _configService = new ConfigurationServiceClient("ConfigurationServiceEndpoint"))
            {
                string currentcontext = "~/";

                for (int index = 0; index < nodes.Length; index++)
                {
                    //CreateNodeCommand is used for creating a node. Other available commands are as follows:
                    //DeleteNodeCommand, MoveNodesCommand, CopyNodesCommand, SetAttributeCommand, DeleteAttributeCommand, RecalculateCommand,
                    //RestartRealtimeCommand, CreateNodeCommand, UpdateNodeCommand, CreateCalculationCommand, UpdateNameCommand,
                    //ReloadExternalMappingsCommand, FlushJobQueueCommand
                    CreateNodeCommand command = new CreateNodeCommand();

                    string nodeName = nodes[index];
                    command.Tag        = nodeName;
                    command.Attributes = new Dictionary <string, string>
                    {
                        ["displayName"] = nodeName
                    };

                    string nodeType;
                    if (index == nodes.Length - 1)
                    {
                        //Creating timeseries node type as concerned for this sample application.
                        nodeType = NodeType.TimeSeries.ToString();                            //Creating Timeseries node type at the below most level(leaf node) where the timeseries data will be pushed.
                        command.Attributes.Add("VectorElementData", GetDescriptor(nodeName)); //Special attributes needed only for Timeseries node.
                        command.Attributes.Add("DataRate", "0");                              //Special attributes needed only for Timeseries node.
                    }
                    else
                    {
                        nodeType = NodeType.Unspecified.ToString(); //Creating unspecified node type for rest of the levels as those are not of concern for this sample application.
                    }

                    command.Attributes.Add("nodeType", nodeType);
                    command.ContextSelector = currentcontext;
                    command.User            = "******";

                    await _configService.ExecuteAsync(new List <Command>() { command }); //This call will create an asset node in Galore.

                    //Preparing context for next level node
                    currentcontext += $"{nodeName}/";
                }
            }
        }
예제 #13
0
        public void SaveWSQImage(int id, byte[] buffer)
        {
            var bioProcessor = new BioProcessor.BioProcessor();
            Dictionary<string, byte[]> templates = bioProcessor.GetTemplatesFromWSQImage(id, buffer);

            var client = new ConfigurationServiceClient();

            Dictionary<string, string> settings = new Dictionary<string, string>();
            foreach (KeyValuePair<string, string> kvp in client.AppSettings())
            {
                settings.Add(kvp.Key, kvp.Value);
            }

            foreach (var kvp in client.ConnectionStrings())
            {
                settings.Add(kvp.Key, kvp.Value);
            }

            var db = new Database(settings);
            db.SaveWSQTemplate(id, templates);
        }
예제 #14
0
        public static ConfigurationServiceClient GetConfigurationServiceClient(string hostName, string port)
        {
            if (!string.IsNullOrEmpty(port) &&
                !port.StartsWith(":"))
                port = ":" + port;

            string endPointUri = string.Format("http://{0}{1}/", hostName, port);

            if (configurationServiceClients == null)
                configurationServiceClients = new Dictionary<string, ConfigurationServiceClient>();

            if (configurationServiceClients.ContainsKey(endPointUri))
                return configurationServiceClients[endPointUri];

            WSHttpBinding binding = GetBinding();

            ConfigurationServiceClient retVal = new ConfigurationServiceClient(binding, new EndpointAddress(endPointUri));
            if (!configurationServiceClients.ContainsKey(endPointUri))
                configurationServiceClients.Add(endPointUri, retVal);

            return retVal;
        }
예제 #15
0
파일: Helper.cs 프로젝트: rid50/ActiveX
        static Helper()
        {
            //System.Diagnostics.Debug.Listeners.Add(new System.Diagnostics.TextWriterTraceListener(@"c:\temp\debug.log"));
            //System.Diagnostics.Debug.WriteLine("kuku", "Helper1::");

            //configurationServiceClient = new ConfigurationServiceClient();

            //BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
            //binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
            //binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;

            BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;

            binding.Name = "BasicHttpBinding_IConfigurationService";
            binding.MessageEncoding = WSMessageEncoding.Mtom;

            //EndpointAddress endpointAddress = new EndpointAddress("http://pscservice/CommonService/ConfigurationService.svc");
            var assemly = System.Reflection.Assembly.GetExecutingAssembly();
            var configuration = ConfigurationManager.OpenExeConfiguration(assemly.Location);
            string url = configuration.AppSettings.Settings["siteConfigurationServiceUrl"].Value;
            EndpointAddress endpointAddress = new EndpointAddress(url);
            configurationServiceClient = new ConfigurationServiceClient(binding, endpointAddress);
        }
예제 #16
0
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            _log.Info("Client Starting");
            //_EventLog = new EventLog("Application", ".", "Deployment Update Windows Service Configuration Client");
            //_EventLog.WriteEntry("Client starting");
            if (DesignerProperties.GetIsInDesignMode(new DependencyObject()) == true)
            {
                return;
            }


            try
            {
                BackgroundWorker bgw = new BackgroundWorker();
                bgw.DoWork             += new DoWorkEventHandler(DoWork_FindService);
                bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(RunWorkerCompleted_FindService);
                bgw.RunWorkerAsync();

                using (ConfigurationServiceClient client = new ConfigurationServiceClient())
                {
                    //State = client.GetServiceStatus();
                    WatcherPath      = client.GetWatcherPath();
                    _OldWatcherPath  = WatcherPath;
                    UriToWatchPath   = client.GetUriToWatchPath();
                    _OldUriWatchPath = UriToWatchPath;
                    Recipients       = new ObservableCollection <MailAddressSurrogate>(client.GetRecipients());
                    _OldRecipients   = Recipients;
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex);
                //_EventLog.WriteEntry(String.Format("Error occurred during initiation {0}{1}{0}{2}{0}{3}", Environment.NewLine, ex.Message, ex.InnerException != null ? ex.InnerException.Message : String.Empty, ex.StackTrace), EventLogEntryType.Error);
                throw ex;
            }
        }
예제 #17
0
 protected internal void SaveButton_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         using (ConfigurationServiceClient client = new ConfigurationServiceClient())
         {
             if (_OldRecipients.Any(x => !Recipients.Contains(x)) || Recipients.Any(x => !_OldRecipients.Contains(x)))
             {
                 client.UpdateRecipients(Recipients.ToList());
                 _OldRecipients = Recipients;
             }
             if (_OldWatcherPath != WatcherPath)
             {
                 client.UpdateWatcherPath(WatcherPath);
                 _OldWatcherPath = WatcherPath;
             }
             if (_OldUriWatchPath != UriToWatchPath)
             {
                 client.UpdateUriToWatchPath(UriToWatchPath);
                 _OldUriWatchPath = UriToWatchPath;
             }
         }
         if (service != null && !service.ServiceHandle.IsInvalid)
         {
             service.Stop();
             service.WaitForStatus(ServiceControllerStatus.Stopped);
             service.Start();
         }
     }
     catch (Exception ex)
     {
         _log.Error(ex);
         //_EventLog.WriteEntry(String.Format("Error occurred during initiation {0}{1}{0}{2}{0}{3}", Environment.NewLine, ex.Message, ex.InnerException != null ? ex.InnerException.Message : String.Empty, ex.StackTrace), EventLogEntryType.Error);
         throw ex;
     }
 }
        //public void Run(string[] args)
        public void Run(ArrayList fingerList)
        {
            //            Stopwatch st = new Stopwatch();
            //            st.Start();
            //_terminate = false;
            //int id = Thread.CurrentThread.ManagedThreadId;
            if (_fillCacheClassList == null)
                _fillCacheClassList = new List<FillMemoryCache>();
            else
                _fillCacheClassList.Clear();

            initDataCache();

            _tokenSource = new CancellationTokenSource();
            CancellationToken ct = _tokenSource.Token;

            Int32 rowcount = 0;
            //for (int i = 0; i < 2; i++)
            //{

            try
            {
                _fillCacheClassList.Add(new FillMemoryCache());
                rowcount = _fillCacheClassList[0].rowcount();
                if (rowcount == -1)
                {
                    dumpCache();
                    CallBack.RespondWithError("The request was cancelled");
                    //CallBack.CacheOperationComplete();
                    _tokenSource.Dispose();
                    return;
                }
                //break;
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                dumpCache();
                CallBack.RespondWithError(ex.Message);
                //CallBack.CacheOperationComplete();
                _tokenSource.Dispose();
                return;
                //Console.WriteLine("Time out, try again ");
            }
            catch (Exception ex)
            {
                dumpCache();
                CallBack.RespondWithError(ex.Message);
                //CallBack.CacheOperationComplete();
                _tokenSource.Dispose();
                return;
                //throw new FaultException(ex.ToString());
                //Console.WriteLine("Time out, try again ");
            }

            _fillCacheClassList.Clear();

            //            }

            //            st.Stop();

            CallBack.RespondWithRecordNumbers(rowcount);
            //CallBack.RespondWithRecordNumbers(Thread.CurrentThread.ManagedThreadId);

            if (ct.IsCancellationRequested)
            {
                dumpCache();
                CallBack.RespondWithError("The request was cancelled");
                //CallBack.CacheOperationComplete();
                _tokenSource.Dispose();
                return;
            }

            //Console.WriteLine("Row count: " + rowcount);

            //int limit = 10000;
            var client = new ConfigurationServiceClient();
            int limit;
            int.TryParse(client.getAppSetting("chunkSize"), out limit);
            if (limit == 0)
            {
                dumpCache();
                CallBack.RespondWithError("Chunk size is invalid, press any key to close");
                _tokenSource.Dispose();
                return;
            }

            //int topindex = (int)(rowcount / limit + 1);
            int topindex = (int)(rowcount / limit);
            if (rowcount % limit != 0)
                topindex++;
            //topindex = 100;
            Task[] taskArray = new Task[topindex];
            //Task[] taskArray = new Task[1];
            int offset = 0;

            Stopwatch stw = new Stopwatch();
            stw.Start();

            //bool go = false;
            //if (args != null && args.Length != 0)
            //{
            //    if (Int32.TryParse(args[0], out offset))
            //    {
            //        if (offset < topindex)
            //        {
            //            offset *= limit;
            //            limit = 1000;
            //            taskArray = new Task[10];
            //            limit = 10000;
            //            taskArray = new Task[1];
            //            go = true;
            //        }

            //        //Console.WriteLine(offset);
            //    }

            //    if (!go)
            //    {
            //        CallBack.RespondWithError(" --- Wrong parameter value provided for AppFabricCache ---");
            //        //Console.WriteLine(" --- Wrong parameter value, press any key to close ---");
            //        //Console.ReadKey();
            //        return;
            //    }
            //}

            //SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
            //SynchronizationContext Context = SynchronizationContext.Current;
            //SendOrPostCallback dlgt = new SendOrPostCallback(CallDelegate);

            var items = MemoryCache.Default.Select(x => x.Key);
            foreach (var key in items)
                MemoryCache.Default.Remove(key);

            /*
            if (_cache.Get("regionNameList") != null)
            {
                ArrayList regionNameList = _cache.Get("regionNameList") as ArrayList;
                foreach (string regionName in regionNameList)
                {
                    if (regionName != null)
                        _cache.Remove(regionName);
                        //_cache.RemoveRegion(regionName);
                }
            }
            */
            _cache.Set("fingerList", new ArrayList(), cacheTimeSpan);
            _cache.Set("regionNameList", new ArrayList(), cacheTimeSpan);
            //_cache.Put("fingerList", new ArrayList(), cacheTimeSpan);
            //_cache.Put("regionNameList", new ArrayList(), cacheTimeSpan);

            //            _tokenSource = new CancellationTokenSource();
            //            CancellationToken ct = _tokenSource.Token;

            BlockingCollection<int> bc = new BlockingCollection<int>();

            //if (true)
            //{

                //int i = 0;
                //taskArray = new Task[1];
                for (int i = 0; i < taskArray.Length; i++)
                {
                    //CallBack.RespondWithError(taskArray.Length.ToString());
                    taskArray[i] = Task.Factory.StartNew((Object obj) =>
                    {
                        ct.ThrowIfCancellationRequested();

                        PopulateStateObject state = obj as PopulateStateObject;

                        //if (state.Dlgt == null)
                        //    state.CallBack.RespondWithError("Null");
                        //else
                        //    state.CallBack.RespondWithError("Not Null");

                        var cl = new FillMemoryCache(state.bc, null, state.fingerList, state.maxPoolSize, state.ct, state.cache);
                        _fillCacheClassList.Add(cl);

                        //var process = new FillAppFabricCache.FillAppFabricCache(state.bc, null, state.fingerList, state.maxPoolSize, state.ct, state.cache);
                        //var process = new FillAppFabricCache.FillAppFabricCache(state.Dlgt, state.Context);
                        //var process = new FillAppFabricCache.FillAppFabricCache();
                        //try
                        //{
                        //process.run(state.LoopCounter * limit + offset, state.LoopCounter * limit + limit, limit - offset, Thread.CurrentThread.ManagedThreadId);
                        //process.run(state.LoopCounter * limit + 90000, state.LoopCounter * limit + limit, limit);

                        cl.run(state.LoopCounter * limit + offset, limit);
                        //cl.run(state.LoopCounter * limit + offset, state.LoopCounter * limit + limit, limit);
                        //process.run(state.LoopCounter * limit + offset, state.LoopCounter * limit + limit, limit);

                        //}
                        //catch (Exception ex)
                        //{
                        //    Console.WriteLine(ex.Message);
                        //}
                        //Console.WriteLine(process.run(1, 2, Thread.CurrentThread.ManagedThreadId));
                    },
                    new PopulateStateObject() { LoopCounter = i, bc = bc, fingerList = fingerList, maxPoolSize = taskArray.Length, ct = ct, cache = _cache },
                    //new StateObject() { LoopCounter = i, Dlgt = dlgt, CallBack = CallBack, Context = Context },
                    _tokenSource.Token,
                    TaskCreationOptions.LongRunning,
                    TaskScheduler.Default);
                }

                Task.Factory.ContinueWhenAll(taskArray, tasks =>
                {
                    bc.CompleteAdding();

                    //foreach (Task<string> task in tasks)
                    //{
                    //    Console.WriteLine(task.Result);
                    //}
                });

                d d = delegate
                {
                    foreach (var item in bc.GetConsumingEnumerable())
                    {
                        CallBack.RespondWithRecordNumbers(item);
                        //Thread.Sleep(100);
                    }
                };
                d();

                try
                {
                    Task.WaitAll(taskArray);
                    _cache.Set("fingerList", fingerList, cacheTimeSpan);
                    _cache.Set("cacheExpirationTime", cacheTimeSpan, cacheTimeSpan);
                }
                catch (Exception ex)
                {
                    foreach (var t in taskArray)
                    {
                        if (t == null)
                            continue;

                        if (t.Status == TaskStatus.Faulted)
                        {
                        //if (ex is System.Data.SqlClient.SqlException)
                        //{
                        //    CallBack.RespondWithError("KUKUKU: " + ex.Message);
                        //    dumpCache();
                        //    _tokenSource.Dispose();
                        //    return;
                        //}
                            bool fault = true;
                            while ((ex is AggregateException) && (ex.InnerException != null))
                            {
                                if (ex.Message.EndsWith("Operation cancelled by user."))
                                {
                                    fault = false;
                                    break;
                                }
                                else if (ex.InnerException.GetType().Name.Equals("TaskCanceledException"))
                                {
                                    if (ex.InnerException.Message.StartsWith("A task was canceled"))
                                    {
                                        fault = false;
                                        break;
                                    }
                                }

                                ex = ex.InnerException;
                            }

                            if (fault)
                            {
                                _tokenSource.Cancel();
                                _tokenSource.Dispose();
                                dumpCache();
                                CallBack.RespondWithError(ex.Message);
                                return;
                            }

                        //ex = ex.InnerException;

                        //}

                        //if (!ex.Message.StartsWith("A task was canceled"))
                        //{
                        //    CallBack.RespondWithError("AAAAAAA: " + ex.Message);
                        //    dumpCache();
                        //    _tokenSource.Dispose();
                        //    return;
                        //}
                        }
                    }
                }
                //finally
                //{
                if (ct.IsCancellationRequested)
                {
                    dumpCache();
                    CallBack.RespondWithError("The request was cancelled");
                }

                _tokenSource.Dispose();
                //}
            //}
            //else
            //{
            //    try
            //    {

            //        //var process = new FillAppFabricCache.FillAppFabricCache(CallBack);
            //        //var process = new FillAppFabricCache.FillAppFabricCache(CallBack);
            //        //var process = new FillAppFabricCache.FillAppFabricCache(dlgt, Context);
            //        var process = new FillAppFabricCache.FillAppFabricCache(null, dlgt, fingerList, ct, _cache);
            //        //process.run(0, 0, 0);
            //        for (int i = 0; i < taskArray.Length; i++)
            //        {
            //            //process.run(state.LoopCounter * limit + offset, state.LoopCounter * limit + limit, limit - offset, Thread.CurrentThread.ManagedThreadId);
            //            //process.run(state.LoopCounter * limit + 90000, state.LoopCounter * limit + limit, limit);

            //            process.run(i * limit + offset, i * limit + limit, limit);
            //        }

            //        //stw.Stop();
            //        //Console.WriteLine(" ----- Count(*) time elapsed: {0}", st.Elapsed);
            //        //Console.WriteLine(" ----- Loop time elapsed: {0}", stw.Elapsed);
            //    }
            //    catch (Exception ex)
            //    {
            //        //Console.WriteLine(ex.Flatten().Message);
            //        //throw ex.Flatten();
            //        while ((ex is AggregateException) && (ex.InnerException != null))
            //            ex = ex.InnerException;

            //        //throw new FaultException(ex.ToString());
            //        CallBack.RespondWithError(ex.ToString());
            //        return;
            //        //Console.WriteLine(ex.ToString());
            //    }
            //    finally
            //    {
            //        _tokenSource.Dispose();
            //        //                    Console.WriteLine(" ------------------ Press any key to close -----------------------");
            //    }
            //}

            stw.Stop();
            TimeSpan ts = stw.Elapsed;
            // Format and display the TimeSpan value.
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}", ts.Hours, ts.Minutes, ts.Seconds);
            //ts.Milliseconds / 10);

            ArrayList list = _cache.Get("regionNameList") as ArrayList;
            if (list != null)
            {
                CallBack.RespondWithText(string.Format(" --- Time elapsed: {0}", elapsedTime));

                //ArrayList list = _cache.Get("regionNameList") as ArrayList;
                foreach (string regionName in list)
                {
                    if (regionName == null)
                    {
                        CallBack.RespondWithError(string.Format(" --- region name is null"));
                        break;
                    }
                }
            }

            CallBack.CacheOperationComplete();

            //Console.WriteLine(" ----- Count(*) time elapsed: {0}", st.Elapsed);
            //Console.WriteLine(" ----- Loop time elapsed: {0}", stw.Elapsed);
            //Console.WriteLine(" ------------------ Press any key to close -----------------------");
            //Console.ReadKey();
        }
예제 #19
0
        //public void run(int from, int to, int count, int threadId)
        //public void run(int from, int to)
        //public void run(int from, int to, int count)
        public void run(int from, int count)
        {
            //string fingerFields = "ri,rm,rr,rl";
            //string fingerFields = "li,lm,lr,ll,ri,rm,rr,rl,lt,rt";

            var sb = new StringBuilder();
            foreach (string finger in _fingerList)
            {
                sb.Append(finger + ",");
            }

            string fingerFields = sb.ToString();
            fingerFields = fingerFields.Remove(fingerFields.Length - 1);
            string[] fingerFieldsArray = fingerFields.Split(new char[] { ',' });

            //string dbFingerTable = System.Configuration.ConfigurationManager.AppSettings["dbFingerTable"];
            //string dbFingerColumn = System.Configuration.ConfigurationManager.AppSettings["dbFingerColumn"];
            //string dbIdColumn = System.Configuration.ConfigurationManager.AppSettings["dbIdColumn"];

            var client = new ConfigurationServiceClient();

            string dbFingerTable = client.getAppSetting("dbFingerTable");
            string dbIdColumn = client.getAppSetting("dbIdColumn");
            string dbPictureTable = client.getAppSetting("dbPictureTable");
            string dbGenderColumn = client.getAppSetting("dbGenderColumn");

            //return;

            //SqlConnection conn = null;
            //SqlCommand cmd = null;
            //SqlDataReader reader = null;

            //byte[] buffer = new byte[0];
            byte[][] buffer = new byte[10][];
            int id = 0; bool gender;
            int rowNumber = 0;

            Stopwatch sw = new Stopwatch();
            //Stopwatch stwd = new Stopwatch();
            //Stopwatch stws = new Stopwatch();
            //stw.Start();
            //stwd.Start();
            //stws.Start();

            //foreach (string region in _cache.GetSystemRegions())
            //{
            //    foreach (var kvp in _cache.GetObjectsInRegion(region))
            //    {
            //        Console.WriteLine("data item ('{0}','{1}') in region {2} of cache {3}", kvp.Key, kvp.Value.ToString(), region, "default");
            //    }
            //}
            //return;

            //if (_cache.Get("fingerList") == null)
            //    _cache.Add("fingerList", _fingerList);

            string regionName = from.ToString();
            _cache.RemoveRegion(regionName);
            _cache.CreateRegion(regionName);

            //ArrayList regionNameList;

            //if (_cache.Get("regionNameList") == null)
            //{
            //    regionNameList = new ArrayList();
            //    _cache.Add("regionNameList", regionNameList);
            //}
            lock (theLock)
            {
                ArrayList regionNameList = _cache.Get("regionNameList") as ArrayList;
                regionNameList.Add(regionName);
                _cache.Put("regionNameList", regionNameList, new TimeSpan(24, 0, 0));
            }
            //try
            //{
            //conn = buildConnectionString();
            //conn = new SqlConnection(client.getConnectionString("ConnectionString"));

            var connectionString = client.getConnectionString("ConnectionString");
            connectionString += String.Format(";Connect Timeout=0;Pooling=true;Min Pool Size=1;Max Pool Size={0}", _maxPoolSize);
            //conn = new SqlConnection(connectionString);

            //conn = new SqlConnection(connectionString);

            using (SqlConnection conn = new SqlConnection(connectionString))
            //try
            {
                //var connStr = getConnectionString();
                //conn = new SqlConnection(connStr);
                conn.Open();
                cmd = new SqlCommand();
                cmd.CommandTimeout = 0;
                cmd.Connection = conn;

                //cmd.CommandText = "SELECT " + dbIdColumn + "," + dbFingerColumn + " FROM " + dbFingerTable + " WHERE AppID = 20095420";

                //cmd.CommandText = "SELECT " + dbIdColumn + "," + dbFingerColumn + " FROM " + dbFingerTable + " WHERE datalength(" + dbFingerColumn + ") IS NOT NULL";
                //cmd.CommandText = String.Format("SELECT AppID, AppWsq FROM (SELECT ROW_NUMBER() OVER(ORDER BY AppID) AS row, AppID, AppWsq FROM Egy_T_FingerPrint WHERE datalength(AppWsq) IS NOT NULL) r WHERE row > {0} and row <= {1}", from, to);
                //cmd.CommandText = String.Format("SELECT AppID, AppWsq FROM Egy_T_FingerPrint WITH (NOLOCK) WHERE datalength(AppWsq) IS NOT NULL ORDER BY AppID ASC OFFSET {0} ROWS FETCH NEXT {1} ROWS ONLY ", from, count);
                //cmd.CommandText = String.Format("SELECT AppID, AppWsq FROM Egy_T_FingerPrint WITH (NOLOCK) ORDER BY AppID ASC OFFSET {0} ROWS FETCH NEXT {1} ROWS ONLY ", from, count);
                //cmd.CommandText = String.Format("SELECT AppID," + fingerFields + " FROM Egy_T_FingerPrint WITH (NOLOCK) WHERE datalength(AppWsq) IS NOT NULL ORDER BY AppID ASC OFFSET {0} ROWS FETCH NEXT {1} ROWS ONLY ", from, count);

                //cmd.CommandText = "SELECT " + dbIdColumn + "," + fingerFields + " FROM " + dbFingerTable;
                //cmd.CommandText = String.Format("SELECT " + dbIdColumn + "," + fingerFields + " FROM " + dbFingerTable + " WITH (NOLOCK) ORDER BY " + dbIdColumn + " ASC OFFSET {0} ROWS FETCH NEXT {1} ROWS ONLY ", from, count);
                //cmd.CommandText = String.Format("SELECT A." + dbIdColumn + ", B." + dbGenderColumn + ", " + fingerFields + " FROM " + dbFingerTable + " As A WITH (NOLOCK) INNER JOIN " + dbPictureTable  + " ORDER BY " + dbIdColumn + " ASC OFFSET {0} ROWS FETCH NEXT {1} ROWS ONLY ", from, count);

                cmd.CommandText = String.Format("SELECT A.{0} As Id, B.{1} As Gender, {2} FROM {3} As A WITH(NOLOCK) INNER JOIN {4} As B ON A.{0} = B.{0} ORDER BY A.{0} ASC OFFSET {5} ROWS FETCH NEXT {6} ROWS ONLY ",
                                                        dbIdColumn, dbGenderColumn, fingerFields, dbFingerTable, dbPictureTable, from, count);
                //cmd.CommandText = String.Format("SELECT AppID, " + fingerFields + " FROM Egy_T_FingerPrint WITH (NOLOCK) ORDER BY AppID ASC OFFSET {0} ROWS FETCH NEXT {1} ROWS ONLY ", from, count);

                //cmd.CommandText = String.Format("SELECT " + fingerFields + " FROM Egy_T_FingerPrint WITH (NOLOCK) ORDER BY AppID ASC OFFSET {0} ROWS FETCH NEXT {1} ROWS ONLY ", from, count);
                //cmd.CommandText = "SELECT AppID, AppWsq FROM Egy_T_FingerPrint WHERE AppID = 20095423";

                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    //reader = cmd.ExecuteReader();

                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            if (_ct.IsCancellationRequested)
                            {
                                break;
                                //_ct.ThrowIfCancellationRequested();
                            }

                            //id = (int)reader[dbIdColumn];
                            id = (int)reader["Id"];
                            gender = (bool)reader["Gender"];
                            //int k = 0;
                            //if (id == 20005140)
                            //    k = 1;

                            rowNumber++;

                            if (rowNumber % 100 == 0)
                            {
                                if (_bc != null)
                                    _bc.Add(100);
                                else
                                    _callback(100);

                                //this.Invoke((Action<AppFabricCacheService.IPopulateCacheCallback>)((callback) =>
                                //{
                                //    callback.RespondWithRecordNumbers(1000);
                                //}), _callback);
                                //throw new Exception(_callback.GetType().ToString());

                                //string conn_name = "foo";
                                //uiContext.Post(new SendOrPostCallback((o) =>
                                //{
                                //    updateConnStatus(conn_name, true);
                                //}), null);

                                //_context.Post(_callback, 1000);

                                //var task = Task.Factory.StartNew(() =>
                                //{
                                //    //int ii = 5 + 5;
                                //    //throw new Exception("aaaaaaaaaaa: " + Thread.CurrentThread.ManagedThreadId);
                                //    CallDelegate(1000);
                                //}, CancellationToken.None, TaskCreationOptions.None, _context);

                                //task.Wait();

                                //_context.Send(state => { AppFabricCacheService.PopulateCacheService.CallBack.RespondWithRecordNumbers((int)state); }, state: 1000);
                                //_context.Send(state => { AppFabricCacheService.PopulateCacheService.CallDelegate(state); }, state: 1000);

                                //_context.Post(CallDelegate, 1000);
                                //_callback(1000);

                                //CallBack.RespondWithRecordNumbers(1000);
                            }
                            //Console.WriteLine("{0}", rowNumber + from);
                            //Console.WriteLine("ID = {0}", id);
                            //if (id == 20000007)
                            //    id = id;

                            //if (!(reader.IsDBNull(1) && reader.IsDBNull(2) && reader.IsDBNull(3) && reader.IsDBNull(4) && reader.IsDBNull(5)
                            //      && reader.IsDBNull(6) && reader.IsDBNull(7) && reader.IsDBNull(8) && reader.IsDBNull(9) && reader.IsDBNull(10)
                            //     )
                            //   )
                            //if (!reader.IsDBNull(1))
                            //                    {
                            //                        id = (int)reader[dbIdColumn];
                            bool approved = false, confirmed = false;
                            int i = 2; // 0 - Id column, 1 - Gender column, 2 is the first finger column we are interested in
                            foreach (string finger in fingerFieldsArray)
                            {
                                FingerListEnum f = (FingerListEnum)Enum.Parse(typeof(FingerListEnum), finger);
                                if (!reader.IsDBNull(i) && ((byte[])reader[finger]).Length > 1)
                                {
                                    if (!approved)
                                        approved = true;
                                    else if (approved && !confirmed)
                                        confirmed = true;

                                    buffer[(int)f] = (byte[])reader[finger];
                                }
                                else
                                    buffer[(int)f] = new byte[0];

                                i++;
                            }

                            if (confirmed)
                                _cache.Add(id.ToString() + (gender ? "m" : "w"), buffer, new TimeSpan(24, 0, 0), regionName);
                            //                    }
                            //else
                            //{
                            //    Console.WriteLine("NULL {0}", id);
                            //}
                        }

                        //if (reader != null)
                        //{
                        //cmd.Cancel();
                        //cmd = null;
                        //reader.Close();
                        //}
                    }
                }

                //if (conn.State == ConnectionState.Open)
                //{
                //conn.Close();
                //}
            }
            //finally
            //{
            //    //try
            //    //{
            //    if (cmd != null)
            //        cmd.Cancel();

            //    if (reader != null)
            //        reader.Close();

            //    if (conn != null && conn.State == ConnectionState.Open)
            //    {
            //        conn.Close();
            //        //conn = null;
            //        //conn.Dispose();
            //        //SqlConnection.ClearPool(conn);
            //    }
            //    //}
            //    //catch (Exception ex)
            //    //{
            //    //    throw new Exception(ex.Message);
            //    //}
            //}
            _ct.ThrowIfCancellationRequested();
        }
예제 #20
0
        public Int32 rowcount()
        {
            SqlConnection conn = null;
            //SqlCommand cmd = null;
            SqlDataReader reader = null;
            int result = -1;
            try
            {
                var client = new ConfigurationServiceClient();
                conn = new SqlConnection(client.getConnectionString("ConnectionString"));

                //conn = new SqlConnection(getConnectionString());
                conn.Open();
                cmd = new SqlCommand();
                cmd.CommandTimeout = 300;
                cmd.Connection = conn;
                //cmd.CommandText = "SELECT count(*) FROM Egy_T_FingerPrint WHERE datalength(AppWsq) IS NOT NULL";
                //cmd.CommandText = "SELECT count(*) FROM Egy_T_FingerPrint";
                cmd.CommandText = "SELECT count(*) FROM " + client.getAppSetting("dbFingerTable");
                reader = cmd.ExecuteReader();
                if (reader.HasRows) {
                    reader.Read();
                    result = reader.GetInt32(0);
                }

                return result;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                try
                {
                    if (reader != null)
                        reader.Close();

                    if (conn != null && conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                        conn = null;
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
        }
예제 #21
0
        static MyConfigurationSettings()
        {
            ConfigurationServiceClient configurationServiceClient = null;
            //ServiceHost configurationServiceClient = null;
            Dictionary<string, string> settings = null;

            String endPointHost = ConfigurationManager.AppSettings["endPointHost"];

            //String baseAddress = ConfigurationManager.AppSettings["endPointServer"];
            //configurationServiceClient.Endpoint.Address

            //var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //var serviceModel = configFile.SectionGroups["system.serviceModel"];
            //var clientSection = serviceModel.Sections["client"];

            //var serviceModelClient = ConfigurationManager.GetSection("system.serviceModel/client");

            //ClientSection serviceModelClient = ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;
            //foreach (ChannelEndpointElement cs in serviceModelClient.Endpoints)
            //{
            //    var address = cs.Address;
            //}

            //String serviceName = "BasicHttpBinding_IConfigurationService";

            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            ServiceModelSectionGroup serviceModelSection = ServiceModelSectionGroup.GetSectionGroup(config);
            ClientSection serviceModelClientSection = serviceModelSection.Client;
            if (serviceModelClientSection.Endpoints[0].Address.Host != endPointHost)
            {
                foreach (ChannelEndpointElement endPoint in serviceModelClientSection.Endpoints)
                {
                    var uri = new Uri(endPoint.Address.Scheme + "://" + endPointHost + ":" + endPoint.Address.Port + endPoint.Address.PathAndQuery);
                    endPoint.Address = uri;
                    //endPoint.Address = new Uri(endPoint.Address.Scheme + "://" + endPointAddress + ":" + endPoint.Address.Port + endPoint.Address.PathAndQuery);
                }
                //serviceModelClientSection.Endpoints.Cast<ChannelEndpointElement>()
                    //                                         .Select(endpoint => { endpoint.Address.Host = endPointHost; return endpoint; });

                //ChannelEndpointElement endPoint = serviceModelClientSection.Endpoints[0];
                //var uri = new Uri(endPoint.Address.Scheme + "://" + endPointHost + ":" + endPoint.Address.Port + endPoint.Address.PathAndQuery);

                //serviceModelClientSection.Endpoints[0].Address = uri;
                config.Save();

                ConfigurationManager.RefreshSection(serviceModelClientSection.SectionInformation.SectionName);
            }

            configurationServiceClient = new ConfigurationServiceClient();

            //configurationServiceClient = new ConfigurationServiceClient(serviceName, endPointAddress);
            //configurationServiceClient = new ServiceHost(typeof(ConfigurationServiceClient), new Uri(baseAddress));

            appSettingsCollection = new NameValueCollection();

            settings = configurationServiceClient.AppSettings();
            foreach (var key in settings.Keys)
            {
                appSettingsCollection.Add(key, settings[key]);
            }

            settings.Clear();

            connectionStringCollection = new ConnectionStringSettingsCollection();

            settings = configurationServiceClient.ConnectionStrings();
            foreach (var key in settings.Keys)
            {
                connectionStringCollection.Add(new ConnectionStringSettings(key, settings[key]));
            }
        }
예제 #22
0
        private static void Main(string[] args)
        {
            //Preload class needed by mongo
            BsonClassMap.LookupClassMap(typeof(BlobId));
            BsonClassMap.LookupClassMap(typeof(DocumentHandle));

            BsonClassMap.RegisterClassMap <FileNameWithExtension>(m =>
            {
                m.AutoMap();
                m.MapProperty(x => x.FileName).SetElementName("name");
                m.MapProperty(x => x.Extension).SetElementName("ext");
            });

            ConfigurationServiceClient.AppDomainInitializer(
                (message, isError, exception) =>
            {
                if (isError)
                {
                    Console.Error.WriteLine(message + "\n" + exception);
                }
                else
                {
                    Console.WriteLine(message);
                }
            },
                "JARVIS_CONFIG_SERVICE",
                null,
                new FileInfo("defaultParameters.config"),
                missingParametersAction: ConfigurationManagerMissingParametersAction.Blank);

            lastErrorFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "_lastError.txt");
            if (args.Length == 1)
            {
                if (args[0] == "install" || args[0] == "uninstall")
                {
                    var runAsSystem = "true".Equals(
                        ConfigurationManager.AppSettings["runs-as-system"],
                        StringComparison.OrdinalIgnoreCase);
                    var dependencies = ConfigurationManager.AppSettings["depends-on-services"] ?? "";

                    ServiceInstallHelper.StartForInstallOrUninstall(
                        runAsSystem, dependencies, ServiceDescriptiveName, ServiceName);
                }
                else if (args[0] == "restore")
                {
                    //Bootstrapper bs = new Bootstrapper();
                    //bs.Start(false);
                    //var restoreJob = bs.GetRestoreJob();
                    //restoreJob.Start();
                }
            }
            else
            {
                var exitcode = StandardStart();
                if (Environment.UserInteractive)
                {
                    if (exitcode != TopshelfExitCode.Ok && Environment.UserInteractive)
                    {
                        Console.WriteLine("Failure exit code: {0} press a key to continue", exitcode.ToString());
                        Console.ReadKey();
                    }
                }
            }
        }
예제 #23
0
        private static void RunShell()
        {
            MongoFlatMapper.EnableFlatMapping();
            ConfigurationServiceClient.AppDomainInitializer(
                (message, isError, exception) =>
            {
                if (isError)
                {
                    Console.Error.WriteLine(message + "\n" + exception);
                }
                else
                {
                    Console.WriteLine(message);
                }
            },
                "JARVIS_CONFIG_SERVICE",
                null,
                new FileInfo("defaultParameters.config"),
                missingParametersAction: ConfigurationManagerMissingParametersAction.Blank);

            var commands = new Dictionary <String, Func <Boolean> >();

            commands.Add("Check oprhaned blob", () =>
            {
                CheckOrphanedBlobs.PerformCheck(DateTime.UtcNow);
                return(false);
            });
            commands.Add("Check tika scheduled job", () =>
            {
                CheckQueuedTikaScheduledJobs.PerformCheck();
                return(false);
            });

            commands.Add("Start sync artifacts job", () =>
            {
                FullArtifactSyncJob.StartSync();
                return(false);
            });

            Menu(commands.Keys.ToList());
            CommandLoop(c =>
            {
                int menuSelection = 0;
                if (Int32.TryParse(c, out menuSelection))
                {
                    var func = commands.ElementAtOrDefault(menuSelection);
                    Console.WriteLine("Selected {0}", func.Key);
                    func.Value();
                }
                else
                {
                    if (String.Equals(c, "q", StringComparison.InvariantCultureIgnoreCase))
                    {
                        return(true);
                    }

                    Console.WriteLine("Comando non valido! Premere un tasto per continuare");
                    Console.ReadKey();
                }
                Menu(commands.Keys.ToList());
                return(false);
            });
        }
예제 #24
0
        public static void Init(ClientConfig config)
        {
            if (appSettings == null)
                appSettings = new Dictionary<string, string>();

            client = ClientFactory.GetConfigurationServiceClient(config.ConfigurationServer, config.ConfigurationServerPort);
            if (GetServerKey() == null)
                throw new InvalidOperationException("Unable to retrieve server key");

            //masterEncryptedAppHash = serverKey.EncryptWithPublicKey(config.ApplicationHash);

            if (clientKey == null)
            {
                string masterEncryptedAppHash = serverKey.EncryptWithPublicKey(config.ApplicationHash);
                RSAKeyPair tempKey = new RSAKeyPair();
                clientKey = GetClientKey(masterEncryptedAppHash, tempKey);
            }

            // if the clientKey is still null
            // we were unable to get it from the service
            if (clientKey == null)
                throw new InvalidOperationException("Unable to retrieve client key.  Make sure that you are using the correct application hash");
        }
예제 #25
0
        private static void RunShell()
        {
            MongoFlatMapper.EnableFlatMapping();

            if (ConsoleHelper.AskYesNoQuestion("Do you want to use Configuration Service? You should say N if doing tasks like migration that does not require configuration service"))
            {
                ConfigurationServiceClient.AppDomainInitializer(
                    (message, isError, exception) =>
                {
                    if (isError)
                    {
                        Console.Error.WriteLine(message + "\n" + exception);
                    }
                    else
                    {
                        Console.WriteLine(message);
                    }
                },
                    "JARVIS_CONFIG_SERVICE",
                    null,
                    new FileInfo("defaultParameters.config"),
                    missingParametersAction: ConfigurationManagerMissingParametersAction.Blank);
            }
            IWindsorContainer _container = new WindsorContainer();

            _container.AddFacility <LoggingFacility>(f => f
                                                     .LogUsing(LoggerImplementation.ExtendedLog4net)
                                                     .WithConfig("log4net.config"));
            _loggerFactory = _container.Resolve <ILoggerFactory>();

            var commands = new Dictionary <String, Func <Boolean> >();

            commands.Add("Check oprhaned blob", () =>
            {
                CheckOrphanedBlobs.PerformCheck(DateTime.UtcNow);
                return(false);
            });

            commands.Add("Check tika scheduled job", () =>
            {
                CheckQueuedTikaScheduledJobs.PerformCheck();
                return(false);
            });

            commands.Add("Start sync artifacts job", () =>
            {
                FullArtifactSyncJob.StartSync();
                return(false);
            });

            commands.Add("Copy blob from GridFs to FileSystemFs", () =>
            {
                var startFromBeginning = ConsoleHelper.AskYesNoQuestion("Do you want to start from the beginning of the stream?");
                BlobStoreSync command  = new BlobStoreSync(_loggerFactory.Create(typeof(BlobStoreSync)));
                command.SyncAllTenants(BlobStoreType.GridFs, BlobStoreType.FileSystem, startFromBeginning);
                return(false);
            });

            commands.Add("Copy blob from FileSystemFs to GridFs", () =>
            {
                var startFromBeginning = ConsoleHelper.AskYesNoQuestion("Do you want to start from the beginning of the stream?");
                BlobStoreSync command  = new BlobStoreSync(_loggerFactory.Create(typeof(BlobStoreSync)));
                command.SyncAllTenants(BlobStoreType.FileSystem, BlobStoreType.GridFs, startFromBeginning);
                return(false);
            });

            Menu(commands.Keys.ToList());
            CommandLoop(c =>
            {
                int menuSelection = 0;
                if (Int32.TryParse(c, out menuSelection))
                {
                    var func = commands.ElementAtOrDefault(menuSelection);
                    Console.WriteLine("Selected {0}", func.Key);
                    func.Value();
                }
                else
                {
                    if (String.Equals(c, "q", StringComparison.InvariantCultureIgnoreCase))
                    {
                        return(true);
                    }

                    Console.WriteLine("Comando non valido! Premere un tasto per continuare");
                    Console.ReadKey();
                }
                Menu(commands.Keys.ToList());
                return(false);
            });
        }