System.Collections.Generic.IEnumerable.Contains(string, System.Collections.Generic.IEqualityComparer)

Here are the examples of the csharp api System.Collections.Generic.IEnumerable.Contains(string, System.Collections.Generic.IEqualityComparer) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1905 Examples 7

19 View Source File : AcsValidator.cs
License : MIT License
Project Creator : AElfProject

public IEnumerable<ValidationResult> Validate(System.Reflection.replacedembly replacedembly, RequiredAcs requiredAcs)
        {
            if (requiredAcs.AcsList.Count == 0)
                return Enumerable.Empty<ValidationResult>(); // No ACS required

            var acsBaseList = GetServiceDescriptorIdenreplacedies(GetServerServiceDefinition(replacedembly));

            if (requiredAcs.RequireAll)
            {
                // Contract should have all listed ACS as a base
                if (requiredAcs.AcsList.Any(acs => !acsBaseList.Contains(acs)))
                    return new List<ValidationResult>
                    {
                        new AcsValidationResult(
                            $"Contract should have all {string.Join(", ", requiredAcs.AcsList)} as base.")
                    };
            }
            else
            {
                // Contract should have at least one of the listed ACS in the list as a base
                if (requiredAcs.AcsList.All(acs => !acsBaseList.Contains(acs)))
                    return new List<ValidationResult>
                    {
                        new AcsValidationResult(
                            $"Contract should have at least {string.Join(" or ", requiredAcs.AcsList)} as base.")
                    };
            }

            return Enumerable.Empty<ValidationResult>();
        }

19 View Source File : RequirePrefixesAttribute.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public override Task<bool> ExecuteCheckAsync(CommandContext ctx, bool help)
            => Task.FromResult((help && this.ShowInHelp) || this.Prefixes.Contains(ctx.Prefix, ctx.CommandsNext.GetStringComparer()));

19 View Source File : SearchIndexBuildRequest.cs
License : MIT License
Project Creator : Adoxio

public static void ProcessMessage(OrganizationServiceCachePluginMessage message, SearchIndexInvalidationData searchIndexInvalidationData = null, OrganizationServiceContext serviceContext = null)
		{
			if (!SearchManager.Enabled)
			{
				ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Search isn't enabled for the current application.");

				return;
			}

			if (message == null)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, "Search Index build failure. Plugin Message is null.");

				return;
			}

			SearchProvider provider;
			var forceBuild = message.Target != null && message.Target.LogicalName == "adx_website";

			if (!TryGetSearchProvider(out provider))
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, "Search Index build failure. Search Provider could not be found.");

				return;
			}
			
			if (forceBuild || BuildMessages.Contains(message.MessageName, MessageComparer))
			{
				PerformBuild(provider);

				ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Search Index was successfully built.");

				return;
			}

            IContentMapProvider contentMapProvider = AdxstudioCrmConfigurationManager.CreateContentMapProvider();

            if (UpdateMessages.Contains(message.MessageName, MessageComparer))
			{
				if (message.Target == null || string.IsNullOrEmpty(message.Target.LogicalName))
				{
					throw new HttpException((int)HttpStatusCode.BadRequest, string.Format("Message {0} requires an EnreplacedyName (enreplacedy logical name) parameter.", message.MessageName));
				}

				if (message.Target == null || message.Target.Id == Guid.Empty)
				{
					throw new HttpException((int)HttpStatusCode.BadRequest, string.Format("Message {0} requires an ID (enreplacedy ID) parameter.", message.MessageName));
				}

				if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.CmsEnabledSearching))
				{
					if (message.Target.LogicalName == "savedquery")
					{
						var cachedSavedQuery = SearchMetadataCache.Instance.SearchSavedQueries.FirstOrDefault(x => x.SavedQueryId == message.Target.Id);
						if (cachedSavedQuery != null)
						{
							// SavedQueryUniqueId is timestamp to verify which change was published and need to invalidate Search Index 
							var actualSavedQueryUniqueId = SearchMetadataCache.Instance.GetSavedQueryUniqueId(message.Target.Id);
							if (cachedSavedQuery.SavedQueryIdUnique != actualSavedQueryUniqueId)
							{
								PerformUpdateAsync(provider, updater => updater.UpdateEnreplacedySet(cachedSavedQuery.EnreplacedyName));
								SearchMetadataCache.Instance.CompleteMetadataUpdateForSearchSavedQuery(cachedSavedQuery, actualSavedQueryUniqueId);
							}
						}
					}

					if (message.Target.LogicalName == "adx_webpage" && searchIndexInvalidationData != null)
					{
						// bypreplaced cache and go straight to CRM in case cache hasn't been updated yet
						var response = serviceContext.Execute(new RetrieveRequest {
							Target =  new EnreplacedyReference(message.Target.LogicalName, message.Target.Id),
							ColumnSet = new ColumnSet(new string[] {
								"adx_parentpageid",
								"adx_websiteid",
								"adx_publishingstateid",
								"adx_partialurl"
							})
						}) as RetrieveResponse;

						if (response != null && response.Enreplacedy != null)
						{ 
							var updatedWebPage = response.Enreplacedy;

							// If the parent page or website change, we need to invalidate that whole section of the web page hierarchy since the web roles
							// may change, including both root and content pages if MLP is enabled.
							if (!EnreplacedyReferenceEquals(searchIndexInvalidationData.ParentPage, updatedWebPage.GetAttributeValue<EnreplacedyReference>("adx_parentpageid")) ||
									!EnreplacedyReferenceEquals(searchIndexInvalidationData.Website, updatedWebPage.GetAttributeValue<EnreplacedyReference>("adx_websiteid")))
							{
								PerformUpdateAsync(provider, updater => updater.UpdateCmsEnreplacedyTree("adx_webpage", message.Target.Id));
							}
							// If the publishing state or partial URL change, this will effect all the content pages and localized enreplacedies underneath them
							// if MLP is enabled. If MLP is disabled, LCID will equal null, and then just all pages/enreplacedies underneath this will reindex.
							else if (!EnreplacedyReferenceEquals(searchIndexInvalidationData.PublishingState, updatedWebPage.GetAttributeValue<EnreplacedyReference>("adx_publishingstateid")) ||
							  searchIndexInvalidationData.PartialUrl != updatedWebPage.GetAttributeValue<string>("adx_partialurl"))
							{
								PerformUpdateAsync(provider, updater => updater.UpdateCmsEnreplacedyTree("adx_webpage", message.Target.Id, searchIndexInvalidationData.Lcid));
							}
						}
					}

					if (message.Target.LogicalName == "adx_webpageaccesscontrolrule_webrole")
					{
						contentMapProvider.Using(contentMap =>
						{
							WebPageAccessControlRuleToWebRoleNode webAccessControlToWebRoleNode;

							if (contentMap.TryGetValue(new EnreplacedyReference(message.Target.LogicalName, message.Target.Id), out webAccessControlToWebRoleNode))
							{
								PerformUpdateAsync(provider, updater => updater.UpdateCmsEnreplacedyTree("adx_webpage", webAccessControlToWebRoleNode.WebPageAccessControlRule.WebPage.Id));
							}
						});
					}

					if (message.Target.LogicalName == "adx_webpageaccesscontrolrule")
                    {
                        contentMapProvider.Using(contentMap =>
                        {
                            WebPageAccessControlRuleNode webAccessControlNode;

                            if (contentMap.TryGetValue(new EnreplacedyReference(message.Target.LogicalName, message.Target.Id), out webAccessControlNode))
                            {
                                PerformUpdateAsync(provider, updater => updater.UpdateCmsEnreplacedyTree("adx_webpage", webAccessControlNode.WebPage.Id));
                            }
                        });
                    }

                    if (message.Target.LogicalName == "adx_communityforumaccesspermission")
                    {
                        contentMapProvider.Using(contentMap =>
                        {
                            ForumAccessPermissionNode forumAccessNode;

                            if (contentMap.TryGetValue(new EnreplacedyReference(message.Target.LogicalName, message.Target.Id), out forumAccessNode))
                            {
                                PerformUpdateAsync(provider, updater => updater.UpdateCmsEnreplacedyTree("adx_communityforum", forumAccessNode.Forum.Id));
                            }
                        });
                    }

					if (message.Target.LogicalName == "connection")
					{
						var fetch = new Fetch
						{
							Enreplacedy = new FetchEnreplacedy("connection")
							{
								Filters = new[] { new Filter {
									Conditions = new List<Condition> { new Condition("connectionid", ConditionOperator.Equal, message.Target.Id) }
								} }
							}
						};

						var connectionEnreplacedy = ((RetrieveSingleResponse)serviceContext.Execute(fetch.ToRetrieveSingleRequest())).Enreplacedy;

						var record1Id = connectionEnreplacedy.GetAttributeValue<EnreplacedyReference>("record1id");
						var record2Id = connectionEnreplacedy.GetAttributeValue<EnreplacedyReference>("record2id");

						// new product replacedociation to knowledge article could mean new product filtering rules
						if (record1Id != null && record1Id.LogicalName == "knowledgearticle" 
							&& record2Id != null && record2Id.LogicalName == "product")
						{
							PerformUpdate(provider, updater => updater.UpdateEnreplacedy("knowledgearticle", record1Id.Id));
						}
					}
					if (message.Target.LogicalName == "adx_contentaccesslevel")
					{
						var fetch = GetEnreplacedyFetch("adx_knowledgearticlecontentaccesslevel", "knowledgearticleid",
							"adx_contentaccesslevelid", message.Target.Id.ToString());

						var enreplacedies = FetchEnreplacedies(serviceContext, fetch);
						var guids = enreplacedies.Select(e => e.GetAttributeValue<Guid>("knowledgearticleid")).ToList();

						PerformUpdateAsync(provider, updater => updater.UpdateEnreplacedySet("knowledgearticle", "knowledgearticleid", guids));
					}
					if (message.Target.LogicalName == "product")
					{
						var fetch = GetEnreplacedyFetch("connection", "record2id", "record1id", message.Target.Id.ToString());

						var enreplacedies = FetchEnreplacedies(serviceContext, fetch);
						var guids = enreplacedies.Select(e => e.GetAttributeValue<EnreplacedyReference>("record2id")).Select(g => g.Id).Distinct().ToList();

						PerformUpdateAsync(provider, updater => updater.UpdateEnreplacedySet("knowledgearticle", "knowledgearticleid", guids));
					}
					if (message.Target.LogicalName == "annotation")
					{
						
						var annotationFetch = new Fetch
						{
							Enreplacedy = new FetchEnreplacedy("annotation", new[] { "objectid" })
							{
								Filters = new[] 
								{
									new Filter
									{
										Conditions = new List<Condition>
										{
											new Condition("annotationid", ConditionOperator.Equal, message.Target.Id),
										}
									}
								}
							}
						};


						var response =
							(RetrieveSingleResponse)serviceContext.Execute(annotationFetch.ToRetrieveSingleRequest());

						if (response.Enreplacedy == null)
						{
							ADXTrace.Instance.TraceError(TraceCategory.Application, $"Retrieve of annotation enreplacedy failed for annotationId : {message.Target.Id}");
							throw new TransientNullReferenceException($"Retrieve of annotation enreplacedy failed for annotationId : {message.Target.Id}");
						}

						var knowledgeArticle = response.Enreplacedy?.GetAttributeValue<EnreplacedyReference>("objectid");
						if (knowledgeArticle == null)
						{
							ADXTrace.Instance.TraceError(TraceCategory.Application, $"Could not find objectId in the retrieved annotation with annotationId : {message.Target.Id}");
							throw new TransientNullReferenceException($"Could not find objectId in the retrieved annotation with annotationId : {message.Target.Id}");
						}

						if (knowledgeArticle.Id != Guid.Empty && knowledgeArticle.LogicalName == "knowledgearticle")
						{
							//Updating Knowledge Article related to this Annotation
							PerformUpdate(provider, updater => updater.UpdateEnreplacedy("knowledgearticle", knowledgeArticle.Id));
						}
					}
					//Re-indexing annotations and related knowledge articles if NotesFilter gets changes
					if (message.Target.LogicalName == "adx_sitesetting" && message.Target.Name == "KnowledgeManagement/NotesFilter")
					{
						var notes = GetAllNotes(serviceContext);
						var knowledgeArticles = notes.Select(n => n.GetAttributeValue<EnreplacedyReference>("objectid"))
								.Distinct().Select(ka => ka.Id).Distinct()
								.ToList();

						PerformUpdateAsync(provider, updater => updater.UpdateEnreplacedySet("annotation", "annotationid", notes.Select(n => n.Id).Distinct().ToList()));
						PerformUpdateAsync(provider, updater => updater.UpdateEnreplacedySet("knowledgearticle", "knowledgearticleid", knowledgeArticles));

						return;
					}
					if (message.Target.LogicalName == "adx_sitesetting" && message.Target.Name == "KnowledgeManagement/DisplayNotes")
					{
						PerformUpdateAsync(provider, updater => updater.DeleteEnreplacedySet("annotation"));

						var notes = GetAllNotes(serviceContext);
						var knowledgeArticles = notes.Select(n => n.GetAttributeValue<EnreplacedyReference>("objectid"))
								.Distinct().Select(ka => ka.Id).Distinct()
								.ToList();

						PerformUpdateAsync(provider, updater => updater.UpdateEnreplacedySet("annotation", "annotationid", notes.Select(n => n.Id).Distinct().ToList()));
						PerformUpdateAsync(provider, updater => updater.UpdateEnreplacedySet("knowledgearticle", "knowledgearticleid", knowledgeArticles));
						return;
					}
				}

                PerformUpdate(provider, updater => updater.UpdateEnreplacedy(message.Target.LogicalName, message.Target.Id));

				ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Search Index was successfully updated. ({0}, {1}:{2})", message.MessageName, EnreplacedyNamePrivacy.GetEnreplacedyName(message.Target.LogicalName), message.Target.Id));

				return;
			}

            if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.CmsEnabledSearching))
            {
                if (replacedociateDisreplacedociateMessages.Contains(message.MessageName, MessageComparer))
                {
                    if (message.Target == null || string.IsNullOrEmpty(message.Target.LogicalName))
                    {
                        throw new HttpException((int)HttpStatusCode.BadRequest, string.Format("Message {0} requires an EnreplacedyName (enreplacedy logical name) parameter.", message.MessageName));
                    }

                    if (message.Target == null || message.Target.Id == Guid.Empty)
                    {
                        throw new HttpException((int)HttpStatusCode.BadRequest, string.Format("Message {0} requires an ID (enreplacedy ID) parameter.", message.MessageName));
                    }

                    if (message.RelatedEnreplacedies == null)
                    {
                        throw new HttpException((int)HttpStatusCode.BadRequest, string.Format("Message {0} requires an EnreplacedyName (enreplacedy logical name) parameter.", message.MessageName));
                    }

                    if ((message.Target.LogicalName == "adx_webpage" && HasRelatedEnreplacedyType(message, "adx_webpageaccesscontrolrule")) ||
                        (message.Target.LogicalName == "adx_communityforum" && HasRelatedEnreplacedyType(message, "adx_communityforumaccesspermission")) ||
                        (message.Target.LogicalName == "adx_ideaforum" && HasRelatedEnreplacedyType(message, "adx_webrole")))
                    {
                        PerformUpdateAsync(provider, updater => updater.UpdateCmsEnreplacedyTree(message.Target.LogicalName, message.Target.Id));
                    }

                    if (message.Target.LogicalName == "adx_webpageaccesscontrolrule" && 
						(HasRelatedEnreplacedyType(message, "adx_webrole") || HasRelatedEnreplacedyType(message, "adx_publishingstate")))
                    {
                        contentMapProvider.Using(contentMap =>
                        {
                            WebPageAccessControlRuleNode webAccessControlNode;

                            if (contentMap.TryGetValue(new EnreplacedyReference(message.Target.LogicalName, message.Target.Id), out webAccessControlNode))
                            {
                                PerformUpdateAsync(provider, updater => updater.UpdateCmsEnreplacedyTree("adx_webpage", webAccessControlNode.WebPage.Id));
                            }
                        });
                    }

                    if (message.Target.LogicalName == "adx_communityforumaccesspermission" && HasRelatedEnreplacedyType(message, "adx_webrole"))
                    {
                        contentMapProvider.Using(contentMap =>
                        {
                            ForumAccessPermissionNode forumAccessNode;

                            if (contentMap.TryGetValue(new EnreplacedyReference(message.Target.LogicalName, message.Target.Id), out forumAccessNode))
                            {
                                PerformUpdateAsync(provider, updater => updater.UpdateCmsEnreplacedyTree("adx_communityforum", forumAccessNode.Forum.Id));
                            }
                        });
                    }

                    if (message.Target.LogicalName == "adx_contentaccesslevel" && HasRelatedEnreplacedyType(message, "knowledgearticle"))
                    {
						foreach (var enreplacedyReference in message.RelatedEnreplacedies)
						{
							if (enreplacedyReference.LogicalName == "knowledgearticle")
							{
								PerformUpdate(provider, updater => updater.UpdateEnreplacedy(enreplacedyReference.LogicalName, enreplacedyReference.Id));
							}
						}
                        
                    }

					//Perform update for disreplacedociate messages from WebNotification Plugin
					if (message.Target.LogicalName == "knowledgearticle" && (HasRelatedEnreplacedyType(message, "adx_contentaccesslevel")))
					{
						PerformUpdate(provider, updater => updater.UpdateEnreplacedy(message.Target.LogicalName, message.Target.Id));
					}

					ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Search Index was successfully updated. ({0}, {1}:{2})", message.MessageName, EnreplacedyNamePrivacy.GetEnreplacedyName(message.Target.LogicalName), message.Target.Id));

                    return;
                }
            }

            if (DeleteMessages.Contains(message.MessageName, MessageComparer))
			{
				if (message.Target == null || string.IsNullOrEmpty(message.Target.LogicalName))
				{
					throw new HttpException((int)HttpStatusCode.BadRequest, string.Format("Message {0} requires an EnreplacedyName (enreplacedy logical name) parameter.", message.MessageName));
				}

				if (message.Target == null || message.Target.Id == Guid.Empty)
				{
					throw new HttpException((int)HttpStatusCode.BadRequest, string.Format("Message {0} requires an ID (enreplacedy ID) parameter.", message.MessageName));
				}

                if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.CmsEnabledSearching))
				{
					if (message.Target.LogicalName == "adx_webpageaccesscontrolrule" && searchIndexInvalidationData.WebPage != null)
					{
						PerformUpdateAsync(provider, updater => updater.UpdateCmsEnreplacedyTree(searchIndexInvalidationData.WebPage.LogicalName, searchIndexInvalidationData.WebPage.Id));
					}

					if (message.Target.LogicalName == "adx_webpageaccesscontrolrule_webrole" && searchIndexInvalidationData.WebPage != null)
					{
						PerformUpdateAsync(provider, updater => updater.UpdateCmsEnreplacedyTree(searchIndexInvalidationData.WebPage.LogicalName, searchIndexInvalidationData.WebPage.Id));
					}

					if (message.Target.LogicalName == "adx_communityforumaccesspermission" && searchIndexInvalidationData.Forum != null)
					{
						PerformUpdateAsync(provider, updater => updater.UpdateCmsEnreplacedyTree(searchIndexInvalidationData.Forum.LogicalName, searchIndexInvalidationData.Forum.Id));
					}

					if (message.Target.LogicalName == "connection")
					{
						// To update Knowledge Article that was related to this connection(Product) we need to retrieve KAid from index
						var relatedEnreplacedyList = GetRelatedEnreplacedies("connectionid", message.Target.Id, 1);

						if (!relatedEnreplacedyList.Any()) { return; }

						// Taking first here since there can only be one Knowledge Article related to connection
						var enreplacedy = relatedEnreplacedyList.First();
						if (enreplacedy.LogicalName != null && enreplacedy.LogicalName.Equals("knowledgearticle"))
						{
							PerformUpdate(provider, updater => updater.UpdateEnreplacedy("knowledgearticle", enreplacedy.Id));
						}
						return;
					}
					if (message.Target.LogicalName == "product" || message.Target.LogicalName == "adx_contentaccesslevel")
					{
						IEnumerable<EnreplacedyReference> relatedKnowledgeArticles = new List<EnreplacedyReference>();
						var indexedFieldName = "adx_contentaccesslevel";

						if (message.Target.LogicalName == "product")
						{
							indexedFieldName = FixedFacetsConfiguration.ProductFieldFacetName;
						}

						relatedKnowledgeArticles = GetRelatedEnreplacedies(indexedFieldName, message.Target.Id, 10000);
						if (!relatedKnowledgeArticles.Any()) { return; }

						var knowledgeArticlesIds =
							relatedKnowledgeArticles.Where(r => r.LogicalName.Equals("knowledgearticle")).Select(i => i.Id).ToList();

						PerformUpdateAsync(provider, updater => updater.UpdateEnreplacedySet("knowledgearticle", "knowledgearticleid", knowledgeArticlesIds));
					}
					if (message.Target.LogicalName == "annotation")
					{
						var relatedKnowledgeArticles = GetRelatedEnreplacedies("annotationid", message.Target.Id, 10);
						var knowledgeArticleId = relatedKnowledgeArticles.Where(a => a.LogicalName == "knowledgearticle").Select(ka => ka.Id).FirstOrDefault();

						//Updating Knowledge Article related to this Annotation
						PerformUpdate(provider, updater => updater.UpdateEnreplacedy("knowledgearticle", knowledgeArticleId));
					}
				}

				PerformUpdate(provider, updater => updater.DeleteEnreplacedy(message.Target.LogicalName, message.Target.Id));

				ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Search Index was successfully updated. ({0}, {1}:{2})", message.MessageName, EnreplacedyNamePrivacy.GetEnreplacedyName(message.Target.LogicalName), message.Target.Id));

				return;
			}

			var supportedMessages = DeleteMessages.Union(BuildMessages.Union(UpdateMessages, MessageComparer), MessageComparer);

			ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format(@"Search Index Build Failed. Message ""{0}"" is not supported. Valid messages are {1}.", message.MessageName, string.Join(", ", supportedMessages.ToArray())));
		}

