Пример #1
0
        /// <summary>
        /// Executes the provided IWindowsServices and supports automatic installation using the command line params -install / -uninstall
        /// </summary>
        /// <param name="args"></param>
        /// <param name="createServices">Function which provides a WindowsServiceCollection of services to execute</param>
        /// <param name="configureContext">Optional application context configuration</param>
        /// <param name="installationSettings">Optional installer configuration with semi-sensible defaults</param>
        /// <param name="registerContainer">Optionally register an IoC container</param>
        /// <param name="agentSettingsManager">Optionally provide agent settings </param>
        public WindowsServiceRunner(string[] args,
            Func<IWindowsService[]> createServices,
            Action<ApplicationContext> configureContext = null,
            Action<System.ServiceProcess.ServiceInstaller,
            ServiceProcessInstaller> installationSettings = null,
            Func<IIocContainer> registerContainer = null,
            IAgentSettingsManager agentSettingsManager = null,
            Action<ApplicationContext,string> notify=null)
        {
            _notify = notify ?? ((ctx,message) => { });
            var log = LogManager.GetLogger(typeof (WindowsServiceRunner));
            _args = args;
            _context = new ApplicationContext();
            _createServices = createServices;
            _agentSettingsManager = agentSettingsManager;
            _logger = log;
            _configureContext = configureContext ?? (ctx => {  });
            _context.ConfigureInstall = installationSettings ?? ((serviceInstaller, serviceProcessInstaller) => { });
            _context.Container = registerContainer;

            if (registerContainer==null)
            {
                throw new ArgumentException("Binding container is null");
            }
            if (registerContainer != null)
            {
                _logger.DebugFormat("container is " + registerContainer.ToString());
            }
        }
        public static string ToDebugString <TParam1>(this Func <TParam1> func)
        {
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
            return(func.ToString());
#else
            return(func.Method.ToDebugString());
#endif
        }
Пример #3
0
 public AssertionRuleEquivalencyStep(
     Expression <Func <IMemberInfo, bool> > predicate,
     Action <IAssertionContext <TSubject> > assertion)
 {
     this.predicate = predicate.Compile();
     this.assertion = assertion;
     description    = predicate.ToString();
 }
Пример #4
0
        public static void Run()
        {
            Func <int, int> func = x => x + x;
            Expression <Func <int, int> > expression = x => x + x;

            WriteLine($"Func to string: {func.ToString()}");
            WriteLine($"Expression to string: {expression.ToString()}");
        }
        protected override TResult Invoke <TResult>(Func <DataConnection, TResult> func)
        {
            Debug.WriteLine(func.ToString());

            using (var dataConnection = new DataConnection(DataProvider, Connection))
            {
                return(func(dataConnection));
            }
        }
        public async Task GetOrAddAsync_return_default_value_when_factory_returns_null()
        {
            Func <Task <string> > factory = () => Task.FromResult((string)null);

            _cache.Setup(x => x.GetAsync(factory.ToString(), CancellationToken.None)).ReturnsAsync(new byte[] { });

            var result = await _genericDistributedCache.GetOrAddAsync(factory);

            result.Should().BeNull();
        }
Пример #7
0
 public void editDataStepView(int No, DataGridView ProgramStep)
 {
     ProgramStep[0, No].Value = No;
     ProgramStep[1, No].Value = this.Name;
     ProgramStep[2, No].Value = this.Position;
     ProgramStep[3, No].Value = this.PBA;
     ProgramStep[4, No].Value = Func.ToString();
     ProgramStep[5, No].Value = this.Spect;
     ProgramStep[6, No].Value = this.Skip;
 }
Пример #8
0
 private static Test CreateBadArgumentCheckTest(Func <T> badUse)
 {
     return(new TestCase(
                "BadArgumentCheck " + badUse.Method,
                () => Assert.Throws(
                    typeof(ArgumentException),
                    () => badUse(),
                    "Subject '{0}' must check for bad arguments",
                    badUse.ToString())));
 }
