Esempio n. 1
0
 public void SetUpUnits(Func<IUnitBuilder> builder)
 {
     Archers(builder.Invoke());
     Chariots(builder.Invoke());
     Legions(builder.Invoke());
     Settlers(builder.Invoke());
 }
        public override ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, string propertyName)
        {
            //Null checks
            if (containerType == null) throw new ArgumentNullException("containerType");
            if (string.IsNullOrEmpty(propertyName)) throw new ArgumentNullException("propertyName");
            var propertyDescriptor = this.GetTypeDescriptor(containerType).GetProperties().Find(propertyName, true);
            if (propertyDescriptor == null) throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, "Property not found (container='{0}', property='{1}'.", containerType.FullName, propertyName));

            //DateTime: For DateTime model accessors, perform the conversion to the users time zone
            if (propertyDescriptor.PropertyType == typeof(DateTime))
            {
                var value = DateTime.MinValue;
                var rawValue = modelAccessor.Invoke();
                if (rawValue != null)
                    value = TimeZoneManager.GetUserTime((DateTime)rawValue);

                return GetMetadataForProperty(() => value, containerType, propertyDescriptor);
            }

            //DateTime?: For DateTime? model accessors, perform the conversion to the users time zone
            if (propertyDescriptor.PropertyType == typeof(DateTime?))
                return GetMetadataForProperty(() =>
                {
                    var dt = (DateTime?)modelAccessor.Invoke();
                    return !dt.HasValue ? dt : TimeZoneManager.GetUserTime(dt.Value);
                }, containerType, propertyDescriptor);

            //Everything else
            return GetMetadataForProperty(modelAccessor, containerType, propertyDescriptor);
        }
        private ActionResult RegiterWithAction(RegisterUserModel model, Func<ActionResult> successAction, Func<ActionResult> defaultAction)
        {
            if (!_auth.ValidateCaptcha()) {
                ModelState.AddModelError("", "Sorry, we failed to validate your captcha. Please try again.");                
                defaultAction.Invoke();
            }

            if (ModelState.IsValid)
            {
                var email = model.Email;
                var password = model.Password;

                if (_auth.RegisterNewUser(email, password))
                {
                    _notification.NotifyUserOnRegistration(email, password);
                    return successAction.Invoke();
                }
                else
                {
                    ModelState.AddModelError("", "Sorry, user with such email already exist. Please register with different email.");
                }
            }

            return defaultAction.Invoke();
        }
        public override ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, string propertyName)
        {
            var propertyDescriptor = this.GetTypeDescriptor(containerType).GetProperties().Find(propertyName, true);

            //DateTime: For DateTime model accessors, perform the conversion to the users time zone
            if (propertyDescriptor.PropertyType == typeof(DateTime))
            {
                var value = DateTime.MinValue;
                var rawValue = modelAccessor.Invoke();
                if (rawValue != null)
                {
                    value = TimeZoneManager.GetUserTime((DateTime) rawValue);
                }

                return this.GetMetadataForProperty(() => value, containerType, propertyDescriptor);
            }

            //DateTime?: For DateTime? model accessors, perform the conversion to the users time zone
            if (propertyDescriptor.PropertyType == typeof(DateTime?))
            {
                return this.GetMetadataForProperty(() =>
                                                   {
                                                       var dt = (DateTime?) modelAccessor.Invoke();
                                                       return !dt.HasValue ? dt : TimeZoneManager.GetUserTime(dt.Value);
                                                   }, containerType, propertyDescriptor);
            }

            //Everything else
            return this.GetMetadataForProperty(modelAccessor, containerType, propertyDescriptor);
        }
Esempio n. 5
0
        public Task Invoke(IOwinContext context, Func<Task> next)
        {
            var request = context.Request;

            if (request.Method != "GET")
                return next.Invoke();

            if (_draftRuleNamesPath.IsWildcardMatch(request.Path))
                return GetDraftRuleNames(context);

            if (!_versionRuleNamesPath.IsWildcardMatch(request.Path))
                return next.Invoke();

            var pathSegmnts = request.Path.Value
                .Split('/')
                .Where(p => !string.IsNullOrWhiteSpace(p))
                .Select(HttpUtility.UrlDecode)
                .ToArray();

            if (pathSegmnts.Length < 2)
                throw new HttpException((int)HttpStatusCode.BadRequest, "Path has too few segments. Expecting " + _versionRuleNamesPath.Value);

            var versionText = pathSegmnts[1];
            int version;
            if (!int.TryParse(versionText, out version))
                throw new HttpException((int)HttpStatusCode.BadRequest, "The version must be a whole number " + _versionRuleNamesPath.Value);

            if (request.Method == "GET")
                return GetRuleNames(context, version);

            return next.Invoke();
        }
Esempio n. 6
0
        private void CompareOne(Func<IComparableObject, object> getElement, string pathToContainer, IComparableObject before, IComparableObject after, List<Difference> differences, List<AttributeChange> attributeChanges,
                                string name)
        {
            var valueBefore = getElement.Invoke(before);
            var valueAfter = getElement.Invoke(after);

            if (valueBefore is IEnumerable<IComparableObject>)
            {
                differences.AddRange(CheckArray(getElement, pathToContainer, before, after));
                return;
            }

            if (valueBefore is IComparableObject)
            {
                differences.AddRange(Compare(AddToPath(pathToContainer, before.IdentifyingText), valueBefore as IComparableObject, valueAfter as IComparableObject));
                return;
            }

            foreach (var comparer in AttributeComparers.Union(new[] { new DefaultAttributeComparer() }))
                if (comparer.CanHandle(valueBefore))
                {
                    var result = comparer.Compare(name, valueBefore, valueAfter);
                    if (result != null)
                        attributeChanges.Add(result);
                    return;
                }

            throw new Exception("Not handled: " + valueBefore.GetType());
        }
Esempio n. 7
0
        private IEnumerable<Difference> CheckArray(Func<IComparableObject, object> getElement, string pathToContainer, IComparableObject before, IComparableObject after)
        {
            var valueBefore = (IEnumerable<IComparableObject>) getElement.Invoke(before);
            var arrayBefore = valueBefore.ToList();

            var valueAfter = getElement.Invoke(after) as IEnumerable<IComparableObject>;
            if (valueAfter == null)
                throw new ArgumentException("after object signature does not match with before object: missing " + valueBefore);

            var arrayAfter = valueAfter.ToList();

            var deletedElements = arrayBefore.Where(x => !arrayAfter.Exists(y => x.Id == y.Id));
            var addedElements = arrayAfter.Where(x => !arrayBefore.Exists(y => x.Id == y.Id));

            var differences = new List<Difference>();
            differences.AddRange(deletedElements.Select(x => new DeletedObject(pathToContainer, before, x)));
            differences.AddRange(addedElements.Select(x => new AddedObject(pathToContainer, after, x)));

            foreach (var elementBefore in arrayBefore)
            {
                var elementAfter = arrayAfter.FirstOrDefault(x => x.Id == elementBefore.Id);
                if (elementAfter != null)
                    differences.AddRange(Compare(AddToPath(pathToContainer, before.IdentifyingText), elementBefore, elementAfter));
            }

            return differences;
        }