19 View Source File : NPCPatches.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public static void NPC_marriageDuties_Postfix(NPC __instance)
        {
            try
            {
                if (ModEntry.tempOfficialSpouse == __instance)
                {
                    ModEntry.tempOfficialSpouse = null;
                }
                return;

                // custom dialogues


                // dialogues

                if (__instance.currentMarriageDialogue == null || __instance.currentMarriageDialogue.Count == 0)
                    return;

                bool gotDialogue = false;

                for (int i = 0; i < __instance.currentMarriageDialogue.Count; i++)
                {
                    MarriageDialogueReference mdr = __instance.currentMarriageDialogue[i];

                    if (mdr.DialogueFile == "Strings\\StringsFromCSFiles")
                    {
                        foreach (string[] array in csMarriageDialoguesChoose)
                        {
                            string key = array[ModEntry.myRand.Next(0, array.Length)];
                            if (array.Contains(key))
                            {
                                Dictionary<string, string> marriageDialogues = null;
                                try
                                {
                                    marriageDialogues = ModEntry.PHelper.Content.Load<Dictionary<string, string>>("Characters\\Dialogue\\MarriageDialogue" + __instance.Name, ContentSource.GameContent);
                                }
                                catch (Exception)
                                {
                                }
                                MarriageDialogueReference mdrn;
                                if (marriageDialogues != null && marriageDialogues.ContainsKey(key))
                                {
                                    mdrn = new MarriageDialogueReference("Characters\\Dialogue\\MarriageDialogue" + __instance.Name, key, mdr.IsGendered, mdr.Subsreplacedutions.ToArray());
                                }
                                else
                                {
                                    mdrn = new MarriageDialogueReference("Characters\\Dialogue\\MarriageDialogue" + __instance.Name, key, mdr.IsGendered, mdr.Subsreplacedutions.ToArray());
                                }
                                if(mdrn != null)
                                {
                                    __instance.currentMarriageDialogue[i] = mdrn;
                                }
                                gotDialogue = true;
                                break;
                            }
                        }
                        if (!gotDialogue)
                        {
                            if (csMarriageDialoguesReplace.Contains(mdr.DialogueKey))
                            {
                                Dictionary<string, string> marriageDialogues = null;
                                try
                                {
                                    marriageDialogues = ModEntry.PHelper.Content.Load<Dictionary<string, string>>("Characters\\Dialogue\\MarriageDialogue" + __instance.Name, ContentSource.GameContent);
                                }
                                catch (Exception)
                                {
                                }
                                if (marriageDialogues != null && marriageDialogues.ContainsKey(mdr.DialogueKey))
                                {
                                    MarriageDialogueReference mdrn = new MarriageDialogueReference("Characters\\Dialogue\\MarriageDialogue" + __instance.Name, mdr.DialogueKey, mdr.IsGendered, mdr.Subsreplacedutions.ToArray());

                                    if (mdrn != null)
                                    {
                                        __instance.currentMarriageDialogue[i] = mdrn;
                                    }
                                    break;
                                }

                            }
                        }

                    }
                    else if (mdr.DialogueFile == "MarriageDialogue")
                    {
                        foreach (string[] array in csMarriageDialoguesChoose)
                        {
                            string key = array[ModEntry.myRand.Next(0, array.Length)];
                            if (array.Contains(key))
                            {
                                Dictionary<string, string> marriageDialogues = null;
                                try
                                {
                                    marriageDialogues = ModEntry.PHelper.Content.Load<Dictionary<string, string>>("Characters\\Dialogue\\MarriageDialogue" + __instance.Name, ContentSource.GameContent);
                                }
                                catch (Exception)
                                {
                                }
                                if (marriageDialogues != null && marriageDialogues.ContainsKey(key))
                                {
                                    MarriageDialogueReference mdrn = new MarriageDialogueReference("Characters\\Dialogue\\MarriageDialogue" + __instance.Name, key, mdr.IsGendered, mdr.Subsreplacedutions.ToArray());
                                    if (mdrn != null)
                                    {
                                        __instance.currentMarriageDialogue[i] = mdrn;
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
/*
                return;
                if (Config.RemoveSpouseOrdinaryDialogue && __instance.Name != Game1.player.spouse && __instance.currentMarriageDialogue.Count > 0)
                {
                    __instance.CurrentDialogue.Clear();
                    foreach (MarriageDialogueReference mdr in __instance.currentMarriageDialogue)
                    {
                        __instance.CurrentDialogue.Push(mdr.GetDialogue(__instance));
                        __instance.currentMarriageDialogue.Clear();
                    }
                }
*/
            }
            catch (Exception ex)
            {
                Monitor.Log($"Failed in {nameof(NPC_marriageDuties_Postfix)}:\n{ex}", LogLevel.Error);
            }
        }

19 View Source File : StyleExtensions.cs
License : MIT License
Project Creator : Adoxio

private static void GetDisplayModeFileGroups(string prefix, IEnumerable<FileNameTrie.Node> nodes, ICollection<DisplayModeFileGroup> groups, string[] displayModeIds)
		{
			var group = new DisplayModeFileGroup(prefix);

			foreach (var node in nodes)
			{
				if (node.Key == FileNameTrie.TerminalNodeKey)
				{
					group.Add(new DisplayModeFile(node.Value));

					continue;
				}

				FileNameTrie.Node terminalNode;

				if (node.TryGetTerminalNode(out terminalNode))
				{
					if (prefix == string.Empty)
					{
						groups.Add(new DisplayModeFileGroup(node.Key)
						{
							new DisplayModeFile(terminalNode.Value)
						});

						continue;
					}

					if (displayModeIds.Contains(node.Key, StringComparer.OrdinalIgnoreCase))
					{
						group.Add(new DisplayModeFile(terminalNode.Value, node.Key));

						continue;
					}
				}

				var nodePrefix = prefix == string.Empty
					? node.Key
					: "{0}.{1}".FormatWith(prefix, node.Key);

				GetDisplayModeFileGroups(nodePrefix, node.Children, groups, displayModeIds);
			}

			if (group.Any())
			{
				groups.Add(group);
			}
		}

19 View Source File : CrmClaimsIdentityFactory.cs
License : MIT License
Project Creator : Adoxio

public override async Task<ClaimsIdenreplacedy> CreateAsync(UserManager<TUser, string> manager, TUser user, string authenticationType)
		{
			var idenreplacedy = await base.CreateAsync(manager, user, authenticationType).WithCurrentCulture();

			var loginInfo = await this.AuthenticationManager.GetExternalLoginInfoAsync();
			var provider = loginInfo?.Login?.LoginProvider;

			if (!string.IsNullOrWhiteSpace(provider))
			{
				idenreplacedy.AddClaim(this.ToClaim("http://schemas.adxstudio.com/xrm/2014/02/idenreplacedy/claims/loginprovider", provider, null));
			}

			if (!string.IsNullOrWhiteSpace(user.Email))
			{
				idenreplacedy.AddClaim(this.ToClaim(System.Security.Claims.ClaimTypes.Email, user.Email, null));
			}

			if (user.ContactId != null)
			{
				idenreplacedy.AddClaim(this.ToClaim("http://schemas.adxstudio.com/xrm/2014/02/idenreplacedy/claims/id", user.ContactId.Id.ToString(), null));
				idenreplacedy.AddClaim(this.ToClaim("http://schemas.adxstudio.com/xrm/2014/02/idenreplacedy/claims/logicalname", user.ContactId.LogicalName, null));
			}

			if (this.KeepExternalLoginClaims)
			{
				if (loginInfo != null && loginInfo.ExternalIdenreplacedy != null)
				{
					// exclude identifier types that may result in producing a false idenreplacedy

					var claims = loginInfo.ExternalIdenreplacedy.Claims.Where(claim => !_externalLoginClaimsToExclude.Contains(claim.Type));
					idenreplacedy.AddClaims(claims);
				}
			}

			return idenreplacedy;
		}

19 View Source File : SceneTransitionHelper.cs
License : MIT License
Project Creator : Aeroluna

internal static void Patch(IDifficultyBeatmap difficultyBeatmap)
        {
            if (difficultyBeatmap.beatmapData is CustomBeatmapData customBeatmapData)
            {
                IEnumerable<string>? requirements = customBeatmapData.beatmapCustomData.Get<List<object>>("_requirements")?.Cast<string>();
                bool noodleRequirement = requirements?.Contains(CAPABILITY) ?? false;
                NoodleController.ToggleNoodlePatches(noodleRequirement);
            }
        }

19 View Source File : ModuleManager.cs
License : MIT License
Project Creator : acid-chicken

public static async Task HandleCommandAsync(SocketMessage socketMessage)
        {
            var position = 0;
            var message = socketMessage as SocketUserMessage;
            var guildChannel = message.Channel as IGuildChannel;
            if (message == null ||
                !(
                    (message.HasMentionPrefix(DiscordClient.CurrentUser, ref position)) ||
                    message.HreplacedtringPrefix
                    (
                        guildChannel != null &&
                        ApplicationConfig.PrefixOverrides.ContainsKey(guildChannel.GuildId) ?
                        ApplicationConfig.PrefixOverrides[guildChannel.GuildId] :
                        Prefix,
                        ref position
                    ) ||
                    (
                        message.Channel is IDMChannel &&
                        message.Author.Id != DiscordClient.CurrentUser.Id
                    )
                ) ||
                (
                    !NonIgnorable.Contains(message.Content.Substring(position).Split(' ')[0]) &&
                    (guildChannel != null && ((guildChannel as ITextChannel)?.Topic?.Contains("./ignore") ?? false))
                )) return;
            await message.AddReactionAsync(Reaction);
            var context = new CommandContext(DiscordClient, message);
            using (var typing = context.Channel.EnterTypingState())
            {
                if (++Busy > ApplicationConfig.Busy && !ApplicationConfig.Managers.Contains(context.User.Id))
                {
                    await context.Channel.SendMessageAsync
                    (
                        text: context.User.Mention,
                        embed:
                            new EmbedBuilder()
                                .Withreplacedle("ビジー状態")
                                .WithDescription("現在Botが混み合っています。時間を空けてから再度お試し下さい。")
                                .WithCurrentTimestamp()
                                .WithColor(Colors.Orange)
                                .WithColor(Colors.Red)
                                .WithFooter(EmbedManager.CurrentFooter)
                                .WithAuthor(context.User)
                    );
                }
                else
                {
                    var result = await Service.ExecuteAsync(context, position);
                    if (!result.IsSuccess)
                    {
                        await context.Channel.SendMessageAsync
                        (
                            text: context.User.Mention,
                            embed:
                                new EmbedBuilder()
                                    .Withreplacedle("コマンドエラー")
                                    .WithDescription(result.ErrorReason)
                                    .WithCurrentTimestamp()
                                    .WithColor(Colors.Red)
                                    .WithFooter(EmbedManager.CurrentFooter)
                                    .WithAuthor(context.User)
                        );
                    }
                }
            }
            Busy--;
            await message.RemoveReactionAsync(Reaction, DiscordClient.CurrentUser);
        }

19 View Source File : RoleService.cs
License : MIT License
Project Creator : aishang2015

public List<string> GetRoleClaimValue(string[] roleIds, string claimType)
        {
            return (from rc in _systemRoleClaimRepository.Get()
                    where rc.ClaimType == claimType && roleIds.Contains(rc.RoleId.ToString())
                    select rc.ClaimValue).Distinct().ToList();
        }

19 View Source File : TabularModelSerializer.cs
License : MIT License
Project Creator : action-bi-toolkit

private static Action<TextWriter> WriteMeasureXml(JToken json)
        {
            return writer =>
            {
                using (var xml = XmlWriter.Create(writer, new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true, WriteEndDoreplacedentOnClose = true }))
                {
                    xml.WriteStartElement("Measure");
                    xml.WriteAttributeString("Name", json.Value<string>("name"));

#if false // Removed in pbixproj v0.6
                    // Handle Expression
                    if (json["expression"] != null)
                    {
                        xml.WriteStartElement("Expression");
                        if (json["expression"] is JArray expr)
                        {
                            xml.WriteCData(String.Join(Environment.NewLine, expr.ToObject<string[]>()));
                        }
                        else
                        {
                            xml.WriteCData(json.Value<string>("expression"));
                        }
                        xml.WriteEndElement();
                    }
#endif
                    // Any other properties
                    foreach (var prop in json.Values<JProperty>().Where(p => !(new[] { "name", "expression", "annotations", "extendedProperties" }).Contains(p.Name)))
                    {
                        xml.WriteStartElement(prop.Name.ToPascalCase());
                        xml.WriteValue(prop.Value.Value<string>());
                        xml.WriteEndElement();
                    }

                    // ExtendedProperties
                    if (json["extendedProperties"] is JArray extendedProperties)
                    {
                        foreach (var extendedProperty in extendedProperties)
                        {
                            xml.WriteStartElement("ExtendedProperty");
                            {
                                xml.WriteCData(extendedProperty.ToString());
                            }
                            xml.WriteEndElement();
                        }
                    }

                    // Annotations
                    if (json["annotations"] is JArray annotations)
                    {
                        foreach (var annotation in annotations)
                        {
                            xml.WriteStartElement("Annotation");
                            xml.WriteAttributeString("Name", annotation.Value<string>("name"));
                            var value = annotation?.Value<string>("value");
                            try
                            {
                                XElement.Parse(value).WriteTo(xml);
                            }
                            catch (XmlException)
                            {
                                xml.WriteValue(value);
                            }
                            xml.WriteEndElement();
                        }
                    }
                }
            };
        }

19 View Source File : DictionaryConverter.cs
License : MIT License
Project Creator : AdrianWilczynski

public override TypeNode Handle(TypeSyntax type)
        {
            if (type is GenericNameSyntax generic && ConvertibleFrom.Contains(generic.Identifier.Text)
                && generic.TypeArgumentList.Arguments.Count == 2)
            {
                var key = _converter.Handle(generic.TypeArgumentList.Arguments[0]);

                if (key is String || key is Number)
                {
                    return new Dictionary(
                        key: key,
                        value: _converter.Handle(generic.TypeArgumentList.Arguments[1]));
                }
            }

            return base.Handle(type);
        }

19 View Source File : PortalRouteHandler.cs
License : MIT License
Project Creator : Adoxio

protected override IPortalContext OnPortalLoaded(RequestContext requestContext, IPortalContext portal)
		{
			if (portal == null) throw new ArgumentNullException("portal");

			if (portal.Enreplacedy != null && _redirectedEnreplacedies.Contains(portal.Enreplacedy.LogicalName))
			{
				// Check if we need to follow any rules with regards to Language Code prefix in URL (only applies if multi-language is enabled)
				var contextLanguageInfo = requestContext.HttpContext.GetContextLanguageInfo();
				if (contextLanguageInfo.IsCrmMultiLanguageEnabled)
				{
					bool needRedirect = requestContext.HttpContext.Request.HttpMethod == WebRequestMethods.Http.Get
											&& ((ContextLanguageInfo.DisplayLanguageCodeInUrl != contextLanguageInfo.RequestUrlHasLanguageCode)
											|| contextLanguageInfo.ContextLanguage.UsedAsFallback);
					if (needRedirect)
					{
						string redirectPath = contextLanguageInfo.FormatUrlWithLanguage();
						ADXTrace.Instance.TraceInfo(TraceCategory.Monitoring, "OnPortalLoaded redirecting(1)");
						requestContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Redirect;
						requestContext.HttpContext.Response.RedirectLocation = redirectPath;
						requestContext.HttpContext.Response.End();
						return null;
					}
				}
			}

			var isInvalidNode = (portal.Enreplacedy == null || portal.Path == null);

			// If the node is null, isn't a CrmSiteMapNode, has no rewrite path, or is a 404, try other options.
			if (isInvalidNode || portal.StatusCode == HttpStatusCode.NotFound)
			{
				var redirectProvider = PortalCrmConfigurationManager.CreateDependencyProvider(PortalName).GetDependency<IRedirectProvider>();
				var context = requestContext.HttpContext;
				var clientUrl = new UrlBuilder(context.Request.Url);

				// Try matching user-defined redirects, and URL history--in that order.
				var redirectMatch = redirectProvider.Match(portal.Website.Id, clientUrl);

				// If we have a successful match, redirect.
				if (redirectMatch.Success)
				{
					ADXTrace.Instance.TraceInfo(TraceCategory.Monitoring, "OnPortalLoaded redirecting(2)");
					context.Trace.Write(GetType().FullName, @"Redirecting path ""{0}"" to ""{1}""".FormatWith(clientUrl.Path, redirectMatch.Location));

					context.Response.StatusCode = (int)redirectMatch.StatusCode;
					context.Response.RedirectLocation = redirectMatch.Location;
					context.Response.End();

					return null;
				}
			}

			return base.OnPortalLoaded(requestContext, portal);
		}

19 View Source File : LocalizationPXExceptionAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private ExpressionSyntax GetMessageExpression(SyntaxNodereplacedysisContext syntaxContext, ImmutableArray<IParameterSymbol> pars, ArgumentListSyntax args)
        {
            syntaxContext.CancellationToken.ThrowIfCancellationRequested();

            ArgumentSyntax messageArg = null;

            foreach (ArgumentSyntax a in args.Arguments)
            {
                IParameterSymbol p = a.DetermineParameter(pars, false);

                if (_messageArgNames.Contains(p?.Name, StringComparer.Ordinal))
                {
                    messageArg = a;
                    break;
                }
            }

            if (messageArg == null || messageArg.Expression == null)
                return null;

            return messageArg.Expression;
        }

19 View Source File : TokenContract_Fees.cs
License : MIT License
Project Creator : AElfProject

private bool ChargeFirstSufficientToken(Dictionary<string, long> symbolToAmountMap, out string symbol,
            out long amount, out long existingBalance)
        {
            symbol = null;
            amount = 0L;
            existingBalance = 0L;
            var fromAddress = Context.Sender;
            string symbolOfValidBalance = null;

            // Traverse available token symbols, check balance one by one
            // until there's balance of one certain token is enough to pay the fee.
            foreach (var symbolToAmount in symbolToAmountMap)
            {
                existingBalance = GetBalance(fromAddress, symbolToAmount.Key);
                symbol = symbolToAmount.Key;
                amount = symbolToAmount.Value;

                if (existingBalance > 0)
                {
                    symbolOfValidBalance = symbol;
                }

                if (existingBalance >= amount) break;
            }

            if (existingBalance >= amount) return true;

            var primaryTokenSymbol = GetPrimaryTokenSymbol(new Empty()).Value;
            if (symbolToAmountMap.Keys.Contains(primaryTokenSymbol))
            {
                symbol = primaryTokenSymbol;
                existingBalance = GetBalance(fromAddress, primaryTokenSymbol);
            }
            else
            {
                symbol = symbolOfValidBalance;
                if (symbol != null)
                {
                    existingBalance = GetBalance(fromAddress, symbolOfValidBalance);
                }
            }

            return false;
        }

19 View Source File : MixedRealityEditorSettings.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static void LogConfigurationWarnings()
        {
            // Ensure compatibility with the pre-2019.3 XR architecture for customers / platforms
            // with legacy requirements.
            if (!XRSettingsUtilities.LegacyXREnabled)
            {
                Debug.LogWarning("<b>Virtual reality supported</b> not enabled. Check <i>XR Settings</i> under <i>Player Settings</i>");
            }

            if (!MixedRealityOptimizeUtils.IsOptimalRenderingPath())
            {
                Debug.LogWarning($"XR stereo rendering mode not set to <b>{RenderingMode}</b>. See <i>Mixed Reality Toolkit</i> > <i>Utilities</i> > <i>Optimize Window</i> tool for more information to improve performance");
            }

            // If targeting Windows Mixed Reality platform
            if (MixedRealityOptimizeUtils.IsBuildTargetUWP())
            {
                if (!MixedRealityOptimizeUtils.IsDepthBufferSharingEnabled())
                {
                    // If depth buffer sharing not enabled, advise to enable setting
                    Debug.LogWarning("<b>Depth Buffer Sharing</b> is not enabled to improve hologram stabilization. See <i>Mixed Reality Toolkit</i> > <i>Utilities</i> > <i>Optimize Window</i> tool for more information to improve performance");
                }

                if (!MixedRealityOptimizeUtils.IsWMRDepthBufferFormat16bit())
                {
                    // If depth format is 24-bit, advise to consider 16-bit for performance.
                    Debug.LogWarning("<b>Depth Buffer Sharing</b> has 24-bit depth format selected. Consider using 16-bit for performance. See <i>Mixed Reality Toolkit</i> > <i>Utilities</i> > <i>Optimize Window</i> tool for more information to improve performance");
                }

                if (!UwpRecommendedAudioSpatializers.Contains(SpatializerUtilities.CurrentSpatializer))
                {
                    Debug.LogWarning($"This application is not using the recommended <b>Audio Spatializer Plugin</b>. Go to <i>Project Settings</i> > <i>Audio</i> > <i>Spatializer Plugin</i> and select one of the following: {string.Join(", ", UwpRecommendedAudioSpatializers)}.");
                }
            }
            else if (SpatializerUtilities.CurrentSpatializer == null)
            {
                Debug.LogWarning($"This application is not using an <b>Audio Spatializer Plugin</b>. Go to <i>Project Settings</i> > <i>Audio</i> > <i>Spatializer Plugin</i> and select one of the available options.");
            }
        }

19 View Source File : MultiplayerConnectedPlayerInstaller.cs
License : MIT License
Project Creator : Aeroluna

private static IReadonlyBeatmapData Exclude(IReadonlyBeatmapData result)
        {
            if (result is CustomBeatmapData customBeatmapData)
            {
                string[] excludedTypes = new string[]
                {
                    ANIMATETRACK,
                    replacedIGNPATHANIMATION,
                };

                customBeatmapData.customEventsData.RemoveAll(n => excludedTypes.Contains(n.type));

                customBeatmapData.customData["isMultiplayer"] = true;
            }

            return result;
        }

19 View Source File : SolutionDefinition.cs
License : MIT License
Project Creator : Adoxio

private static IEnumerable<ManyRelationshipDefinition> Union(IDictionary<string, ManyRelationshipDefinition> first, IDictionary<string, ManyRelationshipDefinition> second, IEnumerable<string> baseSolutions)
		{
			if (first == null && second == null) yield break;

			if (first == null)
			{
				foreach (var relationship in second.Values)
				{
					yield return relationship;
				}

				yield break;
			}

			if (second == null)
			{
				foreach (var relationship in first.Values)
				{
					yield return relationship;
				}

				yield break;
			}

			foreach (var sr in second.Values.Where(e => !baseSolutions.Contains(e.Solution)))
			{
				yield return sr;
			}
		}

19 View Source File : IOHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static void CopyPath(string srcPath, string destPath, string ext = "*.*", bool child = true, bool replace = false, params string[] excludes)
        {
            if (!Directory.Exists(srcPath))
            {
                return;
            }
            CheckPath(destPath);
            foreach (var ch in Directory.GetFiles(srcPath, ext))
            {
                if (excludes != null && excludes.Contains(Path.GetExtension(ch), StringComparer.OrdinalIgnoreCase))
                {
                    continue;
                }
                var ch2 = Path.Combine(destPath, Path.GetFileName(ch));
                if (replace || !File.Exists(ch2))
                {
                    File.Copy(ch, ch2, true);
                }
            }
            if (!child)
            {
                return;
            }
            foreach (var ch in Directory.GetDirectories(srcPath))
            {
                if (excludes != null && excludes.Contains(Path.GetFileName(ch), StringComparer.OrdinalIgnoreCase))
                {
                    continue;
                }
                CopyPath(ch, Path.Combine(destPath, Path.GetFileName(ch) ?? throw new InvalidOperationException()), ext, true, replace, excludes);
            }
        }

19 View Source File : ConfigurationStore.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

public string GetStringOption(ConfigurationOption option)
        {
            if (!_options.Keys.Contains(option.Key))
            {
                return null;
            }
            else if (_options[option.Key] is string @string)
            {
                return @string;
            }
            else if (_options[option.Key] != null)
            {
                throw new ConfigurationStoreException(string.Format("Requested string option \"{0}\" is not a string", option.Key));
            }
            else
            {
                return null;
            }
        }

19 View Source File : UserService.cs
License : MIT License
Project Creator : aishang2015

private async Task AddUserToRolesAsync(SystemUser user, IEnumerable<string> roleIds)
        {
            await _userRoleRepository.RemoveAsync(r => user.Id == r.UserId);

            var roleaArray = from role in _roleRepository.Get()
                             where roleIds.Contains(role.Id.ToString())
                             select role.Name;
            foreach (var roleId in roleIds)
            {
                await _userRoleRepository.AddAsync(new SystemUserRole
                {
                    RoleId = int.Parse(roleId),
                    UserId = user.Id
                });
            }
        }

19 View Source File : WebNotificationHandler.cs
License : MIT License
Project Creator : Adoxio

private void ProcessNotification(CancellationToken cancellationToken, PluginMessageRequest request)
		{
			try
			{
				if (cancellationToken.IsCancellationRequested)
				{
					return;
				}

				if (!WebNotificationCryptography.ValidateRequest(request.Authorization))
				{
					WebNotificationEventSource.Log.AuthorizationValidationFailed();

					return;
				}

				var message = this.GetMessage(request);

				if (message == null)
				{
					WebNotificationEventSource.Log.MessageInvalid();

					return;
				}

				CacheInvalidation.ProcessMessage(message);

				if (SearchIndexApplicableMessages.Contains(message.MessageName, MessageComparer))
				{
					var serviceContext = CrmConfigurationManager.CreateContext();
					SearchIndexBuildRequest.ProcessMessage(message, serviceContext: serviceContext);
				}
			}
			catch (TaskCanceledException e)
			{
				ADXTrace.Instance.TraceWarning(TraceCategory.Application, e.Message);
			}
		}

19 View Source File : CmsEntityServiceProvider.cs
License : MIT License
Project Creator : Adoxio

protected virtual void InterceptTagExtensionChange(HttpContext context, IPortalContext portal, OrganizationServiceContext serviceContext, Enreplacedy enreplacedy, CmsEnreplacedyMetadata enreplacedyMetadata, JObject extensions, CmsEnreplacedyOperation operation, Tuple<string, string, string> taggableEnreplacedy)
		{
			var tagExtension = extensions.Property("tags");

			if (tagExtension == null || tagExtension.Value == null)
			{
				return;
			}

			var tagRelationship = new Relationship(taggableEnreplacedy.Item3);

			var website = portal.Website.ToEnreplacedyReference();
			var appliedTags = tagExtension.Value.Values<string>().Distinct(TagInfo.TagComparer).ToArray();

			var existingTags = operation == CmsEnreplacedyOperation.Create
				? new Enreplacedy[] { }
				: GetTags(serviceContext, enreplacedy, website, taggableEnreplacedy);

			var tagsToRemove = existingTags.Where(e => !appliedTags.Contains(e.GetAttributeValue<string>("adx_name"), TagInfo.TagComparer));

			foreach (var tagToRemove in tagsToRemove)
			{
				serviceContext.DeleteLink(enreplacedy, tagRelationship, tagToRemove);
			}

			var existingTagNames = existingTags.Select(e => e.GetAttributeValue<string>("adx_name")).ToArray();
			var tagsToAdd = appliedTags.Where(t => !existingTagNames.Contains(t, TagInfo.TagComparer));

			foreach (var tagToAdd in tagsToAdd)
			{
				var tagName = tagToAdd;

				var tag = (from t in serviceContext.CreateQuery("adx_tag")
						   where t.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == website
						   where t.GetAttributeValue<string>("adx_name") == tagName
						   select t).FirstOrDefault();

				if (tag == null)
				{
					var newTag = new Enreplacedy("adx_tag");

					newTag.SetAttributeValue("adx_name", tagName);
					newTag.SetAttributeValue("adx_websiteid", website);

					var response = (CreateResponse)serviceContext.Execute(new CreateRequest
					{
						Target = newTag
					});

					newTag.Id = response.id;
					newTag.SetAttributeValue("adx_tagid", response.id);

					serviceContext.Attach(newTag);
					serviceContext.AddLink(enreplacedy, tagRelationship, newTag);
				}
				else
				{
					serviceContext.AddLink(enreplacedy, tagRelationship, tag);
				}
			}
		}

19 View Source File : MoqMethodIdentifier.cs
License : MIT License
Project Creator : Abc-Arbitrage

private bool IsMethodString([CanBeNull] IDeclaredElement declaredElement, params string[] methodName)
		{
			var declaredElementreplacedtring = declaredElement.ConvertToString();

			return methodName.Contains(declaredElementreplacedtring);
		}

19 View Source File : FilterOptionGroup.cs
License : MIT License
Project Creator : Adoxio

private static FilterOption ToFilterOption(AttributeMetadata attributeMetadata, Filter filter,
			string[] selected, int languageCode)
		{
			var label = ToLabel(attributeMetadata as EnumAttributeMetadata, filter, languageCode);
			var id = filter.Extensions.GetExtensionValue("id");

			return new FilterOption
			{
				Id = id,
				Type = filter.Extensions.GetExtensionValue("uiinputtype"),
				Label = label,
				Checked = selected.Contains(id),
				Text = string.Join(",", selected),
			};
		}

19 View Source File : CommandSettings.cs
License : MIT License
Project Creator : actions

public List<string> Validate()
        {
            List<string> unknowns = new List<string>();

            // detect unknown commands
            unknowns.AddRange(_parser.Commands.Where(x => !validCommands.Contains(x, StringComparer.OrdinalIgnoreCase)));

            // detect unknown flags
            unknowns.AddRange(_parser.Flags.Where(x => !validFlags.Contains(x, StringComparer.OrdinalIgnoreCase)));

            // detect unknown args
            unknowns.AddRange(_parser.Args.Keys.Where(x => !validArgs.Contains(x, StringComparer.OrdinalIgnoreCase)));

            return unknowns;
        }

19 View Source File : ArrayConverter.cs
License : MIT License
Project Creator : AdrianWilczynski

public override TypeNode Handle(TypeSyntax type)
        {
            if (type is ArrayTypeSyntax array)
            {
                return new Array(
                    of: _converter.Handle(array.ElementType),
                    rank: array.RankSpecifiers.Aggregate(0, (total, specifier) => total + specifier.Rank));
            }
            else if (type is IdentifierNameSyntax identified && ConvertibleFromIdentified.Contains(identified.Identifier.Text))
            {
                return new Array(
                    of: new Any(),
                    rank: 1);
            }
            else if (type is GenericNameSyntax generic && ConvertibleFromGeneric.Contains(generic.Identifier.Text)
                && generic.TypeArgumentList.Arguments.Count == 1)
            {
                return new Array(
                    of: _converter.Handle(generic.TypeArgumentList.Arguments.Single()),
                    rank: 1);
            }

            return base.Handle(type);
        }

19 View Source File : FilterOptionGroup.cs
License : MIT License
Project Creator : Adoxio

private static FilterOption ToFilterOption(AttributeMetadata attributeMetadata, Condition condition, string[] selected, int languageCode)
		{
			// a scalar option

			var label = ToLabel(attributeMetadata as EnumAttributeMetadata, condition, languageCode)
				?? condition.UiName
					?? condition.Value as string;

			var id = condition.Extensions.GetExtensionValue("id");

			return new FilterOption
			{
				Id = id,
				Type = condition.Extensions.GetExtensionValue("uiinputtype"),
				Label = label,
				Checked = selected.Contains(id),
				Text = string.Join(",", selected),
			};
		}

19 View Source File : MainControl.xaml.cs
License : MIT License
Project Creator : Actipro

private void InitializeFilteredCountries() {
			var countries = new string[] { "PT", "ES", "GB", "FR", "DE" };
			this.FilteredCountries = from c in Country.Countries where countries.Contains(c.Alpha2Code) select c;
			this.SelectedFilteredCountry = "GB";
		}

19 View Source File : ExternalLinkPinCodeSecurityHandler.cs
License : Apache License 2.0
Project Creator : advanced-cms

public bool UserHasAccessToLink(ExternalReviewLink externalReviewLink)
        {
            // check if PIN code option is enabled
            if (!_externalReviewOptions.PinCodeSecurity.Enabled)
            {
                return true;
            }

            // check if PIN code is required for the link
            if (string.IsNullOrEmpty(externalReviewLink.PinCode))
            {
                return true;
            }

            var user = HttpContext.Current.User;
            if (user != null && user.Idenreplacedy != null && user.Idenreplacedy.IsAuthenticated)
            {
                // check if user is in role that allow to access link without PIN code
                if (_externalReviewOptions.PinCodeSecurity.RolesWithoutPin != null)
                {
                    foreach (var role in _externalReviewOptions.PinCodeSecurity.RolesWithoutPin)
                    {
                        if (user.IsInRole(role))
                        {
                            return true;
                        }
                    }
                }

                // check if user is allowed to view the page
                if (user.Idenreplacedy is ClaimsIdenreplacedy idenreplacedy)
                {
                    var claim = idenreplacedy.FindFirst("ExternalReviewTokens");
                    if (claim != null)
                    {
                        if (!string.IsNullOrEmpty(claim.Value))
                        {
                            var tokens = claim.Value.Split('|');
                            return tokens.Contains(externalReviewLink.Token);
                        }
                    }
                }
            }

            return false;
        }

19 View Source File : ConfigurationStore.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

public int? GetIntOption(ConfigurationOption option)
        {
            if (!_options.Keys.Contains(option.Key))
            {
                return null;
            }
            else if (_options[option.Key] is int @int)
            {
                return @int;
            }
            else if (_options[option.Key] != null)
            {
                throw new ConfigurationStoreException(string.Format("Requested int option \"{0}\" is not an int", option.Key));
            }
            else
            {
                return null;
            }
        }

19 View Source File : MobilePhonePackJSON.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public bool CanInvite(NPC npc)
        {
            if(incompatibleMods != null)
            {
                foreach(string mod in incompatibleMods)
                {
                    if (ModEntry.SHelper.ModRegistry.IsLoaded(mod))
                        return false;
                }
            }
            if(requiredMods != null)
            {
                foreach(string mod in requiredMods)
                {
                    if (!ModEntry.SHelper.ModRegistry.IsLoaded(mod))
                        return false;
                }
            }
            if (date && !Game1.player.friendshipData[npc.Name].IsDating() && !Game1.player.friendshipData[npc.Name].IsEngaged() && !Game1.player.friendshipData[npc.Name].IsMarried())
                return false;
            if (!allowMarried && (Game1.player.friendshipData[npc.Name].IsMarried() || Game1.player.friendshipData[npc.Name].IsEngaged()))
                return false;
            if (requireMarried && !Game1.player.friendshipData[npc.Name].IsMarried() && !Game1.player.friendshipData[npc.Name].IsEngaged())
                return false;
            if (allowedNPCs != null && !allowedNPCs.Split(',').Contains(npc.Name))
                return false;
            if (Game1.player.friendshipData[npc.Name].Points < minPoints)
                return false;
            if (maxPoints != -1 && Game1.player.friendshipData[npc.Name].Points >= maxPoints)
                return false;
            if (season != null && Game1.currentSeason != season)
                return false;
            if (dayOfWeek != 0 && Game1.dayOfMonth % 7 != dayOfWeek)
                return false;
            if (Game1.timeOfDay < minTimeOfDay)
                return false;
            if (maxTimeOfDay != -1 && Game1.timeOfDay >= maxTimeOfDay)
                return false;
            return true;

        }

19 View Source File : ArgsParser.cs
License : Apache License 2.0
Project Creator : adamralph

public static (IReadOnlyList<string> Targets, Options Options, IReadOnlyList<string> UnknownOptions, bool showHelp) Parse(IReadOnlyCollection<string> args)
        {
            var helpArgs = args.Where(arg => helpOptions.Contains(arg, StringComparer.OrdinalIgnoreCase));
            var nonHelpArgs = args.Where(arg => !helpOptions.Contains(arg, StringComparer.OrdinalIgnoreCase));

            var targets = nonHelpArgs.Where(arg => !arg.StartsWith("-", StringComparison.Ordinal)).ToList();

            var nonTargets = nonHelpArgs.Where(arg => arg.StartsWith("-", StringComparison.Ordinal));

            var optionArgs = nonTargets.Where(arg => !helpOptions.Contains(arg, StringComparer.OrdinalIgnoreCase)).Select(arg => (arg, true));
            var result = OptionsReader.Read(optionArgs);
            var options = new Options
            {
                Clear = result.Clear,
                DryRun = result.DryRun,
                Host = result.Host,
                ListDependencies = result.ListDependencies,
                ListInputs = result.ListInputs,
                ListTargets = result.ListTargets,
                ListTree = result.ListTree,
                NoColor = result.NoColor,
                NoExtendedChars = result.NoExtendedChars,
                Parallel = result.Parallel,
                SkipDependencies = result.SkipDependencies,
                Verbose = result.Verbose,
            };

            return (targets, options, result.UnknownOptions, helpArgs.Any());
        }

19 View Source File : TokenContract_Helper.cs
License : MIT License
Project Creator : AElfProject

private void replacedertCrossChainTransaction(Transaction originalTransaction, Address validAddress, params string[] validMethodNames)
        {
            var validateResult = validMethodNames.Contains(originalTransaction.MethodName) 
                                 && originalTransaction.To == validAddress;
            replacedert(validateResult, "Invalid transaction.");
        }

19 View Source File : ContextIsolatedTask.cs
License : Microsoft Public License
Project Creator : AArnott

public sealed override bool Execute()
        {
            try
            {
                // We have to hook our own AppDomain so that the TransparentProxy works properly.
                AppDomain.CurrentDomain.replacedemblyResolve += this.CurrentDomain_replacedemblyResolve;

                // On .NET Framework (on Windows), we find native binaries by adding them to our PATH.
                if (this.UnmanagedDllDirectory != null)
                {
                    string pathEnvVar = Environment.GetEnvironmentVariable("PATH");
                    string[] searchPaths = pathEnvVar.Split(Path.PathSeparator);
                    if (!searchPaths.Contains(this.UnmanagedDllDirectory, StringComparer.OrdinalIgnoreCase))
                    {
                        pathEnvVar += Path.PathSeparator + this.UnmanagedDllDirectory;
                        Environment.SetEnvironmentVariable("PATH", pathEnvVar);
                    }
                }

                // Run under our own AppDomain so we can apply the .config file of the MSBuild Task we're hosting.
                // This gives the owner the control over binding redirects to be applied.
                var appDomainSetup = new AppDomainSetup();
                string pathToTaskreplacedembly = this.GetType().replacedembly.Location;
                appDomainSetup.ApplicationBase = Path.GetDirectoryName(pathToTaskreplacedembly);
                appDomainSetup.ConfigurationFile = pathToTaskreplacedembly + ".config";
                var appDomain = AppDomain.CreateDomain("ContextIsolatedTask: " + this.GetType().Name, AppDomain.CurrentDomain.Evidence, appDomainSetup);
                string taskreplacedemblyFullName = this.GetType().replacedembly.GetName().FullName;
                string taskFullName = this.GetType().FullName;
                var isolatedTask = (ContextIsolatedTask)appDomain.CreateInstanceAndUnwrap(taskreplacedemblyFullName, taskFullName);

                return this.ExecuteInnerTask(isolatedTask, this.GetType());
            }
            catch (OperationCanceledException)
            {
                this.Log.LogMessage(MessageImportance.High, "Canceled.");
                return false;
            }
            finally
            {
                AppDomain.CurrentDomain.replacedemblyResolve -= this.CurrentDomain_replacedemblyResolve;
            }
        }

19 View Source File : PublicizeInternals.cs
License : MIT License
Project Creator : aelij

private void CreatePublicreplacedembly(string source, string target)
        {
            var types = ExcludeTypeNames == null ? Array.Empty<string>() : ExcludeTypeNames.Split(Semicolon);

            var replacedembly = replacedemblyDefinition.Readreplacedembly(source,
                new ReaderParameters { replacedemblyResolver = _resolver });

            foreach (var module in replacedembly.Modules)
            {
                foreach (var type in module.GetTypes().Where(type=>!types.Contains(type.FullName)))
                {
                    if (!type.IsNested && type.IsNotPublic)
                    {
                        type.IsPublic = true;
                    }
                    else if (type.IsNestedreplacedembly ||
                             type.IsNestedFamilyOrreplacedembly ||
                             type.IsNestedFamilyAndreplacedembly)
                    {
                        type.IsNestedPublic = true;
                    }

                    foreach (var field in type.Fields)
                    {
                        if (field.Isreplacedembly ||
                            field.IsFamilyOrreplacedembly ||
                            field.IsFamilyAndreplacedembly)
                        {
                            field.IsPublic = true;
                        }
                    }

                    foreach (var method in type.Methods)
                    {
                        if (UseEmptyMethodBodies && method.HasBody)
                        {    
                            var emptyBody = new Mono.Cecil.Cil.MethodBody(method);
                            emptyBody.Instructions.Add(Mono.Cecil.Cil.Instruction.Create(Mono.Cecil.Cil.OpCodes.Ldnull));
                            emptyBody.Instructions.Add(Mono.Cecil.Cil.Instruction.Create(Mono.Cecil.Cil.OpCodes.Throw));
                            method.Body = emptyBody;
                        }

                        if (method.Isreplacedembly ||
                            method.IsFamilyOrreplacedembly ||
                            method.IsFamilyAndreplacedembly)
                        {
                            method.IsPublic = true;
                        }
                    }
                }
            }

            replacedembly.Write(target);
        }

19 View Source File : SolutionDefinition.cs
License : MIT License
Project Creator : Adoxio

private static IEnumerable<EnreplacedyDefinition> Union(IDictionary<string, EnreplacedyDefinition> first, IDictionary<string, EnreplacedyDefinition> second, IEnumerable<string> baseSolutions)
		{
			if (first == null && second == null) yield break;

			if (first == null)
			{
				foreach (var enreplacedy in second.Values)
				{
					yield return enreplacedy;
				}

				yield break;
			}

			if (second == null)
			{
				foreach (var enreplacedy in first.Values)
				{
					yield return enreplacedy;
				}

				yield break;
			}

			foreach (var fe in first.Values)
			{
				EnreplacedyDefinition se;

				if (second.TryGetValue(fe.LogicalName, out se) && fe.Solution == se.Solution)
				{
					yield return Union(fe, se);
				}
				else
				{
					yield return fe;
				}
			}

			foreach (var se in second.Values.Where(e => !baseSolutions.Contains(e.Solution)))
			{
				yield return se;
			}
		}

19 View Source File : BeatmapData.cs
License : MIT License
Project Creator : Aeroluna

private static void Prefix(BeatmapData __instance)
        {
            if (NeedsCheck)
            {
                NeedsCheck = false;
                if (__instance is CustomBeatmapData customBeatmapData)
                {
                    IEnumerable<string>? requirements = customBeatmapData.beatmapCustomData.Get<List<object>>("_requirements")?.Cast<string>();
                    _noodleRequirement = requirements?.Contains(Plugin.CAPABILITY) ?? false;
                }
                else
                {
                    _noodleRequirement = false;
                }
            }
        }

19 View Source File : App.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private void Application_Startup(object sender, StartupEventArgs e)
        {
            if (e.Args.Contains(_devMode, StringComparer.InvariantCultureIgnoreCase))
            {
                DeveloperModManager.Manage.IsDeveloperMode = true;
            }

            if (e.Args.Contains(_quickStart, StringComparer.InvariantCultureIgnoreCase))
            {
                // Used in automation testing, disable animations and delays in transitions 
                UIAutomationTestMode = true;
                SeriesAnimationBase.GlobalEnableAnimations = false;
            }

            try
            {
                Thread.CurrentThread.Name = "UI Thread";

                Log.Debug("--------------------------------------------------------------");
                Log.DebugFormat("SciChart.Examples.Demo: Session Started {0}",
                    DateTime.Now.ToString("dd MMM yyyy HH:mm:ss"));
                Log.Debug("--------------------------------------------------------------");

                var replacedembliesToSearch = new[]
                {
                    typeof (MainWindowViewModel).replacedembly,
                    typeof (AbtBootstrapper).replacedembly, // SciChart.UI.Bootstrap
                    typeof (IViewModelTrait).replacedembly, // SciChart.UI.Reactive 
                };

                _bootStrapper = new Bootstrapper(ServiceLocator.Container, new AttributedTypeDiscoveryService(new ExplicitreplacedemblyDiscovery(replacedembliesToSearch)));
                _bootStrapper.InitializeAsync().Then(() =>
                {
                    if (!UIAutomationTestMode)
                    {
                        // Do this on background thread
                        Task.Run(() =>
                        {
                            //Syncing usages 
                            var syncHelper = ServiceLocator.Container.Resolve<ISyncUsageHelper>();
                            syncHelper.LoadFromIsolatedStorage();

                            //Try sync with service
                            syncHelper.GetRatingsFromServer();
                            syncHelper.SendUsagesToServer();
                            syncHelper.SetUsageOnExamples();
                        });
                    }

                    _bootStrapper.OnInitComplete();
                }).Catch(ex =>
                {
                    Log.Error("Exception:\n\n{0}", ex);
                    MessageBox.Show("Exception occurred in SciChart.Examples.Demo.\r\n. Please send log files located at %CurrentUser%\\AppData\\Local\\SciChart\\SciChart.Examples.Demo.log to support");
                });
            }
            catch (Exception caught)
            {
                Log.Error("Exception:\n\n{0}", caught);
                MessageBox.Show("Exception occurred in SciChart.Examples.Demo.\r\n. Please send log files located at %CurrentUser%\\AppData\\Local\\SciChart\\SciChart.Examples.Demo.log to support");
            }
        }

19 View Source File : MultiplayerConnectedPlayerInstaller.cs
License : MIT License
Project Creator : Aeroluna

private static IReadonlyBeatmapData ExcludeFakeNoteAndAllWalls(IReadonlyBeatmapData result)
        {
            foreach (BeatmapLineData b in result.beatmapLinesData)
            {
                BeatmapLineData refBeatmapLineData = b;
                _beatmapObjectsDataAccessor(ref refBeatmapLineData) = b.beatmapObjectsData.Where(n =>
                {
                    Dictionary<string, object?> dynData;

                    switch (n)
                    {
                        case CustomNoteData customNoteData:
                            dynData = customNoteData.customData;
                            break;

                        case CustomObstacleData customObstacleData:
                            return false;

                        default:
                            return true;
                    }

                    bool? fake = dynData.Get<bool?>(FAKENOTE);
                    if (fake.HasValue && fake.Value)
                    {
                        return false;
                    }

                    return true;
                }).ToList();
            }

            if (result is CustomBeatmapData customBeatmapData)
            {
                string[] excludedTypes = new string[]
                {
                    replacedIGNPLAYERTOTRACK,
                    replacedIGNTRACKPARENT,
                };

                customBeatmapData.customEventsData.RemoveAll(n => excludedTypes.Contains(n.type));
            }

            return result;
        }

19 View Source File : AnnotationDataAdapter.cs
License : MIT License
Project Creator : Adoxio

public IAnnotationResult CreateAnnotation(IAnnotation note, IAnnotationSettings settings = null)
		{
			var serviceContext = _dependencies.GetServiceContext();
			var serviceContextForWrite = _dependencies.GetServiceContextForWrite();

			if (settings == null)
			{
				settings = new AnnotationSettings(serviceContext);
			}
			
			var storageAccount = GetStorageAccount(serviceContext);
			if (settings.StorageLocation == StorageLocation.AzureBlobStorage && storageAccount == null)
			{
				settings.StorageLocation = StorageLocation.CrmDoreplacedent;
			}

			AnnotationCreateResult result = null;

			if (settings.RespectPermissions)
			{
				var enreplacedyPermissionProvider = new CrmEnreplacedyPermissionProvider();
				result = new AnnotationCreateResult(enreplacedyPermissionProvider, serviceContext, note.Regarding);
			}

			// ReSharper disable once PossibleNullReferenceException
			if (!settings.RespectPermissions ||
				(result.PermissionsExist && result.PermissionGranted))
			{
				var enreplacedy = new Enreplacedy("annotation");

				if (note.Owner != null)
				{
					enreplacedy.SetAttributeValue("ownerid", note.Owner);
				}

				enreplacedy.SetAttributeValue("subject", note.Subject);
				enreplacedy.SetAttributeValue("notetext", note.NoteText);
				enreplacedy.SetAttributeValue("objectid", note.Regarding);
				enreplacedy.SetAttributeValue("objecttypecode", note.Regarding.LogicalName);

				if (note.FileAttachment != null)
				{
					var acceptMimeTypes = AnnotationDataAdapter.GetAcceptRegex(settings.AcceptMimeTypes);
					var acceptExtensionTypes = AnnotationDataAdapter.GetAcceptRegex(settings.AcceptExtensionTypes);
					if (!(acceptExtensionTypes.IsMatch(Path.GetExtension(note.FileAttachment.FileName).ToLower()) ||
							acceptMimeTypes.IsMatch(note.FileAttachment.MimeType)))
					{
						throw new AnnotationException(settings.RestrictMimeTypesErrorMessage);
					}

					if (settings.MaxFileSize.HasValue && note.FileAttachment.FileSize > settings.MaxFileSize)
					{
						throw new AnnotationException(settings.MaxFileSizeErrorMessage);
					}

					note.FileAttachment.Annotation = enreplacedy;

					switch (settings.StorageLocation)
					{
					case StorageLocation.CrmDoreplacedent:
						var crmFile = note.FileAttachment as CrmAnnotationFile;
						if (crmFile == null)
						{
							break;
						}

						if (!string.IsNullOrEmpty(settings.RestrictedFileExtensions))
						{
							var blocked = new Regex(@"\.({0})$".FormatWith(settings.RestrictedFileExtensions.Replace(";", "|")));
							if (blocked.IsMatch(crmFile.FileName))
							{
								throw new AnnotationException(settings.RestrictedFileExtensionsErrorMessage);
							}
						}

						enreplacedy.SetAttributeValue("filename", crmFile.FileName);
						enreplacedy.SetAttributeValue("mimetype", crmFile.MimeType);
						enreplacedy.SetAttributeValue("doreplacedentbody", Convert.ToBase64String(crmFile.Doreplacedent));
						break;
					case StorageLocation.AzureBlobStorage:
						enreplacedy.SetAttributeValue("filename", note.FileAttachment.FileName + ".azure.txt");
						enreplacedy.SetAttributeValue("mimetype", "text/plain");
						var fileMetadata = new
						{
							Name = note.FileAttachment.FileName,
							Type = note.FileAttachment.MimeType,
							Size = (ulong)note.FileAttachment.FileSize,
							Url = string.Empty
						};
						enreplacedy.SetAttributeValue("doreplacedentbody",
							Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(fileMetadata, Formatting.Indented))));
						break;
					}
				}

				// Create annotaion but skip cache invalidation.
				var id = (serviceContext as IOrganizationService).ExecuteCreate(enreplacedy, RequestFlag.ByPreplacedCacheInvalidation);

				if (result != null) result.Annotation = note;

				note.AnnotationId = enreplacedy.Id = id;
				note.Enreplacedy = enreplacedy;

				if (note.FileAttachment is AzureAnnotationFile && settings.StorageLocation == StorageLocation.AzureBlobStorage)
				{
					var container = GetBlobContainer(storageAccount, _containerName);

					var azureFile = (AzureAnnotationFile)note.FileAttachment;

					azureFile.BlockBlob = UploadBlob(azureFile, container, note.AnnotationId);

					var fileMetadata = new
					{
						Name = azureFile.FileName,
						Type = azureFile.MimeType,
						Size = (ulong)azureFile.FileSize,
						Url = azureFile.BlockBlob.Uri.AbsoluteUri
					};
					enreplacedy.SetAttributeValue("doreplacedentbody",
						Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(fileMetadata, Formatting.Indented))));
					serviceContextForWrite.UpdateObject(enreplacedy);
					serviceContextForWrite.SaveChanges();

					// NB: This is basically a hack to support replication. Keys are gathered up and stored during replication, and the
					// actual blob replication is handled here.
					var key = note.AnnotationId.ToString("N");
					if (HttpContext.Current.Application.AllKeys.Contains(NoteReplication.BlobReplicationKey))
					{
						var replication =
							HttpContext.Current.Application[NoteReplication.BlobReplicationKey] as Dictionary<string, Tuple<Guid, Guid>[]>;
						if (replication != null && replication.ContainsKey(key))
						{
							CopyBlob(note, replication[key]);
							replication.Remove(key);
						}
					}
				} 
			}

			if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
			{
				PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Note, HttpContext.Current, "create_note", 1, note.Enreplacedy.ToEnreplacedyReference(), "create");
			}

			return result;
		}

