Exemplo n.º 1
0
        public void InsertAfter(int index)
        {
            var refNode = _children?.ElementAtOrDefault(index);

            if (refNode != null)
            {
                InsertAfter(refNode);
            }

            throw new ArgumentOutOfRangeException(nameof(index));
        }
Exemplo n.º 2
0
    //Hide stars initially
    void Awake()
    {
        gameManager = GameObject.FindGameObjectWithTag("GameManager");

        starsEarnedLevel1 = 0;
        starsEarnedLevel2 = 0;

        stars = LoadStars ();
        if (stars.ElementAtOrDefault (0) != null) {
            starsEarnedLevel1 = stars [0];
        } else {
            starsEarnedLevel1 = 0;
        }
        if (stars.ElementAtOrDefault (1) != null) {
            starsEarnedLevel2 = stars [1];
        } else {
            starsEarnedLevel2 = 0;
        }

        level1Star1 = GameObject.FindGameObjectWithTag("Level1Star1");
        level1Star2 = GameObject.FindGameObjectWithTag("Level1Star2");
        level1Star3 = GameObject.FindGameObjectWithTag("Level1Star3");
        level2Star1 = GameObject.FindGameObjectWithTag("Level2Star1");
        level2Star2 = GameObject.FindGameObjectWithTag("Level2Star2");
        level2Star3 = GameObject.FindGameObjectWithTag("Level2Star3");

        //Level 1 Stars
        if (starsEarnedLevel1 == 0) {
            level1Star1.gameObject.SetActive (false);
            level1Star2.gameObject.SetActive (false);
            level1Star3.gameObject.SetActive (false);
        }
        if (starsEarnedLevel1 == 1){
            level1Star2.gameObject.SetActive (false);
            level1Star3.gameObject.SetActive (false);
        }
        if (starsEarnedLevel1 == 2) {
            level1Star3.gameObject.SetActive (false);
        }

        //Level 2 Stars
        if (starsEarnedLevel2 == 0) {
            level2Star1.gameObject.SetActive (false);
            level2Star2.gameObject.SetActive (false);
            level2Star3.gameObject.SetActive (false);
        }
        if (starsEarnedLevel2 == 1){
            level2Star2.gameObject.SetActive (false);
            level2Star3.gameObject.SetActive (false);
        }
        if (starsEarnedLevel2 == 2) {
            level2Star3.gameObject.SetActive (false);
        }
    }
 static void Main()
 {
     string input = Console.ReadLine();
     List<string> list = new List<string>(input.Split(' '));
     Console.Write(list.ElementAt(0) + " ");
     for (int i = 1; i < list.Count; i++)
     {
         if (list.ElementAtOrDefault(i) != list.ElementAtOrDefault(i-1))
         {
             Console.WriteLine();
         }
         Console.Write(list.ElementAtOrDefault(i) + " ");
     }
     Console.WriteLine();
 }
Exemplo n.º 4
0
        public static string GetRandomMessages()
        {
            string message = string.Empty;

            List<LoadingMessages> Messages = new List<LoadingMessages>() 
            {
                new LoadingMessages(){ Message = "Bimmy and Jimmy..."},
                new LoadingMessages(){ Message = "all your base are belong to us..."},
                new LoadingMessages(){ Message = "a winner is you..."},
                new LoadingMessages(){ Message = "I am error..."},
                new LoadingMessages(){ Message = "Make rapid progres..."},
                new LoadingMessages(){ Message = "Congraturation this story is happy end.\nThank you..."},
                new LoadingMessages(){ Message = "I feel asleep..."},
                new LoadingMessages(){ Message = "This is not enough golds..."},
                new LoadingMessages(){ Message = "You have completed a great game..."},
                new LoadingMessages(){ Message = "Go ahead and rest our heroes..."},
                new LoadingMessages(){ Message = "You're winner!..."},
            };

            Random rnd = new Random();
            int index = rnd.Next(Messages.Count);

            message = Messages.ElementAtOrDefault(index).Message;

            return message;
        }
Exemplo n.º 5
0
		/// <summary>
		/// Prepares the alphabet for encypting/decryping
		/// </summary>
		private void SetupAlphabet()
		{
			var seps = new List<char>();
			var guards = new List<char>();

			foreach (var prime in primes)
			{
				var c = Alphabet.ElementAtOrDefault(prime - 1);
				if (c != default(char))
				{
					seps.Add(c);
					Alphabet = Alphabet.Replace(c, ' ');
				}
			}

			foreach (var index in sepsIndices)
			{
				var separator = seps.ElementAtOrDefault(index);
				if (separator != default(char))
				{
					guards.Add(separator);
					seps.RemoveAt(index);
				}
			}

			Alphabet = Alphabet.Replace(" ", string.Empty);
			Alphabet = ConsistentShuffle(Alphabet, Salt);
			
			this.seps = seps.ToArray();
			this.guards = guards.ToArray();
		}