Esempio n. 8
0
 public Envelope(Func<double, double> function, double time, double start, double end, int size)
 {
     double[] timePoints = new double[size + 1];
     double[] valuPoints = new double[size + 1];
     decimal delta = (decimal)(time / size);
     decimal start_ = (decimal)start;
     decimal end_ = (decimal)end;
     decimal inc = (end_ - start_) / size;
     decimal x;
     int indexcounter = 0;
     if (start_ < end_)
     {
         for (x = start_; x <= end_; x += inc)
         {
             timePoints[indexcounter] = (double)(indexcounter * delta);
             valuPoints[indexcounter] = function.Invoke((double)x);
             indexcounter++;
         }
     }
     else
     {
         for (x = start_; x >= end_; x += inc)
         {
             timePoints[indexcounter] = (double)(indexcounter * delta);
             valuPoints[indexcounter] = function.Invoke((double)x);
             indexcounter++;
         }
     }
     double maxvalue = 0;
     double minvalue = 0;
     //Move function up if parts are negative until its all in the positive.
     for (int x2 = 0; x2 < size + 1; x2++)
     {
         if (valuPoints[x2] < minvalue)
             minvalue = valuPoints[x2];
     }
     //Get the biggest element.
     for (int x2 = 0; x2 < size + 1; x2++)
     {
         valuPoints[x2] = valuPoints[x2] + (minvalue * -1);
         if (valuPoints[x2] > maxvalue)
             maxvalue = valuPoints[x2];
     }
     //Now scale the values to the time.
     if (maxvalue != 0)
     {
         for (int x2 = 0; x2 < size + 1; x2++)
         {
             valuPoints[x2] = Math.Abs((valuPoints[x2] / maxvalue) * time);
         }
     }
     this.timePoints = timePoints;
     clampArray(valuPoints);
     this.valuPoints = valuPoints;
     arraylength = timePoints.Length;
     sort();
     recalculateMaxTime();
 }
        public static void Run(string title, bool isBaseline, int tryCount, Func<object> action)
        {
            Console.Write("  {0,-20} ", title + ":");
            object result = null;
            Stopwatch bestTimer = null;

            for (int i = 0; i < tryCount; i++) {
                for (int j = 0; j < 5; j++) {
                    Thread.Sleep(10);
                    GC.WaitForPendingFinalizers();
                    GC.GetTotalMemory(true);
                }
                var timer = new Stopwatch();
                timer.Start();
                result = action.Invoke();
                timer.Stop();
                if (bestTimer==null || bestTimer.Elapsed > timer.Elapsed)
                    bestTimer = timer;
            }

            double time = bestTimer.Elapsed.TotalMilliseconds;
            if (time < 0.05) {
                // Too short, let's use average instead of min time
                for (int j = 0; j < 5; j++) {
                    Thread.Sleep(10);
                    GC.WaitForPendingFinalizers();
                    GC.GetTotalMemory(true);
                }
                var timer = new Stopwatch();
                timer.Start();
                int tryCount2 = tryCount*10;
                for (int i = tryCount2; i > 0; i--)
                    result = action.Invoke();
                timer.Stop();
                time = timer.Elapsed.TotalMilliseconds / tryCount2;
            }

            bool timeInMS = time >= 0.1;
            Console.Write("{0,9:F3}{1}", timeInMS ? time : time * 1000, timeInMS ? "ms" : "ns");

            if (isBaseline) {
                Baseline = time;
                Console.Write(", baseline");
            }
            else
                Console.Write(", x{0,5:F2}", time / Baseline);

            if (DisplayEnumeratorType) {
                if (result is IEnumerable<int> && !(result is List<int>))
                    Console.Write(" ({0})", (result as IEnumerable<int>).GetEnumerator().GetType().Name);
                else if (result is IEnumerable<string>)
                    Console.Write(" ({0})", (result as IEnumerable<string>).GetEnumerator().GetType().Name);
            }
            Console.WriteLine();
        }
        public NameValueCell(string name, Func<string> valueGet, Action<string> valueSet)
        {
            this.BackgroundColor = UIColor.Clear;
            this.Frame = new RectangleF (0, 0, 100, 100);

            int labelXPos = 10;
            int label2XPos = 75;
            NameLabel = new UILabel (new RectangleF (
                labelXPos, 11,  label2XPos-(labelXPos+5), 21));
            NameLabel.AutoresizingMask = UIViewAutoresizing.None;
            NameLabel.BackgroundColor = UIColor.Clear;
            NameLabel.Font = UIFont.SystemFontOfSize (14);
            NameLabel.AdjustsFontSizeToFitWidth = true;
            NameLabel.TextAlignment = UITextAlignment.Right;
            NameLabel.Text = name;
            NameLabel.TextColor = UIColor.Blue;
            this.Add (NameLabel);

            ValueLabel = new UILabel (new RectangleF (
                label2XPos, 11,  this.Frame.Width-(label2XPos+10), 21));
            ValueLabel.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
            ValueLabel.BackgroundColor = UIColor.Clear;
            ValueLabel.Font = UIFont.BoldSystemFontOfSize (17);
            ValueLabel.AdjustsFontSizeToFitWidth = true;
            ValueLabel.Text = valueGet.Invoke ();
            this.Add (ValueLabel);

            ValueTextField = new UITextField (new RectangleF (
                label2XPos, 11,  this.Frame.Width-(label2XPos+10), 21));

            ValueTextField.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
            ValueTextField.BackgroundColor = UIColor.Clear;
            ValueTextField.Font = UIFont.BoldSystemFontOfSize (17);
            ValueTextField.AdjustsFontSizeToFitWidth = true;
            ValueTextField.Text = valueGet.Invoke ();
            ValueTextField.ReturnKeyType = UIReturnKeyType.Done;
            ValueTextField.ClearButtonMode = UITextFieldViewMode.Always;
            ValueTextField.ShouldReturn = delegate {
                ValueTextField.ResignFirstResponder ();
                return true;
            };

            ValueTextField.EditingDidEnd += delegate {
                _valueSet.Invoke (ValueTextField.Text);
            };

            this.Add (ValueTextField);

            _valueGet = valueGet;
            _valueSet = valueSet;
        }
Esempio n. 11
0
        public static void WithoutConfiguration(
            Func<string, int> fakedDelegate)
        {
            "establish"
                .x(() => fakedDelegate = A.Fake<Func<string, int>>());

            "when faking a delegate type and invoking without configuration"
                .x(() => fakedDelegate.Invoke("foo"));

            "it should be possible to assert the call"
                .x(() => A.CallTo(() => fakedDelegate.Invoke("foo")).MustHaveHappened());

            "it should be possible to assert the call without specifying invoke method"
                .x(() => A.CallTo(() => fakedDelegate("foo")).MustHaveHappened());
        }
            public static void Start(Func<Object,Task<bool>> task, Func<object,bool> stopCondition = null)
            {
                var isStarted = false;

                Worker.Start(() =>
                {                   
                    using (new MemoryHelper())
                    {
                        try
                        {
                            if (!isStarted)
                            {
                                Logger.Log("Starting new Bot Thread Id={0}", Thread.CurrentThread.ManagedThreadId);
                                _logic = new ActionRunCoroutine(task);
                                _logic.Start(null);
                                isStarted = true;
                            }
                            Tick();
                        }
                        catch (InvalidOperationException ex)
                        {                            
                            Logger.LogDebug("CheckInCoroutine() Derp {0}", ex);
                        }

                    }

                    if (stopCondition != null && stopCondition.Invoke(null))
                    {
                        Logger.Log("Bot Thread Finished Id={0}", Thread.CurrentThread.ManagedThreadId);
                        return true;
                    }
                        
                    return false;
                });
            }
Esempio n. 13
0
        private BuildRunResults runBuild(string buildExecutable, string arguments, string target, Func<bool> abortIfTrue)
        {
            if (_configuration.MSBuildAdditionalParameters.Length > 0)
                arguments += " " + _configuration.MSBuildAdditionalParameters;
            var timer = Stopwatch.StartNew();
            DebugLog.Debug.WriteInfo("Running build: {0} {1}", buildExecutable, arguments);
            Process process = new Process();
            process.StartInfo = new ProcessStartInfo(buildExecutable, arguments);
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow = true;

            process.Start();
            string line;
            var buildResults = new BuildRunResults(target);
            var lines = new List<string>();
            while ((line = process.StandardOutput.ReadLine()) != null)
            {
                if (abortIfTrue.Invoke())
                {
                    process.Kill();
                    process.WaitForExit();
                    AutoTest.Core.DebugLog.Debug.WriteDebug("Aborting build run");
                    return new BuildRunResults(target);
                }
                lines.Add(line);
            }
            process.WaitForExit();
            timer.Stop();
            var parser = new MSBuildOutputParser(buildResults, lines.ToArray());
            parser.Parse();
            buildResults.SetTimeSpent(timer.Elapsed);
            return buildResults;
        }
Esempio n. 14
0
 /// <summary>
 /// Runs a string command and returns the result parsed by a provided parser
 /// </summary>
 /// <param name="command">Command to send to ECU</param>
 /// <param name="parser">Anonymous method to parse ECU response</param>
 /// <returns>ECU response parsed by provided parser</returns>
 public Task<object> Run(string command, Func<string, object> parser)
 {
     return Task.Run(async () =>
     {
         return parser.Invoke(await Run(command));
     });
 }
Esempio n. 15
0
 /// <summary>
 /// Runs an ObdPid command and returns the result parsed by a provided parser
 /// </summary>
 /// <param name="command"></param>
 /// <param name="parser"></param>
 /// <returns></returns>
 public Task<object> Run(ObdPid command, Func<string, object> parser)
 {
     return Task.Run(async () =>
     {
         return parser.Invoke(await Run(command.StringValue()));
     });
 }