19 View Source File : DiagnosticsController.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public async Task<IActionResult> Index()
        {
            var localAddresses = new string[] { "127.0.0.1", "::1", HttpContext.Connection.LocalIpAddress.ToString() };
            if (!localAddresses.Contains(HttpContext.Connection.RemoteIpAddress.ToString()))
            {
                return NotFound();
            }

            var model = new DiagnosticsViewModel(await HttpContext.AuthenticateAsync());
            return View(model);
        }

19 View Source File : Admin.cs
License : MIT License
Project Creator : 2881099

async public static Task<bool> Use(HttpContext context, IFreeSql fsql, string requestPathBase, Dictionary<string, Type> dicEnreplacedyTypes) {
			HttpRequest req = context.Request;
			HttpResponse res = context.Response;

			var remUrl = req.Path.ToString().Substring(requestPathBase.Length).Trim(' ', '/').Split('/');
			var enreplacedyName = remUrl.FirstOrDefault();

			if (!string.IsNullOrEmpty(enreplacedyName)) {

				if (dicEnreplacedyTypes.TryGetValue(enreplacedyName, out var enreplacedyType) == false) throw new Exception($"UseFreeAdminLtePreview 错误,找不到实体类型:{enreplacedyName}");

				var tb = fsql.CodeFirst.GetTableByEnreplacedy(enreplacedyType);
				if (tb == null) throw new Exception($"UseFreeAdminLtePreview 错误,实体类型无法映射:{enreplacedyType.FullName}");

				var tpl = _tpl.Value;

				switch (remUrl.ElementAtOrDefault(1)?.ToLower()) {
					case null:
						//首页
						if (true) {
							MakeTemplateFile($"{enreplacedyName}-list.html", Views.List);

							//ManyToOne/OneToOne
							var getlistFilter = new List<(TableRef, string, string, Dictionary<string, object>, List<Dictionary<string, object>>)>();
							foreach (var prop in tb.Properties) {
								if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
								var tbref = tb.GetTableRef(prop.Key, false);
								if (tbref == null) continue;
								switch (tbref.RefType) {
									case TableRefType.OneToMany: continue;
									case TableRefType.ManyToOne:
										getlistFilter.Add(await Utils.GetTableRefData(fsql, tbref));
										continue;
									case TableRefType.OneToOne:
										continue;
									case TableRefType.ManyToMany:
										getlistFilter.Add(await Utils.GetTableRefData(fsql, tbref));
										continue;
								}
							}

							int.TryParse(req.Query["page"].FirstOrDefault(), out var getpage);
							int.TryParse(req.Query["limit"].FirstOrDefault(), out var getlimit);
							if (getpage <= 0) getpage = 1;
							if (getlimit <= 0) getlimit = 20;

							var getselect = fsql.Select<object>().AsType(enreplacedyType);
							foreach (var getlistF in getlistFilter) {
								var qv = req.Query[getlistF.Item3].ToArray();
								if (qv.Any()) {
									switch (getlistF.Item1.RefType) {
										case TableRefType.OneToMany: continue;
										case TableRefType.ManyToOne:
											getselect.Where(Utils.GetObjectWhereExpressionContains(tb, enreplacedyType, getlistF.Item1.Columns[0].CsName, qv));
											continue;
										case TableRefType.OneToOne:
											continue;
										case TableRefType.ManyToMany:
											if (true) {
												var midType = getlistF.Item1.RefMiddleEnreplacedyType;
												var midTb = fsql.CodeFirst.GetTableByEnreplacedy(midType);
												var midISelect = typeof(ISelect<>).MakeGenericType(midType);

												var funcType = typeof(Func<,>).MakeGenericType(typeof(object), typeof(bool));
												var expParam = Expression.Parameter(typeof(object), "a");
												var midParam = Expression.Parameter(midType, "mdtp");

												var anyMethod = midISelect.GetMethod("Any");
												var selectExp = qv.Select(c => Expression.Convert(Expression.Constant(FreeSql.Internal.Utils.GetDataReaderValue(getlistF.Item1.MiddleColumns[1].CsType, c)), getlistF.Item1.MiddleColumns[1].CsType)).ToArray();
												var expLambad = Expression.Lambda<Func<object, bool>>(
													Expression.Call(
														Expression.Call(
															Expression.Call(
																Expression.Constant(fsql),
																typeof(IFreeSql).GetMethod("Select", new Type[0]).MakeGenericMethod(midType)
															),
															midISelect.GetMethod("Where", new[] { typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(midType, typeof(bool))) }),
															Expression.Lambda(
																typeof(Func<,>).MakeGenericType(midType, typeof(bool)),
																Expression.AndAlso(
																	Expression.Equal(
																		Expression.MakeMemberAccess(Expression.TypeAs(expParam, enreplacedyType), tb.Properties[getlistF.Item1.Columns[0].CsName]),
																		Expression.MakeMemberAccess(midParam, midTb.Properties[getlistF.Item1.MiddleColumns[0].CsName])
																	),
																	Expression.Call(
																		Utils.GetLinqContains(getlistF.Item1.MiddleColumns[1].CsType),
																		Expression.NewArrayInit(
																			getlistF.Item1.MiddleColumns[1].CsType,
																			selectExp
																		),
																		Expression.MakeMemberAccess(midParam, midTb.Properties[getlistF.Item1.MiddleColumns[1].CsName])
																	)
																),
																midParam
															)
														),
														anyMethod,
														Expression.Default(anyMethod.GetParameters().FirstOrDefault().ParameterType)
													),
													expParam);

												getselect.Where(expLambad);
											}
											continue;
									}
								}
							}

							var getlistTotal = await getselect.CountAsync();
							var getlist = await getselect.Page(getpage, getlimit).ToListAsync();
							var gethashlists = new Dictionary<string, object>[getlist.Count];
							var gethashlistsIndex = 0;
							foreach (var getlisreplacedem in getlist) {
								var gethashlist = new Dictionary<string, object>();
								foreach (var getcol in tb.ColumnsByCs) {
									gethashlist.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(getlisreplacedem));
								}
								gethashlists[gethashlistsIndex++] = gethashlist;
							}

							var options = new Dictionary<string, object>();
							options["tb"] = tb;
							options["getlist"] = gethashlists;
							options["getlistTotal"] = getlistTotal;
							options["getlistFilter"] = getlistFilter;
							var str = _tpl.Value.RenderFile($"{enreplacedyName}-list.html", options);
							await res.WriteAsync(str);
						}
						return true;
					case "add":
					case "edit":
						//编辑页
						object gereplacedem = null;
						Dictionary<string, object> gethash = null;
						if (req.Query.Any()) {
							gereplacedem = Activator.CreateInstance(enreplacedyType);
							foreach (var getpk in tb.Primarys) {
								var reqv = req.Query[getpk.CsName].ToArray();
								if (reqv.Any())
									fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getpk.CsName, reqv.Length == 1 ? (object)reqv.FirstOrDefault() : reqv);
							}
							gereplacedem = await fsql.Select<object>().AsType(enreplacedyType).WhereDynamic(gereplacedem).FirstAsync();
							if (gereplacedem != null) {
								gethash = new Dictionary<string, object>();
								foreach (var getcol in tb.ColumnsByCs) {
									gethash.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(gereplacedem));
								}
							}
						}

						if (req.Method.ToLower() == "get") {
							MakeTemplateFile($"{enreplacedyName}-edit.html", Views.Edit);

							//ManyToOne/OneToOne
							var getlistFilter = new Dictionary<string, (TableRef, string, string, Dictionary<string, object>, List<Dictionary<string, object>>)>();
							var getlistManyed = new Dictionary<string, IEnumerable<string>>();
							foreach (var prop in tb.Properties) {
								if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
								var tbref = tb.GetTableRef(prop.Key, false);
								if (tbref == null) continue;
								switch (tbref.RefType) {
									case TableRefType.OneToMany: continue;
									case TableRefType.ManyToOne:
										getlistFilter.Add(prop.Key, await Utils.GetTableRefData(fsql, tbref));
										continue;
									case TableRefType.OneToOne:
										continue;
									case TableRefType.ManyToMany:
										getlistFilter.Add(prop.Key, await Utils.GetTableRefData(fsql, tbref));

										if (gereplacedem != null) {
											var midType = tbref.RefMiddleEnreplacedyType;
											var midTb = fsql.CodeFirst.GetTableByEnreplacedy(midType);
											var manyed = await fsql.Select<object>().AsType(midType)
												.Where(Utils.GetObjectWhereExpression(midTb, midType, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]))
												.ToListAsync();
											getlistManyed.Add(prop.Key, manyed.Select(a => fsql.GetEnreplacedyValueWithPropertyName(midType, a, tbref.MiddleColumns[1].CsName).ToString()));
										}
										continue;
								}
							}

							var options = new Dictionary<string, object>();
							options["tb"] = tb;
							options["gethash"] = gethash;
							options["getlistFilter"] = getlistFilter;
							options["getlistManyed"] = getlistManyed;
							options["postaction"] = $"{requestPathBase}restful-api/{enreplacedyName}";
							var str = _tpl.Value.RenderFile($"{enreplacedyName}-edit.html", options);
							await res.WriteAsync(str);

						} else {
							if (gereplacedem == null) {
								gereplacedem = Activator.CreateInstance(enreplacedyType);
								foreach(var getcol in tb.Columns.Values) {
									if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "create_time", "createtime" }.Contains(getcol.CsName.ToLower()))
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, DateTime.Now);
								}
							}
							var manySave = new List<(TableRef, object[], List<object>)>();
							if (req.Form.Any()) {
								foreach(var getcol in tb.Columns.Values) {
									if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "update_time", "updatetime" }.Contains(getcol.CsName.ToLower()))
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, DateTime.Now);

									var reqv = req.Form[getcol.CsName].ToArray();
									if (reqv.Any())
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, reqv.Length == 1 ? (object)reqv.FirstOrDefault() : reqv);
								}
								//ManyToMany
								foreach (var prop in tb.Properties) {
									if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
									var tbref = tb.GetTableRef(prop.Key, false);
									if (tbref == null) continue;
									switch (tbref.RefType) {
										case TableRefType.OneToMany: continue;
										case TableRefType.ManyToOne:
											continue;
										case TableRefType.OneToOne:
											continue;
										case TableRefType.ManyToMany:
											var midType = tbref.RefMiddleEnreplacedyType;
											var mtb = fsql.CodeFirst.GetTableByEnreplacedy(midType);

											var reqv = req.Form[$"mn_{prop.Key}"].ToArray();
											var reqvIndex = 0;
											var manyVals = new object[reqv.Length];
											foreach (var rv in reqv) {
												var miditem = Activator.CreateInstance(midType);
												foreach (var getcol in tb.Columns.Values) {
													if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "create_time", "createtime" }.Contains(getcol.CsName.ToLower()))
														fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, getcol.CsName, DateTime.Now);

													if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "update_time", "updatetime" }.Contains(getcol.CsName.ToLower()))
														fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, getcol.CsName, DateTime.Now);
												}
												//fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]);
												fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, tbref.MiddleColumns[1].CsName, rv);
												manyVals[reqvIndex++] = miditem;
											}
											var molds = await fsql.Select<object>().AsType(midType).Where(Utils.GetObjectWhereExpression(mtb, midType, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0])).ToListAsync();
											manySave.Add((tbref, manyVals, molds));
											continue;
									}
								}
							}


							using (var db = fsql.CreateDbContext()) {

								var dbset = db.Set<object>();
								dbset.AsType(enreplacedyType);

								await dbset.AddOrUpdateAsync(gereplacedem);

								foreach (var ms in manySave) {
									var midType = ms.Item1.RefMiddleEnreplacedyType;
									var moldsDic = ms.Item3.ToDictionary(a => fsql.GetEnreplacedyKeyString(midType, a, true));

									var manyset = db.Set<object>();
									manyset.AsType(midType);
									
									foreach (var msVal in ms.Item2) {
										fsql.SetEnreplacedyValueWithPropertyName(midType, msVal, ms.Item1.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]);
										await manyset.AddOrUpdateAsync(msVal);
										moldsDic.Remove(fsql.GetEnreplacedyKeyString(midType, msVal, true));
									}
									manyset.RemoveRange(moldsDic.Values);
								}

								await db.SaveChangesAsync();
							}
							gethash = new Dictionary<string, object>();
							foreach (var getcol in tb.ColumnsByCs) {
								gethash.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(gereplacedem));
							}

							await Utils.Jsonp(context, new { code = 0, success = true, message = "Success", data = gethash });
						}
						return true;
					case "del":
						if (req.Method.ToLower() == "post") {

							var delitems = new List<object>();
							var reqv = new List<string[]>();
							foreach(var delpk in tb.Primarys) {
								var reqvs = req.Form[delpk.CsName].ToArray();
								if (reqv.Count > 0 && reqvs.Length != reqv[0].Length) throw new Exception("删除失败,联合主键参数传递不对等");
								reqv.Add(reqvs);
							}
							if (reqv[0].Length == 0) return true;

							using (var ctx = fsql.CreateDbContext()) {
								var dbset = ctx.Set<object>();
								dbset.AsType(enreplacedyType);

								for (var a = 0; a < reqv[0].Length; a++) {
									object delitem = Activator.CreateInstance(enreplacedyType);
									var delpkindex = 0;
									foreach (var delpk in tb.Primarys)
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, delitem, delpk.CsName, reqv[delpkindex++][a]);
									dbset.Remove(delitem);
								}
								await ctx.SaveChangesAsync();
							}

							await Utils.Jsonp(context, new { code = 0, success = true, message = "Success" });
							return true;
						}
						break;
				}
			}
			return false;
		}