Пример #9
0
 /// <summary>
 /// Sets up an inline handler for messages of type <typeparamref name="TMessage"/>
 /// </summary>
 public BuiltinHandlerActivator Handle <TMessage>(Func <TMessage, Task> handlerFunction)
 {
     if (handlerFunction == null)
     {
         throw new ArgumentNullException(nameof(handlerFunction));
     }
     AssertHasNotBeenStarted(handlerFunction.ToString());
     _handlerInstances.Add(new Handler <TMessage>((bus, message) => handlerFunction(message), () => Bus));
     return(this);
 }
Пример #10
0
 public override void GetObjectData(SerializationInfo info, StreamingContext context)
 {
     base.GetObjectData(info, context);
     if (info == null)
     {
         throw new ArgumentNullException(nameof(info));
     }
     info.AddValue(nameof(Solved), Solved);
     info.AddValue("Solution", _solution.ToString());
 }
Пример #11
0
        private static void ShowExpressionTrees()
        {
            Func <int, int, int> addDelegate = (a, b) => a + b;
            Expression <Func <int, int, int> > addExpression = (a, b) => a + b;

            Console.WriteLine("Delegate {0}", addDelegate.ToString());
            Console.WriteLine("Expression {0}", addExpression.ToString());

            Console.WriteLine("addDelegate: {0}", addDelegate(12, 30));
            Console.WriteLine("addExpression: {0}", addExpression.Compile()(12, 30));
        }
Пример #12
0
 public static T SafeCall <T>(this object obj, Func <T> func) where T : class
 {
     try
     {
         return(func());
     }
     catch (Exception ex)
     {
         Log.Warn("SafeCall of the {0} method failed".FormatWith(func.ToString()), typeof(Extensions), ex);
         return(null);
     }
 }
Пример #13
0
 public ValeoUser[] Find(Func <ValeoUser, bool> predicator)
 {
     try
     {
         return(_context.Users.Where(predicator).ToArray());
     }
     catch (Exception e)
     {
         _logger.LogError(e, $"Error on Find User: {predicator.ToString()}.");
         throw;
     }
 }
Пример #14
0
 public override string ToString(bool printReadably)
 {
     if (ast != null)
     {
         return("<fn " + Printer.pr_str(fparams, true) +
                " " + Printer.pr_str(ast, true) + ">");
     }
     else
     {
         return("<builtin_function " + fn.ToString() + ">");
     }
 }
 public static T SafeCall <T>(this object obj, Func <T> func) where T : class
 {
     try
     {
         return(func());
     }
     catch (Exception ex)
     {
         Log.Warn(ex, $"SafeCall of the {func.ToString()} method failed");
         return(null);
     }
 }
Пример #16
0
 public TEntity[] Find(Func <TEntity, bool> predicator)
 {
     try
     {
         return(Collection.AsNoTracking().Where(predicator).ToArray());
     }
     catch (Exception e)
     {
         _logger.LogError(e, $"Error on Find {typeof(TEntity).FullName}: {predicator.ToString()}.");
         throw;
     }
 }
Пример #17
0
        private T GetRandomValue <T>(Func <AllTypesModel, T> selector)
        {
            var random         = new Random();
            var data           = Data.GetDataFromServer <IEnumerable <AllTypesModel> >(GlobalConstants.ServerBaseUrl + GlobalConstants.AllTypesModelFullDataUrl);
            var dataLength     = data.Count();
            var startIndex     = random.Next((int)(0.3 * dataLength), (int)(0.7 * dataLength));
            var lookInDataPart = data.Skip(startIndex);
            var item           = lookInDataPart.First(x => selector(x) != null && selector.ToString() != string.Empty);
            var value          = selector(item);

            return(value);
        }
 public Registration[] Find(Func <Registration, bool> predicator)
 {
     try
     {
         return(_context.Registrations.Where(predicator).ToArray());
     }
     catch (Exception e)
     {
         _logger.LogError(e, $"Error on Find Registration: {predicator.ToString()}.");
         throw;
     }
 }
Пример #19
0
 public override string ToString()
 {
     if (ast != null)
     {
         return("<fn* " + Mal.printer._pr_str(fparams, true) +
                " " + Mal.printer._pr_str(ast, true) + ">");
     }
     else
     {
         return("<builtin_function " + fn.ToString() + ">");
     }
 }