Esempio n. 16
0
        public Task MinimizeGameOnce(CancellationToken token, Func<GameInfo> getCurrentGame)
        {
            return Task.Factory.StartNew(() =>
                {
                    var currentGame = getCurrentGame.Invoke();
                    while (!token.IsCancellationRequested)
                    {
                        var process = Process.GetProcessesByName(currentGame.ProcessName).FirstOrDefault();

                        if (process != null)
                        {
                                var gameWnd = PInvoke.FindWindow(currentGame.WindowTitle);
                                var wndState = PInvoke.GetWindowState(gameWnd);

                            if (gameWnd.ToInt32() != 0 && (wndState == 1 || wndState == 3))
                            {
                                PInvoke.MinimizeWindow(currentGame.WindowTitle);
                                break;
                            }
                        }

                        Thread.Sleep(1000); // Sleep for a second
                    }
                });
        }
        public override object GetOrCreate(string key, Func<object> callback)
        {
            Mandate.ParameterNotNull(Instances, "[ThreadStatic]_reference");
            Mandate.ParameterNotNull(callback, "callback");

            return Instances.GetOrAdd(key, x => callback.Invoke());
        }
        private static IEnumerable<string> TryDeduceMatchingCandidateSnapshot(
            ImageWrapper transformedOriginalSnapshot,
            IEnumerable<string> candidateSnapshots,
            Func<ImageWrapper, Maybe<ImageWrapper>> candidateTranform
            )
        {
            var candidateResultList = new ConcurrentBag<Tuple<string, int>>();
            using (var originaImageAsLockbit = new LockBitImage(transformedOriginalSnapshot.Image))
            {
                Parallel.ForEach(candidateSnapshots, candidateSnapshot =>
                {
                    var candidateComparisonResult = from loadedCandidateSnapshot in TryLoadImage(candidateSnapshot)
                                                    from transformedCandidate in candidateTranform.Invoke(loadedCandidateSnapshot)
                                                    let candidateLockbitImage = new LockBitImage(transformedCandidate.Image)
                                                    let similarityIndex = SimilarityCalculator.CalculateSimilarityIndex(
                                                        originaImageAsLockbit,
                                                        candidateLockbitImage
                                                    )
                                                    select CommonFunctions.ExecThenDispose(
                                                        () => Tuple.Create<string, int>(candidateSnapshot, similarityIndex),
                                                        loadedCandidateSnapshot,
                                                        transformedCandidate,
                                                        candidateLockbitImage
                                                    );
                    candidateComparisonResult.Apply(i => candidateResultList.Add(i));
                });
            }

            return from candidateTuple in candidateResultList
                   where candidateTuple.Item2 >= 69
                   select candidateTuple.Item1;
        }
Esempio n. 19
0
 public Forest(int Trees, int DataSize, int Rounds, Func<int, DataSet> DataGenerator, Func<AttributeValue[]> EntryGenerator, Func<AttributeValue[], bool> Validator, int Target)
 {
     _Target = Target;
     for (int i = 0; i < Trees; ++i)
     {
         DataSet D = DataGenerator.Invoke(DataSize);
         _Trees.Add(new DecisionTree(D, Target));
         _DataSets.Add(D);
     }
     for (int i = 0; i < Rounds; ++i)
     {
         Console.WriteLine(i);
         AttributeValue[] E = EntryGenerator.Invoke();
         for (int j = 0; j < _Trees.Count; ++j)
         {
             AttributeValue Answer = _Trees[j].MakeDecision(E);
             E[Target] = Answer;
             if (!Validator.Invoke(E))
             {
                 Console.WriteLine("RECONSTRUCT TREE {0}", j);
                 _DataSets[j].AddEntry(E);
                 _Trees[j] = new DecisionTree(_DataSets[j], Target);
             }
         }
     }
 }
Esempio n. 20
0
 protected IWebDriver VerifyToContinue(Func<TestTarget, IWebDriver> factoryFunc, TestTarget target)
 {
     var driver = factoryFunc.Invoke(target);
     if (driver == null)
         throw new NullReferenceException("driver not found for environment: " + target.ToString());
     return driver;
 }
Esempio n. 21
0
        /*async*/
        public Task CheckOnProcess(CancellationToken ct, Func<GameInfo> getGameInfo)
        {
            /*await*/ return Task.Factory.StartNew(() =>
                {
                    // Check for the process every few seconds
                    // If it's running, trigger idle kick avoidance
                    // If state changes from running or to running, trigger an event
                    var previousState = false;

                    while (!ct.IsCancellationRequested)
                    {
                        var currentGame = getGameInfo.Invoke();

                        if (currentGame != null)
                        {
                            var process =
                                Process.GetProcessesByName(currentGame.ProcessName).FirstOrDefault();
                            var isRunning = process != null;
                            if (isRunning != previousState && OnProcessStateChanged != null)
                                OnProcessStateChanged.Invoke(this,
                                                             new ProcessStateChangeEventArgs() {IsRunning = isRunning});

                            previousState = isRunning;

                            foreach (var crashDetector in _crashDetectors)
                            {
                                crashDetector.DetectCrash(currentGame.ProcessName,
                                                           currentGame.FaultWindowTitle);
                            }
                        }

                        Thread.Sleep(5000);
                    }
                });
        }
Esempio n. 22
0
 public void Debug(Func<string> messageFactory)
 {
     if (IsDebugEnabled)
     {
         Logger.Log(DeclaringType, Level.Debug, messageFactory.Invoke(), null);
     }
 }
Esempio n. 23
0
 /// <summary>開始交易</summary>
 /// <param name="connStr"></param>
 /// <param name="tran"></param>
 /// <returns></returns>
 public static int StartTransaction(string connStr, Func<SqlTransaction, int> tran)
 {
     int result = 0;
     using (SqlConnection conn = OpenConnection(connStr))
     using (SqlTransaction transaction = conn.BeginTransaction())
     {
         try
         {
             result = tran.Invoke(transaction);
         }
         catch
         {
             result = -1;
         }
         if (result > 0)
         {
             transaction.Commit();
         }
         else
         {
             transaction.Rollback();
         }
     }
     return result;
 }
        /// <summary>
        /// Creates trees of view models that represents the hierarchy of the given taxa.
        /// A method delegate for creating a taxon view model should be provided.
        /// If the method returns null, the taxon won't be included in the tree.
        /// The taxa hierarchy is traversed in a breadth-first manner so the ordering of the taxa in each level is preserved.
        /// </summary>
        /// <param name="taxa">The taxa.</param>
        /// <param name="viewModelBuilder">A method that creates a taxon view model by given taxon.
        /// If null is returned, the taxon won't be included in the tree.</param>
        /// <param name="sort">The sort.</param>
        /// <param name="manager">The taxonomy manager that will be used to retrieve the children.</param>
        /// <param name="taxaCountLimit">The maximum number of taxa that will be included in the tree.</param>
        /// <returns></returns>
        public static IList<TaxonViewModel> BuildTaxaTree(
            IQueryable<Taxon> taxa,
            Func<ITaxon, TaxonViewModel> viewModelBuilder,
            Func<IQueryable<Taxon>, IQueryable<Taxon>> sort,
            TaxonomyManager manager,
            int taxaCountLimit)
        {
            var sortedTaxa = sort.Invoke(taxa);
            var trees = new List<TaxonViewModel>();
            var currentTaxaCount = 0;
            foreach (var taxon in sortedTaxa)
            {
                var subTree = TaxaViewModelTreeBuilder.BuildTaxaTreeBfs(taxon, viewModelBuilder, sort, manager, taxaCountLimit, ref currentTaxaCount);
                if (subTree != null)
                {
                    trees.Add(subTree);
                }

                if (taxaCountLimit > 0 && currentTaxaCount >= taxaCountLimit)
                {
                    break;
                }
            }

            return trees;
        }
Esempio n. 25
0
        /// <summary>
        /// Method to get the attempted value for the property and to execute the callback method to retreive the 'real' value,
        /// then set the property whilst executing the correct events.
        /// The event order is based on how the DefaultModelBinder sets properties so figured I'd go with these 'best practices'.
        /// </summary>
        /// <param name="controllerContext"></param>
        /// <param name="bindingContext"></param>
        /// <param name="propertyDescriptor"></param>
        /// <param name="getValue">callback method to get the 'real' value</param>        
        protected internal void SetPropertyValue(ControllerContext controllerContext,
                                        ModelBindingContext bindingContext,
                                        PropertyDescriptor propertyDescriptor,
                                        Func<string, object> getValue)
        {
            var valueObject = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name);
            if (valueObject != null)
            {
                var val = valueObject.AttemptedValue;
                //get the real value from the callback
                var realVal = getValue.Invoke(val);

                //add the bound value to model state if it's not already there, generally only simple props will be there
                if (!bindingContext.ModelState.ContainsKey(propertyDescriptor.Name))
                {
                    bindingContext.ModelState.Add(propertyDescriptor.Name, new ModelState());
                    bindingContext.ModelState.SetModelValue(propertyDescriptor.Name, new ValueProviderResult(realVal, val, null));
                }

                //set the value
                if (OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor, realVal))
                {
                    SetProperty(controllerContext, bindingContext, propertyDescriptor, realVal);
                    OnPropertyValidated(controllerContext, bindingContext, propertyDescriptor, realVal);
                    return;
                }
            }
        }
        /// <summary>
        /// Retrieve an object from the response document.
        /// </summary>
        /// <param name="func"></param>
        /// <returns></returns>
        public object Retrieve(Func<dynamic, object> func)
        {
            try
            {
                return func.Invoke(_parsedContent).Value;
            }
            catch { }

            try
            {
                return func.Invoke(_parsedContent);
            }
            catch { }

            return null;
        }