19 View Source File : MenuService.cs
License : MIT License
Project Creator : aishang2015

public (string, string) GetIdentificationRoutes(string[] menuIds)
        {
            var query = from menu in _menuRepository.Get()
                        where menuIds.Contains(menu.Id.ToString())
                        select menu;
            var identifications = string.Join(',', query
                .Where(m => !string.IsNullOrEmpty(m.Identification)).Select(m => m.Identification));
            var routes = string.Join(',', query
                .Where(m => !string.IsNullOrEmpty(m.Route)).Select(m => m.Route));
            return (identifications, routes);
        }

19 View Source File : AboutProductHandler.cs
License : MIT License
Project Creator : Adoxio

private bool HasAdminPrivileges()
		{
			var contentMap = AdxstudioCrmConfigurationManager.CreateContentMapProvider();
			var webSiteEnreplacedy = PortalContext.Current.Website;

			if (webSiteEnreplacedy == null)
			{
				return false;
			}

			WebsiteNode webSite = null;
			contentMap.Using(map => map.TryGetValue(webSiteEnreplacedy, out webSite));

			if (webSite == null)
			{
				return false;
			}

			// Get names of current user roles
			var roleNames = Roles.GetRolesForUser();

			// Select these role nodes
			var userRoles = webSite.WebRoles.Where(role => roleNames.Contains(role.Name));

			// Select web site access permissions
			var permissions = userRoles.SelectMany(role => role.WebsiteAccesses);
 
			// Check if there is permission with all options active
			var hasAcccess =
				permissions.Any(p => p.ManageContentSnippets.Value && p.ManageSiteMarkers.Value
					&& p.ManageWebLinkSets.Value && p.PreviewUnpublishedEnreplacedies.Value);

			return hasAcccess;
		}