Exemplo n.º 6
0
    public override bool InView(Transform t)
    {
        
        //bool b = base.OutOfView(t);
        if ((t.getChildBounds().max.x) < WorldScreenSize.x)
        {
            t.gameObject.SetActive(false);
            randomSelection = SubObjects.Where(i => i.gameObject.activeSelf == false).ToList();
            negativeSelectoin = SubObjects.Where(i => i.gameObject.activeSelf == true).ToList();

            Transform f =t;
            foreach (Transform x in negativeSelectoin)
                if (x.transform.position.x > f.position.x)
                    f = x;
           
            if (randomSelection.Count > 0)
            {
                Transform freeObject = randomSelection.ElementAtOrDefault(new System.Random().Next() % randomSelection.Count());
                freeObject.gameObject.SetActive(true);
                if (IgnorNameTags == null)
                    freeObject.position = f.position + new Vector3(f.getChildBounds().size.x, 0, 0);
                else
                    freeObject.position = f.position + new Vector3(f.getChildBounds(IgnorNameTags).size.x, 0, 0);

                //util.Debugger.Log("bound orignal " + f.name, f.getChildBounds(IgnorNameTags));
                //util.Debugger.Log("bound newObject " + freeObject.name, freeObject.getChildBounds(IgnorNameTags));
            }

            randomSelection = null;
            negativeSelectoin = null;
            return false;

        }
        return true;
    }
        public void Execute(List<string> arguments)
        {
            if (arguments.Count == 0)
            {
                ShowNoArgsMessage();
            }
            else
            {
                while (arguments.Count != 0)
                {
                    string key;
                    string value;

                    key = arguments[0];
                    arguments.RemoveAt(0);

                    if (arguments.ElementAtOrDefault(0) != null)
                    {
                        value = arguments[0];
                        arguments.RemoveAt(0);
                    }
                    else
                    {
                        value = "<null>";
                    }
                    Console.WriteLine("{0} - {1}", key, value);
                }
            }
        }
        public IEnumerable <PageProcessingInfo> GeneratePageInfoBy(int startPage, IEnumerable <int> needsToBeReprocessed)
        {
            List <int?> reprocessedPages    = new List <int?>(needsToBeReprocessed.ConvertToNullableInts());
            int         pageCollectionIndex = 0;
            bool        normalIncrementMode = false;

            do
            {
                var reprocessedPage = reprocessedPages?.ElementAtOrDefault(pageCollectionIndex);
                if (normalIncrementMode || (reprocessedPage == null || startPage < reprocessedPage))
                {
                    normalIncrementMode = true;
                    yield return(new PageProcessingInfo
                    {
                        Page = startPage,
                        IsReprocessing = reprocessedPages.Contains(startPage)
                    });

                    startPage++;
                }
                else
                {
                    pageCollectionIndex++;
                    yield return(new PageProcessingInfo()
                    {
                        Page = reprocessedPage.Value,
                        IsReprocessing = true
                    });
                }
            } while (true);
        }
        public SkillEffectName InsertSkillEffectName(string name, string heroName, Skill skill, List<string> skillEffectValues)
        {
            HeroCreator heroCreator = new HeroCreator();
            SkillEffectName skillEffectName;
            Hero hero = heroCreator.getHeroByName(heroName);

            Skill completeSkill = SkillCreator.SelectSkill(skill.Name, hero.ID);            

            bool exists = checkIfSkillNameExists(name, completeSkill, completeSkill.Description, out skillEffectName);

            if (!exists)
            {
                skillEffectName.Name = name.Trim();
                skillEffectName.SkillId = completeSkill.ID;
                if (skillEffectValues.FirstOrDefault() != null)
                    skillEffectName.ValueLv1 = skillEffectValues.First();
                if (skillEffectValues.ElementAtOrDefault(1) != null)
                    skillEffectName.ValueLv2 = skillEffectValues.ElementAt(1);
                if (skillEffectValues.ElementAtOrDefault(2) != null)
                    skillEffectName.ValueLv3 = skillEffectValues.ElementAt(2);
                if (skillEffectValues.ElementAtOrDefault(3) != null)
                    skillEffectName.ValueLv4 = skillEffectValues. ElementAt(3);
                if (skillEffectValues.LastOrDefault() != null)
                    skillEffectName.ValueScepter = skillEffectValues.Last();            

                using (Dota2Entities ctx = new Dota2Entities())
                {
                    try
                    {
                        skillEffectName = ctx.SkillEffectName.Add(skillEffectName);
                        ctx.SaveChanges();
                        Console.WriteLine("Skill " + name + " Created");
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                }
            }
            return skillEffectName;
        }
Exemplo n.º 10
0
            internal void InitCurOutfitTriggerInfo()
            {
                Logger.Log(DebugLogLevel, $"[InitCurOutfitTriggerInfo][{ChaControl.chaFile.parameter?.fullname}] Fired!!");

                TriggerEnabled = false;

                CurOutfitTriggerInfo = CharaTriggerInfo?.ElementAtOrDefault(CurrentCoordinateIndex);
                if (CurOutfitTriggerInfo == null)
                {
                    Logger.Log(DebugLogLevel, "[InitCurOutfitTriggerInfo] CurOutfitTriggerInfo is Null");
                    return;
                }

                if (MakerAPI.InsideMaker)
                {
                    CheckOutfitTriggerInfoCount(CurrentCoordinateIndex);
                }

                if (CurOutfitTriggerInfo.Parts.Count() < 20)
                {
                    Logger.Log(DebugLogLevel, $"[InitOutfitTriggerInfo][{ChaControl.chaFile.parameter?.fullname}] TriggerEnabled false");
                    return;
                }

                TriggerEnabled = true;
                VirtualGroupStates.Clear();
//				CurSlotTriggerInfo = new AccTriggerInfo(0);

                FillVirtualGroupStates();

                if (MakerAPI.InsideMaker)
                {
                    if (AccessoriesApi.SelectedMakerAccSlot > CurOutfitTriggerInfo.Parts.Count())
                    {
                        AccSlotChangedHandler(0, true);
                    }
                    else
                    {
                        AccSlotChangedHandler(AccessoriesApi.SelectedMakerAccSlot, true);
                    }
                }
                else if (KKAPI.Studio.StudioAPI.InsideStudio)
                {
                    UpdateStudioUI();
                    SyncAllAccToggle();
                }
                else
                {
                    UpdateHUI();
                    SyncAllAccToggle();
                }
            }
Exemplo n.º 11
0
        public TestDetailsBusinessModel GetTestDetailsByTestSuit(PreviewTestBusinessModel previewTest, int?questionNumber, int questionType)
        {
            List <int> allquestionsForPreview = GetQuestionsForPreviewTestSuite(previewTest);
            var        questionNumberList     = FilterQuestionsByType(allquestionsForPreview, (QuestionType)questionType);

            questionNumber = questionNumber == null && questionNumberList.Count > 0 ? questionNumberList.ElementAtOrDefault(0) : questionNumber;
            if (questionNumber == null)
            {
                return(null);
            }
            var index = questionNumberList.IndexOf((int)questionNumber);
            int?previousQuestionId = questionNumberList.ElementAtOrDefault(index - 1);
            int?nextQuestionId     = questionNumberList.ElementAtOrDefault(index + 1);
            var result             = (from b in _context.Query <Question>()
                                      where b.Id == questionNumber
                                      select new TestDetailsBusinessModel
            {
                QuestionId = b.Id,
                Marks = b.Marks,
                QuestionType = b.QuestionType,
                AnswerType = b.AnswerType,
                QuestionDescription = b.QuestionDescription,
                OptionCount = b.OptionCount,
                Option1 = b.Option1,
                Option2 = b.Option2,
                Option3 = b.Option3,
                Option4 = b.Option4,
                Option5 = b.Option5,
                Option6 = b.Option6,
                Option7 = b.Option7,
                Option8 = b.Option8,
                DisplayQuestionNumber = index + 1
            }).FirstOrDefault();

            if (result == null)
            {
                return(null);
            }
            result.PreviousQuestionId = index <= 0 ? null : previousQuestionId;
            result.NextQuestionId     = index >= questionNumberList.Count - 1 ? null : nextQuestionId;
            if (questionType == (int)QuestionType.Practical && result.PreviousQuestionId == null)
            {
                List <int> objectiveQuestions = FilterQuestionsByType(allquestionsForPreview, QuestionType.Objective);
                result.PreviousQuestionId = objectiveQuestions?.ElementAtOrDefault(objectiveQuestions.Count - 1);
            }
            if (questionType == (int)QuestionType.Objective && result.NextQuestionId == null)
            {
                List <int> practicalQuestions = FilterQuestionsByType(allquestionsForPreview, QuestionType.Practical);
                result.NextQuestionId = practicalQuestions?.ElementAtOrDefault(0);
            }
            return(result);
        }
Exemplo n.º 12
0
        private void Search(string artist = null, string group = null, string name = null, List <string> tagList = null)
        {
            currentPage    = 1;
            thumbnailsList = fc.SearchFolders(artist, group, name, tagList, imagesPerPage);
            totalPages     = thumbnailsList != null?thumbnailsList.Count() : 1;

            totalFolders = thumbnailsList != null?thumbnailsList.Sum(th => th.Count) : 0;

            UpdateCurrentPageTextBlock();
            UpdateFoldersFoundTextBlock();
            listboxGallery.ItemsSource = thumbnailsList?.ElementAtOrDefault(0);
            ResetScroll();
        }
Exemplo n.º 13
0
 /// <summary>
 /// реализует отбор кандидатов на скрещивание и мутацию
 /// </summary>
 /// <param name="generation"></param>
 public List<double> Selection(List<double> generation)
 {
     //не факт что удаляются именно эти 2 выбранных кандидата
     List<double> res = new List<double>();
     for (int i = 0; i < DefaultSizePopulation/3; i++)
     {
         double candidate1 = generation.ElementAtOrDefault(rnd.Next(generation.Count));
         res.Add(candidate1);
     }
     //generation.Remove(candidate1);
     //generation.Remove(candidate2);
     
     return res;
 }
Exemplo n.º 14
0
        public void InitializeGame()
        {
            Frames = new List<IFrame>();

            for (var index = 0; index < DefaultFrameNumber; index++)
            {
                Frames.Add(new Frame());
            }

            for (var currentFrameIndex = 0; currentFrameIndex < DefaultFrameNumber; currentFrameIndex++)
            {
                var prevFrameIndex = currentFrameIndex - 1;
                var nextFrameIndex = currentFrameIndex + 1;

                var prevFrame = Frames.ElementAtOrDefault(prevFrameIndex);
                var nextFrame = Frames.ElementAtOrDefault(nextFrameIndex);

                Frames.ElementAt(currentFrameIndex).PrevFrame = prevFrame;
                Frames.ElementAt(currentFrameIndex).NextFrame = nextFrame;
            }

            CurrentFrame = Frames.ElementAt(0);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Returns the culture retrieved from the provided URL path segments.
        /// Null is returned if a valid culture could not be retrieved.
        /// </summary>
        /// <param name="urlPathSegments">The segments to retrieve the URL form</param>
        /// <param name="cultureIndexInPath">The index of the culture in the URL path</param>
        /// <returns></returns>
        private CultureInfo GetCultureFromUrlPath(List <string> urlPathSegments, int cultureIndexInPath = 0)
        {
            CultureInfo urlCulture = null;

            try
            {
                urlCulture = CultureInfo.CreateSpecificCulture(urlPathSegments?.ElementAtOrDefault(cultureIndexInPath));
            }
            catch (Exception)
            {
                //Silently ignore.
            }

            return(urlCulture);
        }
Exemplo n.º 16
0
        internal static Result <BaseComponent> TrySetComponent(BaseComponent?component, string newValue, ElementIndex elementIndex)
        {
            if (elementIndex.SubComponentIndex.HasValue)
            {
                if (component == null || !(component is ComplexComponent complexComponent))
                {
                    return(ErrorReturn <BaseComponent>($"failed to find subComponent on message with {elementIndex}, as the component was not found"));
                }
                List <BaseSubComponent> subComponents = complexComponent?.SubComponents != null?complexComponent.SubComponents.ToList() : new List <BaseSubComponent>();

                BaseSubComponent?subComponent = subComponents?.ElementAtOrDefault(elementIndex.SubComponentIndex.Value - 1);
                if (subComponent == null)
                {
                    return(ErrorReturn <BaseComponent>($"failed to find subComponent {elementIndex}"));
                }
                subComponents ![elementIndex.SubComponentIndex.Value - 1] = new SubComponent(subComponent, newValue);//set the right type of subcomponent if we ever add others.
Exemplo n.º 17
0
        public static bool getChance(int tableSize, int chance)
        {
            List<int> Table = new List<int>();
            for (int i = 0; i < tableSize; i++)
            {
                Table.Add(0);
            }
            for (int j = 0; j < chance; j++)
            {
                    Table[j] = 1;
            }

            int r = Table.ElementAtOrDefault(new System.Random().Next() % Table.Count());

            if (r == 1)
                return true;
            return false;
        }
Exemplo n.º 18
0
 public static List<Card> CardShuffle(List<Card> Cards)
 {
     List<Card> Deck = new List<Card>();
     for(int i = 0; i< Cards.Count; i++)
     {
         Deck.Add(null);
     }
     Random random = new Random();
     foreach(Card c in Cards)
     {
         int randomValue = random.Next(0, Cards.Count);
         while(Deck.ElementAtOrDefault(randomValue) != null) {
             randomValue = random.Next(0, Cards.Count);
         }
         Deck[randomValue] = c;
     }
     return Deck;
 }
Exemplo n.º 19
0
        public void Run(
            string key, string inpath, string outpath, 
            bool noHeader, int numRowsToSelect)
        {
            // load into list
            var rows = new List<string>();
            using (var rdr = new StreamReader(File.OpenRead(inpath)))
            {
                while (!rdr.EndOfStream)
                {
                    rows.Add(rdr.ReadLine());
                }
            }
            Console.WriteLine("Loaded " + rows.Count + " rows.");

            // determine row limits
            var rowMin = 1;
            var rowMax = rows.Count;
            if (!noHeader) rowMin++;
            if (numRowsToSelect > rowMax - rowMin + 1) numRowsToSelect = rowMax - rowMin + 1;
            Console.WriteLine("Retrieving random " + numRowsToSelect + " rows between "
                + rowMin + " and " + rowMax + ".");

            // get randoms
            var rclient = new Demot.RandomOrgApi.RandomOrgApiClient(key);
            var rs = rclient.GenerateIntegers(numRowsToSelect, rowMin, rowMax, false);
            var randomRows = rs.Integers.ToList();

            // output
            using (TextWriter writer = File.CreateText(outpath))
            {
                if (!noHeader) writer.WriteLine(rows[0]);
                foreach (var randomi in randomRows)
                {
                    var line = rows.ElementAtOrDefault(randomi - 1);
                    if (line != null) writer.WriteLine(line);
                }
            }
            Console.WriteLine("Output to " + outpath + " completed.");
        }
Exemplo n.º 20
0
        public static void TryExtractBlobs(string pathBase, List <Memory <byte> > blobs, bool allTypes, List <string?>?names, bool singleFile, bool useDirnameAsName, bool forceExtension, string?extension, UnbundlerFlags flags)
        {
            for (var index = 0; index < blobs.Count; index++)
            {
                var datablob  = blobs[index];
                var name      = $"{index:X4}";
                var foundName = names?.ElementAtOrDefault(index);
                var ext       = $".{extension ?? GetExtension(datablob.Span)}";
                if (foundName != null)
                {
                    name = foundName.SanitizeFilename();
                    ext  = !string.IsNullOrWhiteSpace(Path.GetExtension(name)) && !forceExtension ? string.Empty : ext;
                    if (File.Exists($@"{pathBase}\{name}{ext}"))
                    {
                        var oname = name + "_";
                        var i     = 1;
                        while (File.Exists($@"{pathBase}\{name}{ext}"))
                        {
                            name = oname + $"{i++:X}";
                        }
                    }
                }

                var path = $@"{pathBase}\{name}{ext}";
                if (singleFile && blobs.Count == 1)
                {
                    if (useDirnameAsName)
                    {
                        path = pathBase + $".{ext}";
                    }
                    else
                    {
                        path = Path.Combine(Path.GetDirectoryName(pathBase) ?? string.Empty, $"{name}{ext}");
                    }
                }

                TryExtractBlob(path, datablob.Span, allTypes, flags, false);
            }
        }
Exemplo n.º 21
0
        public async Task ImportCiphersAsync(
            List<Cipher> folders,
            List<Cipher> ciphers,
            IEnumerable<KeyValuePair<int, int>> folderRelationships)
        {
            // create all the folders
            var folderTasks = new List<Task>();
            foreach(var folder in folders)
            {
                folderTasks.Add(_cipherRepository.CreateAsync(folder));
            }
            await Task.WhenAll(folderTasks);

            // associate the newly created folders to the ciphers
            foreach(var relationship in folderRelationships)
            {
                var cipher = ciphers.ElementAtOrDefault(relationship.Key);
                var folder = folders.ElementAtOrDefault(relationship.Value);

                if(cipher == null || folder == null)
                {
                    continue;
                }

                cipher.FolderId = folder.Id;
            }

            // create all the ciphers
            await _cipherRepository.CreateAsync(ciphers);

            // push
            var userId = folders.FirstOrDefault()?.UserId ?? ciphers.FirstOrDefault()?.UserId;
            if(userId.HasValue)
            {
                await _pushService.PushSyncCiphersAsync(userId.Value);
            }
        }
Exemplo n.º 22
0
		void ConvertBody(List<ILNode> body, int startPos, int bodyLength, List<KeyValuePair<ILLabel, StateRange>> labels)
		{
			newBody = new List<ILNode>();
			newBody.Add(MakeGoTo(labels, 0));
			List<SetState> stateChanges = new List<SetState>();
			int currentState = -1;
			// Copy all instructions from the old body to newBody.
			for (int pos = startPos; pos < bodyLength; pos++) {
				ILExpression expr = body[pos] as ILExpression;
				if (expr != null && expr.Code == ILCode.Stfld && expr.Arguments[0].MatchThis()) {
					// Handle stores to 'state' or 'current'
					if (GetFieldDefinition(expr.Operand as FieldReference) == stateField) {
						if (expr.Arguments[1].Code != ILCode.Ldc_I4)
							throw new SymbolicAnalysisFailedException();
						currentState = (int)expr.Arguments[1].Operand;
						stateChanges.Add(new SetState(newBody.Count, currentState));
					} else if (GetFieldDefinition(expr.Operand as FieldReference) == currentField) {
						newBody.Add(new ILExpression(ILCode.YieldReturn, null, expr.Arguments[1]));
					} else {
						newBody.Add(body[pos]);
					}
				} else if (returnVariable != null && expr != null && expr.Code == ILCode.Stloc && expr.Operand == returnVariable) {
					// handle store+branch to the returnVariable
					ILExpression br = body.ElementAtOrDefault(++pos) as ILExpression;
					if (br == null || !(br.Code == ILCode.Br || br.Code == ILCode.Leave) || br.Operand != returnLabel || expr.Arguments[0].Code != ILCode.Ldc_I4)
						throw new SymbolicAnalysisFailedException();
					int val = (int)expr.Arguments[0].Operand;
					if (val == 0) {
						newBody.Add(new ILExpression(ILCode.YieldBreak, null));
					} else if (val == 1) {
						newBody.Add(MakeGoTo(labels, currentState));
					} else {
						throw new SymbolicAnalysisFailedException();
					}
				} else if (expr != null && expr.Code == ILCode.Ret) {
					if (expr.Arguments.Count != 1 || expr.Arguments[0].Code != ILCode.Ldc_I4)
						throw new SymbolicAnalysisFailedException();
					// handle direct return (e.g. in release builds)
					int val = (int)expr.Arguments[0].Operand;
					if (val == 0) {
						newBody.Add(new ILExpression(ILCode.YieldBreak, null));
					} else if (val == 1) {
						newBody.Add(MakeGoTo(labels, currentState));
					} else {
						throw new SymbolicAnalysisFailedException();
					}
				} else if (expr != null && expr.Code == ILCode.Call && expr.Arguments.Count == 1 && expr.Arguments[0].MatchThis()) {
					MethodDefinition method = GetMethodDefinition(expr.Operand as MethodReference);
					if (method == null)
						throw new SymbolicAnalysisFailedException();
					StateRange stateRange;
					if (method == disposeMethod) {
						// Explicit call to dispose is used for "yield break;" within the method.
						ILExpression br = body.ElementAtOrDefault(++pos) as ILExpression;
						if (br == null || !(br.Code == ILCode.Br || br.Code == ILCode.Leave) || br.Operand != returnFalseLabel)
							throw new SymbolicAnalysisFailedException();
						newBody.Add(new ILExpression(ILCode.YieldBreak, null));
					} else if (finallyMethodToStateRange.TryGetValue(method, out stateRange)) {
						// Call to Finally-method
						int index = stateChanges.FindIndex(ss => stateRange.Contains(ss.NewState));
						if (index < 0)
							throw new SymbolicAnalysisFailedException();
						
						ILLabel label = new ILLabel();
						label.Name = "JumpOutOfTryFinally" + stateChanges[index].NewState;
						newBody.Add(new ILExpression(ILCode.Leave, label));
						
						SetState stateChange = stateChanges[index];
						// Move all instructions from stateChange.Pos to newBody.Count into a try-block
						stateChanges.RemoveRange(index, stateChanges.Count - index); // remove all state changes up to the one we found
						ILTryCatchBlock tryFinally = new ILTryCatchBlock();
						tryFinally.TryBlock = new ILBlock(newBody.GetRange(stateChange.NewBodyPos, newBody.Count - stateChange.NewBodyPos));
						newBody.RemoveRange(stateChange.NewBodyPos, newBody.Count - stateChange.NewBodyPos); // remove all nodes that we just moved into the try block
						tryFinally.CatchBlocks = new List<ILTryCatchBlock.CatchBlock>();
						tryFinally.FinallyBlock = ConvertFinallyBlock(method);
						newBody.Add(tryFinally);
						newBody.Add(label);
					}
				} else {
					newBody.Add(body[pos]);
				}
			}
			newBody.Add(new ILExpression(ILCode.YieldBreak, null));
		}
Exemplo n.º 23
0
        private IIndicatorResult GetInidcatorResult(Rule rule, List <Candle> candles)
        {
            // period is the minutes between when the crossing test should be performed
            // tests on tradingview with bitcoin return best results using a 30 min space on a 5 min chart
            decimal period = rule.Value.GetValueOrDefault(30);


            if (candles.Count < 19 || (candles.Last().Timestamp.Minute != 0 && candles.Last().Timestamp.Minute % period != 0))
            {
                return new IndicatorResult
                       {
                           Message = $"IsCrossingOver - within period",
                           Result  = false,
                       }
            }
            ;


            Candle lastCandle       = candles.ElementAtOrDefault(candles.Count - 1);
            Candle secondLastCandle = candles.ElementAtOrDefault(candles.Count - 2);



            switch ((IndicatorRulesEnumerations.CrossingRulesEnum)rule.IndicatorRuleTypeId)
            {
            case IndicatorRulesEnumerations.CrossingRulesEnum.IsCrossingOver:


                if (lastCandle.IsBullish() && secondLastCandle.IsBearish())
                {
                    return(new IndicatorResult
                    {
                        Message = $"IsCrossingOver - true lastCandle.IsBullish() && secondLastCandle.IsBearish() {JsonConvert.SerializeObject(lastCandle)} && {JsonConvert.SerializeObject(secondLastCandle)}",
                        Result = true,
                    });
                }
                else
                {
                    return(new IndicatorResult
                    {
                        Message = $"IsCrossingOver - false lastCandle.IsBullish() && secondLastCandle.IsBearish() {JsonConvert.SerializeObject(lastCandle)} && {JsonConvert.SerializeObject(secondLastCandle)}",
                        Result = false,
                    });
                }



            case IndicatorRulesEnumerations.CrossingRulesEnum.IsCrossingUnder:


                // To check as having crossed under the last bar close is less than the last bar open
                // and it was the opposite on the bar immediately preceding it.

                if (lastCandle.IsBearish() && secondLastCandle.IsBullish())
                {
                    return(new IndicatorResult
                    {
                        Message = $"IsCrossingUnder - true lastCandle.IsBearish() && secondLastCandle.IsBullish() {JsonConvert.SerializeObject(lastCandle)} && {JsonConvert.SerializeObject(secondLastCandle)}",
                        Result = true,
                    });
                }
                else
                {
                    return(new IndicatorResult
                    {
                        Message = $"IsCrossingUnder - false lastCandle.IsBearish() && secondLastCandle.IsBullish() {JsonConvert.SerializeObject(lastCandle)} && {JsonConvert.SerializeObject(secondLastCandle)}",
                        Result = false,
                    });
                }

            default:
                return(new IndicatorResult {
                    Message = "Error", Result = false
                });
            }
        }
Exemplo n.º 24
0
        /**
         * Evaluate play chance and if it succeeds get a randomly (shuffle) selected clip from the clip collection.
         */
        private AudioMateClip GetRandomClip(bool skipPlayChance = false)
        {
            if (_clips == null)
            {
                return(null);
            }
            var randomClip  = (AudioMateClip)null;
            var randomIndex = -1;

            try
            {
                // PlayChance test
                var randomChance = (float)UnityEngine.Random.Range(0, 100) / 100;

                if (!skipPlayChance && PlayChance < randomChance)
                {
                    return(null);
                }

                if (ShuffleMode)
                {
                    if (_unplayedClipsList.Count == 1)
                    {
                        randomClip = _clips[_unplayedClipsList.First()];

                        _lastPlayedClipIndex = _unplayedClipsList.ElementAtOrDefault(0);
                        ResetUnplayedClips();
                        return(randomClip);
                    }
                    // ShuffleMode play
                    if (_unplayedClipsList.Count < 1)
                    {
                        ResetUnplayedClips();
                    }

                    // After playing the last clip of the unplayed clips list and resetting it can theoretically happen that
                    // the next random clip is the same as the last random clip. If that happens lets repeat randomization
                    // until we get another clip index.
                    randomIndex = UnityEngine.Random.Range(0, _unplayedClipsList.Count);
                    if (_clips.Count > 1)
                    {
                        var safety = 0;
                        while (randomIndex == _lastPlayedClipIndex)
                        {
                            randomIndex = UnityEngine.Random.Range(0, _unplayedClipsList.Count);
                            if (++safety < 100)
                            {
                                continue;
                            }
                            return(null);
                        }
                    }
                    randomClip = _clips.ElementAtOrDefault(_unplayedClipsList.ElementAtOrDefault(randomIndex));

                    // Remove played clip from unplayedClipsList list
                    _unplayedClipsList.RemoveAt(randomIndex);
                }
                else
                {
                    // Standard play
                    randomIndex = UnityEngine.Random.Range(0, _clips.Count);
                    randomClip  = _clips.ElementAtOrDefault(randomIndex);
                }

                // Set last clip index to keep track of the current position
                _lastPlayedClipIndex = randomIndex;
            }
            catch (Exception e)
            {
                SuperController.LogError($"AudioMate.{nameof(AudioMateClipCollection)}.{nameof(GetRandomClip)}: randomIndex: {randomIndex} {e}");
            }

            return(randomClip);
        }
Exemplo n.º 25
0
 public NodeModel this[int index]
 {
     get { return(items.ElementAtOrDefault(index)); }
 }
Exemplo n.º 26
0
        static void Main(string[] args)
        {
            List <int> numbers = new List <int>()
            {
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10
            };

            //ElementAt

            Console.WriteLine("______________________________ElementAt_______________________________");
            //The ElementAt operator is used to return an element from a specific index.
            //Throws ArgumentOutOfRange Exception in case of specific index out of range.

            int MethodSyntax = numbers.ElementAt(1);

            Console.WriteLine(MethodSyntax);

            var eleat1 = (from num in numbers
                          select num).ElementAt(1);

            Console.WriteLine(eleat1);
            try
            {
                Console.WriteLine(numbers.ElementAt(10));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }



            // ElementAtOrDefault
            Console.WriteLine("\n________________________________ElementAtDefault______________________________");
            //Returns a default value in case the specific index is out of range.
            Console.WriteLine(numbers.ElementAtOrDefault(8));
            Console.WriteLine($"index out of range so it returns default value without any exceptioins {0}    :     ", numbers.ElementAtOrDefault(15));
            var eleat2 = (from num in numbers
                          select num).ElementAtOrDefault(99);

            Console.WriteLine(eleat2);


            //First
            Console.WriteLine("\n__________________________________First__________________________________________");
            //The Linq First Method is used to return the first element from a data source
            //Throws invalidOperationException in case of it's failed with condition
            Console.WriteLine(numbers.First());
            Console.WriteLine(numbers.First(num => num > 5));
            Console.WriteLine(numbers.First(num => num % 2 == 0));

            var first1 = (from num in numbers
                          select num).First(num => num % 2 == 0);

            Console.WriteLine(first1);
            //Console.WriteLine(numbers.First(num => num > 50));  => throws exception

            Console.WriteLine("\n_______________________________________FirstOrDefault_________________________________");
            //it returns a default value of a specified generic type, instead of throwing an exception if no element found for the specified condition.
            //Returns Null in case it's failed with condition
            Console.WriteLine(numbers.FirstOrDefault());
            Console.WriteLine(numbers.FirstOrDefault(num => num > 500));


            var first2 = (from num in numbers
                          select num).FirstOrDefault();

            Console.WriteLine(first2);


            Console.WriteLine("\n_______________________________________Last_____________________________________________");
            //The Last Method in Linq is used to return the last element from a data source
            //InvalidOperationException in case of sequence contain no element
            Console.WriteLine(numbers.Last());
            Console.WriteLine(numbers.Last(num => num % 2 == 0));
            Console.WriteLine(numbers.Last(num => num % 4 == 0));

            var last1 = (from num in numbers
                         select num).Last();

            Console.WriteLine(last1);

            Console.WriteLine("\n______________________________________LastOrDefault______________________________________");
            //it returns a default value of a specified generic type, instead of throwing an exception if no element found for the specified condition.
            Console.WriteLine(numbers.LastOrDefault());
            Console.WriteLine(numbers.LastOrDefault(num => num > 11));

            var last2 = (from num in numbers
                         select num).LastOrDefault();

            Console.WriteLine(last2);


            Console.WriteLine("\n_____________________________________________Single___________________________________________");

            //The Linq Single Method is used to returns a single element from a data source or you can say from a sequence.
            //Exception occured in these three conditions
            //  1) If the data source is empty.
            //  2)When the given condition does not satisfy any element in the sequence.
            //  3)If the given condition satisfies more than one element.
            Console.WriteLine(numbers.Single(num => num == 5));

            var single1 = (from num in numbers
                           select num).Single(num => num == 5);

            Console.WriteLine(single1);

            Console.WriteLine("\n______________________________________________SingleOrDefault____________________________________");
            //it returns a default value of a specified generic type, instead of throwing an exception if no element found for the specified condition.
            //System.InvalidOperationException: 'Sequence contains more than one matching element'
            //Console.WriteLine(numbers.SingleOrDefault(num => num%2 ==0));
            Console.WriteLine(numbers.SingleOrDefault(num => num > 10));

            var single2 = (from num in numbers
                           select num).SingleOrDefault(num => num > 10);

            Console.WriteLine(single2);
        }
Exemplo n.º 27
0
        private DiffResult GenerateDiffResult()
        {
            for (int i = 0; i < NA.Count; i++)
            {
                if (NA[i].OC != DiffCounter.Zero &&
                    NA[i].NC != DiffCounter.Zero)
                {
                    if (NA[i].OC == NA[i].NC &&
                        NA[i].OC == DiffCounter.One &&
                        NA[i].NC == DiffCounter.One)
                    {
                        var olno = NA[i].OLNO ?? null;

                        if (olno != null)
                        {
                            NA[i].Index = olno.Value;
                            if (OA.ElementAtOrDefault(olno.Value) != null)
                            {
                                OA[olno.Value].Index = i;
                            }
                        }
                    }
                }
            }


            var smallestUpperBound = Math.Min(NA.Count, OA.Count);

            for (var i = 0; i < smallestUpperBound; i++)
            {
                // Do something with collection1[index] and collection2[index]
                if (NA[i].Line.Equals(OA[i].Line) &&
                    (IsInTable(NA[i + 1]) &&
                     IsInTable(OA[i + 1])))
                {
                    var oline = ((List <ITextLine>)O.Lines).ElementAtOrDefault(i + 1);
                    if (oline != null && OA.ElementAtOrDefault(i + 1) != null)
                    {
                        var line = (ITextLine)table[oline.Line];
                        OA[i + 1] = line;
                    }

                    var nline = ((List <ITextLine>)N.Lines).ElementAtOrDefault(i + 1);
                    if (nline != null && NA.ElementAtOrDefault(i + 1) != null)
                    {
                        var line = (ITextLine)table[nline.Line];
                        NA[i + 1] = line;
                    }
                }
            }

            for (var i = smallestUpperBound - 1; i >= 1; i--)
            {
                if (NA[i].Line.Equals(OA[i].Line) &&
                    (IsInTable(NA[i - 1]) &&
                     IsInTable(OA[i - 1])))
                {
                    var oline = ((List <ITextLine>)O.Lines).ElementAtOrDefault(i - 1);
                    if (oline != null && OA.ElementAtOrDefault(i - 1) != null)
                    {
                        var line = (ITextLine)table[oline.Line];
                        OA[i - 1] = line;
                    }

                    var nline = ((List <ITextLine>)N.Lines).ElementAtOrDefault(i - 1);
                    if (nline != null && NA.ElementAtOrDefault(i - 1) != null)
                    {
                        var line = (ITextLine)table[nline.Line];
                        NA[i - 1] = line;
                    }
                }
            }
            //NA[i] = table[line] and NA[i].Olno = null then its a new Line in NA
            //if NA[i] == OA[i] but NA[i+1] != OA[i+1]
            var diffNA = new Diff[table.Count];
            var diffOA = new Diff[table.Count];

            return(null);
        }
Exemplo n.º 28
0
		/// <summary>
		/// Inlines the stloc instruction at block.Body[pos] into the next instruction, if possible.
		/// </summary>
		public bool InlineOneIfPossible(List<AstNode> body, int pos, bool aggressive)
		{
			AstVariable v;
			AstExpression inlinedExpression;
			if (body[pos].Match(AstCode.Stloc, out v, out inlinedExpression) && !v.IsPinned) {
				if (InlineIfPossible(v, inlinedExpression, body.ElementAtOrDefault(pos+1), aggressive)) {
					// Assign the ranges of the stloc instruction:
					inlinedExpression.ILRanges.AddRange(((AstExpression)body[pos]).ILRanges);
					// Remove the stloc instruction:
					body.RemoveAt(pos);
					return true;
				} else if (numLdloc.GetOrDefault(v) == 0 && numLdloca.GetOrDefault(v) == 0) {
					// The variable is never loaded
					if (inlinedExpression.HasNoSideEffects()) {
						// Remove completely
						body.RemoveAt(pos);
						return true;
					} else if (inlinedExpression.CanBeExpressionStatement() && v.IsGenerated) {
						// Assign the ranges of the stloc instruction:
						inlinedExpression.ILRanges.AddRange(((AstExpression)body[pos]).ILRanges);
						// Remove the stloc, but keep the inner expression
						body[pos] = inlinedExpression;
						return true;
					}
				}
			}
			return false;
		}
 public WearAuthenticator Get(int position)
 {
     return(_view.ElementAtOrDefault(position));
 }
Exemplo n.º 30
0
        public Resultados <AgrotoxicoFiltro> Filtrar(Filtro <AgrotoxicoFiltro> filtros)
        {
            Resultados <AgrotoxicoFiltro> retorno = new Resultados <AgrotoxicoFiltro>();

            using (BancoDeDados bancoDeDados = BancoDeDados.ObterInstancia())
            {
                string  comandtxt = string.Empty;
                Comando comando   = bancoDeDados.CriarComando("");

                #region Adicionando Filtros

                comandtxt += comando.FiltroAndLike("a.nome_comercial", "nome_comercial", filtros.Dados.NomeComercial, true, true);

                comandtxt += comando.FiltroAnd("a.numero_cadastro", "numero_cadastro", filtros.Dados.NumeroCadastro);

                comandtxt += comando.FiltroAnd("a.numero_registro_ministerio", "numero_registro_ministerio", filtros.Dados.NumeroRegistroMinisterio);

                if (filtros.Dados.Situacao != "0")
                {
                    comandtxt += comando.FiltroAnd("a.cadastro_ativo", "cadastro_ativo", (filtros.Dados.Situacao != "1"?"0":"1"));
                }

                if (filtros.Dados.ClasseUso > 0)
                {
                    comandtxt += comando.FiltroIn("a.id", "select t1.agrotoxico from tab_agrotoxico_classe_uso t1 where t1.classe_uso =:classe_uso", "classe_uso", filtros.Dados.ClasseUso);
                }

                if (filtros.Dados.ModalidadeAplicacao > 0)
                {
                    comandtxt += comando.FiltroIn("a.id", "select t10.agrotoxico from tab_agro_cult_moda_aplicacao t9, tab_agrotoxico_cultura t10 where t9.agrotoxico_cultura = t10.id and t9.modalidade_aplicacao = :modalidade_aplicacao", "modalidade_aplicacao", filtros.Dados.ModalidadeAplicacao);
                }

                if (filtros.Dados.GrupoQuimico > 0)
                {
                    comandtxt += comando.FiltroIn("a.id", "select t11.agrotoxico from tab_agrotoxico_grupo_quimico t11 where t11.grupo_quimico = :grupo_quimico", "grupo_quimico", filtros.Dados.GrupoQuimico);
                }

                comandtxt += comando.FiltroAnd("a.classificacao_toxicologica", "classificacao_toxicologica", filtros.Dados.ClassificacaoToxicologica);

                if (!String.IsNullOrWhiteSpace(filtros.Dados.TitularRegistro))
                {
                    comandtxt += comando.FiltroAndLike("nvl(p.nome, p.razao_social)", "titular_registro", filtros.Dados.TitularRegistro, true, true);
                }

                comandtxt += comando.FiltroAnd("a.numero_processo_sep", "numero_processo_sep", filtros.Dados.NumeroProcessoSep);

                if (!String.IsNullOrWhiteSpace(filtros.Dados.IngredienteAtivo))
                {
                    comandtxt += comando.FiltroIn("a.id", "select t3.agrotoxico from tab_ingrediente_ativo t2, tab_agrotoxico_ing_ativo t3 where t2.id = t3.ingrediente_ativo and upper(t2.texto) like upper('%'||:ingrediente||'%')", "ingrediente", filtros.Dados.IngredienteAtivo);
                }

                if (!String.IsNullOrWhiteSpace(filtros.Dados.Cultura))
                {
                    comandtxt += comando.FiltroIn("a.id", "select t5.agrotoxico from tab_cultura t4, tab_agrotoxico_cultura t5 where t4.id = t5.cultura and upper(t4.texto) like upper('%'||:cultura||'%')", "cultura", filtros.Dados.Cultura);
                }

                if (!String.IsNullOrWhiteSpace(filtros.Dados.Praga))
                {
                    comandtxt += comando.FiltroIn(@"a.id", "select t8.agrotoxico from tab_praga t6, tab_agrotoxico_cultura_praga t7, tab_agrotoxico_cultura t8 where t6.id = t7.praga and t7.agrotoxico_cultura = t8.id and upper(nvl(t6.nome_cientifico, t6.nome_comum)) like upper('%'||:praga||'%')", "praga", filtros.Dados.Praga);
                }

                List <String> ordenar = new List <String>();
                List <String> colunas = new List <String>()
                {
                    "numero_cadastro", "nome_comercial", "titular_registro", "situacao"
                };

                if (filtros.OdenarPor > 0)
                {
                    ordenar.Add(colunas.ElementAtOrDefault(filtros.OdenarPor - 1));
                }
                else
                {
                    ordenar.Add("numero_cadastro");
                }
                #endregion

                #region Executa a pesquisa nas tabelas

                comando.DbCommand.CommandText = String.Format(@"select count(a.id) qtd from tab_agrotoxico a, tab_pessoa p where a.titular_registro = p.id " + comandtxt);

                retorno.Quantidade = Convert.ToInt32(bancoDeDados.ExecutarScalar(comando));

                if (retorno.Quantidade < 1)
                {
                    Validacao.Add(Mensagem.Funcionario.NaoEncontrouRegistros);
                    return(retorno);
                }

                comando.AdicionarParametroEntrada("menor", filtros.Menor);
                comando.AdicionarParametroEntrada("maior", filtros.Maior);

                comandtxt = String.Format(@"select a.id, (case when a.possui_cadastro>0 then 'Sim' else 'Não' end)  possui_cadastro,
				(case when a.cadastro_ativo>0 then 'Ativo' else 'Inativo' end) situacao, a.numero_cadastro, a.nome_comercial, 
				nvl(p.nome, p.razao_social) titular_registro, a.arquivo from tab_agrotoxico a, tab_pessoa p where a.titular_registro = p.id {0} {1}"                ,
                                          comandtxt, DaHelper.Ordenar(colunas, ordenar));

                comando.DbCommand.CommandText = @"select * from (select a.*, rownum rnum from ( " + comandtxt + @") a) where rnum <= :maior and rnum >= :menor";

                #endregion

                using (IDataReader reader = bancoDeDados.ExecutarReader(comando))
                {
                    #region Adicionando os dados na classe de retorno

                    AgrotoxicoFiltro agro;
                    while (reader.Read())
                    {
                        agro                 = new AgrotoxicoFiltro();
                        agro.Id              = reader.GetValue <Int32>("id");
                        agro.ArquivoId       = reader.GetValue <Int32>("arquivo");
                        agro.NumeroCadastro  = reader.GetValue <String>("numero_cadastro");
                        agro.NomeComercial   = reader.GetValue <String>("nome_comercial");
                        agro.TitularRegistro = reader.GetValue <String>("titular_registro");
                        agro.Situacao        = reader.GetValue <String>("situacao");

                        retorno.Itens.Add(agro);
                    }

                    reader.Close();
                    #endregion
                }
            }

            return(retorno);
        }
Exemplo n.º 31
0
 public override IMenuComponent TryGetChild(int i)
 {
     return(_menuComponents.ElementAtOrDefault(i));
 }
Exemplo n.º 32
0
        public DataTable GetReportTable(TaskValidationResult task, DataTable existingTable = null, List <ValidationOutcome> outcomes = null)
        {
            var table = new DataTable(task.task.name + "_prop_validation");

            table.SetDescription("Property validation results for task [" + task.task.name + "]");


            var column_task = table.Columns.Add("Task").SetWidth(25);


            var column_propertyName = table.Columns.Add("Property").SetGroup("Declaration").SetWidth(20);

            var column_propertyType = table.Columns.Add("Type").SetGroup("Declaration").SetWidth(10);

            var column_contentType = table.Columns.Add("Content").SetGroup("Declaration").SetWidth(10);

            var column_valueformat = table.Columns.Add("Format").SetGroup("Declaration").SetWidth(10);

            var column_frequency = table.Columns.Add("Frequency").SetWidth(10);

            var column_outcome = table.Columns.Add("Outcome").SetGroup("Result").SetWidth(10);

            var column_message = table.Columns.Add("Comment").SetGroup("Result").SetWidth(50);



            var column_linkedNode = table.Columns.Add("Node").SetWidth(10).SetGroup("Values");



            var column_DistinctValues = table.Columns.Add("Distinct").SetGroup("Values").SetWidth(10);
            var column_examplevalues1 = table.Columns.Add("Example1").SetGroup("Values").SetWidth(25).SetHeading("Example").SetDesc("Example value found at the property");
            var column_examplevalues2 = table.Columns.Add("Example2").SetGroup("Values").SetWidth(25).SetHeading("Example").SetDesc("Example value found at the property");
            var column_examplevalues3 = table.Columns.Add("Example3").SetGroup("Values").SetWidth(25).SetHeading("Example").SetDesc("Example value found at the property");
            var column_examplevalues4 = table.Columns.Add("Example4").SetGroup("Values").SetWidth(25).SetHeading("Example").SetDesc("Example value found at the property");
            var column_examplevalues5 = table.Columns.Add("Example5").SetGroup("Values").SetWidth(25).SetHeading("Example").SetDesc("Example value found at the property");

            var column_SpamPropertyMeasure = table.Columns.Add("SpamPropertyMeasure").SetGroup("Values").SetHeading("Spam").SetDesc("Measure describing probability that this property is a spam property").SetFormat("F3").SetWidth(10);


            var column_allcontenttypes = table.Columns.Add("All types").SetWidth(100);



            var column_xpath = table.Columns.Add("XPath").SetWidth(100);



            var results = GetResults();

            foreach (var rpair in results)
            {
                table.SetAdditionalInfoEntry(rpair.Key.ToString(), rpair.Value.Count, "Number of properties having outcome [" + rpair.Key.ToString() + "]");
            }


            DataTable targetTable = table;

            if (existingTable != null)
            {
                targetTable = existingTable;
            }

            if (outcomes == null)
            {
                outcomes = new List <ValidationOutcome>()
                {
                    ValidationOutcome.Validated, ValidationOutcome.Modified, ValidationOutcome.Invalid, ValidationOutcome.undefined
                };
            }

            foreach (var oc in outcomes)
            {
                submethod(results[oc], targetTable);
            }


            void submethod(IEnumerable <TaskPropertyValidation> plist, DataTable _targetTable = null)
            {
                foreach (TaskPropertyValidation p in plist)
                {
                    var dr = _targetTable.NewRow();

                    dr[column_task.ColumnName] = task.task.name;
                    dr[column_SpamPropertyMeasure.ColumnName] = p.SpamPropertyMeasure;

                    List <string> d_vals = p.ValueCounter.GetDistinctItems().trimToLimit(25, true, "...", false, true);

                    dr[column_DistinctValues.ColumnName] = p.DistinctValues;

                    dr[column_examplevalues1.ColumnName] = d_vals.ElementAtOrDefault(0);
                    dr[column_examplevalues2.ColumnName] = d_vals.ElementAtOrDefault(1);
                    dr[column_examplevalues3.ColumnName] = d_vals.ElementAtOrDefault(2);
                    dr[column_examplevalues4.ColumnName] = d_vals.ElementAtOrDefault(3);
                    dr[column_examplevalues5.ColumnName] = d_vals.ElementAtOrDefault(4);

                    dr[column_propertyType.ColumnName] = p.item.ValueTypeName;         // source.propertyType;

                    dr[column_frequency.ColumnName] = p.Frequency;                     //.GetRatio(task.score.metaPropertyNameCounter.DistinctCount());

                    dr[column_SpamPropertyMeasure.ColumnName] = p.SpamPropertyMeasure; //f.GetRatio(validation_calls); //source.persistance;

                    dr[column_propertyName.ColumnName] = p.item.PropertyName;          // source.propertyName;

                    dr[column_message.ColumnName] = p.Message;                         // source.message;

                    dr[column_outcome.ColumnName]    = p.Outcome;
                    dr[column_linkedNode.ColumnName] = p.LinkedNodes;                  // source.linkedNode;

                    dr[column_contentType.ColumnName] = p.item.ContentType.ToString(); // source.contentType;
                    dr[column_valueformat.ColumnName] = p.item.ValueFormat;            // source.valueformat;

                    dr[column_allcontenttypes.ColumnName] = p.item.AllContentTypes.getEnumListFromFlags <CellContentType>().toCsvInLine();
                    dr[column_xpath.ColumnName]           = p.XPath; //.xpath;
                    _targetTable.Rows.Add(dr);
                }
            }

            return(targetTable);
        }
        public Dictionary<TemplateModel, List<FieldCodeSummaryModel>> ProcessDocumentTemplates(string connectionString)
        {
            Application wordApplication = this.Initialise();

            var analysisData = new Dictionary<TemplateModel, List<FieldCodeSummaryModel>>();
            try
            {
                using (var sqlConnection = new SqlConnection(connectionString))
                {
                    sqlConnection.Open();

                    var noOfTemplates = GetNoOfTemplates(sqlConnection);
                    var reader = GetData(sqlConnection);

                    if (reader.HasRows)
                    {
                        var index = 1;
                        var threads = new List<Thread>();
                        while (reader.Read())
                        {
                            var templateName = reader.GetString(4);
                            var docContent = (byte[])reader["DocContent"];

                            threads.Add(new Thread(() => ParseTemplate(analysisData, wordApplication, noOfTemplates, templateName, docContent, ref index)));
                        }

                        const int threadCount = 8;

                        for (var j = 0; j < Math.Ceiling((double)threads.Count / threadCount); j++)
                        {
                            var threadsToKickOff = new List<Thread>();
                            for (var k = 0; k < threadCount; k++)
                            {
                                var theIndexWeWant = (j * threadCount) + k;

                                Debug.WriteLine("index is {0}", theIndexWeWant);
                                var aThread = threads.ElementAtOrDefault(theIndexWeWant);
                                if (aThread != null)
                                {
                                    threadsToKickOff.Add(aThread);
                                }
                            }

                            threadsToKickOff.ForEach(t => t.Start());
                            threadsToKickOff.ForEach(t => t.Join());
                        }
                    }

                    return analysisData;
                }
            }
            finally
            {
                this.Cleanup(wordApplication);
            }
        }
Exemplo n.º 34
0
        public static string decompress(string compressed)
        {

            Decompress_Data data = new Decompress_Data();

            List<string> dictionary = new List<string>();
            int next = 0;
            int enlargeIn = 4;
            int numBits = 3;
            string entry = "";
            string result = "";
            int i = 0;
            dynamic w = "";
            dynamic c = "";
            int errorCount = 0;

            data.str = compressed;
            data.val = (int)compressed[0];
            data.position = 32768;
            data.index = 1;

            try
            {
                for (i = 0; i < 3; i++)
                {
                    dictionary.Add(i.ToString());
                }

                next = readBits(2, data);

                switch (next)
                {
                    case 0:
                        c = Convert.ToChar(readBits(8, data)).ToString();
                        break;
                    case 1:
                        c = Convert.ToChar(readBits(16, data)).ToString();
                        break;
                    case 2:
                        return "";
                }

                dictionary.Add(c);
                w = result = c;

                while (true)
                {
                    c = readBits(numBits, data);
                    int cc = (int)(c);

                    switch (cc)
                    {
                        case 0:
                            if (errorCount++ > 10000)
                                throw new Exception("To many errors");

                            c = Convert.ToChar(readBits(8, data)).ToString();
                            dictionary.Add(c);
                            c = dictionary.Count - 1;
                            enlargeIn--;

                            break;
                        case 1:
                            c = Convert.ToChar(readBits(16, data)).ToString();
                            dictionary.Add(c);
                            c = dictionary.Count - 1;
                            enlargeIn--;

                            break;
                        case 2:
                            return result;
                    }

                    if (enlargeIn == 0)
                    {
                        enlargeIn = (int)Math.Pow(2, numBits);
                        numBits++;
                    }


                    if (dictionary.ElementAtOrDefault((int)c) != null) // if (dictionary[c] ) <------- original Javascript Equivalant
                    {
                        entry = dictionary[c];
                    }
                    else
                    {
                        if (c == dictionary.Count)
                        {
                            entry = w + w[0];
                        }
                        else
                        {
                            return null;
                        }
                    }

                    result += entry;
                    dictionary.Add(w + entry[0]);
                    enlargeIn--;
                    w = entry;

                    if (enlargeIn == 0)
                    {
                        enlargeIn = (int)Math.Pow(2, numBits);
                        numBits++;
                    }
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
		bool TransformArrayInitializers(List<ILNode> body, ILExpression expr, int pos)
		{
			ILVariable v, v2, v3;
			ILExpression newarrExpr;
			TypeReference arrayType;
			ILExpression lengthExpr;
			int arrayLength;
			if (expr.Match(ILCode.Stloc, out v, out newarrExpr) &&
			    newarrExpr.Match(ILCode.Newarr, out arrayType, out lengthExpr) &&
			    lengthExpr.Match(ILCode.Ldc_I4, out arrayLength) &&
			    arrayLength > 0)
			{
				MethodReference methodRef;
				ILExpression methodArg1;
				ILExpression methodArg2;
				FieldDefinition field;
				if (body.ElementAtOrDefault(pos + 1).Match(ILCode.Call, out methodRef, out methodArg1, out methodArg2) &&
				    methodRef.DeclaringType.FullName == "System.Runtime.CompilerServices.RuntimeHelpers" &&
				    methodRef.Name == "InitializeArray" &&
				    methodArg1.Match(ILCode.Ldloc, out v2) &&
				    v == v2 &&
				    methodArg2.Match(ILCode.Ldtoken, out field) &&
				    field != null && field.InitialValue != null)
				{
					ILExpression[] newArr = new ILExpression[arrayLength];
					if (DecodeArrayInitializer(TypeAnalysis.GetTypeCode(arrayType), field.InitialValue, newArr)) {
						body[pos] = new ILExpression(ILCode.Stloc, v, new ILExpression(ILCode.InitArray, arrayType, newArr));
						body.RemoveAt(pos + 1);
						new ILInlining(method).InlineIfPossible(body, ref pos);
						return true;
					}
				}
				
				// Put in a limit so that we don't consume too much memory if the code allocates a huge array
				// and populates it extremely sparsly. However, 255 "null" elements in a row actually occur in the Mono C# compiler!
				const int maxConsecutiveDefaultValueExpressions = 300;
				List<ILExpression> operands = new List<ILExpression>();
				int numberOfInstructionsToRemove = 0;
				for (int j = pos + 1; j < body.Count; j++) {
					ILExpression nextExpr = body[j] as ILExpression;
					int arrayPos;
					if (nextExpr != null &&
					    nextExpr.Code.IsStoreToArray() &&
					    nextExpr.Arguments[0].Match(ILCode.Ldloc, out v3) &&
					    v == v3 &&
					    nextExpr.Arguments[1].Match(ILCode.Ldc_I4, out arrayPos) &&
					    arrayPos >= operands.Count &&
					    arrayPos <= operands.Count + maxConsecutiveDefaultValueExpressions)
					{
						while (operands.Count < arrayPos)
							operands.Add(new ILExpression(ILCode.DefaultValue, arrayType));
						operands.Add(nextExpr.Arguments[2]);
						numberOfInstructionsToRemove++;
					} else {
						break;
					}
				}
				if (operands.Count == arrayLength) {
					expr.Arguments[0] = new ILExpression(ILCode.InitArray, arrayType, operands);
					body.RemoveRange(pos + 1, numberOfInstructionsToRemove);
					
					new ILInlining(method).InlineIfPossible(body, ref pos);
					return true;
				}
			}
			return false;
		}
Exemplo n.º 36
0
        void post_initialize(bool arrange_tokens , InitializeParam param)
        {
            tokens = text.Parse();
            var f = tokens.ElementAtOrDefault(0);
            Debug.Assert(f != null);

            //正文的第一行作为标题
            if(f.tag == TokenTypes.Part && f.text.Length < 20)//不要很长的标题
            {
                topic_source = WeiboTopicSource.FirstSentence;
                topic = f.text.Trim();
            }
           // var url = string.Empty;
            //正文有标题
            foreach(var t in tokens)
            {
                if (t.tag == TokenTypes.Topic)
                {
                    topic = t.text;
                    topic_source = WeiboTopicSource.Trend;
                    //break;
                }
                if(t.tag == TokenTypes.Quote && topic_source == WeiboTopicSource.Reserved)
                {
                    topic_source = WeiboTopicSource.Quote;
                    topic = t.text.Trim();
                }
                if(t.tag == TokenTypes.Hyperlink && t.text.Contains("http://t.cn/"))
                {
                    if (param.url == null)
                        param.url = t.text;
                }
            }
            if(retweeted_status != null)
            {
                //使用rt中的标题
                if(retweeted_status.topic_source != WeiboTopicSource.Reserved)
                {
                    topic_source = WeiboTopicSource.Retweeted;
                    topic = retweeted_status.topic;
                }

                if (retweeted_status.has_pic && !has_pic)
                {
                    has_pic = true;
                    bmiddle_pic = retweeted_status.bmiddle_pic;
                    thumbnail_pic = retweeted_status.thumbnail_pic;

                    thumb_pic_width = retweeted_status.thumb_pic_width;
                    thumb_pic_height = retweeted_status.thumb_pic_height;
                }
                
            }

            //在使用正文首行作为标题前,如果有url的标题,就用url标题
            if(!string.IsNullOrEmpty(param.url))
                fetch_url_info(param.url);

            if (arrange_tokens == false)
                return;

            if(retweeted_status != null)
            {
                if(tokens.Count > 0)
                    tokens.Insert(0,new Token{tag = TokenTypes.Writer, text = user.screen_name});
                tokens.Insert(0, new Token { tag = TokenTypes.Break });
                tokens.Insert(0, new Token { tag = TokenTypes.Break });
                tokens.InsertRange(0,retweeted_status.tokens);
            }

            //从正文中删除标题内容
            if (tokens.Count > 0 && topic == tokens[0].text)
            {
                tokens.RemoveAt(0);//去掉第一句
            }
            //去除正文开始的标点
            while (tokens.Count > 0)
            {
                var tag =tokens[0].tag;
                if ( (tag== TokenTypes.Punctuation || tag == TokenTypes.Break) && tokens[0].text != "《")
                    tokens.RemoveAt(0);
                else
                    break;
            }
        }
Exemplo n.º 37
0
        public static T Parse <T>(Action <bool> extraHelp, string[] args) where T : ICLIFlags
        {
            if (args.Length == 0)
            {
                FullHelp <T>(extraHelp);
                return(null);
            }

            var iface = typeof(T);

            if (!(Activator.CreateInstance(iface) is T instance))
            {
                return(null);
            }

            var presence         = new HashSet <string>();
            var positionals      = new List <object>();
            var values           = new Dictionary <string, string>();
            var dictionaryValues = new Dictionary <string, Dictionary <string, string> >();
            var arrayValues      = new Dictionary <string, List <string> >();

            var fields = iface.GetFields();

            foreach (var field in fields)
            {
                var flagattr = field.GetCustomAttribute <CLIFlagAttribute>(true);
                if (flagattr == null || flagattr.AllPositionals)
                {
                    continue;
                }
                var t = field.FieldType;
                if (t.IsGenericType &&
                    t.GetGenericTypeDefinition()
                    .IsAssignableFrom(typeof(Dictionary <,>)))
                {
                    var aliasattrs = field.GetCustomAttributes <AliasAttribute>(true)
                                     .ToArray();
                    if (aliasattrs.Length > 0)
                    {
                        foreach (var aliasattr in aliasattrs)
                        {
                            dictionaryValues.Add(aliasattr.Alias, new Dictionary <string, string>());
                        }
                    }
                    dictionaryValues.Add(flagattr.Flag, new Dictionary <string, string>());
                }

                if (t.IsGenericType &&
                    t.GetGenericTypeDefinition()
                    .IsAssignableFrom(typeof(List <>)))
                {
                    var aliasattrs = field.GetCustomAttributes <AliasAttribute>(true)
                                     .ToArray();
                    if (aliasattrs.Length > 0)
                    {
                        foreach (var aliasattr in aliasattrs)
                        {
                            arrayValues.Add(aliasattr.Alias, new List <string>());
                        }
                    }
                    arrayValues.Add(flagattr.Flag, new List <string>());
                }
            }

            for (var i = 0; i < args.Length; ++i)
            {
                var arg = args[i];
                if (arg[0] == '-')
                {
                    if (arg[1] == '-')
                    {
                        var name  = arg.Substring(2);
                        var value = "true";
                        if (name.Contains('='))
                        {
                            value = name.Substring(name.IndexOf('=') + 1);
                            name  = name.Substring(0, name.IndexOf('='));
                        }

                        presence.Add(name);
                        if (dictionaryValues.ContainsKey(name))
                        {
                            var key = args[++i];
                            if (key.Contains('='))
                            {
                                value = key.Substring(key.IndexOf('=') + 1);
                                key   = key.Substring(0, key.IndexOf('='));
                            }

                            dictionaryValues[name][key] = value;
                        }
                        else if (arrayValues.ContainsKey(name))
                        {
                            arrayValues[name]
                            .Add(args[++i]);
                        }
                        else
                        {
                            values[name] = value;
                        }
                    }
                    else
                    {
                        var letters = arg.Substring(1)
                                      .ToArray();
                        foreach (var letter in letters)
                        {
                            if (letter == '=')
                            {
                                break;
                            }
                            if (letter == '?' || letter == 'h')
                            {
                                Help <T>(false, new Dictionary <string, string>());
                                extraHelp?.Invoke(true);
                                return(null);
                            }

                            presence.Add(letter.ToString());

                            var value = "true";
                            if (arg.Contains('='))
                            {
                                value = arg.Substring(arg.IndexOf('=') + 1);
                            }
                            var name = letter.ToString();
                            if (dictionaryValues.ContainsKey(name))
                            {
                                var key = args[++i];
                                if (key.Contains('='))
                                {
                                    value = key.Substring(key.IndexOf('=') + 1);
                                    key   = key.Substring(0, key.IndexOf('='));
                                }

                                dictionaryValues[name][key] = value;
                            }
                            else if (arrayValues.ContainsKey(name))
                            {
                                arrayValues[name]
                                .Add(args[++i]);
                            }
                            else
                            {
                                values[name] = value;
                            }
                        }
                    }
                }
                else
                {
                    positionals.Add(arg);
                }
            }


            var flagAttributes = fields.Select(x => (field: x, attribute: x.GetCustomAttribute <CLIFlagAttribute>(true)))
                                 .Where(x => x.attribute != null)
                                 .OrderBy(x => x.attribute.Positional)
                                 .ToArray();

            var positionalsField = default(FieldInfo);


            var newPositionals = new List <object>(Enumerable.Repeat(default(object), Math.Max(positionals.Count, flagAttributes.Max(x => x.attribute.Positional) + 1)));

            var positionalTicker = 0;

            foreach (var(field, flagAttribute) in flagAttributes.Where(x => x.attribute.Positional > -1))
            {
                if (!field.GetCustomAttributes <AliasAttribute>().Select(x => x.Alias).Concat(new[] { flagAttribute.Flag }).Any(x => presence.Contains(x)))
                {
                    newPositionals[flagAttribute.Positional] = positionals.ElementAtOrDefault(flagAttribute.Positional);
                    positionalTicker += 1;
                }
            }

            foreach (var positional in positionals.Skip(positionalTicker))
            {
                newPositionals[positionalTicker] = positionals.ElementAtOrDefault(positionalTicker);
                positionalTicker += 1;
            }

            positionals = newPositionals;

            foreach (var(field, flagAttribute) in flagAttributes)
            {
                if (flagAttribute.AllPositionals)
                {
                    positionalsField = field;
                    continue;
                }

                var kind = FieldKind.Default;
                var t    = field.FieldType;
                if (t.IsGenericType &&
                    t.GetGenericTypeDefinition()
                    .IsAssignableFrom(typeof(Dictionary <,>)))
                {
                    kind = FieldKind.Dictionary;
                }
                else if (t.IsGenericType &&
                         t.GetGenericTypeDefinition()
                         .IsAssignableFrom(typeof(List <>)))
                {
                    kind = FieldKind.Array;
                }
                var    value         = flagAttribute.Default;
                object key           = string.Empty;
                var    insertedValue = false;
                if (flagAttribute.Positional > -1 && positionals.Count > flagAttribute.Positional && positionals[flagAttribute.Positional] != null)
                {
                    value = positionals[flagAttribute.Positional] ?? value;
                }

                if (!string.IsNullOrWhiteSpace(flagAttribute.Flag))
                {
                    if (!presence.Contains(flagAttribute.Flag))
                    {
                        var aliasattrs = field.GetCustomAttributes <AliasAttribute>(true)
                                         .ToArray();
                        if (aliasattrs.Length > 0)
                        {
                            foreach (var aliasattr in aliasattrs)
                            {
                                if (presence.Contains(aliasattr.Alias))
                                {
                                    insertedValue = true;
                                    if (kind == FieldKind.Default)
                                    {
                                        value = values[aliasattr.Alias];
                                    }
                                    else if (kind == FieldKind.Dictionary)
                                    {
                                        value = dictionaryValues[aliasattr.Alias];
                                    }
                                    else if (kind == FieldKind.Array)
                                    {
                                        value = arrayValues[aliasattr.Alias];
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        insertedValue = true;
                        if (kind == FieldKind.Default)
                        {
                            value = values[flagAttribute.Flag];
                        }
                        else if (kind == FieldKind.Dictionary)
                        {
                            value = dictionaryValues[flagAttribute.Flag];
                        }
                        else if (kind == FieldKind.Array)
                        {
                            value = arrayValues[flagAttribute.Flag];
                        }
                    }

                    if (flagAttribute.Positional > 0)
                    {
                    }
                }

                if (value != null)
                {
                    if (flagAttribute.Valid != null)
                    {
                        if (!flagAttribute.Valid.Contains(value.ToString()))
                        {
                            Console.Error.WriteLine($"Value {value} is invalid for flag {flagAttribute.Flag}, valid values are {string.Join(", ", flagAttribute.Valid)}");
                            FullHelp <T>(extraHelp);
                            return(null);
                        }
                    }

                    if (flagAttribute.Parser != null && insertedValue && flagAttribute.Parser.Length == 2)
                    {
                        var parserclass = Type.GetType(flagAttribute.Parser[0]);
                        var method      = parserclass?.GetMethod(flagAttribute.Parser[1]);
                        if (method != null)
                        {
                            var @params = method.GetParameters();
                            if (kind == FieldKind.Default)
                            {
                                if (@params.Length == 1 &&
                                    @params[0]
                                    .ParameterType.Name ==
                                    "String" &&
                                    method.ReturnType.Name == "Object")
                                {
                                    value = method.Invoke(null, new object[] { (string)value });
                                }
                            }
                            else if (kind == FieldKind.Dictionary)
                            {
                                if (@params.Length == 1 &&
                                    @params[0]
                                    .ParameterType.Name ==
                                    "Dictionary`2" &&
                                    method.ReturnType.Name == "Object")
                                {
                                    value = method.Invoke(null, new object[] { (Dictionary <string, string>)value });
                                }
                            }
                            else if (kind == FieldKind.Array)
                            {
                                if (@params.Length == 1 &&
                                    @params[0]
                                    .ParameterType.Name ==
                                    "List`1" &&
                                    method.ReturnType.Name == "Object")
                                {
                                    value = method.Invoke(null, new object[] { (List <string>)value });
                                }
                            }
                        }
                    }

                    field.SetValue(instance, value);
                }
                else if (flagAttribute.Required)
                {
                    Console.Error.WriteLine(string.IsNullOrWhiteSpace(flagAttribute.Flag) ? $"Positional {flagAttribute.Positional} is required" : $"Flag {flagAttribute.Flag} is required");

                    FullHelp <T>(extraHelp);
                    return(null);
                }
                else if (field.FieldType.IsClass && field.FieldType.GetConstructor(Type.EmptyTypes) != null)
                {
                    field.SetValue(instance, Activator.CreateInstance(field.FieldType));
                }
            }

            if (positionalsField != default)
            {
                positionalsField.SetValue(instance, positionals.Select(x => x?.ToString()).ToArray());
            }

            return(instance);
        }
		bool IntroducePostIncrementForVariables(List<ILNode> body, ILExpression expr, int pos)
		{
			// Works for variables and static fields/properties
			
			// expr = ldloc(i)
			// stloc(i, add(expr, ldc.i4(1)))
			// ->
			// expr = postincrement(1, ldloca(i))
			ILVariable exprVar;
			ILExpression exprInit;
			if (!(expr.Match(ILCode.Stloc, out exprVar, out exprInit) && exprVar.IsGenerated))
				return false;
			
			//The next expression
			ILExpression nextExpr = body.ElementAtOrDefault(pos + 1) as ILExpression;
			if (nextExpr == null)
				return false;
			
			ILCode loadInstruction = exprInit.Code;
			ILCode storeInstruction = nextExpr.Code;
			bool recombineVariable = false;
			
			// We only recognise local variables, static fields, and static getters with no arguments
			switch (loadInstruction) {
				case ILCode.Ldloc:
					//Must be a matching store type
					if (storeInstruction != ILCode.Stloc)
						return false;
					ILVariable loadVar = (ILVariable)exprInit.Operand;
					ILVariable storeVar = (ILVariable)nextExpr.Operand;
					if (loadVar != storeVar) {
						if (loadVar.OriginalVariable != null && loadVar.OriginalVariable == storeVar.OriginalVariable)
							recombineVariable = true;
						else
							return false;
					}
					break;
				case ILCode.Ldsfld:
					if (storeInstruction != ILCode.Stsfld)
						return false;
					if (exprInit.Operand != nextExpr.Operand)
						return false;
					break;
				case ILCode.CallGetter:
					// non-static getters would have the 'this' argument
					if (exprInit.Arguments.Count != 0)
						return false;
					if (storeInstruction != ILCode.CallSetter)
						return false;
					if (!IsGetterSetterPair(exprInit.Operand, nextExpr.Operand))
						return false;
					break;
				default:
					return false;
			}
			
			ILExpression addExpr = nextExpr.Arguments[0];
			
			int incrementAmount;
			ILCode incrementCode = GetIncrementCode(addExpr, out incrementAmount);
			if (!(incrementAmount != 0 && addExpr.Arguments[0].MatchLdloc(exprVar)))
				return false;
			
			if (recombineVariable) {
				// Split local variable, unsplit these two instances
				// replace nextExpr.Operand with exprInit.Operand
				ReplaceVariables(method, oldVar => oldVar == nextExpr.Operand ? (ILVariable)exprInit.Operand : oldVar);
			}
			
			switch (loadInstruction) {
				case ILCode.Ldloc:
					exprInit.Code = ILCode.Ldloca;
					break;
				case ILCode.Ldsfld:
					exprInit.Code = ILCode.Ldsflda;
					break;
				case ILCode.CallGetter:
					exprInit = new ILExpression(ILCode.AddressOf, null, exprInit);
					break;
			}
			expr.Arguments[0] = new ILExpression(incrementCode, incrementAmount, exprInit);
			body.RemoveAt(pos + 1); // TODO ILRanges
			return true;
		}
Exemplo n.º 39
0
        public AmzProduct GetProduct(int productId)
        {
            IEnumerable<AmzProduct> result = new List<AmzProduct>();

            using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
            {
                conn.Open();
                try
                {
                    result = conn.Query<AmzProduct>(@"
                    SELECT * 
                    FROM amz.Products
                    where ProductId = @productId
                    ", new { productId });
                }
                catch (Exception ex)
                {
                    logger.Error(ex);
                }

            }

            if (result.Any())
                return result.ElementAtOrDefault(0);


            return null;

        }
Exemplo n.º 40
0
        private void HandleEvent(string ev, List<string> args)
        {
            switch (ev)
            {
                case "START_LOOT_ROLL":
                    EvaluateRollItem(Convert.ToInt32(args.ElementAtOrDefault(0)));
                    break;

                case "CONFIRM_DISENCHANT_ROLL":
                case "CONFIRM_LOOT_ROLL":
                    WoWScript.ExecuteNoResults("ConfirmLootRoll(" + args.ElementAtOrDefault(0) + "," + args.ElementAtOrDefault(1) + ")");
                    break;

                case "LOOT_BIND_CONFIRM":
                    WoWScript.ExecuteNoResults("ConfirmLootSlot(" + args.ElementAtOrDefault(0) + ")");
                    break;

                case "USE_BIND_CONFIRM":
                    WoWScript.ExecuteNoResults("ConfirmBindOnUse()");
                    break;

                case "EQUIP_BIND_CONFIRM":
                case "AUTOEQUIP_BIND_CONFIRM":
                    WoWScript.ExecuteNoResults("EquipPendingItem(" + args.ElementAtOrDefault(0) + ")");
                    break;

                case "ITEM_PUSH":
                    // New item in inventory.
                    _lastPulse = DateTime.MinValue;
                    break;

                case "ACTIVE_TALENT_GROUP_CHANGED":
                case "CHARACTER_POINTS_CHANGED":
                case "PLAYER_ENTERING_WORLD":
                    // Update weightsets
                    break;
            }
        }
Exemplo n.º 41
0
 public LocaleTable this[Language lang] => tables.ElementAtOrDefault((int)lang);
Exemplo n.º 42
0
        /// <summary>
        /// Appends the documents to primary document.
        /// </summary>
        /// <param name="primaryDocument">The primary document.</param>
        /// <param name="documentstoAppend">The documents to append.</param>
        /// <returns></returns>
        public byte[] AppendDocumentsToPrimaryDocument(byte[] primaryDocument, List<byte[]> documentstoAppend)
        {
            if (documentstoAppend == null)
            {
                throw new ArgumentNullException("documentstoAppend");
            }

            if (primaryDocument == null)
            {
                throw new ArgumentNullException("primaryDocument");
            }

            byte[] output = null;

            using (MemoryStream finalDocumentStream = new MemoryStream())
            {
                finalDocumentStream.Write(primaryDocument, 0, primaryDocument.Length);

                using (WordprocessingDocument finalDocument = WordprocessingDocument.Open(finalDocumentStream, true))
                {
                    SectionProperties finalDocSectionProperties = null;
                    this.UnprotectDocument(finalDocument);

                    SectionProperties tempSectionProperties = finalDocument.MainDocumentPart.Document.Descendants<SectionProperties>().LastOrDefault();

                    if (tempSectionProperties != null)
                    {
                        finalDocSectionProperties = tempSectionProperties.CloneNode(true) as SectionProperties;
                    }

                    this.RemoveContentControlsAndKeepContents(finalDocument.MainDocumentPart.Document);

                    foreach (byte[] documentToAppend in documentstoAppend)
                    {
                        AlternativeFormatImportPart subReportPart = finalDocument.MainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML);
                        SectionProperties secProperties = null;

                        using (MemoryStream docToAppendStream = new MemoryStream())
                        {
                            docToAppendStream.Write(documentToAppend, 0, documentToAppend.Length);

                            using (WordprocessingDocument docToAppend = WordprocessingDocument.Open(docToAppendStream, true))
                            {
                                this.UnprotectDocument(docToAppend);

                                tempSectionProperties = docToAppend.MainDocumentPart.Document.Descendants<SectionProperties>().LastOrDefault();

                                if (tempSectionProperties != null)
                                {
                                    secProperties = tempSectionProperties.CloneNode(true) as SectionProperties;
                                }

                                this.RemoveContentControlsAndKeepContents(docToAppend.MainDocumentPart.Document);
                                docToAppend.MainDocumentPart.Document.Save();
                            }

                            docToAppendStream.Position = 0;
                            subReportPart.FeedData(docToAppendStream);
                        }

                        if (documentstoAppend.ElementAtOrDefault(0).Equals(documentToAppend))
                        {
                            AssignSectionProperties(finalDocument.MainDocumentPart.Document, finalDocSectionProperties);
                        }

                        AltChunk altChunk = new AltChunk();
                        altChunk.Id = finalDocument.MainDocumentPart.GetIdOfPart(subReportPart);
                        finalDocument.MainDocumentPart.Document.AppendChild(altChunk);

                        if (!documentstoAppend.ElementAtOrDefault(documentstoAppend.Count - 1).Equals(documentToAppend))
                        {
                            AssignSectionProperties(finalDocument.MainDocumentPart.Document, secProperties);
                        }

                        finalDocument.MainDocumentPart.Document.Save();
                    }

                    finalDocument.MainDocumentPart.Document.Save();
                }

                finalDocumentStream.Position = 0;
                output = new byte[finalDocumentStream.Length];
                finalDocumentStream.Read(output, 0, output.Length);
                finalDocumentStream.Close();
            }

            return output;
        }
Exemplo n.º 43
0
 /// <summary>
 /// Retrieve a specific title text record from the list.
 /// </summary>
 /// <remarks>
 /// Returns an empty record in case the index is invalid.
 /// </remarks>
 /// <param name="index">number of the title record to return</param>
 /// <returns>title record at the specified index, or empty record if the index is invalid.</returns>
 public NdefTextRecord Title(int index)
 {
     return(Titles.ElementAtOrDefault(index));
 }
Exemplo n.º 44
0
        private void EnterDataIntoForm()
        {
            Console.WriteLine("Inside " + GetType().Name + " - " + System.Reflection.MethodBase.GetCurrentMethod().Name);

            ClearAll();

            //Need to seperate scoring and non-scoring performances
            List <Performance> scoringPerfs    = new List <Performance>();
            List <Performance> nonScoringPerfs = new List <Performance>();

            if (allPerfs != null)
            {
                foreach (Performance p in allPerfs)
                {
                    if (p.athleteName == "A Relay")
                    {
                        scoringPerfs.Add(p);
                    }
                    else
                    {
                        nonScoringPerfs.Add(p);
                    }
                }
            }

            if (scoringPerfs.ElementAtOrDefault(0) != null)
            {
                txtName1.Text   = scoringPerfs[0].athleteName;
                cboSchool1.Text = scoringPerfs[0].schoolName;
                txtPerf1.Text   = em.ConvertToTimedData(scoringPerfs[0].performance);
            }
            if (scoringPerfs.ElementAtOrDefault(1) != null)
            {
                txtName2.Text   = scoringPerfs[1].athleteName;
                cboSchool2.Text = scoringPerfs[1].schoolName;
                txtPerf2.Text   = em.ConvertToTimedData(scoringPerfs[1].performance);
            }
            if (scoringPerfs.ElementAtOrDefault(2) != null)
            {
                txtName3.Text   = scoringPerfs[2].athleteName;
                cboSchool3.Text = scoringPerfs[2].schoolName;
                txtPerf3.Text   = em.ConvertToTimedData(scoringPerfs[2].performance);
            }
            if (scoringPerfs.ElementAtOrDefault(3) != null)
            {
                txtName4.Text   = scoringPerfs[3].athleteName;
                cboSchool4.Text = scoringPerfs[3].schoolName;
                txtPerf4.Text   = em.ConvertToTimedData(scoringPerfs[3].performance);
            }
            if (scoringPerfs.ElementAtOrDefault(4) != null)
            {
                txtName5.Text   = scoringPerfs[4].athleteName;
                cboSchool5.Text = scoringPerfs[4].schoolName;
                txtPerf5.Text   = em.ConvertToTimedData(scoringPerfs[4].performance);
            }
            if (scoringPerfs.ElementAtOrDefault(5) != null)
            {
                txtName6.Text   = scoringPerfs[5].athleteName;
                cboSchool6.Text = scoringPerfs[5].schoolName;
                txtPerf6.Text   = em.ConvertToTimedData(scoringPerfs[5].performance);
            }

            //ADD NON SCORING PERFS HERE
            if (nonScoringPerfs.ElementAtOrDefault(0) != null)
            {
                txtName17.Text   = nonScoringPerfs[0].athleteName;
                cboSchool17.Text = nonScoringPerfs[0].schoolName;
                txtPerf17.Text   = em.ConvertToTimedData(nonScoringPerfs[0].performance);
            }
            if (nonScoringPerfs.ElementAtOrDefault(1) != null)
            {
                txtName18.Text   = nonScoringPerfs[1].athleteName;
                cboSchool18.Text = nonScoringPerfs[1].schoolName;
                txtPerf18.Text   = em.ConvertToTimedData(nonScoringPerfs[1].performance);
            }
            if (nonScoringPerfs.ElementAtOrDefault(2) != null)
            {
                txtName19.Text   = nonScoringPerfs[2].athleteName;
                cboSchool19.Text = nonScoringPerfs[2].schoolName;
                txtPerf19.Text   = em.ConvertToTimedData(nonScoringPerfs[2].performance);
            }
            if (nonScoringPerfs.ElementAtOrDefault(3) != null)
            {
                txtName20.Text   = nonScoringPerfs[3].athleteName;
                cboSchool20.Text = nonScoringPerfs[3].schoolName;
                txtPerf20.Text   = em.ConvertToTimedData(nonScoringPerfs[3].performance);
            }
            if (nonScoringPerfs.ElementAtOrDefault(4) != null)
            {
                txtName21.Text   = nonScoringPerfs[4].athleteName;
                cboSchool21.Text = nonScoringPerfs[4].schoolName;
                txtPerf21.Text   = em.ConvertToTimedData(nonScoringPerfs[4].performance);
            }
            if (nonScoringPerfs.ElementAtOrDefault(5) != null)
            {
                txtName22.Text   = nonScoringPerfs[5].athleteName;
                cboSchool22.Text = nonScoringPerfs[5].schoolName;
                txtPerf22.Text   = em.ConvertToTimedData(nonScoringPerfs[5].performance);
            }
            if (nonScoringPerfs.ElementAtOrDefault(6) != null)
            {
                txtName23.Text   = nonScoringPerfs[6].athleteName;
                cboSchool23.Text = nonScoringPerfs[6].schoolName;
                txtPerf23.Text   = em.ConvertToTimedData(nonScoringPerfs[6].performance);
            }
            if (nonScoringPerfs.ElementAtOrDefault(7) != null)
            {
                txtName24.Text   = nonScoringPerfs[7].athleteName;
                cboSchool24.Text = nonScoringPerfs[7].schoolName;
                txtPerf24.Text   = em.ConvertToTimedData(nonScoringPerfs[7].performance);
            }
            if (nonScoringPerfs.ElementAtOrDefault(8) != null)
            {
                txtName25.Text   = nonScoringPerfs[8].athleteName;
                cboSchool25.Text = nonScoringPerfs[8].schoolName;
                txtPerf25.Text   = em.ConvertToTimedData(nonScoringPerfs[8].performance);
            }
            if (nonScoringPerfs.ElementAtOrDefault(9) != null)
            {
                txtName26.Text   = nonScoringPerfs[9].athleteName;
                cboSchool26.Text = nonScoringPerfs[9].schoolName;
                txtPerf26.Text   = em.ConvertToTimedData(nonScoringPerfs[9].performance);
            }
            if (nonScoringPerfs.ElementAtOrDefault(10) != null)
            {
                txtName27.Text   = nonScoringPerfs[10].athleteName;
                cboSchool27.Text = nonScoringPerfs[10].schoolName;
                txtPerf27.Text   = em.ConvertToTimedData(nonScoringPerfs[10].performance);
            }
            if (nonScoringPerfs.ElementAtOrDefault(11) != null)
            {
                txtName28.Text   = nonScoringPerfs[11].athleteName;
                cboSchool28.Text = nonScoringPerfs[11].schoolName;
                txtPerf28.Text   = em.ConvertToTimedData(nonScoringPerfs[11].performance);
            }
            if (nonScoringPerfs.ElementAtOrDefault(12) != null)
            {
                txtName29.Text   = nonScoringPerfs[12].athleteName;
                cboSchool29.Text = nonScoringPerfs[12].schoolName;
                txtPerf29.Text   = em.ConvertToTimedData(nonScoringPerfs[12].performance);
            }
            if (nonScoringPerfs.ElementAtOrDefault(13) != null)
            {
                txtName30.Text   = nonScoringPerfs[13].athleteName;
                cboSchool30.Text = nonScoringPerfs[13].schoolName;
                txtPerf30.Text   = em.ConvertToTimedData(nonScoringPerfs[13].performance);
            }
            if (nonScoringPerfs.ElementAtOrDefault(14) != null)
            {
                txtName31.Text   = nonScoringPerfs[14].athleteName;
                cboSchool31.Text = nonScoringPerfs[14].schoolName;
                txtPerf31.Text   = em.ConvertToTimedData(nonScoringPerfs[14].performance);
            }
            if (nonScoringPerfs.ElementAtOrDefault(15) != null)
            {
                txtName32.Text   = nonScoringPerfs[15].athleteName;
                cboSchool32.Text = nonScoringPerfs[15].schoolName;
                txtPerf32.Text   = em.ConvertToTimedData(nonScoringPerfs[15].performance);
            }

            Console.WriteLine("Leaving " + GetType().Name + " - " + System.Reflection.MethodBase.GetCurrentMethod().Name);
        }
        public async Task CheckProxies(Action onDisabled,
                                       Action onError,
                                       Action onGood,
                                       Action onDone)
        {
            var proxies = Proxies.ToList();

            var threadEndCb = new Action <Thread>((t) =>
            {
                lock (ThreadsSync)
                    CheckThreads.Remove(t);
            });

            foreach (var proxy in proxies)
            {
                if (!(proxy?.Enabled ?? false))
                {
                    onDisabled?.Invoke();
                    continue;
                }

                var thread = new Thread(new ThreadStart(() =>
                {
                    try
                    {
                        var client = new RestSharp.RestClient("https://store.steampowered.com/login/")
                        {
                            Proxy = proxy.ToWebProxy()
                        };
                        var request  = new RestSharp.RestRequest("", RestSharp.Method.GET);
                        var response = client.Execute(request);
                        if (!response.IsSuccessful)
                        {
                            proxy.Enabled = false;
                            proxy.Status  = Enums.ProxyStatus.Broken;
                            onError?.Invoke();
                        }
                        else
                        {
                            if (Regex.IsMatch(response.Content, @"(steamcommunity\.com|steampowered\.com)", RegexOptions.IgnoreCase))
                            {
                                proxy.Status = Enums.ProxyStatus.Working;
                                onGood?.Invoke();
                            }
                            else
                            {
                                proxy.Enabled = false;
                                proxy.Status  = Enums.ProxyStatus.Broken;
                                onError?.Invoke();
                            }
                        }

                        Logger.Debug($"Proxy({proxy.Host}:{proxy.Port}): {proxy.Status.ToString()}");
                        threadEndCb(Thread.CurrentThread);
                    }
                    catch (ThreadAbortException)
                    {
                        Logger.Info("Check proxy thread stopped.");
                        threadEndCb(Thread.CurrentThread);
                    }
                    catch (Exception ex)
                    {
                        Logger.Error("Check proxy thread error.", ex);
                        onError?.Invoke();
                        threadEndCb(Thread.CurrentThread);
                    }
                }));

                CheckThreads.Add(thread);
            }

            await Task.Factory.StartNew(async() =>
            {
                var thrs = new List <Thread>(10);
                while (CheckThreads.Count > 0)
                {
                    lock (ThreadsSync)
                    {
                        var _thrs = CheckThreads.Take(10 - thrs.Count);
                        thrs.AddRange(_thrs);

                        for (int i = thrs.Count - 1; i > -1; i--)
                        {
                            var t = thrs.ElementAtOrDefault(i);
                            switch (t.ThreadState)
                            {
                            case ThreadState.Unstarted:
                                t.Start();
                                break;

                            case ThreadState.Stopped:
                                thrs.Remove(t);
                                break;
                            }
                        }
                    }

                    await Task.Delay(1000);
                }

                onDone?.Invoke();
            });
        }
        public ActionResult StepEnd()
        {
            //Nhận reqest từ trang index
            string phone    = Request.Form["phone"];
            string fullname = Request.Form["fullname"];
            string email    = Request.Form["email"];
            string address  = Request.Form["address"];
            string note     = Request.Form["note"];
            //kiểm tra xem có customer chưa và cập nhật lại
            Customer newCus = new Customer();
            var      cus    = db.Customers.FirstOrDefault(p => p.cusPhone.Equals(phone));

            if (cus != null)
            {
                //nếu có số điện thoại trong db rồi
                //cập nhật thông tin và lưu
                cus.cusFullName     = fullname;
                cus.cusEmail        = email;
                cus.cusAddress      = address;
                db.Entry(cus).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();
            }
            else
            {
                //nếu chưa có sđt trong db
                //thêm thông tin và lưu
                newCus.cusPhone    = phone;
                newCus.cusFullName = fullname;
                newCus.cusEmail    = email;
                newCus.cusAddress  = address;
                db.Customers.Add(newCus);
                db.SaveChanges();
            }
            //Thêm thông tin vào order và orderdetail
            List <CartItem> giohang = Session["giohang"] as List <CartItem>;
            //thêm order mới
            Order  newOrder   = new Order();
            Random rd         = new Random();
            string newIDOrder = (Int32.Parse(db.Orders.OrderBy(p => p.orderDateTime).FirstOrDefault().orderID.Replace("HD", "")) + 1).ToString();

            newOrder.orderID       = "HD" + rd.Next(1000000);
            newOrder.cusPhone      = phone;
            newOrder.orderMessage  = note;
            newOrder.orderDateTime = DateTime.Now.ToString();
            newOrder.orderStatus   = "0";
            db.Orders.Add(newOrder);
            db.SaveChanges();
            //thêm details
            for (int i = 0; i < giohang.Count; i++)
            {
                OrderDetail newOrdts = new OrderDetail();
                newOrdts.orderID        = newOrder.orderID;
                newOrdts.proID          = giohang.ElementAtOrDefault(i).SanPhamID;
                newOrdts.ordtsQuantity  = giohang.ElementAtOrDefault(i).SoLuong;
                newOrdts.ordtsThanhTien = giohang.ElementAtOrDefault(i).ThanhTien.ToString();
                db.OrderDetails.Add(newOrdts);
                db.SaveChanges();
            }
            Session["MHD"]   = "HD" + newIDOrder;
            Session["Phone"] = phone;
            //lấy tổng số tiền cần thanh toán
            int total = 0;

            foreach (CartItem cartItem in giohang)
            {
                total += cartItem.ThanhTien;
            }
            //xoá sạch giỏ hàng
            giohang.Clear();

            string payment_method = Request.Form["pay"];

            if (payment_method == "NL" || payment_method == "ATM_ONLINE")
            {
                //ngân lượng
                RequestInfo info = new RequestInfo();
                info.Merchant_id       = NganLuongAPI.merchant_id;
                info.Merchant_password = NganLuongAPI.merchant_password;
                info.Receiver_email    = NganLuongAPI.receiver_email;
                info.cur_code          = NganLuongAPI.cur_code;
                info.bank_code         = Request.Form["bankcode"];
                info.Order_code        = newOrder.orderID;
                info.Total_amount      = total.ToString();
                info.fee_shipping      = "0";
                info.Discount_amount   = "0";
                info.order_description = "order description here...";
                info.return_url        = "http://localhost:61765";
                info.cancel_url        = "http://localhost:61765";

                info.Buyer_fullname = Request.Form["fullname"];
                info.Buyer_email    = Request.Form["email"];
                info.Buyer_mobile   = Request.Form["phone"];

                NganLuongAPI objNLChecout = new NganLuongAPI();
                ResponseInfo result       = objNLChecout.GetUrlCheckout(info, payment_method);

                if (result.Error_code == "00")
                {
                    Response.Redirect(result.Checkout_url);
                }
            }
            //
            // ví việt
            else if (payment_method == "VV")
            {
                Dictionary <string, string> fields = new Dictionary <string, string>();
                fields.Add("version", ViVietAPI.version);
                fields.Add("locale", ViVietAPI.locale);
                fields.Add("access_code", ViVietAPI.access_code);
                fields.Add("merch_txn_ref", (new ViVietAPI()).Merch_txn_ref);
                fields.Add("merchant_site", ViVietAPI.merchant_site);
                fields.Add("order_info", "order information here...");
                fields.Add("order_no", (new ViVietAPI()).Order_no);
                fields.Add("order_desc", "order description here...");
                fields.Add("shipping_fee", "0");
                fields.Add("tax_fee", "0");
                fields.Add("total_amount", total.ToString());
                fields.Add("currency", ViVietAPI.currency);
                fields.Add("return_url", ViVietAPI.return_url);
                fields.Add("cancel_url", ViVietAPI.cancel_url);

                fields.Add("secure_hash", ViVietAPI.getSecureHash(fields));
                // Create a redirection URL
                string redirectUrl = ViVietAPI.createRedirectUrl(fields);
                Console.WriteLine(redirectUrl);
                Response.Redirect(redirectUrl);
            }
            //
            //Momo
            else if (payment_method == "MM")
            {
                //before sign HMAC SHA256 signature
                string rawHash = "partnerCode=" +
                                 MoMoAPI.partnerCode + "&accessKey=" +
                                 MoMoAPI.accessKey + "&requestId=" +
                                 "123421232144" + "&amount=" +
                                 total.ToString() + "&orderId=" +
                                 newOrder.orderID + "&orderInfo=" +
                                 "order infomation here..." + "&returnUrl=" +
                                 MoMoAPI.returnUrl + "&notifyUrl=" +
                                 MoMoAPI.notifyUrl + "&extraData=" +
                                 "";

                //sign signature SHA256
                string signature = MoMoAPI.signSHA256(rawHash, MoMoAPI.secretKey);

                //build body json request
                JObject message = new JObject
                {
                    { "partnerCode", MoMoAPI.partnerCode },
                    { "accessKey", MoMoAPI.accessKey },
                    { "requestId", "123421232144" },
                    { "amount", total.ToString() },
                    { "orderId", newOrder.orderID },
                    { "orderInfo", "order infomation here..." },
                    { "returnUrl", MoMoAPI.returnUrl },
                    { "notifyUrl", MoMoAPI.notifyUrl },
                    { "requestType", "captureMoMoWallet" },
                    { "signature", signature }
                };
                string  responseFromMomo = MoMoAPI.sendPaymentRequest(MoMoAPI.endpoint, message.ToString());
                JObject jmessage         = JObject.Parse(responseFromMomo);
                try
                {
                    Response.Redirect(jmessage.GetValue("payUrl").ToString());
                }
                catch
                {
                    string fail = "Return from MoMo: " + jmessage.ToString();
                }
            }
            //chuyển sang trang thanh toán
            return(RedirectToAction("HoaDon", "ThanhToan"));
        }
Exemplo n.º 47
0
        private async Task ProcessWebConsoleLinesQueueAsync(bool runOnce = false)
        {
            while (!_jobCompletionSource.Task.IsCompleted || runOnce)
            {
                if (_webConsoleLineAggressiveDequeue && ++_webConsoleLineAggressiveDequeueCount > _webConsoleLineAggressiveDequeueLimit)
                {
                    Trace.Info("Stop aggressive process web console line queue.");
                    _webConsoleLineAggressiveDequeue = false;
                }

                // Group consolelines by timeline record of each step
                Dictionary <Guid, List <TimelineRecordLogLine> > stepsConsoleLines = new Dictionary <Guid, List <TimelineRecordLogLine> >();
                List <Guid>     stepRecordIds = new List <Guid>(); // We need to keep lines in order
                int             linesCounter  = 0;
                ConsoleLineInfo lineInfo;
                while (_webConsoleLineQueue.TryDequeue(out lineInfo))
                {
                    if (!stepsConsoleLines.ContainsKey(lineInfo.StepRecordId))
                    {
                        stepsConsoleLines[lineInfo.StepRecordId] = new List <TimelineRecordLogLine>();
                        stepRecordIds.Add(lineInfo.StepRecordId);
                    }

                    if (lineInfo.Line?.Length > 1024)
                    {
                        Trace.Verbose("Web console line is more than 1024 chars, truncate to first 1024 chars");
                        lineInfo.Line = $"{lineInfo.Line.Substring(0, 1024)}...";
                    }

                    stepsConsoleLines[lineInfo.StepRecordId].Add(new TimelineRecordLogLine(lineInfo.Line, lineInfo.LineNumber));
                    linesCounter++;

                    // process at most about 500 lines of web console line during regular timer dequeue task.
                    // Send the first line of output to the customer right away
                    // It might take a while to reach 500 line outputs, which would cause delays before customers see the first line
                    if ((!runOnce && linesCounter > 500) || _firstConsoleOutputs)
                    {
                        break;
                    }
                }

                // Batch post consolelines for each step timeline record
                foreach (var stepRecordId in stepRecordIds)
                {
                    // Split consolelines into batch, each batch will container at most 100 lines.
                    int batchCounter = 0;
                    List <List <TimelineRecordLogLine> > batchedLines = new List <List <TimelineRecordLogLine> >();
                    foreach (var line in stepsConsoleLines[stepRecordId])
                    {
                        var currentBatch = batchedLines.ElementAtOrDefault(batchCounter);
                        if (currentBatch == null)
                        {
                            batchedLines.Add(new List <TimelineRecordLogLine>());
                            currentBatch = batchedLines.ElementAt(batchCounter);
                        }

                        currentBatch.Add(line);

                        if (currentBatch.Count >= 100)
                        {
                            batchCounter++;
                        }
                    }

                    if (batchedLines.Count > 0)
                    {
                        // When job finish, web console lines becomes less interesting to customer
                        // We batch and produce 500 lines of web console output every 500ms
                        // If customer's task produce massive of outputs, then the last queue drain run might take forever.
                        // So we will only upload the last 200 lines of each step from all buffered web console lines.
                        if (runOnce && batchedLines.Count > 2)
                        {
                            Trace.Info($"Skip {batchedLines.Count - 2} batches web console lines for last run");
                            batchedLines = batchedLines.TakeLast(2).ToList();
                        }

                        int errorCount = 0;
                        foreach (var batch in batchedLines)
                        {
                            try
                            {
                                // we will not requeue failed batch, since the web console lines are time sensitive.
                                await _jobServer.AppendTimelineRecordFeedAsync(_scopeIdentifier, _hubName, _planId, _jobTimelineId, _jobTimelineRecordId, stepRecordId, batch.Select(x => x.Line).ToList(), batch[0].LineNumber, default(CancellationToken));

                                if (_firstConsoleOutputs)
                                {
                                    _firstConsoleOutputs = false;
                                    HostContext.WritePerfCounter("WorkerJobServerQueueAppendFirstConsoleOutput");
                                }
                            }
                            catch (Exception ex)
                            {
                                Trace.Info("Catch exception during append web console line, keep going since the process is best effort.");
                                Trace.Error(ex);
                                errorCount++;
                            }
                        }

                        Trace.Info("Try to append {0} batches web console lines for record '{2}', success rate: {1}/{0}.", batchedLines.Count, batchedLines.Count - errorCount, stepRecordId);
                    }
                }

                if (runOnce)
                {
                    break;
                }
                else
                {
                    _webConsoleLinesDequeueNow = new TaskCompletionSource <object>();
                    await Task.WhenAny(
                        Task.Delay(_webConsoleLineAggressiveDequeue ? _aggressiveDelayForWebConsoleLineDequeue : TimeSpan.FromMilliseconds(_webConsoleLineUpdateRate)),
                        _webConsoleLinesDequeueNow.Task);
                }
            }
        }
Exemplo n.º 48
0
        static bool Step2(List<ILNode> body, ref int pos)
        {
            // stloc(CS$0$0001, callvirt(class System.Threading.Tasks.Task`1<bool>::GetAwaiter, awaiterExpr)
            // brtrue(IL_7C, call(valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<bool>::get_IsCompleted, ldloca(CS$0$0001)))
            // await(ldloca(CS$0$0001))
            // ...
            // IL_7C:
            // arg_8B_0 = call(valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<bool>::GetResult, ldloca(CS$0$0001))
            // initobj(valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<bool>, ldloca(CS$0$0001))

            ILExpression loadAwaiter;
            ILVariable awaiterVar;
            if (!body[pos].Match(ILCode.Await, out loadAwaiter))
                return false;
            if (!loadAwaiter.Match(ILCode.Ldloca, out awaiterVar))
                return false;

            ILVariable stackVar;
            ILExpression stackExpr;
            while (pos >= 1 && body[pos - 1].Match(ILCode.Stloc, out stackVar, out stackExpr))
                pos--;

            // stloc(CS$0$0001, callvirt(class System.Threading.Tasks.Task`1<bool>::GetAwaiter, awaiterExpr)
            ILExpression getAwaiterCall;
            if (!(pos >= 2 && body[pos - 2].MatchStloc(awaiterVar, out getAwaiterCall)))
                return false;
            IMethod getAwaiterMethod;
            ILExpression awaitedExpr;
            if (!(getAwaiterCall.Match(ILCode.Call, out getAwaiterMethod, out awaitedExpr) || getAwaiterCall.Match(ILCode.Callvirt, out getAwaiterMethod, out awaitedExpr)))
                return false;

            if (awaitedExpr.Code == ILCode.AddressOf) {
                // remove 'AddressOf()' when calling GetAwaiter() on a value type
                awaitedExpr = awaitedExpr.Arguments[0];
            }

            // brtrue(IL_7C, call(valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<bool>::get_IsCompleted, ldloca(CS$0$0001)))
            ILLabel label;
            ILExpression getIsCompletedCall;
            if (!(pos >= 1 && body[pos - 1].Match(ILCode.Brtrue, out label, out getIsCompletedCall)))
                return false;

            int labelPos = body.IndexOf(label);
            if (labelPos < pos)
                return false;
            for (int i = pos + 1; i < labelPos; i++) {
                // validate that we aren't deleting any unexpected instructions -
                // between the await and the label, there should only be the stack, awaiter and state logic
                ILExpression expr = body[i] as ILExpression;
                if (expr == null)
                    return false;
                switch (expr.Code) {
                    case ILCode.Stloc:
                    case ILCode.Initobj:
                    case ILCode.Stfld:
                    case ILCode.Await:
                        // e.g.
                        // stloc(CS$0$0001, ldfld(StateMachine::<>u__$awaitere, ldloc(this)))
                        // initobj(valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<bool>, ldloca(CS$0$0002_66))
                        // stfld('<AwaitInLoopCondition>d__d'::<>u__$awaitere, ldloc(this), ldloc(CS$0$0002_66))
                        // stfld('<AwaitInLoopCondition>d__d'::<>1__state, ldloc(this), ldc.i4(-1))
                        break;
                    default:
                        return false;
                }
            }
            if (labelPos + 1 >= body.Count)
                return false;
            ILExpression resultAssignment = body[labelPos + 1] as ILExpression;
            ILVariable resultVar;
            ILExpression getResultCall;
            bool isResultAssignment = resultAssignment.Match(ILCode.Stloc, out resultVar, out getResultCall);
            if (!isResultAssignment)
                getResultCall = resultAssignment;
            var method = getResultCall.Operand as IMethod;
            if (!(method != null && !method.IsField && method.Name == "GetResult"))
                return false;

            pos -= 2; // also delete 'stloc', 'brtrue' and 'await'
            body.RemoveRange(pos, labelPos - pos);//TODO: Preserve ILRanges?
            Debug.Assert(body[pos] == label);

            pos++;
            if (isResultAssignment) {
                Debug.Assert(body[pos] == resultAssignment);
                //TODO: Preserve ILRanges?
                resultAssignment.Arguments[0] = new ILExpression(ILCode.Await, null, awaitedExpr);
            } else {
                //TODO: Preserve ILRanges?
                body[pos] = new ILExpression(ILCode.Await, null, awaitedExpr);
            }

            // if the awaiter variable is cleared out in the next instruction, remove that instruction
            if (IsVariableReset(body.ElementAtOrDefault(pos + 1), awaiterVar)) {
                body.RemoveAt(pos + 1);//TODO: Preserve ILRanges?
            }

            return true;
        }
Exemplo n.º 49
0
		/// <summary>
		/// Inlines the stloc instruction at block.Body[pos] into the next instruction, if possible.
		/// </summary>
		public bool InlineOneIfPossible(ILBlockBase block, List<ILNode> body, int pos, bool aggressive)
		{
			ILVariable v;
			ILExpression inlinedExpression;
			if (body[pos].Match(ILCode.Stloc, out v, out inlinedExpression) && !v.IsPinned) {
				if (InlineIfPossible(v, inlinedExpression, body.ElementAtOrDefault(pos+1), aggressive)) {
					// Assign the ranges of the stloc instruction:
					if (context.CalculateILRanges)
						inlinedExpression.ILRanges.AddRange(body[pos].ILRanges);
					// Remove the stloc instruction:
					body.RemoveAt(pos);
					return true;
				} else if (numLdloc.GetOrDefault(v) == 0 && numLdloca.GetOrDefault(v) == 0) {
					// The variable is never loaded
					if (inlinedExpression.HasNoSideEffects()) {
						// Remove completely
						AnalyzeNode(body[pos], -1);
						if (context.CalculateILRanges)
							Utils.AddILRanges(block, body, pos);
						body.RemoveAt(pos);
						return true;
					} else if (inlinedExpression.CanBeExpressionStatement() && v.GeneratedByDecompiler) {
						// Assign the ranges of the stloc instruction:
						if (context.CalculateILRanges)
							inlinedExpression.ILRanges.AddRange(body[pos].ILRanges);
						// Remove the stloc, but keep the inner expression
						body[pos] = inlinedExpression;
						return true;
					}
				}
			}
			return false;
		}
Exemplo n.º 50
0
        bool MakeAssignmentExpression(List <ILNode> body, ILExpression expr, int pos)
        {
            // exprVar = ...
            // stloc(v, exprVar)
            // ->
            // exprVar = stloc(v, ...))
            ILVariable   exprVar;
            ILExpression initializer;

            if (!(expr.Match(ILCode.Stloc, out exprVar, out initializer) && exprVar.IsGenerated))
            {
                return(false);
            }
            ILExpression nextExpr = body.ElementAtOrDefault(pos + 1) as ILExpression;
            ILVariable   v;
            ILExpression stLocArg;

            if (nextExpr.Match(ILCode.Stloc, out v, out stLocArg) && stLocArg.MatchLdloc(exprVar))
            {
                ILExpression store2 = body.ElementAtOrDefault(pos + 2) as ILExpression;
                if (StoreCanBeConvertedToAssignment(store2, exprVar))
                {
                    // expr_44 = ...
                    // stloc(v1, expr_44)
                    // anystore(v2, expr_44)
                    // ->
                    // stloc(v1, anystore(v2, ...))
                    ILInlining inlining = new ILInlining(method);
                    if (inlining.numLdloc.GetOrDefault(exprVar) == 2 && inlining.numStloc.GetOrDefault(exprVar) == 1)
                    {
                        body.RemoveAt(pos + 2);                     // remove store2
                        body.RemoveAt(pos);                         // remove expr = ...
                        nextExpr.Arguments[0] = store2;
                        store2.Arguments[store2.Arguments.Count - 1] = initializer;

                        inlining.InlineIfPossible(body, ref pos);

                        return(true);
                    }
                }

                body.RemoveAt(pos + 1);                 // remove stloc
                nextExpr.Arguments[0] = initializer;
                ((ILExpression)body[pos]).Arguments[0] = nextExpr;
                return(true);
            }
            else if ((nextExpr.Code == ILCode.Stsfld || nextExpr.Code == ILCode.CallSetter || nextExpr.Code == ILCode.CallvirtSetter) && nextExpr.Arguments.Count == 1)
            {
                // exprVar = ...
                // stsfld(fld, exprVar)
                // ->
                // exprVar = stsfld(fld, ...))
                if (nextExpr.Arguments[0].MatchLdloc(exprVar))
                {
                    body.RemoveAt(pos + 1);                     // remove stsfld
                    nextExpr.Arguments[0] = initializer;
                    ((ILExpression)body[pos]).Arguments[0] = nextExpr;
                    return(true);
                }
            }
            return(false);
        }
Exemplo n.º 51
0
        bool IntroducePostIncrementForVariables(List <ILNode> body, ILExpression expr, int pos)
        {
            // Works for variables and static fields/properties

            // expr = ldloc(i)
            // stloc(i, add(expr, ldc.i4(1)))
            // ->
            // expr = postincrement(1, ldloca(i))
            ILVariable   exprVar;
            ILExpression exprInit;

            if (!(expr.Match(ILCode.Stloc, out exprVar, out exprInit) && exprVar.IsGenerated))
            {
                return(false);
            }
            if (!(exprInit.Code == ILCode.Ldloc || exprInit.Code == ILCode.Ldsfld || (exprInit.Code == ILCode.CallGetter && exprInit.Arguments.Count == 0)))
            {
                return(false);
            }

            ILExpression nextExpr = body.ElementAtOrDefault(pos + 1) as ILExpression;

            if (nextExpr == null)
            {
                return(false);
            }
            if (exprInit.Code == ILCode.CallGetter)
            {
                if (!(nextExpr.Code == ILCode.CallSetter && IsGetterSetterPair(exprInit.Operand, nextExpr.Operand)))
                {
                    return(false);
                }
            }
            else
            {
                if (!(nextExpr.Code == (exprInit.Code == ILCode.Ldloc ? ILCode.Stloc : ILCode.Stsfld) && nextExpr.Operand == exprInit.Operand))
                {
                    return(false);
                }
            }
            ILExpression addExpr = nextExpr.Arguments[0];

            int    incrementAmount;
            ILCode incrementCode = GetIncrementCode(addExpr, out incrementAmount);

            if (!(incrementAmount != 0 && addExpr.Arguments[0].MatchLdloc(exprVar)))
            {
                return(false);
            }

            if (exprInit.Code == ILCode.Ldloc)
            {
                exprInit.Code = ILCode.Ldloca;
            }
            else if (exprInit.Code == ILCode.CallGetter)
            {
                exprInit = new ILExpression(ILCode.AddressOf, null, exprInit);
            }
            else
            {
                exprInit.Code = ILCode.Ldsflda;
            }
            expr.Arguments[0] = new ILExpression(incrementCode, incrementAmount, exprInit);
            body.RemoveAt(pos + 1);             // TODO ILRanges
            return(true);
        }
Exemplo n.º 52
0
 public Category Get(int position)
 {
     return(_all.ElementAtOrDefault(position));
 }
Exemplo n.º 53
0
        public void Select_SourceIsIList_ElementAtOrDefault()
        {
            var source = new List<int> { 1, 2, 3, 4 }.AsReadOnly().Select(i => i * 2);
            for (int i = 0; i != 4; ++i)
                Assert.Equal(i * 2 + 2, source.ElementAtOrDefault(i));
            Assert.Equal(0, source.ElementAtOrDefault(-1));
            Assert.Equal(0, source.ElementAtOrDefault(4));
            Assert.Equal(0, source.ElementAtOrDefault(40));

            Assert.Equal(6, source.Skip(1).ElementAtOrDefault(1));
            Assert.Equal(0, source.Skip(2).ElementAtOrDefault(9));
        }
Exemplo n.º 54
0
 private void initExits(List<Room> exits)
 {
     for (int x = 0; x < 4; x++)
     {
         if (exits.ElementAtOrDefault(x) == null)
         {
             this.exits.Add(null);
         }
         else
         {
             this.exits.Add(exits.ElementAtOrDefault(x));
         }
     }
 }
		bool MakeAssignmentExpression(List<ILNode> body, ILExpression expr, int pos)
		{
			// exprVar = ...
			// stloc(v, exprVar)
			// ->
			// exprVar = stloc(v, ...))
			ILVariable exprVar;
			ILExpression initializer;
			if (!(expr.Match(ILCode.Stloc, out exprVar, out initializer) && exprVar.IsGenerated))
				return false;
			ILExpression nextExpr = body.ElementAtOrDefault(pos + 1) as ILExpression;
			ILVariable v;
			ILExpression stLocArg;
			if (nextExpr.Match(ILCode.Stloc, out v, out stLocArg) && stLocArg.MatchLdloc(exprVar)) {
				ILExpression store2 = body.ElementAtOrDefault(pos + 2) as ILExpression;
				if (StoreCanBeConvertedToAssignment(store2, exprVar)) {
					// expr_44 = ...
					// stloc(v1, expr_44)
					// anystore(v2, expr_44)
					// ->
					// stloc(v1, anystore(v2, ...))
					ILInlining inlining = new ILInlining(method);
					if (inlining.numLdloc.GetOrDefault(exprVar) == 2 && inlining.numStloc.GetOrDefault(exprVar) == 1) {
						body.RemoveAt(pos + 2); // remove store2
						body.RemoveAt(pos); // remove expr = ...
						nextExpr.Arguments[0] = store2;
						store2.Arguments[store2.Arguments.Count - 1] = initializer;
						
						inlining.InlineIfPossible(body, ref pos);
						
						return true;
					}
				}
				
				body.RemoveAt(pos + 1); // remove stloc
				nextExpr.Arguments[0] = initializer;
				((ILExpression)body[pos]).Arguments[0] = nextExpr;
				return true;
			} else if ((nextExpr.Code == ILCode.Stsfld || nextExpr.Code == ILCode.CallSetter || nextExpr.Code == ILCode.CallvirtSetter) && nextExpr.Arguments.Count == 1) {
				// exprVar = ...
				// stsfld(fld, exprVar)
				// ->
				// exprVar = stsfld(fld, ...))
				if (nextExpr.Arguments[0].MatchLdloc(exprVar)) {
					body.RemoveAt(pos + 1); // remove stsfld
					nextExpr.Arguments[0] = initializer;
					((ILExpression)body[pos]).Arguments[0] = nextExpr;
					return true;
				}
			}
			return false;
		}
Exemplo n.º 56
0
        static void Main(string[] args)
        {
            String[] data = { "naveen", "ajay", "lokesh" };
            var      name = from dat in data
                            where dat.Contains('a')
                            select dat;
            var linqname = data.Where(s => s.Contains('a'));

            Console.WriteLine(string.Join(" ", name));
            Console.WriteLine(string.Join(" ", linqname));

            List <student> studentarray = new List <student> {
                new student {
                    id = 10, name = "naveen", des = "developer", salary = 12500, Branch = "CSE"
                },
                new student {
                    id = 20, name = "hanumanth rao", des = "developer", salary = 12500, Branch = "MECH"
                },
                new student {
                    id = 30, name = "krishna", des = "Senior Developer", salary = 50000, Branch = "CIVIL"
                },
                new student {
                    id = 45, name = "abhishek", des = "UI", salary = 50000, Branch = "CSE"
                },
                new student {
                    id = 45, name = "abhishek", des = "UI", salary = 50000, Branch = "CSE"
                }
            };

            List <teacher> teacherarray = new List <teacher> {
                new teacher {
                    id = 10, Name = "Ramesh", Branch = "CSE"
                },
                new teacher {
                    id = 20, Name = "Priyanka", Branch = "MECH"
                },
                new teacher {
                    id = 30, Name = "MAX", Branch = "CIVIL"
                }
            };
            //working with List
            var nameswise = (from d in studentarray
                             where d.salary > 12500 && d.salary <= 50000
                             select new { d.name, d.salary, d.id }).ToList();

            Console.WriteLine(string.Join("\n", nameswise));//.(s=>s.name + " "+s.salary)));

            var data2 = studentarray.ToList();
            var data1 = data2.Where(d => d.salary > 12500 && d.salary <= 50000).Select(s => new { s.name, s.salary });

            Console.WriteLine(string.Join(" ", data1.Select(s => s.name)));

            //using delegate
            Console.WriteLine("\n\t\t\t***using delegate***");
            isnum number = (s) =>
            {
                int y = 10;
                Console.WriteLine("welcome");
                return(s.salary > y);
            };

            Console.WriteLine(number(studentarray[0]));


            //ofType
            //Console.WriteLine("\n\t\t\t***using OFTYPE***");
            //IList dataset = new ArrayList { 1, "naveen", 2, "res" };
            //var oftyperes = from dt in dataset.OfType<string>() select dt;
            //Console.WriteLine(string.Join(" ", oftyperes));

            //Getting Multiple Elemenents at a time
            Console.WriteLine("\n==>Getting Multiple Elemenents at a time");
            var names = studentarray.Where(s => s.salary > 12500 && s.salary <= 50000).Select(s => new { s.name, s.salary }).FirstOrDefault();

            Console.WriteLine(string.Join("\n", names.name + " " + names.salary));//.(s=>s.name + " "+s.salary)));

            //OrderBy
            Console.WriteLine("\n\t\t\t***Using OrderBy***");

            var orderbyres = from student in studentarray where student.salary > 1000 orderby student.name ascending select student;

            Console.WriteLine(string.Join("\n", orderbyres.Select(d => new { d.name, d.salary })));
            //OrderBy in Method Syntax
            var regorderbyres = studentarray.Where(s => s.salary > 1000).OrderBy(h => h.name).Select(d => d.name);

            Console.WriteLine(string.Join("\n", regorderbyres));
            Console.WriteLine("\n");
            var regorderbyresdesc = studentarray.Where(s => s.salary > 1000).OrderByDescending(h => h.name).Select(d => d.name);

            Console.WriteLine(string.Join("\n", regorderbyresdesc));

            //ThenBy (it is secondary sorting means EX:tow class have same name but we need less age person first then we are using thenby sorting.)
            Console.WriteLine("\n\t\t\t***Using THENBY***");
            var thenbyres = from student in studentarray
                            where student.salary > 1000
                            orderby student.name, student.salary
            select student;

            Console.WriteLine("====using tow statements in a orderby line");
            Console.WriteLine(string.Join("\n", thenbyres.Select(d => new { d.name, d.salary })));
            Console.WriteLine("====using reg and thenby");
            var regthenbyres = studentarray.OrderBy(s => s.name).ThenBy(d => d.salary).Where(s => s.salary > 20000);

            Console.WriteLine(string.Join("\n", regthenbyres.Select(d => new { d.name, d.salary })));

            /*
             * ThenBy==>worked on only method syntax(using regular exp).
             * Multiple fileds not allowed in Methodsyntax when using orderby with , saparator used in query based syntaxes.
             */

            //GroupBy

            Console.WriteLine("\n\t\t\t***Using GroupBY***");
            var groupbyres = from student in studentarray
                             group student by student.name;

            Console.WriteLine("===Using ForEach Loop");
            foreach (var k in groupbyres)
            {
                Console.WriteLine(string.Join(" \n", k.Key));
                foreach (var value in k)
                {
                    Console.WriteLine(string.Join(" ", value.name + " " + value.salary));
                }
            }
            Console.WriteLine("==>Using Linq NestedQuery Loop" + string.Join(" ", groupbyres.Select(s => "\n" + s.Key + string.Join(" ", s.Select(d => "\n" + d.name + " " + d.salary)))));// s.Key.name + " " + s.Key.salary)));

            //Multiple Creteria
            Console.WriteLine("===Multiple Creteria");
            var groupbyres1 = from student in studentarray
                              group student by new { student.name, student.salary };

            Console.WriteLine("===Using ForEach Loop");
            foreach (var k in groupbyres1)
            {
                Console.WriteLine(string.Join(" \n", k.Key.name));
                foreach (var value in k)
                {
                    Console.WriteLine(string.Join(" ", value.name + " " + value.salary));
                }
            }
            Console.WriteLine("==>Using Linq NestedQuery Loop" + string.Join(" ", groupbyres1.Select(s => "\n" + s.Key.name + string.Join(" ", s.Select(d => "\n" + d.name + " " + d.salary)))));// s.Key.name + " " + s.Key.salary)));


            Console.WriteLine("===Using Reg with Multiple Creteria");
            var reggroupbyres = studentarray.GroupBy(s => new { s.name, s.salary });

            Console.WriteLine("===Using ForEach Loop");
            foreach (var k in reggroupbyres)
            {
                Console.WriteLine(string.Join(" \n", k.Key.name));
                foreach (var value in k)
                {
                    Console.WriteLine(string.Join(" ", value.name + " " + value.salary));
                }
            }
            Console.WriteLine("==>Using Linq NestedQuery Loop" + string.Join(" ", reggroupbyres.Select(s => "\n" + s.Key.name + string.Join(" ", s.Select(d => "\n" + d.name + " " + d.salary)))));// s.Key.name + " " + s.Key.salary)));
            //ToLookup
            Console.WriteLine("\n\t\t\t***Using ToLookup***");

            /*ToLookup is the same as GroupBy; the only difference is GroupBy execution is deferred, whereas ToLookup execution is immediate.
             * Also, ToLookup is only applicable in Method syntax. ToLookup is not supported in the query syntax.
             */
            var tookupres = studentarray.ToLookup(s => new { s.salary, s.name });

            Console.WriteLine("===Using ForEach Loop");
            foreach (var k in tookupres)
            {
                Console.WriteLine(string.Join(" \n", k.Key.name));
                foreach (var value in k)
                {
                    Console.WriteLine(string.Join(" ", value.name + " " + value.salary));
                }
            }

            Console.WriteLine("==>Using Linq NestedQuery Loop:" + string.Join(" ", tookupres.Select(s => "\n" + s.Key.name + string.Join(" ", s.Select(d => "\n" + d.name + " " + d.salary)))));// s.Key.name + " " + s.Key.salary)));
            //JOIN

            Console.WriteLine("\n\t\t\t***Using JOIN***");

            /*
             * from... in outerSequence
             *  join... in innerSequence
             *  on  outerKey equals innerKey
             *  select ...
             *
             * public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(this IEnumerable<TOuter> outer,
             * IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector,
             * Func<TInner, TKey> innerKeySelector,
             * Func<TOuter, TInner, TResult> resultSelector);
             *
             * Ex:- Outer.join(inner,
             * outer=>outer.key ==>Condition,
             * inner=>inner.key ==>Condition,
             * (oter,inner)=>new{selectors(outer.key,inner.key)} ==>result Set
             * )
             */
            Console.WriteLine("===using Query based condition along with where condition");
            var joinres = from s in studentarray
                          join r in teacherarray
                          on s.id equals r.id
                          where s.salary > 20000
                          select new { k = s.name, r = r.Name };

            Console.WriteLine(string.Join("\n", joinres.Select(s => s.k + "===>" + s.r)));

            Console.WriteLine("===using Method based");
            var regjoinres = studentarray.Where(s => s.Branch == "CSE").Join(teacherarray, student => student.id, teacher => teacher.id, (student, teacher) => new { k = student.name, r = teacher.Name });

            Console.WriteLine(string.Join("\n", regjoinres.Select(s => s.k + "===>" + s.r)));


            //GroupJOIN

            Console.WriteLine("\n\t\t\t***USING GROUPJOIN***");
            var reggropujoinres = teacherarray.GroupJoin(studentarray, tea => tea.Branch, std => std.Branch, (tea, stdgroup) => new { tea = tea.Branch, Student = stdgroup });

            foreach (var groupkey in reggropujoinres)
            {
                Console.WriteLine(groupkey.tea);
                foreach (var value in groupkey.Student)
                {
                    Console.WriteLine(value.name + "==>" + value.salary);
                }
            }
            Console.WriteLine("===Query Based:");
            var groupjoinres = from teach in teacherarray

                               join std in studentarray
                               on teach.Branch equals std.Branch
                               into StudentGroup
                               select new { Branch = teach.Branch, Students = StudentGroup };

            foreach (var joingroup in groupjoinres)
            {
                Console.WriteLine(joingroup.Branch);
                foreach (var stdentinfo in joingroup.Students)
                {
                    Console.WriteLine(stdentinfo.name + "==>" + stdentinfo.salary);
                }
            }

            Console.WriteLine("\t\t\t***ALL and ANY***");
            var allres = studentarray.All(s => s.salary < 1200000 && s.salary > 100000);

            Console.WriteLine(string.Join("\n", "ALL==>Above 100000 and below 1200000 is contain:" + allres.ToString()));
            var anyres = studentarray.Any(s => s.salary > 1000 && s.salary < 1200000);

            Console.WriteLine(string.Join("\n", "ANY==>Above 1000 and below 1200000 is contain:" + anyres.ToString()));

            Console.WriteLine("\t\t\t***USING CONTAINS WITH EQUALITY COMPARER CLASS***");
            student stdstudent = new student()
            {
                id = 10, name = "naveen", Branch = "CSE"
            };

            Console.WriteLine(studentarray.Contains(stdstudent, new IScompareTrue()));

            Console.WriteLine("\t\t\t***USING AGGRIGATE alias CONTATINATION***");
            IList <string> list = new List <string>()
            {
                "A", "B", "C", "D", "E", "F", "G"
            };
            var aggrigateres = list.Aggregate((s1, s2) => s1 + "," + s2);

            Console.WriteLine(string.Join(" ", aggrigateres));
            Console.WriteLine("===>Using class Values");
            var Aggrigatesrudent = studentarray.Aggregate <student, string>("Student Names: ", (std, s) => std = std + s.name + ",");

            Console.WriteLine(string.Join("", Aggrigatesrudent));
            Console.WriteLine("===>Removing Last Letter:");
            var aggrigratestudent = studentarray.Where(s => s.Branch == "CSE").Aggregate(string.Empty, (std, s) => std += s.name + ",", std => std.Substring(0, std.Length - 1));

            Console.WriteLine(string.Join("", aggrigratestudent));

            Console.WriteLine("\t\t\t***USING MAX***");
            //This Was done by using IComparaBle check class(teacher) once...
            var maxres = teacherarray.Max();

            Console.WriteLine(string.Join("\n", maxres.Name));
            var maxresevensalary = teacherarray.Max(i =>
            {
                if (i.id % 2 == 0)
                {
                    return(i);
                }
                return(null);
            });

            Console.WriteLine(string.Join("\n", "Even Numbered Teacher NAME:" + maxresevensalary.Name.ToUpper() + " Worked on fllowing Branch:" + maxresevensalary.Branch));

            Console.WriteLine("\n\t\t\t***Using ElementAt && ElementAtOrDefault***");
            IList <int> intlist = new List <int>()
            {
                10, 12, 14, 15, 65, 42, 20
            };
            IList <string> stringlist = new List <string>()
            {
                "one", "two", "four", "five", "six", "seven"
            };
            IList <int> emptylist = new List <int>();

            Console.WriteLine("0th Element :" + intlist.ElementAt(0));
            Console.WriteLine("0th Element :" + stringlist.ElementAt(0));
            Console.WriteLine("First Element :" + intlist.ElementAt(1));
            Console.WriteLine("First Element: " + stringlist.ElementAt(1));
            Console.WriteLine("Default 0 otherwise print value :" + intlist.ElementAtOrDefault(2));
            Console.WriteLine("Default null otherwise print value :" + stringlist.ElementAtOrDefault(2));

            Console.WriteLine("\n\t\t\t***Using First & FirstOrDefault***");

            Console.WriteLine("0th Element :" + intlist.First());

            Console.WriteLine("0th Element :" + stringlist.First());
            Console.WriteLine("0th Element checking even or not :" + intlist.First(i => i % 2 == 0));
            Console.WriteLine("Default index out of range otherwise print value :" + intlist.FirstOrDefault());
            Console.WriteLine("Default null otherwise print value :" + stringlist.FirstOrDefault());
            //Console.WriteLine("IF it is Empty List it's get error:" + emptylist.First().ToString());
            Console.WriteLine("1st Element in emptyList FirstOrDefault: {0}", emptylist.FirstOrDefault());

            Console.WriteLine("\n\t\t\t***Using  Last & LastOrDefault***");
            Console.WriteLine("Last Element " + intlist.Last());
            Console.WriteLine("Last Element " + stringlist.Last());
            Console.WriteLine("Last Element or default " + intlist.LastOrDefault());
            Console.WriteLine("Last Element or defalt " + stringlist.LastOrDefault());
            Console.WriteLine("Last Element with even num " + intlist.LastOrDefault(i => i % 2 == 0));
            //Console.WriteLine("Last Element with contains {0}", stringlist.LastOrDefault(k=>k.Contains("s")));

            Console.WriteLine("\n\t\t\t***Using  Single & SingleOrDefault***");

            /*
             * List Must have single element otherwise its thrown exception.
             * if list is empty its given default value 0 or null when we use SingleOrDefault()
             */
            Console.WriteLine("Single Element " + intlist.SingleOrDefault(i => i == 10));
            Console.WriteLine("\n\t\t\t***Using  SequenceEqual***");

            /*
             *  The SequenceEqual method checks whether the number of elements, value of each element and order of elements in two collections are equal or not.
             *  Order Must Be Same.
             */
            IList <int> intlist1 = new List <int>()
            {
                10, 12, 14, 15, 10, 42, 20
            };

            Console.WriteLine(intlist.SequenceEqual(intlist1));

            Console.WriteLine("\n\t\t\t***Using  DefaultIfEmpty***");
            var isdefaultarray = new List <string>();
            var Newlist1       = isdefaultarray.DefaultIfEmpty();
            var Newlist2       = isdefaultarray.DefaultIfEmpty("NONE");

            Console.WriteLine("Defalt Value Count for Newlist1 :" + Newlist1.Count());
            Console.WriteLine("Defalt Value for Newlist1 at index 0 :" + Newlist1.ElementAt(0));

            Console.WriteLine("Defalt Value Count Newlist2 :" + Newlist2.Count());
            Console.WriteLine("Defalt Value for Newlist1 at index 0 :" + Newlist2.ElementAt(0));

            Console.WriteLine("\n\t\t\t***Using  Repeat***");
            var repeatlist = Enumerable.Repeat <int>(10, 10);

            Console.WriteLine("Repeat Count is {0}", repeatlist.Count() + "\nElements are :" + string.Join(" ", repeatlist));

            //First Year Students
            List <BtechStudents> firstyearstudents = new List <BtechStudents>()
            {
                new BtechStudents {
                    ID = 1, Name = "Ajay", Branch = "MECH", Year = 1
                },
                new BtechStudents {
                    ID = 2, Name = "Kumar", Branch = "ECE", Year = 1
                },
                new BtechStudents {
                    ID = 3, Name = "NavaDheep", Branch = "EEE", Year = 1
                },
            };
            //Second Year Students
            List <BtechStudents> secondyearstudents = new List <BtechStudents>()
            {
                new BtechStudents {
                    ID = 1, Name = "Ajay", Branch = "MECH", Year = 2
                },
                new BtechStudents {
                    ID = 2, Name = "Kumar", Branch = "ECE", Year = 2
                },
                new BtechStudents {
                    ID = 3, Name = "naveen", Branch = "CSE", Year = 2
                },
            };
            var FullRecords = firstyearstudents.Concat(secondyearstudents);

            // Console.WriteLine("Count IS:"+ FullRecords.Count() + "\nFrom Fist and Second Year Student are:\n"+string.Join("\n",FullRecords.Select(s=>"ID:"+s.ID +" Name:"+s.Name)));
            //Console.WriteLine("Coolection is:"); FullRecords.ToList().ForEach(s => Console.WriteLine($"ID:{s.ID} Name: {s.Name}"));
            Console.WriteLine("\n\t\t\t***Using  Distinct***");

            /*
             * The Distinct operator is Not Supported in C# Query syntax. However, you can use Distinct method of query variable or wrap whole query into brackets and then call Distinct().
             */
            var distinctres = studentarray.Distinct(new ISDistinctcompareTrue());

            Console.WriteLine("Int Distinct Collection :" + string.Join(" ", intlist1.Distinct()));
            Console.WriteLine(string.Join("\n", distinctres.Select(s => s.name + "==>" + s.Branch + "==>" + s.id + "==>" + s.des + "==>" + s.salary)));

            Console.WriteLine("\nExample: Select the Distinct ID,Name from FirstYear and Second Year data..");
            Console.WriteLine("\nFrom Fist and Second Year Student are:\n" + string.Join("\n", FullRecords.Select(s => "ID:" + s.ID + " Name:" + s.Name + " ==> " + s.Year + " year")));
            var distinctcollections = FullRecords.Distinct(new IssameasSecondyear());

            Console.WriteLine("Distinct Collections are:\n" + string.Join("\n", distinctcollections.Select(s => "ID: " + s.ID + " Name: " + s.Name + " Year: " + s.Year)));

            Console.WriteLine("\n\t\t\t***Using  Except***");

            /*
             * The Except operator is Not Supported in C# & VB.Net Query syntax. However, you can use Distinct method on query variable or wrap whole query into brackets and then call Except().
             */
            IList <student> ExceptCollectionOfstudent = new List <student>()
            {
                new student {
                    id = 10, name = "naveen", des = "developer", Branch = "CSE", salary = 12500
                },
                new student {
                    id = 45, name = "abhishek", des = "UI", Branch = "CSE", salary = 50000
                },
                new student {
                    id = 100, name = "ajay", des = "UI", Branch = "MCA", salary = 50000
                }
            };
            var exceptres = studentarray.Except(ExceptCollectionOfstudent, new ISDistinctcompareTrue());

            Console.WriteLine("Collection of Ecept Method\n" + string.Join(" \n", exceptres.Select(s => s.name + " " + s.id)));


            Console.WriteLine("\nExample: Select ID,Name from FirstYear and Second Year data Except Failure Candidates of First Year..");
            List <BtechStudents> FailureCandidates = new List <BtechStudents>()
            {
                new BtechStudents {
                    ID = 3, Name = "NavaDheep", Branch = "EEE", Year = 1
                }
            };

            var ExceptcollectionsofStudents = FullRecords.Except(FailureCandidates, new IssameasSecondyear());

            Console.WriteLine("Except Collections are :\n" + string.Join("\n", ExceptcollectionsofStudents.Select(s => "ID: " + s.ID + " Name:" + s.Name + " " + s.Year + " Year")));
            Console.WriteLine("\n\t\t\t***Using  Intersect***");

            /*
             * It returns a new collection that includes common elements that exists in both the collection. Consider the following example.
             * The Intersect operator is Not Supported in C# & VB.Net Query syntax. However, you can use the Intersect method on a query variable or wrap whole query into brackets and then call Intersect().
             */
            var intersectRes = studentarray.Intersect(ExceptCollectionOfstudent, new ISDistinctcompareTrue());

            Console.WriteLine("Collection of Intersect Method\n" + string.Join(" \n", intersectRes.Select(s => s.name + " " + s.id)));

            Console.WriteLine("\nExample: Select ID,Name from FirstYear and Second Year data Who are same..");
            var studentintersectresult = firstyearstudents.Intersect(secondyearstudents, new IssameasSecondyear());

            Console.WriteLine("\nCollection of Student Intersect Records:\n" + string.Join(" \n", studentintersectresult.Select(s => "ID:" + s.ID + " Name: " + s.Name)));
            Console.WriteLine("\n\t\t\t***Using  Union***");

            /*
             * The Union extension method requires two collections and returns a new collection that includes distinct elements from both the collections.
             * The Union operator is Not Supported in C# & VB.Net Query syntax. However, you can use Union method on query variable or wrap whole query into brackets and then call Union().
             */
            var unionres = studentarray.Union(ExceptCollectionOfstudent, new ISDistinctcompareTrue());

            Console.WriteLine("Collection of UNION Method\n" + string.Join(" \n", unionres.Select(s => s.name + " " + s.id)));

            /*
             * Example: If the first year B'tech students was goe's to Secondyear classes,But the New peoples was Joined into same class. Find the count and list of students in SecondYearClass.
             * For FirstYear And Second Year maintain saperate Data...
             */

            Console.WriteLine("\nExample: If the first year B'tech students was goe's to Secondyear classes,But the New peoples was Joined into same class. Find the count and list of students in FirstYear and SecondYear Classes Without repeating." +
                              "For FirstYear And Second Year maintain saperate Data...\n");
            var Result = firstyearstudents.Union(secondyearstudents, new IssameasSecondyear());

            Console.WriteLine($"Collection List Count: {Result.Count()} \nCollection List is\n" + string.Join("\n", Result.Select(S => "ID:" + S.ID + " Name:" + S.Name)));

            Console.WriteLine("\n\t\t\t***Using  Skip & SkipWhile***");

            /*
             * Skip:	Skips elements up to a specified position starting from the first element in a sequence.
             * SkipWhile:	Skips elements based on a condition until an element does not satisfy the condition. If the first element itself doesn't satisfy the condition, it then skips 0 elements and returns all the elements in the sequence.
             * SkipWhile:- skips the elements upto condition is satisfied after satisfied once it won't work it can display the remaining elements..
             */
            Console.WriteLine("Skips elements up to a specified position starting from the first element in a sequence.\nAfter Skip upto the 2nd position the collections are:  " + string.Join(" ", intlist.Skip(2).Select(s => s)));
            Console.WriteLine("SkipWhile:\nSkip while Collection with max lenth 3 are :\n" + string.Join("\n", stringlist.SkipWhile(s => s.Length < 4)));

            Console.WriteLine("\n\t\t\t***Using  Take & TakeWhile***");

            /*
             * Take:	Takes elements up to a specified position starting from the first element in a sequence.
             * TakeWhile:	Returns elements from the first element until an element does not satisfy the condition. If the first element itself doesn't satisfy the condition then returns an empty collection.
             */
            Console.WriteLine("Take elements up to a specified position starting from the first element in a sequence.\nAfter Take upto the 2nd position the collections are:  " + string.Join(" ", intlist.Take(2).Select(s => s)));
            Console.WriteLine("TakeWhile:\nTake while Collection with max Size 3 are :\n" + string.Join("\n", stringlist.TakeWhile(s => s.Length < 4)));


            Console.WriteLine("\n\t\t\t***Using AsEnumerable & AsQueryable Conversion***");

            var asenumarableres = studentarray.Select(s => s).Where(s => s.salary > 12500).AsEnumerable();

            Console.WriteLine(string.Join(" ", asenumarableres.Select(s => s.name)));
            Console.WriteLine(string.Join(" ", from nameunder1 in asenumarableres select nameunder1.name));
            var asenumarableresqury = studentarray.Select(s => s).Where(s => s.salary > 12500).AsQueryable();

            Console.WriteLine(string.Join(" ", from nameunder1 in asenumarableresqury select nameunder1.name));

            Console.WriteLine("\n\t\t\t***Using Expression***");
            Stopwatch watch = new Stopwatch();

            watch.Start();
            Expression <Func <student, bool> > isstudent = s => s.salary > 10000 && s.salary < 50000 && s.Branch == "Cse";
            Func <student, bool> isreallyeligible        = isstudent.Compile();
            var result = isreallyeligible(new student {
                id = 20, name = "naveen", des = "gdsjb", Branch = "Cse", salary = 20000
            });

            watch.Stop();
            Console.WriteLine(result + "  ==>" + watch.ElapsedMilliseconds);
            watch.Restart();
            Func <student, bool> isfunc = s => s.salary > 10000 && s.salary < 50000 && s.Branch == "Cse";
            var resultfunc = isfunc(new student {
                id = 20, name = "naveen", des = "gdsjb", Branch = "Cse", salary = 10000
            });

            watch.Stop();
            Console.WriteLine(resultfunc + "  ==>" + watch.ElapsedMilliseconds);
            Console.ReadKey();
        }
		bool IntroduceFixedStatements(List<ILNode> body, int i)
		{
			ILExpression initValue;
			ILVariable pinnedVar;
			int initEndPos;
			if (!MatchFixedInitializer(body, i, out pinnedVar, out initValue, out initEndPos))
				return false;
			
			ILFixedStatement fixedStmt = body.ElementAtOrDefault(initEndPos) as ILFixedStatement;
			if (fixedStmt != null) {
				ILExpression expr = fixedStmt.BodyBlock.Body.LastOrDefault() as ILExpression;
				if (expr != null && expr.Code == ILCode.Stloc && expr.Operand == pinnedVar && IsNullOrZero(expr.Arguments[0])) {
					// we found a second initializer for the existing fixed statement
					fixedStmt.Initializers.Insert(0, initValue);
					body.RemoveRange(i, initEndPos - i);
					fixedStmt.BodyBlock.Body.RemoveAt(fixedStmt.BodyBlock.Body.Count - 1);
					if (pinnedVar.Type.IsByReference)
						pinnedVar.Type = new PointerType(((ByReferenceType)pinnedVar.Type).ElementType);
					return true;
				}
			}
			
			// find where pinnedVar is reset to 0:
			int j;
			for (j = initEndPos; j < body.Count; j++) {
				ILVariable v2;
				ILExpression storedVal;
				// stloc(pinned_Var, conv.u(ldc.i4(0)))
				if (body[j].Match(ILCode.Stloc, out v2, out storedVal) && v2 == pinnedVar) {
					if (IsNullOrZero(storedVal)) {
						break;
					}
				}
			}
			// Create fixed statement from i to j
			fixedStmt = new ILFixedStatement();
			fixedStmt.Initializers.Add(initValue);
			fixedStmt.BodyBlock = new ILBlock(body.GetRange(initEndPos, j - initEndPos)); // from initEndPos to j-1 (inclusive)
			body.RemoveRange(i + 1, Math.Min(j, body.Count - 1) - i); // from i+1 to j (inclusive)
			body[i] = fixedStmt;
			if (pinnedVar.Type.IsByReference)
				pinnedVar.Type = new PointerType(((ByReferenceType)pinnedVar.Type).ElementType);
			
			return true;
		}
        protected void SaveBtn_Click(object sender, EventArgs e)
        {
            FromDateTxt.Text = ReformateDateFromPicker(FromDateTxt.Text);
            entry            = new Entry();
            Entry_List       = new List <Entry>();
            Sale             = new PurchaseInvoice();
            LSales           = new List <PurchaseInvoice>();
            int RecordID          = 0;
            int EntryIDInEditMode = 0;
            int MaxEntrID;

            if (!TaxFlag)
            {
                //entry.maxid();
                MaxEntrID = (int)db.Entry.ToList().Max(o => o.EntryID) + 1;
                // MaxEntrID =MoveID;
            }
            else
            {
                MaxEntrID = OldKeadID;
            }
            decimal Mab3at = 0, Khasm = 0, khasmarba7tgary = 0, AddedValueTax = 0;

            foreach (var grdrow in Result_lst)
            {
                // entry.maxRecordID(entry.MoveID);
                RecordID = (int)db.Entry.ToList().Where(o => o.EntryID == MaxEntrID).Max(s => s.RecordID) + 1;
                // = RecordID;

                Mab3at += grdrow.SValue;

                //حالة التعديل
                if (EditFlag == true && FalseCounter != Result_lst.Count)
                {
                    if (grdrow.KeadNo != 0)
                    {
                        EntryIDInEditMode = grdrow.KeadNo;
                    }
                    else
                    {
                        grdrow.KeadNo = Result_lst.ElementAtOrDefault(0).KeadNo;
                    }

                    Entry_List.Add(new Entry()
                    {
                        EntryID       = grdrow.KeadNo,
                        RecordID      = int.Parse(grdrow.moveID),
                        EntryType     = " قيد" + BillTypeDrop.SelectedItem.Text,
                        SubAccount_id = grdrow.subAccountID,//  العميل دائن يقيمة البضاعه
                        value         = grdrow.SValue,
                        status        = "دائن",
                        Date          = DateTime.Parse(FromDateTxt.Text, CultureInfo.CreateSpecificCulture("ar-EG")),
                        description   = "المورد دائن يقيمة البضاعه",
                    });
                }
                else
                {
                    Entry_List.Add(new Entry()
                    {
                        EntryID       = MaxEntrID,
                        RecordID      = int.Parse(grdrow.moveID),
                        EntryType     = " قيد" + BillTypeDrop.SelectedItem.Text,
                        SubAccount_id = grdrow.subAccountID,//  العميل دائن يقيمة البضاعه
                        value         = grdrow.SValue,
                        status        = "دائن",
                        Date          = DateTime.Parse(FromDateTxt.Text, CultureInfo.CreateSpecificCulture("ar-EG")),
                        description   = "المورد دائن يقيمة البضاعه",
                    });
                }


                RecordID++;



                Sale = db.PurchaseInvoice.FirstOrDefault(o => o.PurchaseType == bool.Parse(BillTypeDrop.SelectedValue) &
                                                         o.KeadNo == int.Parse(grdrow.moveID));
                //   Sale.GetPOByOrderID(grdrow.moveID,bool.Parse( BillTypeDrop.SelectedValue));
                //  Sale.KeadNo = MaxEntrID;
                if (FalseCounter == Result_lst.Count)//جديد
                {
                    Sale.KeadNo = MaxEntrID;
                }
                else
                {
                    Sale.KeadNo = grdrow.KeadNo;
                }
                LSales.Add(Sale);
            }
            /////////////////End Loop
            if (EditFlag == true && FalseCounter != Result_lst.Count)
            {
                if (Mab3at > 0)
                {
                    Entry_List.Add(new Entry()
                    {
                        EntryID       = EntryIDInEditMode,
                        RecordID      = 0,
                        EntryType     = " قيد" + BillTypeDrop.SelectedItem.Text,
                        SubAccount_id = 32010002,//حساب المشتريات
                        value         = Mab3at,
                        status        = "مدين",
                        Date          = DateTime.Parse(FromDateTxt.Text, CultureInfo.CreateSpecificCulture("ar-EG")),
                        description   = "حساب المشتريات",
                    });
                }
            }
            else
            {
                if (Mab3at > 0)
                {
                    Entry_List.Add(new Entry()
                    {
                        EntryID       = MaxEntrID,
                        RecordID      = 0,
                        EntryType     = " قيد" + BillTypeDrop.SelectedItem.Text,
                        SubAccount_id = 32010002,//حساب المبيعات
                        value         = Mab3at,
                        status        = "مدين",
                        Date          = DateTime.Parse(FromDateTxt.Text, CultureInfo.CreateSpecificCulture("ar-EG")),
                        description   = "حساب المشتريات",
                    });
                }
            }


            ///////////////////////



            if (EditFlag == true && FalseCounter != Result_lst.Count)
            {
                foreach (var en in Entry_List)
                {
                    en.LoginID = ExtendedMethod.LoginedUser.Id;
                    db.Entry.AddOrUpdate();
                }
                db.SaveChanges();
                //  entry.Operations("Edit", Entry_List);
                addErrorTxt.Text = "تم الحفظ بنجاح";
            }
            else
            {
                db.Entry.AddRange(Entry_List);
                db.SaveChanges();
                //  entry.Operations("Add", Entry_List);
                addErrorTxt.Text = "تمت الاضافة بنجاح";
            }
            addErrorTxt.ForeColor = System.Drawing.Color.Green;
            foreach (var s in LSales)
            {
                // s.UserID = ExtendedMethod.LoginedUser.Id;
                db.PurchaseInvoice.AddOrUpdate(s);
            }
            db.SaveChanges();
            //  Sale.Operations("Edit", LSales);
            AccountGrd.DataSource = null;
            AccountGrd.DataBind();

            FromDateTxt.Text           = DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day;
            BillTypeDrop.SelectedIndex = 0;
        }
Exemplo n.º 59
0
        public void ShowStateGUI()
        {
            GUI.backgroundColor = new Color(0.8f,0.8f,1);

            GUILayout.BeginHorizontal();

            if (m_EditMode == EditMode.Nothing)
            {
                if (GUILayout.Button("Add Variable", GUILayout.MaxWidth(120), GUILayout.ExpandWidth(false)))
                {
                    m_EditMode = EditMode.AddNewVariable;
                    m_EditVariable = new Variable();
                    m_EditVariable.m_GameObject = gameObject;
                    m_AttachScript = false;
                }
            }
            else
            {
                if (GUILayout.Button("Cancel", GUILayout.MaxWidth(120), GUILayout.ExpandWidth(false)))
                {
                    m_EditVariable.RemoveScript();
                    m_EditMode = EditMode.Nothing;
                    m_EditVariable = new Variable();
                    m_EditVariable.m_GameObject = gameObject;
                }
            }

            if ((m_EditMode == EditMode.AddNewVariable || m_EditMode == EditMode.EditExistingVariable) && GUILayout.Button("Ok", GUILayout.MaxWidth(120), GUILayout.ExpandWidth(false)))
            {
                if (m_EditMode == EditMode.AddNewVariable)
                {
                    if (!HasVariable(m_EditVariable.m_Name) && m_EditVariable.m_Name != "")
                    {
                        Variable newVariable = new Variable(m_EditVariable) ;

                        AddVariable(newVariable);

                        m_EditMode = EditMode.Nothing;
                    }
                    else
                    {
                        EditorUtility.DisplayDialog("Error", "There is already a variable with this name in this state. Please give the variable a unique name to be called from", "Ok");
                    }
                }
                else
                {
                    Variable newVariable = new Variable(m_EditVariable.m_Name, m_EditVariable.GetValue());
                    newVariable.m_GameObject = gameObject;

                    if (m_AttachScript)
                    {
                        newVariable.SetScript(m_EditVariable.m_UpdateScript);
                    }

                    SetVariable(newVariable);

                    m_EditMode = EditMode.Nothing;
                }
            }

            GUILayout.FlexibleSpace();
            float nameWidth = 100;
            float typeWidth = 100;
            float valueWidth = 60;
            float scriptWidth = 180;

            EditorGUIUtility.labelWidth = 80;
            m_DebugMode = EditorGUILayout.Toggle("DebugMode: ", m_DebugMode, GUILayout.MaxWidth (95));
            GUILayout.EndHorizontal ();

            GUILayout.BeginHorizontal();
            GUI.color = Color.yellow;
            GUILayout.Label("Name", GUILayout.MaxWidth(nameWidth), GUILayout.MinWidth(nameWidth), GUILayout.ExpandWidth(false));
            GUILayout.Label("Type", GUILayout.MaxWidth(typeWidth), GUILayout.MinWidth(typeWidth), GUILayout.ExpandWidth(false));
            GUILayout.Label("Value", GUILayout.MaxWidth(valueWidth), GUILayout.MinWidth(valueWidth), GUILayout.ExpandWidth(false));
            GUILayout.Label("Script", GUILayout.MaxWidth(scriptWidth), GUILayout.MinWidth(scriptWidth), GUILayout.ExpandWidth(false));
            GUI.color = Color.white;
            GUILayout.EndHorizontal();

            if (m_EditMode == EditMode.AddNewVariable || m_EditMode == EditMode.EditExistingVariable)
            {
                GUILayout.BeginHorizontal();

                if (m_EditMode == EditMode.AddNewVariable)
                    m_EditVariable.m_Name = EditorGUILayout.TextField(m_EditVariable.m_Name, GUILayout.MaxWidth(nameWidth), GUILayout.MinWidth(nameWidth), GUILayout.ExpandWidth(false));
                else
                    EditorGUILayout.LabelField(m_EditVariable.m_Name, GUILayout.MaxWidth(nameWidth), GUILayout.MinWidth(nameWidth), GUILayout.ExpandWidth(false));

                VariableType variableType = (VariableType)EditorGUILayout.EnumPopup(m_EditVariable.GetVariableType(), GUILayout.MaxWidth(typeWidth), GUILayout.MinWidth(typeWidth), GUILayout.ExpandWidth(false));
                if (variableType != m_EditVariable.GetVariableType())
                {
                    m_EditVariable.SetVariableType(variableType);
                    m_AttachScript = false;
                }

                if (m_EditVariable.GetVariableType () == VariableType.BOOLEAN)
                {
                    int index = (bool)m_EditVariable.GetValue() ? 1 : 0;

                    index = EditorGUILayout.Popup(index, m_BooleanStrings, GUILayout.MaxWidth(valueWidth), GUILayout.MinWidth(valueWidth), GUILayout.ExpandWidth(false));

                    m_EditVariable.SetValue(index == 1 ? true : false);
                }
                else if (m_EditVariable.GetVariableType() == VariableType.STRING)
                {
                    string stringValue = (string)m_EditVariable.GetValue();
                    m_EditVariable.SetValue(EditorGUILayout.TextArea(stringValue, GUILayout.MaxWidth(valueWidth), GUILayout.MinWidth(valueWidth), GUILayout.ExpandWidth(false)));
                }
                else if (m_EditVariable.GetVariableType() == VariableType.INT)
                {
                    int intValue = (int)m_EditVariable.GetValue();
                    m_EditVariable.SetValue(EditorGUILayout.IntField((int)intValue, GUILayout.MaxWidth(valueWidth), GUILayout.MinWidth(valueWidth), GUILayout.ExpandWidth(false)));
                }
                else if (m_EditVariable.GetVariableType() == VariableType.FLOAT)
                {
                    float floatValue = (float)m_EditVariable.GetValue();
                    m_EditVariable.SetValue(EditorGUILayout.FloatField(floatValue, GUILayout.MaxWidth(valueWidth), GUILayout.MinWidth(valueWidth), GUILayout.ExpandWidth(false)));
                }

                if (m_AttachScript = EditorGUILayout.Toggle(m_AttachScript, GUILayout.MaxWidth(10)))
                {
                    List<ScriptDescriptor> sensorScripts = ScriptManager.GetScriptsByType(typeof(BaseSensor));
                    List<ScriptDescriptor> filteredSensorScripts = new List<ScriptDescriptor>();
                    List<String> sensorScriptNames = new List<String>();

                    for (int i = 0; i < sensorScripts.Count(); i++)
                    {
                        if (sensorScripts[i].m_ReturnType.ToUpper() == m_EditVariable.GetVariableType().ToString())
                        {
                            filteredSensorScripts.Add(sensorScripts[i]);
                            sensorScriptNames.Add(sensorScripts[i].m_Name);
                        }
                    }

                    if (filteredSensorScripts.Count == 0)
                    {
                        EditorGUILayout.HelpBox("None of the sensor scripts return a type compatible with this variable type", MessageType.Info);
                    }
                    else
                    {
                        int sensorScriptIndex = -1;

                        if (m_EditVariable.m_UpdateScriptType != null)
                            sensorScriptIndex = filteredSensorScripts.FindIndex(sensorScript => sensorScript.m_Type == m_EditVariable.m_UpdateScriptType);

                        int newSensorScriptIndex = EditorGUILayout.Popup(Mathf.Max(sensorScriptIndex, 0), sensorScriptNames.ToArray(), GUILayout.MaxWidth(scriptWidth), GUILayout.MinWidth(valueWidth), GUILayout.ExpandWidth(false));

                        if ((newSensorScriptIndex > -1) && (newSensorScriptIndex != sensorScriptIndex))
                        {
                            m_EditVariable.SetScript(filteredSensorScripts.ElementAtOrDefault(newSensorScriptIndex).m_Type);

                            if (m_DebugMode)
                                Debug.Log("Updating AttachedScript: " + filteredSensorScripts.ElementAt(newSensorScriptIndex).m_Name);
                        }
                    }
                }
                else
                    m_EditVariable.RemoveScript();

                GUILayout.EndHorizontal();

                if (m_AttachScript && m_EditVariable.HasScript())
                {
                    m_EditVariable.m_UpdateScript.ShowScriptGUI();
                }
            }

            if (m_Variables.Count == 0)
            {
                EditorGUILayout.HelpBox("There are no variables in this state. Add some with the Add Variable button", MessageType.Info);
            }

            foreach (KeyValuePair<string, Variable> pair in m_Variables.ToArray())
            {
                if (pair.Value != null)
                {
                    GUILayout.BeginHorizontal();
                    GUI.color = Color.white;
                    GUI.backgroundColor = Color.white;

                    if (Application.isPlaying)
                    {
                        GUILayout.Label(pair.Value.m_Name, GUILayout.MaxWidth(nameWidth), GUILayout.MinWidth(nameWidth), GUILayout.ExpandWidth(false));
                        GUILayout.Label(pair.Value.GetType().ToString(), GUILayout.MaxWidth(typeWidth), GUILayout.MinWidth(typeWidth), GUILayout.ExpandWidth(false));

                        if (pair.Value.GetValue() != null)
                            GUILayout.Label(pair.Value.GetValue().ToString(), GUILayout.MaxWidth(valueWidth), GUILayout.MinWidth(valueWidth), GUILayout.ExpandWidth(false));
                        else
                            GUILayout.Label("", GUILayout.MaxWidth(valueWidth), GUILayout.MinWidth(valueWidth), GUILayout.ExpandWidth(false));

                        if (pair.Value.HasScript())
                        {
                            ScriptNameAttribute nameAttribute = pair.Value.m_UpdateScriptType.GetCustomAttributes(typeof(ScriptNameAttribute), false).FirstOrDefault() as ScriptNameAttribute;

                            GUILayout.Label(nameAttribute.name, GUILayout.MaxWidth(scriptWidth), GUILayout.MinWidth(scriptWidth), GUILayout.ExpandWidth(false));
                        }
                    }
                    else
                    {
                        GUILayout.Label(pair.Value.m_Name, GUILayout.MaxWidth(nameWidth), GUILayout.MinWidth(nameWidth), GUILayout.ExpandWidth(false));
                        GUILayout.Label(pair.Value.GetTypeString(), GUILayout.MaxWidth(typeWidth), GUILayout.MinWidth(typeWidth), GUILayout.ExpandWidth(false));

                        if (pair.Value.GetValue() != null)
                            GUILayout.Label(pair.Value.GetValue().ToString(), GUILayout.MaxWidth(valueWidth), GUILayout.MinWidth(valueWidth), GUILayout.ExpandWidth(false));

                        if (pair.Value.HasScript())
                        {
                            ScriptNameAttribute nameAttribute = pair.Value.m_UpdateScriptType.GetCustomAttributes(typeof(ScriptNameAttribute), false).FirstOrDefault() as ScriptNameAttribute;

                            GUILayout.Label(nameAttribute.name, GUILayout.MaxWidth(scriptWidth), GUILayout.MinWidth(scriptWidth), GUILayout.ExpandWidth(false));
                        }

                        GUILayout.FlexibleSpace(); //Set layout passed this point to align to the right
                        GUI.backgroundColor = new Color(0.6f, 1f, 0.6f);

                        if (GUILayout.Button("E", GUILayout.MaxWidth(20)))
                        {
                            EditVariable(pair.Value);
                        }

                        GUI.backgroundColor = new Color(1,0.6f,0.6f);

                        if (GUILayout.Button("X", GUILayout.MaxWidth(20)))
                        {
                            if (EditorUtility.DisplayDialog("Delete Variable " + pair.Value.m_Name, "Are you sure?", "Yes", "No"))
                            {
                                pair.Value.RemoveScript();
                                RemoveVariable(pair.Value.m_Name);
                            }
                        }
                    }

                    GUILayout.EndHorizontal();
                }
            }

            GUI.backgroundColor = Color.white;
            GUI.color = Color.white;
        }
        void ConvertBody(List <ILNode> body, int startPos, int bodyLength, List <KeyValuePair <ILLabel, StateRange> > labels)
        {
            newBody = new List <ILNode>();
            newBody.Add(MakeGoTo(labels, 0));
            List <SetState> stateChanges = new List <SetState>();
            int             currentState = -1;

            // Copy all instructions from the old body to newBody.
            for (int pos = startPos; pos < bodyLength; pos++)
            {
                ILExpression expr = body[pos] as ILExpression;
                if (expr != null && expr.Code == ILCode.Stfld && expr.Arguments[0].MatchThis())
                {
                    // Handle stores to 'state' or 'current'
                    if (GetFieldDefinition(expr.Operand as FieldReference) == stateField)
                    {
                        if (expr.Arguments[1].Code != ILCode.Ldc_I4)
                        {
                            throw new SymbolicAnalysisFailedException();
                        }
                        currentState = (int)expr.Arguments[1].Operand;
                        stateChanges.Add(new SetState(newBody.Count, currentState));
                    }
                    else if (GetFieldDefinition(expr.Operand as FieldReference) == currentField)
                    {
                        newBody.Add(new ILExpression(ILCode.YieldReturn, null, expr.Arguments[1]));
                    }
                    else
                    {
                        newBody.Add(body[pos]);
                    }
                }
                else if (returnVariable != null && expr != null && expr.Code == ILCode.Stloc && expr.Operand == returnVariable)
                {
                    // handle store+branch to the returnVariable
                    ILExpression br = body.ElementAtOrDefault(++pos) as ILExpression;
                    if (br == null || !(br.Code == ILCode.Br || br.Code == ILCode.Leave) || br.Operand != returnLabel || expr.Arguments[0].Code != ILCode.Ldc_I4)
                    {
                        throw new SymbolicAnalysisFailedException();
                    }
                    int val = (int)expr.Arguments[0].Operand;
                    if (val == 0)
                    {
                        newBody.Add(new ILExpression(ILCode.YieldBreak, null));
                    }
                    else if (val == 1)
                    {
                        newBody.Add(MakeGoTo(labels, currentState));
                    }
                    else
                    {
                        throw new SymbolicAnalysisFailedException();
                    }
                }
                else if (expr != null && expr.Code == ILCode.Ret)
                {
                    if (expr.Arguments.Count != 1 || expr.Arguments[0].Code != ILCode.Ldc_I4)
                    {
                        throw new SymbolicAnalysisFailedException();
                    }
                    // handle direct return (e.g. in release builds)
                    int val = (int)expr.Arguments[0].Operand;
                    if (val == 0)
                    {
                        newBody.Add(new ILExpression(ILCode.YieldBreak, null));
                    }
                    else if (val == 1)
                    {
                        newBody.Add(MakeGoTo(labels, currentState));
                    }
                    else
                    {
                        throw new SymbolicAnalysisFailedException();
                    }
                }
                else if (expr != null && expr.Code == ILCode.Call && expr.Arguments.Count == 1 && expr.Arguments[0].MatchThis())
                {
                    MethodDefinition method = GetMethodDefinition(expr.Operand as MethodReference);
                    if (method == null)
                    {
                        throw new SymbolicAnalysisFailedException();
                    }
                    StateRange stateRange;
                    if (method == disposeMethod)
                    {
                        // Explicit call to dispose is used for "yield break;" within the method.
                        ILExpression br = body.ElementAtOrDefault(++pos) as ILExpression;
                        if (br == null || !(br.Code == ILCode.Br || br.Code == ILCode.Leave) || br.Operand != returnFalseLabel)
                        {
                            throw new SymbolicAnalysisFailedException();
                        }
                        newBody.Add(new ILExpression(ILCode.YieldBreak, null));
                    }
                    else if (finallyMethodToStateRange.TryGetValue(method, out stateRange))
                    {
                        // Call to Finally-method
                        int index = stateChanges.FindIndex(ss => stateRange.Contains(ss.NewState));
                        if (index < 0)
                        {
                            throw new SymbolicAnalysisFailedException();
                        }

                        ILLabel label = new ILLabel();
                        label.Name = "JumpOutOfTryFinally" + stateChanges[index].NewState;
                        newBody.Add(new ILExpression(ILCode.Leave, label));

                        SetState stateChange = stateChanges[index];
                        // Move all instructions from stateChange.Pos to newBody.Count into a try-block
                        stateChanges.RemoveRange(index, stateChanges.Count - index);                         // remove all state changes up to the one we found
                        ILTryCatchBlock tryFinally = new ILTryCatchBlock();
                        tryFinally.TryBlock = new ILBlock(newBody.GetRange(stateChange.NewBodyPos, newBody.Count - stateChange.NewBodyPos));
                        newBody.RemoveRange(stateChange.NewBodyPos, newBody.Count - stateChange.NewBodyPos);                         // remove all nodes that we just moved into the try block
                        tryFinally.CatchBlocks  = new List <ILTryCatchBlock.CatchBlock>();
                        tryFinally.FinallyBlock = ConvertFinallyBlock(method);
                        newBody.Add(tryFinally);
                        newBody.Add(label);
                    }
                }
                else
                {
                    newBody.Add(body[pos]);
                }
            }
            newBody.Add(new ILExpression(ILCode.YieldBreak, null));
        }