Esempio n. 27
0
 protected HttpResponseMessage GetHttpResponse(HttpRequestMessage request, Func<HttpResponseMessage> codeToExecute)
 {
     HttpResponseMessage response = null;
     try
     {
         response = codeToExecute.Invoke();
     }
     catch (SecurityException ex)
     {
         response = request.CreateResponse(HttpStatusCode.Unauthorized, ex.Message);
     }
     catch(FaultException<AuthorizationValidationException> ex)
     {
         response = request.CreateResponse(HttpStatusCode.Unauthorized, ex.Message);
     }
     catch(FaultException ex)
     {
         response = request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
     }
     catch(Exception ex)
     {
         response = request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
     }
     return response;
 }
        public static void SubscribeAllHandlers(Func<Type, object> getInstance)
        {
            AppDomain.CurrentDomain.GetAssemblies().ToList()
                     .SelectMany(s => s.GetTypes())
                     .Where( t => typeof (IHandler).IsAssignableFrom(t) && t != typeof(IHandler) && t != typeof(CommandHandler<>) && t!= typeof(EventHandler<>))
                     .ToList()
                     .ForEach(t =>
                         {
                             object handler;
                             try
                             {
                                 handler = getInstance.Invoke(t);
                             }
                             catch (Exception ex)
                             {
                                 throw new Exception(string.Format("SubscribeAllHandlers could not getInstance of type {0} resulting in esception message {1}", t, ex.Message));
                             }
                             
                             try
                             {
                                 t.GetMethod("Subscribe").Invoke(handler, null);
                             }
                             catch (Exception ex)
                             {
                                 throw new Exception(string.Format("SubscribeAllHandlers could not invoke Subscribe method on type {0} resulting in esception message {1}", t, ex.Message));
                             }

                         });
        }               
        private static bool ProcessAllSubFolders(SPFolder Folder, bool recursive, Func<SPFolder, bool> methodToCall)
        {
            IList<SPFolder> subFolders = Folder.SubFolders.Cast<SPFolder>().ToList<SPFolder>();

            foreach (SPFolder subFolder in subFolders)
            {
                //Loop through all sub webs recursively
                bool bContinue;

                bContinue = methodToCall.Invoke(subFolder);

                if (!bContinue)
                    return false;

                if (recursive && subFolder.Exists)
                {
                    bContinue = ProcessAllSubFolders(subFolder, recursive, methodToCall);

                    if (!bContinue)
                        return false;
                }
            }

            return true;
        }
Esempio n. 30
0
        private void PerformLog(Type type, Level level, Func<string> messageDelegate, Exception ex)
        {
            ThreadContext.Properties["subscriber"] = _subscriber.Email;
            ThreadContext.Properties["subscriberId"] = _subscriber.Id;

            _log.Logger.Log(type, level, messageDelegate.Invoke(), ex);
        }
 public static T ParseSingleValue <T>(this IDictionary <string, string[]> headers, string name, Func <string, T> parser)
 {
     return(parser.Invoke(headers.GetSingleValue(name)));
 }
Esempio n. 32
0
 protected override Task <object> Execute(TestCommand command, CancellationToken cancellationToken) =>
 Task.FromResult(callback.Invoke(command));
        /// <summary>
        /// insert delete update 模式中 获取 拼接字段
        /// </summary>
        /// <param name="Model">拼接模式(默认为update)</param>
        /// <returns></returns>
        protected string GetSQLParam<T>(T Entity, string Model, Func<T, T> Func = null ) where T:class,new()
        {
            string SQL = "";
            string SQLParary = "";
            string key = "";
            //int index = 0;
            string[] ModelType = { "insert", "delete", "update" };
            T t = new T();
            Type Entity_type = t.GetType();

            if (Model == ModelType[0])
            {
                List<KeyValue> keyvalueList = MapFactory.GetEntityProperty(Entity, out key);

                //string key = "";
                //int index = 0;
                //string SQLPararyKey = "";
                //string SQLPararyValue = "";
                //foreach (KeyValue kv in keyvalueList)
                //{
                //    SQLPararyKey += kv.Key;
                //    SQLPararyValue += "'" + kv.Value + "'";
                //    if (keyvalueList.Count() - 1 != index)
                //    {
                //        SQLPararyKey += ",";
                //        SQLPararyValue += ",";
                //    }
                //    index++;
                //}
                SQLParary = SQLKeyValueFilter(Model, keyvalueList);

                //SQL = "INSERT INTO " + Entity_type.Name + " ( " + SQLPararyKey + " ) "
                //    + " Value ( " + SQLPararyValue + " )";
                SQL = "INSERT INTO " + Entity_type.Name + SQLParary  ;
            }
            else if (Model == ModelType[1])
            {
                //T t = new T();
                //Type Entity_type = t.GetType();
                T Value = Func.Invoke(t);//获取返回值
                //string key = "";
                //List<KeyValue> keyvalueList = MapFactory.GetEntityProperty(Value, out key);
                //int index = 0;
                //SQLParary = "";
                //foreach (KeyValue kv in keyvalueList)
                //{
                //    SQLParary += kv.Key + " = '" + kv.Value + "'";
                //    if (keyvalueList.Count() - 1 != index)
                //    {
                //        SQLParary += " AND ";
                //    }
                //    index++;
                //}
                 List<KeyValue> List = MapFactory.GetEntityProperty(Value, out key);
                 SQLParary = SQLKeyValueFilter(Model, List);
                 SQL = " DELETE FROM " + Entity_type.Name + " WHERE " + SQLParary + ";";
            }
            else
            {
                List<KeyValue> keyvalueList = MapFactory.GetEntityProperty(Entity, out key);
                string TableName = MapFactory.SelectEntityTableName<T>(Entity);
                SQLParary = SQLKeyValueFilter(Model, keyvalueList);
                var keyvalue = keyvalueList.Single(s => s.Key == key);
                //string Key = "";
                //string Value = "";
                //List<KeyValue> PropertyName = MapFactory.GetEntityProperty(Entity, out Key);
                //SQLParary = "";
                //int index = 0;
                //foreach (KeyValue Name in keyvalueList)
                //{

                //        SQLParary += Name.Key + " = " + "'" + Name.Value + "'";

                //    if (keyvalueList.Count() - 1 != index)
                //    {
                //        SQLParary += ",";
                //    }
                //    if (Name.Key == key)
                //    {
                //        Value = Name.Value;
                //    }
                //    index++;
                //}
                SQL = "UPDATE " + TableName + " SET  " + SQLParary + " WHERE " + key + " = '" + keyvalue.Value + "'";

            }

            return SQL;
        }
Esempio n. 34
0
 /// <summary>
 /// 解决ilist没有foreach的问题
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="list"></param>
 /// <param name="action"></param>
 public static async Task ForEachAsync_ <T>(this IEnumerable <T> list, Func <T, Task> action)
 {
     await list.ForEachAsync_(async (index, x) => await action.Invoke(x));
 }
Esempio n. 35
0
        public bool IsSatisfiedBy(T entity)
        {
            Func <T, bool> predicate = ToExpression().Compile();

            return(predicate.Invoke(entity));
        }