19 View Source File : JsonTransforms.cs
License : MIT License
Project Creator : action-bi-toolkit

public static JObject RemoveProperties(this JObject json, params string[] propertyNames)
        {
            JToken RemovePropertiesRec(JToken token)
            {
                switch (token)
                {
                    case JObject obj:
                        return propertyNames == null ? obj : new JObject(obj.Properties()
                            .Where(p => !propertyNames.Contains(p.Name))
                            .Select(p => new JProperty(p.Name, RemovePropertiesRec(p.Value))));
                    case JArray arr:
                        return new JArray(arr.Select(RemovePropertiesRec));
                    default:
                        return token;
                }
            };

            return RemovePropertiesRec(json) as JObject;
        }

19 View Source File : XmlHelper.cs
License : MIT License
Project Creator : 279328316

public T DeserializeNode<T>(XmlNode node = null) where T : clreplaced, new()
        {
            T model = new T();
            XmlNode firstChild;
            if (node == null)
            {
                node = root;
            }
            firstChild = node.FirstChild;

            Dictionary<string, string> dict = new Dictionary<string, string>();

            XmlAttributeCollection xmlAttribute = node.Attributes;
            if (node.Attributes.Count > 0)
            {
                for (int i = 0; i < node.Attributes.Count; i++)
                {
                    if (!dict.Keys.Contains(node.Attributes[i].Name))
                    {
                        dict.Add(node.Attributes[i].Name, node.Attributes[i].Value);
                    }
                }
            }
            if (!dict.Keys.Contains(firstChild.Name))
            {
                dict.Add(firstChild.Name, firstChild.InnerText);
            }
            XmlNode next = firstChild.NextSibling;
            while (next != null)
            {
                if (!dict.Keys.Contains(next.Name))
                {
                    dict.Add(next.Name, next.InnerText);
                }
                else
                {
                    throw new Exception($"重复的属性Key:{next.Name}");
                }
                next = next.NextSibling;
            }


            #region 为对象赋值

            Type modelType = typeof(T);
            List<PropertyInfo> piList = modelType.GetProperties().Where(pro => (pro.PropertyType.Equals(typeof(string)) || pro.PropertyType.IsValueType) && pro.CanRead && pro.CanWrite).ToList();

            foreach (PropertyInfo pi in piList)
            {
                string dictKey = dict.Keys.FirstOrDefault(key => key.ToLower() == pi.Name.ToLower());
                if (!string.IsNullOrEmpty(dictKey))
                {
                    string value = dict[dictKey];
                    TypeConverter typeConverter = TypeDescriptor.GetConverter(pi.PropertyType);
                    if (typeConverter != null)
                    {
                        if (typeConverter.CanConvertFrom(typeof(string)))
                            pi.SetValue(model, typeConverter.ConvertFromString(value));
                        else
                        {
                            if (typeConverter.CanConvertTo(pi.PropertyType))
                                pi.SetValue(model, typeConverter.ConvertTo(value, pi.PropertyType));
                        }
                    }
                }
            }
            #endregion
            return model;
        }