Пример #20
0
 public static Result <TReturn> ToResult(Func <TReturn> evaluator)
 {
     try
     {
         return(new Result <TReturn>(evaluator(), typeof(TReturn)));
     }
     catch (Exception ex)
     {
         var b = evaluator.ToString();
         return(Failed(ex, ex.Message, b));
     }
 }
Пример #21
0
 public void RegisterMapping <S, T>(Func <object> mapper)
 {
     if (mapper() is T)
     {
         _mappers.Add(new Tuple <Type, Type>(typeof(S), typeof(T)),
                      mapper);
     }
     else
     {
         throw new InvalidProgramException("Invalid mapper provided: " + mapper.ToString());
     }
 }
Пример #22
0
        private static void CallAsync(IMessageSource source, IMessage message, Func <object[], object> target, bool extend)
        {
            UInt64 id; if (message.TryGetTransferId(out id))

            {
                object[] args; message.TryGetInvocationArgs(out args);
                if (extend)
                {
                    args = args.Insert(0, source);
                }
                try
                {
                    Task task = target(args) as Task;
                    if (task != null)
                    {
                        task.ContinueWith((tsk) => CallAsyncResult(tsk, source, id));
                    }
                    else
                    {
                        throw new ContextMarshalException(string.Concat(target.ToString(), " not async or not returning System.Threading.Tasks.Task"));
                    }
                }
                catch (Exception er)
                {
                    try
                    {
                        source.Respond(new ExceptionMessage(message, er));
                    }
                    catch (Exception fatal)
                    {
                        Application.Error(fatal);
                    }
                }
            }
            else
            {
                throw new ContextMarshalException(string.Concat(target.ToString(), " needs a transfer identifier"));
            }
        }
        public async Task RefreshAsync_refreshes_cache()
        {
            const string objectToCache = "some object value";

            Func <Task <string> > factory = () => Task.FromResult(objectToCache);

            _cache.Setup(x => x.GetAsync(factory.ToString(), CancellationToken.None)).ReturnsAsync((byte[])null);
            _cache.Setup
            (
                x => x.SetAsync
                (
                    factory.ToString(),
                    Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(objectToCache)),
                    It.IsAny <DistributedCacheEntryOptions>(), CancellationToken.None
                )
            );

            var   method = _genericDistributedCache.RefreshCacheAsync(factory);
            await method;

            method.IsCompletedSuccessfully.Should().BeTrue();
        }
        public async Task GetOrAddAsync_adds_to_cache_when_item_in_cache_is_empty_byte_array()
        {
            const string objectToCache = "some object value";

            Func <Task <string> > factory = () => Task.FromResult(objectToCache);

            _cache.Setup(x => x.GetAsync(factory.ToString(), CancellationToken.None)).ReturnsAsync(new byte[] {});
            _cache.Setup
            (
                x => x.SetAsync
                (
                    factory.ToString(),
                    Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(objectToCache)),
                    It.IsAny <DistributedCacheEntryOptions>(), CancellationToken.None
                )
            );

            var result = await _genericDistributedCache.GetOrAddAsync(factory);

            result.Should().NotBeNull();
            result.Should().Be(objectToCache);
        }
Пример #25
0
 public DelegateGrouper(Func <T, object> GroupProvider, string Name)
 {
     if (GroupProvider == null)
     {
         throw new ArgumentNullException();
     }
     this.Name = Name;
     if (Name == null)
     {
         this.Name = GroupProvider.ToString();
     }
     this.GroupProvider = GroupProvider;
 }
Пример #26
0
 public TEntity Get(Func <TEntity, bool> expression)
 {
     try
     {
         return(Collection
                .FirstOrDefault(expression));
     }
     catch (Exception e)
     {
         _logger.LogError(e, $"Error on Get {typeof(TEntity).FullName}: {expression.ToString()}.");
         throw;
     }
 }
Пример #27
0
        public static bool Boolean(this Func <bool> source)
        {
            switch (source.ToString())
            {
            case "S":
            case "Y":
            case "1":
                return(true);

            default:
                return(false);
            }
        }