Esempio n. 36
0
 public TOut Map(TIn source)
 {
     return(_mapping.Invoke(source));
 }
        // Code in the main function is executed
        static void Main(string[] args)
        {
            // Prints string out to the console with a line break (Write = No Line Break)
            Console.WriteLine("What is your name : ");

            // Accept input from the user
            string name = Console.ReadLine();

            // You can combine Strings with +
            Console.WriteLine("Hello " + name);

            // ---------- DATA TYPES ----------

            // Booleans are true or false
            bool canVote = true;

            // Characters are single 16 bit unicode characters
            char grade = 'A';

            // Integer with a max number of 2,147,483,647
            int maxInt = int.MaxValue;

            // Long with a max number of 9,223,372,036,854,775,807
            long maxLong = long.MaxValue;

            // Decimal has a maximum value of 79,228,162,514,264,337,593,543,950,335
            // If you need something bigger look up BigInteger
            decimal maxDec = decimal.MaxValue;

            // A float is a 32 bit number with a maxValue of 3.402823E+38 with 7 decimals of precision
            float maxFloat = float.MaxValue;

            // A float is a 32 bit number with a maxValue of 1.797693134E+308 with 15 decimals of precision
            double maxDouble = double.MaxValue;

            // You can combine strings with other values with +
            Console.WriteLine("Max Int : " + maxDouble);

            // The dynamic data type is defined at run time
            dynamic otherName = "Paul";

            otherName = 1;

            // The var data type is defined when compiled and then can't change
            var anotherName = "Tom";

            // ERROR : anotherName = 2;
            Console.WriteLine("Hello " + anotherName);

            // How to get the type and how to format strings
            Console.WriteLine("anotherName is a {0}", anotherName.GetTypeCode());

            // ---------- MATH ----------

            Console.WriteLine("5 + 3 = " + (5 + 3));
            Console.WriteLine("5 - 3 = " + (5 - 3));
            Console.WriteLine("5 * 3 = " + (5 * 3));
            Console.WriteLine("5 / 3 = " + (5 / 3));
            Console.WriteLine("5.2 % 3 = " + (5.2 % 3));

            int i = 0;

            Console.WriteLine("i++ = " + (i++));
            Console.WriteLine("++i = " + (++i));
            Console.WriteLine("i-- = " + (i--));
            Console.WriteLine("--i = " + (--i));

            Console.WriteLine("i += 3 " + (i += 3));
            Console.WriteLine("i -= 2 " + (i -= 2));
            Console.WriteLine("i *= 2 " + (i *= 2));
            Console.WriteLine("i /= 2 " + (i /= 2));
            Console.WriteLine("i %= 2 " + (i %= 2));

            // Casting : If no magnitude is lost casting happens automatically, but otherwise it must be done
            // like this

            double pi    = 3.14;
            int    intPi = (int)pi; // put the data type to convert to between braces

            // Math Functions
            // Acos, Asin, Atan, Atan2, Cos, Cosh, Exp, Log, Sin, Sinh, Tan, Tanh
            double number1 = 10.5;
            double number2 = 15;

            Console.WriteLine("Math.Abs(number1) " + (Math.Abs(number1)));
            Console.WriteLine("Math.Ceiling(number1) " + (Math.Ceiling(number1)));
            Console.WriteLine("Math.Floor(number1) " + (Math.Floor(number1)));
            Console.WriteLine("Math.Max(number1, number2) " + (Math.Max(number1, number2)));
            Console.WriteLine("Math.Min(number1, number2) " + (Math.Min(number1, number2)));
            Console.WriteLine("Math.Pow(number1, 2) " + (Math.Pow(number1, 2)));
            Console.WriteLine("Math.Round(number1) " + (Math.Round(number1)));
            Console.WriteLine("Math.Sqrt(number1) " + (Math.Sqrt(number1)));

            // Random Numbers
            Random rand = new Random();

            Console.WriteLine("Random Number Between 1 and 10 " + (rand.Next(1, 11)));

            // ---------- CONDITIONALS ----------

            // Relational Operators : > < >= <= == !=
            // Logical Operators : && || ^ !

            // If Statement
            int age = 17;

            if ((age >= 5) && (age <= 7))
            {
                Console.WriteLine("Go to elementary school");
            }
            else if ((age > 7) && (age < 13))
            {
                Console.WriteLine("Go to middle school");
            }
            else
            {
                Console.WriteLine("Go to high school");
            }

            if ((age < 14) || (age > 67))
            {
                Console.WriteLine("You shouldn't work");
            }

            Console.WriteLine("! true = " + (!true));

            // Ternary Operator

            bool canDrive = age >= 16 ? true : false;

            // Switch is used when you have limited options
            // Fall through isn't allowed with C# unless there are no statements between cases
            // You can't check multiple values at once

            switch (age)
            {
            case 0:
                Console.WriteLine("Infant");
                break;

            case 1:
            case 2:
                Console.WriteLine("Toddler");

                // Goto can be used to jump to a label elsewhere in the code
                goto Cute;

            default:
                Console.WriteLine("Child");
                break;
            }

            // Lable we can jump to with Goto
Cute:
            Console.WriteLine("Toddlers are cute");

            // ---------- LOOPING ----------

            int i = 0;

            while (i < 10)
            {
                // If i = 7 then skip the rest of the code and start with i = 8
                if (i == 7)
                {
                    i++;
                    continue;
                }

                // Jump completely out of the loop if i = 9
                if (i == 9)
                {
                    break;
                }

                // You can't convert an int into a bool : Print out only odds
                if ((i % 2) > 0)
                {
                    Console.WriteLine(i);
                }
                i++;
            }

            // The do while loop will go through the loop at least once
            string guess;

            do
            {
                Console.WriteLine("Guess a Number ");
                guess = Console.ReadLine();
            } while (!guess.Equals("15"));  // How to check String equality

            // Puts all changes to the iterator in one place
            for (int j = 0; j < 10; j++)
            {
                if ((j % 2) > 0)
                {
                    Console.WriteLine(j);
                }
            }

            // foreach cycles through every item in an array or collection
            string randStr = "Here are some random characters";

            foreach (char c in randStr)
            {
                Console.WriteLine(c);
            }

            // ---------- STRINGS ----------

            // Escape Sequences : \' \" \\ \b \n \t

            string sampString = "A bunch of random words";

            // Check if empty
            Console.WriteLine("Is empty " + String.IsNullOrEmpty(sampString));
            Console.WriteLine("Is empty " + String.IsNullOrWhiteSpace(sampString));
            Console.WriteLine("String Length " + sampString.Length);

            // Find a string index (Starts with 0)
            Console.WriteLine("Index of bunch " + sampString.IndexOf("bunch"));

            // Get a substring
            Console.WriteLine("2nd Word " + sampString.Substring(2, 6));

            string sampString2 = "More random words";

            // Are strings equal
            Console.WriteLine("Strings equal " + sampString.Equals(sampString2));

            // Compare strings
            Console.WriteLine("Starts with A bunch " + sampString.StartsWith("A bunch"));
            Console.WriteLine("Ends with words " + sampString.EndsWith("words"));

            // Trim white space at beginning and end or (TrimEnd / TrimStart)
            sampString = sampString.Trim();

            // Replace words or characters
            sampString = sampString.Replace("words", "characters");
            Console.WriteLine(sampString);

            // Remove starting at a defined index up to the second index
            sampString = sampString.Remove(0, 2);
            Console.WriteLine(sampString);

            // Join values in array and save to string
            string[] names = new string[3] {
                "Matt", "Joe", "Paul"
            };
            Console.WriteLine("Name List " + String.Join(", ", names));

            // Formatting : Currency, Decimal Places, Before Decimals, Thousands Separator
            string fmtStr = String.Format("{0:c} {1:00.00} {2:#.00} {3:0,0}", 1.56, 15.567, .56, 1000);

            Console.WriteLine(fmtStr.ToString());

            // ---------- STRINGBUILDER ----------
            // Each time you create a string you actually create another string in memory
            // StringBuilders are used when you want to be able to edit a string without creating new ones

            StringBuilder sb = new StringBuilder();

            // Append a string to the StringBuilder (AppendLine also adds a newline at the end)
            sb.Append("This is the first sentence.");

            // Append a formatted string
            sb.AppendFormat("My name is {0} and I live in {1}", "Derek", "Pennsylvania");

            // Clear the StringBuilder
            // sb.Clear();

            // Replaces every instance of the first with the second
            sb.Replace("a", "e");

            // Remove characters starting at the index and then up to the defined index
            sb.Remove(5, 7);

            // Out put everything
            Console.WriteLine(sb.ToString());

            // ---------- ARRAYS ----------
            // Declare an array
            int[] randNumArray;

            // Declare the number of items an array can contain
            int[] randArray = new int[5];

            // Declare and initialize an array
            int[] randArray2 = { 1, 2, 3, 4, 5 };

            // Get array length
            Console.WriteLine("Array Length " + randArray2.Length);

            // Get item at index
            Console.WriteLine("Item 0 " + randArray2[0]);

            // Cycle through array
            for (int i = 0; i < randArray2.Length; i++)
            {
                Console.WriteLine("{0} : {1}", i, randArray2[i]);
            }

            // Cycle with foreach
            foreach (int num in randArray2)
            {
                Console.WriteLine(num);
            }

            // Get the index of an item or -1
            Console.WriteLine("Where is 1 " + Array.IndexOf(randArray2, 1));

            string[] names = { "Tom", "Paul", "Sally" };

            // Join an array into a string
            string nameStr = string.Join(", ", names);

            Console.WriteLine(nameStr);

            // Split a string into an array
            string[] nameArray = nameStr.Split(',');

            // Create a multidimensional array
            int[,] multArray = new int[5, 3];

            // Create and initialize a multidimensional array
            int[,] multArray2 = { { 0, 1 }, { 2, 3 }, { 4, 5 } };

            // Cycle through multidimensional array
            foreach (int num in multArray2)
            {
                Console.WriteLine(num);
            }

            // Cycle and have access to indexes
            for (int x = 0; x < multArray2.GetLength(0); x += 1)
            {
                for (int y = 0; y < multArray2.GetLength(1); y += 1)
                {
                    Console.WriteLine("{0} | {1} : {2}", x, y, multArray2[x, y]);
                }
            }

            // ---------- LISTS ----------
            // A list unlike an array automatically resizes

            // Create a list and add values
            List <int> numList = new List <int>();

            numList.Add(5);
            numList.Add(15);
            numList.Add(25);

            // Add an array to a list
            int[] randArray = { 1, 2, 3, 4, 5 };
            numList.AddRange(randArray);

            // Clear a list
            // numList.Clear();

            // Copy an array into a List
            List <int> numList2 = new List <int>(randArray);

            // Create a List with array
            List <int> numList3 = new List <int>(new int[] { 1, 2, 3, 4 });

            // Insert in a specific index
            numList.Insert(1, 10);

            // Remove a specific value
            numList.Remove(5);

            // Remove at an index
            numList.RemoveAt(2);

            // Cycle through a List with foreach or
            for (int i = 0; i < numList.Count; i++)
            {
                Console.WriteLine(numList[i]);
            }

            // Return the index for a value or -1
            Console.WriteLine("4 is in index " + numList3.IndexOf(4));

            // Does the List contain a value
            Console.WriteLine("5 in list " + numList3.Contains(5));

            // Search for a value in a string List
            List <string> strList = new List <string>(new string[] { "Tom", "Paul" });

            Console.WriteLine("Tom in list " + strList.Contains("tom", StringComparer.OrdinalIgnoreCase));

            // Sort the List
            strList.Sort();

            // ---------- EXCEPTION HANDLING ----------
            // All the exceptions
            // msdn.microsoft.com/en-us/library/system.systemexception.aspx#inheritanceContinued

            try
            {
                Console.Write("Divide 10 by ");
                int num = int.Parse(Console.ReadLine());
                Console.WriteLine("10 / {0} =  {1}", num, (10 / num));
            }

            // Specifically catches the divide by zero exception
            catch (DivideByZeroException ex)
            {
                Console.WriteLine("Can't divide by zero");

                // Get additonal info on the exception
                Console.WriteLine(ex.GetType().Name);
                Console.WriteLine(ex.Message);

                // Throw the exception to the next inline
                // throw ex;

                // Throw a specific exception
                throw new InvalidOperationException("Operation Failed", ex);
            }

            // Catches any other exception
            catch (Exception ex)
            {
                Console.WriteLine("An error occurred");
                Console.WriteLine(ex.GetType().Name);
                Console.WriteLine(ex.Message);
            }

            // ---------- CLASSES & OBJECTS ----------

            Animal bulldog = new Animal(13, 50, "Spot", "Woof");

            Console.WriteLine("{0} says {1}", bulldog.name, bulldog.sound);

            // Console.WriteLine("No. of Animals " + Animal.getNumOfAnimals());

            // ---------- ENUMS ----------

            Temperature micTemp = Temperature.Low;

            Console.Write("What Temp : ");

            Console.ReadLine();

            switch (micTemp)
            {
            case Temperature.Freeze:
                Console.WriteLine("Temp on Freezing");
                break;

            case Temperature.Low:
                Console.WriteLine("Temp on Low");
                break;

            case Temperature.Warm:
                Console.WriteLine("Temp on Warm");
                break;

            case Temperature.Boil:
                Console.WriteLine("Temp on Boil");
                break;
            }

            // ---------- STRUCTS ----------
            Customers bob = new Customers();

            bob.createCust("Bob", 15.50, 12345);

            bob.showCust();

            // ---------- ANONYMOUS METHODS ----------
            // An anonymous method has no name and its return type is defined by the return used in the method

            GetSum sum = delegate(double num1, double num2) {
                return(num1 + num2);
            };

            Console.WriteLine("5 + 10 = " + sum(5, 10));

            // ---------- LAMBDA EXPRESSIONS ----------
            // A lambda expression is used to act as an anonymous function or expression tree

            // You can assign the lambda expression to a function instance
            Func <int, int, int> getSum = (x, y) => x + y;

            Console.WriteLine("5 + 3 = " + getSum.Invoke(5, 3));

            // Get odd numbers from a list
            List <int> numList = new List <int> {
                5, 10, 15, 20, 25
            };

            // With an Expression Lambda the input goes in the left (n) and the statements go on the right
            List <int> oddNums = numList.Where(n => n % 2 == 1).ToList();

            foreach (int num in oddNums)
            {
                Console.Write(num + ", ");
            }

            // ---------- FILE I/O ----------
            // The StreamReader and StreamWriter allows you to create text files while reading and
            // writing to them

            string[] custs = new string[] { "Tom", "Paul", "Greg" };

            using (StreamWriter sw = new StreamWriter("custs.txt"))
            {
                foreach (string cust in custs)
                {
                    sw.WriteLine(cust);
                }
            }

            string custName = "";

            using (StreamReader sr = new StreamReader("custs.txt"))
            {
                while ((custName = sr.ReadLine()) != null)
                {
                    Console.WriteLine(custName);
                }
            }

            Console.Write("Hit Enter to Exit");
            string exitApp = Console.ReadLine();
        }