19 View Source File : FrmBrowser.cs
License : GNU General Public License v3.0
Project Creator : 9vult

private void BtnAdd_Click(object sender, EventArgs e)
        {
            string url = gfxBrowser.Url.ToString();
            string name = string.Empty;
            string num = string.Empty;
            switch (cmboSource.SelectedItem.ToString().ToLower())
            {
                case "mangadex":
                    name = url.Split('/')[5];
                    num = url.Split('/')[4];
                    url = MangaDexHelper.MANGADEX_URL + "/api/manga/" + num;

                    Manga m = new MangaDex(FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, num)), url);

                    FrmEdit editor = new FrmEdit(m, false);
                    DialogResult result = editor.ShowDialog();

                    if (result == DialogResult.OK)
                    {
                        // cleanup
                        foreach (Chapter ch in m.GetChapters())
                        {
                            try
                            {
                                string s = ch.GetChapterRoot().ToString();
                                Directory.Delete(ch.GetChapterRoot().ToString());
                            } catch (Exception) { }
                        }

                        WFClient.dbm.GetMangaDB().Add(m);

                        String[] dls = m.GetDLChapters();
                        if (dls == null || dls[0].Equals("-1"))
                        {
                            foreach (Chapter c in m.GetSetPrunedChapters(false))
                            {
                                WFClient.dlm.AddToQueue(new MangaDexDownload(c));
                            }
                        } else
                        {   // Only download selected chapters
                            foreach (Chapter c in m.GetSetPrunedChapters(false))
                            {
                                if (dls.Contains(c.GetNum()))
                                {
                                    WFClient.dlm.AddToQueue(new MangaDexDownload(c));
                                }
                            }
                        }
                        // Start downloading the first one
                        WFClient.dlm.DownloadNext();
                    } else
                    {

                    }
                    break;
                case "kissmanga":

                    // MessageBox.Show("Sorry, can't do this yet! ;(\n\n(ignore the download started box)");
                    // break;
                    // TODO

                    string kName = KissMangaHelper.GetName(url);
                    string kHash = KissMangaHelper.GetHash(url);

                    // Manga km = new Manga(FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, num)), url);

                    Manga km = new KissManga(FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, kHash)), url);

                    FrmEdit editor1 = new FrmEdit(km, false);
                    DialogResult result1 = editor1.ShowDialog();

                    if (result1 == DialogResult.OK)
                    {
                        // cleanup
                        foreach (Chapter ch in km.GetChapters())
                        {
                            try
                            {
                                string s = ch.GetChapterRoot().ToString();
                                Directory.Delete(ch.GetChapterRoot().ToString());
                            }
                            catch (Exception) { }
                        }

                        WFClient.dbm.GetMangaDB().Add(km);

                        String[] dls = km.GetDLChapters();
                        if (dls == null || dls[0].Equals("-1"))
                        {
                            foreach (Chapter c in km.GetSetPrunedChapters(false))
                            {
                                WFClient.dlm.AddToQueue(new KissMangaDownload(c));
                            }
                        }
                        else
                        {   // Only download selected chapters
                            foreach (Chapter c in km.GetSetPrunedChapters(false))
                            {
                                if (dls.Contains(c.GetNum()))
                                {
                                    WFClient.dlm.AddToQueue(new KissMangaDownload(c));
                                }
                            }
                        }
                        // Start downloading the first one
                        WFClient.dlm.DownloadNext();
                    }
                    else
                    {

                    }
                    break;
                case "nhentai": 
                    num = url.Split('/')[4];
                    name = gfxBrowser.Doreplacedentreplacedle.Substring(0, gfxBrowser.Doreplacedentreplacedle.IndexOf("nhentai:") - 3);

                    JObject hJson = new JObject(
                        new JProperty("hentai",
                            new JObject(
                                new JProperty("replacedle", name),
                                new JProperty("num",  num),
                                new JProperty("url",  url))));

                    DirectoryInfo hDir = FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, "h" + num));

                    Hentai h = new Nhentai(hDir, hJson.ToString());

                    FrmEdit edit = new FrmEdit(h, false);
                    DialogResult rezult = edit.ShowDialog();

                    if (rezult == DialogResult.OK)
                    {
                        WFClient.dbm.GetMangaDB().Add(h);

                        Chapter ch = h.GetChapters()[0];
                        WFClient.dlm.AddToQueue(new NhentaiDownload(ch));
                        // Start downloading the first one
                        WFClient.dlm.DownloadNext();
                    } 
                    break;
            }
            MessageBox.Show("Download started! You may close the browser at any time, but please keep MikuReader open until the download has completed.");
        }