Пример #28
0
        private void анонимныйМетодToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Countit count = delegate
            {
                richTextBox1.Text += "Веполнение анонимного метода " + "\r\n";
                for (int i = 0; i < 5; i++)
                {
                    richTextBox1.Text += i.ToString() + " ";
                }

                richTextBox1.Text += "\r\n" + "\r\n";
            };

            count();

            Countit1 count1 = delegate(int end)
            {
                richTextBox1.Text += "Веполнение анонимного метода c передачей аргументв" + "\r\n";
                for (int i = 0; i < end; i++)
                {
                    richTextBox1.Text += i.ToString() + " ";
                }

                richTextBox1.Text += "\r\n" + "\r\n";
            };

            count1(10);

            Func <int, int, int> func = PlusFunc();
            int rezult = func(2, 3);

            richTextBox1.Text += "Резултат обобщенного делегата: " + rezult.ToString();


            richTextBox1.Text += "\r\n" + "\r\n" + "ЛЯМБДА - ВЫРАЖЕНИЯ!!!!!!" + "\r\n";

            Func <int, int, int> func1 = PlusFunc1();
            int rezult1 = func1(2, 3);

            richTextBox1.Text += "Результат выполнения лямбда-выражения: " + rezult1.ToString() + "\r\n";
            richTextBox1.Text += "Маленький прикол. Ошибок не вызывает: " + func1.ToString() + "\r\n";



            richTextBox1.Text += "\r\n" + "\r\n" + "ЛЯМБДА-ВЫРАЖЕНИЕ ВНУТРИ ЛЯМБДА ВЫРАЖЕНИЯ" + "\r\n";
            Func <Func <int, int, int>, int, int> funcsuper = (k, f) => k(3, 5) * f;
            int rezultsuper = funcsuper(func1, 3);

            richTextBox1.Text += "Результат выполнения супер лямбда-выражения: " + rezultsuper.ToString() + "\r\n";
        }
        public async Task GetOrAddAsync_return_item_in_cache()
        {
            const string objectToCache = "some object value";

            Func <Task <string> > factory = () => Task.FromResult(objectToCache);

            _cache.Setup(x => x.GetAsync(factory.ToString(), CancellationToken.None))
            .ReturnsAsync(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(objectToCache)));

            var result = await _genericDistributedCache.GetOrAddAsync(factory);

            result.Should().NotBeNull();
            result.Should().Be(objectToCache);
        }
Пример #30
0
 public void Delete(Func <TEntity, bool> predicator)
 {
     try
     {
         var entities = Find(predicator);
         Collection.RemoveRange(entities);
         _context.SaveChanges();
     }
     catch (Exception e)
     {
         _logger.LogError(e, $"Error on Delete {typeof(TEntity).FullName}: {predicator.ToString()}.");
         throw;
     }
 }