Esempio n. 38
0
 private async Task <bool> WhenPredicateFails()
 {
     return(this._whenPredicate != null && (!await _whenPredicate.Invoke()));
 }
Esempio n. 39
0
            protected override TimeSpan?GetNextDelay(Exception lastException)
            {
                var baseDelay = base.GetNextDelay(lastException);

                return(baseDelay != null && _getNextDelay != null?_getNextDelay.Invoke(lastException) : baseDelay);
            }
Esempio n. 40
0
 public virtual bool CanExecute(object parameter) => _canExecuteAction.Invoke(parameter);
Esempio n. 41
0
 public static T Tap <T, Y>(this T o, Func <T, Y> func)
 {
     func.Invoke(o);
     return(o);
 }
Esempio n. 42
0
        public TResult Excecute<TResult>(
            Func<TIService, TResult> serviceCall,
            int retryAttempts = 1,
            Action<CommunicationException> exceptionHandler = null)
        {
            var errors = 0;
            var completed = false;
            CommunicationException exception = null;
            var response = default(TResult);

            while (!completed && errors < retryAttempts)
            {
                try
                {
                    if (!this.ServiceClient.State.IsReady())
                    {
                        this.DisposeClient();

                        if (!this.ServiceClient.State.IsReady())
                        {
                            throw new CommunicationObjectFaultedException($"WCF Client state is not valid. Connection Status [{this.ServiceClient.State}]");
                        }
                    }

                    response = serviceCall.Invoke(this.ServiceClient);
                    completed = true;
                }
                catch (CommunicationException comsException)
                {
                    exception = comsException;
                    if (exceptionHandler != null)
                    {
                        try
                        {
                            exceptionHandler.Invoke(exception);
                        }
                        catch (CommunicationException reThrowException)
                        {
                            exception = reThrowException;
                        }
                    }

                    errors++;
                    var logErrorMessage = $"WCF Operation Failure: Service [{typeof(TClient)}].[{serviceCall.Method.Name}] Attempt ({errors}/{retryAttempts}). Exception [{exception.Message}]";

                    if (retryAttempts > 1)
                    {
                        var logSleepMessage = $"Retry cooldown initiated ({RetryCoolDownInSeconds}s)";

                        Thread.Sleep(new TimeSpan(0, 0, RetryCoolDownInSeconds));
                    }
                }
                finally
                {
                    if (!completed)
                    {
                        this.DisposeClient();
                    }
                    else
                    {
                        this.ServiceClient.Close();
                    }
                }
            }

            if (!completed)
            {
                throw exception ?? new CommunicationException($"WCF Operation Failure: Service [{typeof(TClient)}].[{serviceCall.Method.Name}]");
            }

            return response;
        }
Esempio n. 43
0
        private Statement PreStatement(Type interfaceType, SqlMap sqlMap, MethodInfo methodInfo,
                                       Type returnType, bool isTaskReturnType, out ExecuteBehavior executeBehavior)
        {
            var statementAttr = methodInfo.GetCustomAttribute <StatementAttribute>();
            var methodName    = _sqlIdNamingConvert == null
                ? methodInfo.Name
                : _sqlIdNamingConvert.Invoke(interfaceType, methodInfo);

            if (isTaskReturnType && methodInfo.Name.EndsWith("Async") && _sqlIdNamingConvert == null)
            {
                methodName = methodName.Substring(0, methodName.Length - 5);
            }

            if (statementAttr != null)
            {
                statementAttr.Id = !String.IsNullOrEmpty(statementAttr.Id) ? statementAttr.Id : methodName;
            }
            else
            {
                statementAttr = new StatementAttribute
                {
                    Id = methodName
                };
            }

            var       fullSqlId = $"{sqlMap.Scope}.{statementAttr.Id}";
            Statement statement;

            if (String.IsNullOrEmpty(statementAttr.Sql))
            {
                statement = sqlMap.GetStatement(fullSqlId);
            }
            else
            {
                if (sqlMap.Statements.ContainsKey(fullSqlId))
                {
                    throw new SmartSqlException($"Statement.FullSqlId:[{fullSqlId}] already exists!");
                }

                var resultCacheAttr = methodInfo.GetCustomAttribute <ResultCacheAttribute>();
                statement = new Statement
                {
                    SqlMap        = sqlMap,
                    Id            = statementAttr.Id,
                    StatementType = _statementAnalyzer.Analyse(statementAttr.Sql),
                    SqlTags       = new List <ITag>
                    {
                        new SqlText(statementAttr.Sql, sqlMap.SmartSqlConfig.Database.DbProvider.ParameterPrefix)
                    },
                    CommandType = statementAttr.CommandType,
                    EnablePropertyChangedTrack = statementAttr.EnablePropertyChangedTrack,
                    ReadDb = statementAttr.ReadDb
                };
                if (statementAttr.CommandTimeout > 0)
                {
                    statement.CommandTimeout = statementAttr.CommandTimeout;
                }


                if (statementAttr.SourceChoice != DataSourceChoice.Unknow)
                {
                    statement.SourceChoice = statementAttr.SourceChoice;
                }

                if (resultCacheAttr != null)
                {
                    statement.CacheId = ParseCacheFullId(sqlMap.Scope, resultCacheAttr.CacheId);
                    statement.Cache   = sqlMap.GetCache(statement.CacheId);
                }

                sqlMap.Statements.Add(statement.FullSqlId, statement);
            }

            returnType = isTaskReturnType ? returnType.GetGenericArguments().FirstOrDefault() : returnType;
            if (returnType == typeof(DataTable))
            {
                statementAttr.Execute = ExecuteBehavior.GetDataTable;
            }

            if (returnType == typeof(DataSet))
            {
                statementAttr.Execute = ExecuteBehavior.GetDataSet;
            }

            if (statementAttr.Execute == ExecuteBehavior.Auto)
            {
                if (CommonType.IsValueTuple(returnType))
                {
                    statementAttr.Execute = ExecuteBehavior.QuerySingle;
                }
                else if (returnType == CommonType.Int32 || returnType == CommonType.Void || returnType == null)
                {
                    statementAttr.Execute = ExecuteBehavior.Execute;
                    if (returnType == CommonType.Int32)
                    {
                        if (statement.StatementType.HasFlag(Configuration.StatementType.Select))
                        {
                            statementAttr.Execute = ExecuteBehavior.ExecuteScalar;
                        }
                    }
                }
                else if (returnType.IsValueType || returnType == CommonType.String)
                {
                    statementAttr.Execute = ExecuteBehavior.ExecuteScalar;
                    if (!statement.StatementType.HasFlag(Configuration.StatementType.Select))
                    {
                        statementAttr.Execute = ExecuteBehavior.Execute;
                    }
                }
                else
                {
                    var isQueryEnumerable = typeof(IEnumerable).IsAssignableFrom(returnType);
                    statementAttr.Execute = isQueryEnumerable ? ExecuteBehavior.Query : ExecuteBehavior.QuerySingle;
                }
            }

            executeBehavior = statementAttr.Execute;
            return(statement);
        }