19 View Source File : TestProjectProvider.cs
License : MIT License
Project Creator : Abc-Arbitrage

public bool IsTestProject(IPsiModule psiModule)
        {
            if (!_isMoqContainedByProjectName.TryGetValue(psiModule.DisplayName, out var isMoqContained))
            {
                IReadOnlyList<IPsiModuleReference> references = psiModule.GetPsiServices().Modules.GetModuleReferences(psiModule);
                isMoqContained = references.Any(r => MoqReferenceNames.Contains(r.Module.Name));
                _isMoqContainedByProjectName.Add(psiModule.DisplayName, isMoqContained);
            }

            return isMoqContained;
        }

19 View Source File : FileContainerHttpClient.cs
License : MIT License
Project Creator : actions

private async Task<Stream> DownloadAsync(
            Int64 containerId,
            String itemPath,
            String contentType,
            CancellationToken cancellationToken,
            Guid scopeIdentifier,
            Object userState = null)
        {
            HttpResponseMessage response = await ContainerGetRequestAsync(containerId, itemPath, contentType, cancellationToken, scopeIdentifier, userState).ConfigureAwait(false);

            response.EnsureSuccessStatusCode();

            if (response.StatusCode == HttpStatusCode.NoContent)
            {
                throw new ContainerNoContentException();
            }

            if (VssStringComparer.ContentType.Equals(response.Content.Headers.ContentType.MediaType, contentType))
            {
                if (response.Content.Headers.ContentEncoding.Contains("gzip", StringComparer.OrdinalIgnoreCase))
                {
                    return new GZipStream(await response.Content.ReadreplacedtreamAsync().ConfigureAwait(false), CompressionMode.Decompress);
                }
                else
                {
                    return await response.Content.ReadreplacedtreamAsync().ConfigureAwait(false);
                }
            }
            else
            {
                throw new ContainerUnexpectedContentTypeException(contentType, response.Content.Headers.ContentType.MediaType);
            }
        }

19 View Source File : JsonConfigurationContractResolver.cs
License : MIT License
Project Creator : Adoxio

private JsonObjectContract CreateEnreplacedyReferenceObjectContract(Type objectType)
		{
			var contract = base.CreateObjectContract(objectType);

			var propertiesToRemove = contract.Properties
				.Where(e => !EnreplacedyReferencePropertyWhitelist.Contains(e.PropertyName, StringComparer.Ordinal))
				.ToArray();

			foreach (var property in propertiesToRemove)
			{
				contract.Properties.Remove(property);
			}

			return contract;
		}

See More Examples