Пример #31
0
        int FindIndex <T>(IEnumerable <T> collection, Func <T, bool> predicate)
        {
            int index = 0;

            foreach (T item in collection)
            {
                if (predicate(item))
                {
                    return(index);
                }
                ++index;
            }

            throw new NotFoundException(typeof(T), predicate.ToString());
        }
 public static void AddJavaScript(this HtmlHelper htmlHelper, Func<object, HelperResult> script)
 {
     List<string> scriptList = htmlHelper.ViewContext.HttpContext.Items[_js] as List<string>;
     if (scriptList != null)
     {
         if (!scriptList.Contains(script.ToString()))
         {
             scriptList.Add(script.Invoke(null).ToString());
         }
     }
     else
     {
         scriptList = new List<string>();
         scriptList.Add(script.Invoke(null).ToString());
         htmlHelper.ViewContext.HttpContext.Items.Add(_js, scriptList);
     }
 }
        public void ReferenceAllTypesInClosedGenericParametersWithReferences(
            Tuple<IInnerInterface, InnerEventArgs, InnerDelegate> arg0,
            List<InnerEnum> innerEnums,
            InnerStruct[] innerStructs,
            Lazy<InnerStruct.InnerStructInnerEnum> innerStructInnerEnum,
            IEnumerable<InnerStruct.IInnerStructInnerInterface> innerStructInnerInterface,
            Dictionary<InnerStruct.InnerStructInnerStruct, InnerStruct.InnerStructInnerClass> innerStructInnerClassByInnerStructInnerStruct,
            Func<InnerAbstractClass, InnerAbstractClass.InnerAbstractClassInnerEnum, InnerAbstractClass.IInnerAbstractClassInnerInterface> getInnerAbstractClass,
            List<Dictionary<InnerAbstractClass.InnerAbstractClassStruct, IEnumerable<InnerImplementingClass[]>>> stuff)
        {
            string toStringHolder;

            toStringHolder = arg0.ToString();
            toStringHolder = arg0.Item1.ToString();
            toStringHolder = arg0.Item2.ToString();
            toStringHolder = arg0.Item3.ToString();
            toStringHolder = innerEnums.ToString();
            toStringHolder = innerEnums.First().ToString();
            toStringHolder = innerStructs.ToString();
            toStringHolder = innerStructs[0].ToString();
            toStringHolder = innerStructInnerEnum.ToString();
            toStringHolder = innerStructInnerEnum.Value.ToString();
            toStringHolder = innerStructInnerInterface.ToString();
            toStringHolder = innerStructInnerInterface.ToString();
            toStringHolder = innerStructInnerClassByInnerStructInnerStruct.ToString();
            toStringHolder = innerStructInnerClassByInnerStructInnerStruct.Keys.First().ToString();
            toStringHolder = innerStructInnerClassByInnerStructInnerStruct.Values.First().ToString();
            toStringHolder = getInnerAbstractClass.ToString();
            toStringHolder = stuff.ToString();
            toStringHolder = stuff[0].ToString();
            toStringHolder = stuff[0].Keys.First().ToString();
            toStringHolder = stuff[0].Values.First().ToString();
            toStringHolder = stuff[0].Values.First().First().ToString();
        }
Пример #34
0
        void CheckGetColorContexts(MainForm form, DataEntry[] de, Func<uint, IWICColorContext[], uint> method)
        {
            IWICColorContext[] contexts = null;
            IWICImagingFactory factory = new WICImagingFactory() as IWICImagingFactory;
            try
            {
                try
                {
                    contexts = new IWICColorContext[method(0, null)];
                }
                catch (Exception e)
                {
                    form.CheckHRESULT(this, WinCodecError.WINCODEC_ERR_UNSUPPORTEDOPERATION, e, "0, NULL", de);

                    return;
                }
                if (contexts.Length > 0)
                {
                    for (int i = 0; i < contexts.Length; i++)
                    {
                        contexts[i] = factory.CreateColorContext();
                    }
                    try
                    {
                        method((uint)contexts.Length, contexts);

                        int index = 0;
                        foreach (IWICColorContext c in contexts)
                        {
                            if (c == null)
                            {
                                form.Add(this, method.ToString(Resources._0_NULLItem), de, new DataEntry(Resources.Index, index));
                            }
                            index++;
                        }
                    }
                    catch (Exception e)
                    {
                        form.Add(this, method.ToString(Resources._0_Failed), de, new DataEntry(e));
                    }
                }
            }
            finally
            {
                contexts.ReleaseComObject();
                factory.ReleaseComObject();
            }
        }
Пример #35
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="contract"></param>
        /// <param name="factory"></param>
        /// <param name="lifestyleType"></param>
        public ComponentInfo(string id, Type contract, Func<object> factory, LifestyleFlags lifestyleType)
        {
            Guard.NotNull(contract,"contract");
            Guard.NotNull(factory,"factory");
          
            contracts.Add(contract);
            ContractService.GetContracts(contract, contracts);

            Id = id;
            if (string.IsNullOrEmpty(id))
                Id = factory.ToString() + "/" + contract.FullName;

            if (contract.IsOpenGenericType())
                Lifestyle = LifestyleType.GetGenericLifestyle(lifestyleType);
            else
                Lifestyle = LifestyleType.GetLifestyle(lifestyleType);

            Activator = ActivatorType.Factory;
            Factory = factory;
            Name = Id;
        }