Esempio n. 44
0
 /// <summary>
 /// auth服务器配置
 /// </summary>
 public static void AuthUseServerConfig(this ContainerBuilder builder, Func <AuthServerConfig> config)
 {
     builder.Register(_ => config.Invoke()).AsSelf().AsImplementedInterfaces().SingleInstance();
 }
Esempio n. 45
0
        protected override int DoExecute(ITaskContextInternal context)
        {
            if (_targetTree == null)
            {
                throw new ArgumentNullException(nameof(_targetTree), "TargetTree must be set before Execution of target.");
            }

            if (_mustCondition != null)
            {
                var conditionMeet = _mustCondition.Invoke();

                if (conditionMeet == false)
                {
                    throw new TaskExecutionException($"Condition in must was not meet. Failed to execute target: '{TargetName}'.", 50);
                }
            }

#if  !NETSTANDARD1_6
            context.LogInfo($"Executing target {TargetName}", Color.DimGray);
#else
            context.LogInfo($"Executing target {TargetName}");
#endif

            _targetTree.EnsureDependenciesExecuted(context, TargetName);
            _targetTree.MarkTargetAsExecuted(this);

            if (_args.TargetsToExecute != null)
            {
                if (!_args.TargetsToExecute.Contains(TargetName))
                {
                    throw new TaskExecutionException($"Target {TargetName} is not on the TargetsToExecute list", 3);
                }
            }

            int taskGroupsCount = _taskGroups.Count;
            List <System.Threading.Tasks.Task> tasks = new List <System.Threading.Tasks.Task>();
            for (int i = 0; i < taskGroupsCount; i++)
            {
                int tasksCount = _taskGroups[i].Tasks.Count;
                if (_taskGroups[i].CleanupOnCancel)
                {
                    CleanUpStore.AddCleanupAction(_taskGroups[i].FinallyAction);
                }

                try
                {
                    for (int j = 0; j < tasksCount; j++)
                    {
                        var task = (TaskHelp)_taskGroups[i].Tasks[j].task;
#if !NETSTANDARD1_6
                        context.LogInfo($"Executing task {task.TaskName}", Color.DimGray);
#else
                        context.LogInfo($"Executing task {task.TaskName}");
#endif

                        if (_taskGroups[i].Tasks[j].taskExecutionMode == TaskExecutionMode.Synchronous)
                        {
                            _taskGroups[i].Tasks[j].task.ExecuteVoid(context);
                        }
                        else
                        {
                            tasks.Add(_taskGroups[i].Tasks[j].task.ExecuteVoidAsync(context));
                            if (j + 1 < tasksCount)
                            {
                                if (_taskGroups[i].Tasks[j + 1].taskExecutionMode != TaskExecutionMode.Synchronous)
                                {
                                    continue;
                                }
                                if (tasks.Count <= 0)
                                {
                                    continue;
                                }
                                Task.WaitAll(tasks.ToArray());
                                tasks = new List <Task>();
                            }
                            else if (i + 1 < taskGroupsCount)
                            {
                                if (_taskGroups[i + 1].Tasks[0].taskExecutionMode != TaskExecutionMode.Synchronous)
                                {
                                    continue;
                                }
                                if (tasks.Count <= 0)
                                {
                                    continue;
                                }
                                Task.WaitAll(tasks.ToArray());
                                tasks = new List <Task>();
                            }
                            else if (tasksCount > 0)
                            {
                                Task.WaitAll(tasks.ToArray());
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    _taskGroups[i].OnErrorAction?.Invoke(context, e);
                    throw;
                }
                finally
                {
                    if (!CleanUpStore.StoreAccessed)
                    {
                        if (_taskGroups[i].CleanupOnCancel)
                        {
                            CleanUpStore.RemoveCleanupAction(_taskGroups[i].FinallyAction);
                        }

                        _taskGroups[i].FinallyAction?.Invoke(context);
                    }
                }
            }

            return(0);
        }
Esempio n. 46
0
        async Task <JObject> GetHttpJObjectAsync(HttpClient client, string url, HttpStatusCode[] semiAcceptableStatusCodes, Func <string, string> retryFunc, string tenantId, string clientId, string clientSecret)
        {
            var retryUrl = url;

            for (var tries = 1; tries <= 10; tries++)
            {
                var result = string.Empty;
                try
                {
                    Log($"Getting (try {tries}): '{retryUrl}'");
                    using var response = await client.GetAsync(retryUrl);

                    result = await response.Content.ReadAsStringAsync();

                    if (semiAcceptableStatusCodes != null && semiAcceptableStatusCodes.Contains(response.StatusCode))
                    {
                        return(null);
                    }

                    if (response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        Log("Renewing access token.");
                        var accessToken = await GetAzureAccessTokenAsync(tenantId, clientId, clientSecret);

                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    }
                    else
                    {
                        response.EnsureSuccessStatusCode();
                    }

                    if (result.Length > 0)
                    {
                        if (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("RestDebug")))
                        {
                            File.WriteAllText($"result_{Logcount++}.json", JToken.Parse(result).ToString());
                        }
                        return(JObject.Parse(result));
                    }
                }
                catch (Exception ex) when(ex is HttpRequestException || ex is TaskCanceledException || ex is JsonReaderException)
                {
                    Log($"Couldn't get url: {ex.Message}");
                    Log($"Result: '{result}'");

                    if (result.Length > 0 && result != "\"\"")
                    {
                        var filename = $"result_{Resultcount++}.html";
                        Log($"Saving result to file: {filename}");
                        SaveCrapResult(filename, result);
                    }

                    if (retryFunc != null)
                    {
                        retryUrl = retryFunc.Invoke(result);
                    }

                    if (tries == 10)
                    {
                        throw;
                    }
                    await Task.Delay(2000);
                }
            }

            throw new Exception("Couldn't get url.");
        }
        /// <summary>
        /// Creates a paginated confirm embed.
        /// </summary>
        /// <param name="channel">Channel to embed in.</param>
        /// <param name="client">DiscordSocketClient instance</param>
        /// <param name="currentPage">current page from 0 to lastpage</param>
        /// <param name="pageFunc">Func returning EmbedBuilder for each page</param>
        /// <param name="pageCount">Total number of pages.</param>
        /// <param name="addPaginatedFooter">whether footer with current page numbers should be added or not</param>
        /// <param name="reactUsers">additional users which can change pages</param>
        /// <param name="pageChangeAllowedWithPermissions">overturn reactUsers if certain permission is available</param>
        /// <returns></returns>
        public static async Task SendPaginatedConfirmAsync(this IMessageChannel channel, DiscordSocketClient client, int currentPage, Func <int, Task <EmbedBuilder> > pageFunc, int?pageCount = null, bool addPaginatedFooter = true, IGuildUser[] reactUsers = null, Func <GuildPermissions, bool> pageChangeAllowedWithPermissions = null)
        {
            reactUsers ??= new IGuildUser[0];
            if (pageChangeAllowedWithPermissions == null)
            {
                pageChangeAllowedWithPermissions = gp => gp.ManageMessages;
            }

            var embed = await pageFunc(currentPage).ConfigureAwait(false);

            if (addPaginatedFooter)
            {
                embed.AddPaginatedFooter(currentPage, pageCount);
            }

            var msg = await channel.EmbedAsync(embed);

            if (pageCount == 0)
            {
                return;
            }

            var _ = Task.Run(async() => {
                await msg.AddReactionAsync(ArrowLeft).ConfigureAwait(false);
                await msg.AddReactionAsync(ArrowRight).ConfigureAwait(false);

                await Task.Delay(ReactionStartDelay).ConfigureAwait(false);

                async void ChangePage(SocketReaction r)
                {
                    try {
                        if (!r.User.IsSpecified || r.User.Value is IGuildUser gu && reactUsers.All(u => u.Id != r.UserId) && !pageChangeAllowedWithPermissions.Invoke(gu.GuildPermissions) && !gu.GuildPermissions.Administrator)
                        {
                            return;
                        }

                        if (r.Emote.Name == ArrowLeft.Name)
                        {
                            if (currentPage != 0)
                            {
                                var toSend = await pageFunc(--currentPage).ConfigureAwait(false);
                                if (addPaginatedFooter)
                                {
                                    toSend.AddPaginatedFooter(currentPage, pageCount);
                                }
                                await msg.ModifyAsync(x => x.Embed = toSend.Build()).ConfigureAwait(false);
                            }
                        }
                        else if (r.Emote.Name == ArrowRight.Name)
                        {
                            if (pageCount == null || currentPage < pageCount - 1)
                            {
                                var toSend = await pageFunc(++currentPage).ConfigureAwait(false);
                                if (addPaginatedFooter)
                                {
                                    toSend.AddPaginatedFooter(currentPage, pageCount);
                                }
                                await msg.ModifyAsync(x => x.Embed = toSend.Build()).ConfigureAwait(false);
                            }
                        }
                    } catch (InvalidOperationException e) {
                        LogManager.GetCurrentClassLogger().Error(e);
                    } catch { }
                }

                using (msg.OnReaction(client, ChangePage, ChangePage)) {
                    await Task.Delay(ReactionTime).ConfigureAwait(false);
                }

                await msg.RemoveAllReactionsAsync().ConfigureAwait(false);
            });
        }
Esempio n. 48
0
        public virtual void RevisionReady(string version,
                                          IDictionary <string, IList <RevisionFile> > revisionFiles,
                                          IDictionary <string, IList <string> > copiedFiles,
                                          IDictionary <string, Directory> sourceDirectory)
        {
            Directory      taxonomyClientDirectory = sourceDirectory[IndexAndTaxonomyRevision.TAXONOMY_SOURCE];
            Directory      indexClientDirectory    = sourceDirectory[IndexAndTaxonomyRevision.INDEX_SOURCE];
            IList <string> taxonomyFiles           = copiedFiles[IndexAndTaxonomyRevision.TAXONOMY_SOURCE];
            IList <string> indexFiles           = copiedFiles[IndexAndTaxonomyRevision.INDEX_SOURCE];
            string         taxonomySegmentsFile = IndexReplicationHandler.GetSegmentsFile(taxonomyFiles, true);
            string         indexSegmentsFile    = IndexReplicationHandler.GetSegmentsFile(indexFiles, false);

            bool success = false;

            try
            {
                // copy taxonomy files before index files
                IndexReplicationHandler.CopyFiles(taxonomyClientDirectory, taxonomyDirectory, taxonomyFiles);
                IndexReplicationHandler.CopyFiles(indexClientDirectory, indexDirectory, indexFiles);

                // fsync all copied files (except segmentsFile)
                if (taxonomyFiles.Count > 0)
                {
                    taxonomyDirectory.Sync(taxonomyFiles);
                }
                indexDirectory.Sync(indexFiles);

                // now copy and fsync segmentsFile, taxonomy first because it is ok if a
                // reader sees a more advanced taxonomy than the index.
                if (taxonomySegmentsFile != null)
                {
                    taxonomyClientDirectory.Copy(taxonomyDirectory, taxonomySegmentsFile, taxonomySegmentsFile, IOContext.READ_ONCE);
                }
                indexClientDirectory.Copy(indexDirectory, indexSegmentsFile, indexSegmentsFile, IOContext.READ_ONCE);

                if (taxonomySegmentsFile != null)
                {
                    taxonomyDirectory.Sync(new[] { taxonomySegmentsFile });
                }
                indexDirectory.Sync(new[] { indexSegmentsFile });

                success = true;
            }
            finally
            {
                if (!success)
                {
                    taxonomyFiles.Add(taxonomySegmentsFile); // add it back so it gets deleted too
                    IndexReplicationHandler.CleanupFilesOnFailure(taxonomyDirectory, taxonomyFiles);
                    indexFiles.Add(indexSegmentsFile);       // add it back so it gets deleted too
                    IndexReplicationHandler.CleanupFilesOnFailure(indexDirectory, indexFiles);
                }
            }

            // all files have been successfully copied + sync'd. update the handler's state
            currentRevisionFiles = revisionFiles;
            currentVersion       = version;

            WriteToInfoStream("revisionReady(): currentVersion=" + currentVersion + " currentRevisionFiles=" + currentRevisionFiles);

            // update the segments.gen file
            IndexReplicationHandler.WriteSegmentsGen(taxonomySegmentsFile, taxonomyDirectory);
            IndexReplicationHandler.WriteSegmentsGen(indexSegmentsFile, indexDirectory);

            // Cleanup the index directory from old and unused index files.
            // NOTE: we don't use IndexWriter.deleteUnusedFiles here since it may have
            // side-effects, e.g. if it hits sudden IO errors while opening the index
            // (and can end up deleting the entire index). It is not our job to protect
            // against those errors, app will probably hit them elsewhere.
            IndexReplicationHandler.CleanupOldIndexFiles(indexDirectory, indexSegmentsFile);
            IndexReplicationHandler.CleanupOldIndexFiles(taxonomyDirectory, taxonomySegmentsFile);

            // successfully updated the index, notify the callback that the index is
            // ready.
            if (callback != null)
            {
                try {
                    callback.Invoke();
                } catch (Exception e) {
                    throw new IOException(e.Message, e);
                }
            }
        }
Esempio n. 49
0
 public void OnEvent(DisruptorEvent evt)
 {
     evt.Write(_stepFunc.Invoke(evt.Read <TStepIn>()));
 }
Esempio n. 50
0
 /// <returns>Collection of modified lines in "index: added line /+ removed line" format</returns>
 public ICollection <string> GetDifference()
 {
     return(_action.Invoke());
 }
Esempio n. 51
0
        public void BindRecord(SqliteStatement statement, int index, TRecord record)
        {
            var value = _getter.Invoke(record);

            _converter.BindProperty(statement, index, value);
        }
 internal Task WriteValues(TEntity entity, NpgsqlBinaryImporter binaryImporter, CancellationToken cancellationToken)
 {
     return(_valueWriter.Invoke(entity, binaryImporter, cancellationToken));
 }
Esempio n. 53
0
 public void AddStep <TStepIn, TStepOut>(Func <TStepIn, TStepOut> stepFunc)
 {
     _pipelineSteps.Add(objInput => stepFunc.Invoke((TStepIn)(object)objInput));
 }
Esempio n. 54
0
 public override void Execute()
 {
     conductor.Completed += OnCallCompleted;
     ThreadPool.QueueUserWorkItem(x => call.Invoke(conductor), null);
 }
Esempio n. 55
0
 protected override TDestination MapObject(IObjectMapperContext objectMapper, TSource source)
 {
     return(mappingFunc.Invoke(objectMapper, source));
 }
Esempio n. 56
0
        public static string UploadImageIncontent(string content, out string firstImage, Func <string, string> uploadImage)
        {
            firstImage = String.Empty;

            string newContent = content;

            if (String.IsNullOrEmpty(newContent))
            {
                return(newContent);
            }

            try
            {
                string strRegex = @"<img.+?src=[\""'](?<SRC>.+?)[\""'].*?>";
                Regex  myRegex  = new Regex(strRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline);

                Match match = myRegex.Match(newContent);
                if (match.Success)
                {
                    newContent = myRegex.Replace(newContent, m => string.Format("<p style=\"text-align:center\"><img src=\"{0}\" /></p>", uploadImage.Invoke(m.Groups["SRC"].Value)));
                }


                foreach (Match matchAvatar in myRegex.Matches(newContent))
                {
                    if (matchAvatar.Success)
                    {
                        firstImage = matchAvatar.Groups["SRC"].Value;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                // Todo
            }
            return(newContent);
        }
 /// <summary>
 /// https://docs.ruby-lang.org/ja/latest/method/Object/i/yield_self.html
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="obj"></param>
 /// <param name="action"></param>
 /// <returns></returns>
 public static T YieldSelf <T>(this T obj, Func <T, object> action)
 {
     action.Invoke(obj);
     return(obj);
 }
Esempio n. 58
0
        public async void OnNext(long value)
        {
            T data = await loadAction.Invoke();

            callBackAction.Invoke(data);
        }
Esempio n. 59
0
        /// <summary>
        ///     Gets info an assembly
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string AssemblyInfo <T>(Func <T, string> value) where T : Attribute
        {
            T attribute = (T)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(T));

            return(value.Invoke(attribute));
        }
Esempio n. 60
0
 public int LinqOptimizer()
 => linqOptimizerQuery.Invoke();