Here are the examples of the csharp api System.Collections.Generic.IEnumerable.Contains(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2084 Examples
19
Source : BooleanExpressionResovle.cs
with Apache License 2.0
from 1448376744
with Apache License 2.0
from 1448376744
private bool IsLikeExpression(MethodCallExpression node)
{
var array = new string[]
{
nameof(string.Contains),
nameof(string.StartsWith),
nameof(string.EndsWith)
};
return node.Method.DeclaringType == typeof(string)
&& array.Contains(node.Method.Name)
&& node.Arguments.Count == 1;
}
19
Source : ExpressionActivator.cs
with Apache License 2.0
from 1448376744
with Apache License 2.0
from 1448376744
private string ResovleOperator(string text)
{
var operators = new string[] { "!", "*", "/", "%", "+", "-", "<", ">", "<=", ">=", "==", "!=", "&&", "||" };
for (int i = 0; i < text.Length - 1; i++)
{
var opt1 = text[i].ToString();
var opt2 = text.Substring(i, 2);
if (operators.Contains(opt2))
{
return opt2;
}
else if(operators.Contains(opt1))
{
return opt1;
}
}
throw new Exception("resolve operator eroor");
}
19
Source : EventSourceReader.cs
with MIT License
from 3ventic
with MIT License
from 3ventic
private async Task ReaderAsync()
{
try
{
if (string.Empty != LastEventId)
{
if (Hc.DefaultRequestHeaders.Contains("Last-Event-Id"))
{
Hc.DefaultRequestHeaders.Remove("Last-Event-Id");
}
Hc.DefaultRequestHeaders.TryAddWithoutValidation("Last-Event-Id", LastEventId);
}
using (HttpResponseMessage response = await Hc.GetAsync(Uri, HttpCompletionOption.ResponseHeadersRead))
{
response.EnsureSuccessStatusCode();
if (response.Headers.TryGetValues("content-type", out IEnumerable<string> ctypes) || ctypes?.Contains("text/event-stream") == false)
{
throw new ArgumentException("Specified URI does not return server-sent events");
}
Stream = await response.Content.ReadreplacedtreamAsync();
using (var sr = new StreamReader(Stream))
{
string evt = DefaultEventType;
string id = string.Empty;
var data = new StringBuilder(string.Empty);
while (true)
{
string line = await sr.ReadLineAsync();
if (line == string.Empty)
{
// double newline, dispatch message and reset for next
if (data.Length > 0)
{
MessageReceived?.Invoke(this, new EventSourceMessageEventArgs(data.ToString().Trim(), evt, id));
}
data.Clear();
id = string.Empty;
evt = DefaultEventType;
continue;
}
else if (line.First() == ':')
{
// Ignore comments
continue;
}
int dataIndex = line.IndexOf(':');
string field;
if (dataIndex == -1)
{
dataIndex = line.Length;
field = line;
}
else
{
field = line.Substring(0, dataIndex);
dataIndex += 1;
}
string value = line.Substring(dataIndex).Trim();
switch (field)
{
case "event":
// Set event type
evt = value;
break;
case "data":
// Append a line to data using a single \n as EOL
data.Append($"{value}\n");
break;
case "retry":
// Set reconnect delay for next disconnect
int.TryParse(value, out ReconnectDelay);
break;
case "id":
// Set ID
LastEventId = value;
id = LastEventId;
break;
default:
// Ignore other fields
break;
}
}
}
}
}
catch (Exception ex)
{
Disconnect(ex);
}
}
19
Source : LastNames.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
public static Continent FindreplacedociatedContinent(string lastName)
{
foreach (var keyValuePair in PerContinent)
{
if (keyValuePair.Value.Contains(lastName))
{
return keyValuePair.Key;
}
}
throw new NotSupportedException($"The lastname ({lastName}) is not replacedociated to any Continent in our lib.");
}
19
Source : ResourceRepository.cs
with MIT License
from 99x
with MIT License
from 99x
internal static void Initialize(replacedembly callingreplacedembly)
{
Repo = new ResourceRepository();
var ignorereplacedemblies = new string[] {"RadiumRest", "RadiumRest.Core", "RadiumRest.Selfhost", "mscorlib"};
var referencedreplacedemblies = callingreplacedembly.GetReferencedreplacedemblies();
var currentAsm = replacedembly.GetExecutingreplacedembly().GetName();
var scanreplacedemblies = new List<replacedemblyName>() { callingreplacedembly.GetName()};
foreach (var asm in referencedreplacedemblies)
{
if (asm == currentAsm)
continue;
if (!ignorereplacedemblies.Contains(asm.Name))
scanreplacedemblies.Add(asm);
}
foreach (var refAsm in scanreplacedemblies)
{
try
{
var asm = replacedembly.Load(refAsm.FullName);
foreach (var typ in asm.GetTypes())
{
if (typ.IsSubclreplacedOf(typeof(RestResourceHandler)))
{
var clreplacedAttribObj = typ.GetCustomAttributes(typeof(RestResource), false).FirstOrDefault();
string baseUrl;
if (clreplacedAttribObj != null)
{
var clreplacedAttrib = (RestResource)clreplacedAttribObj;
baseUrl = clreplacedAttrib.Path;
baseUrl = baseUrl.StartsWith("/") ? baseUrl : "/" + baseUrl;
}
else baseUrl = "";
var methods = typ.GetMethods();
foreach (var method in methods)
{
var methodAttribObject = method.GetCustomAttributes(typeof(RestPath), false).FirstOrDefault();
if (methodAttribObject != null)
{
var methodAttrib = (RestPath)methodAttribObject;
string finalUrl = baseUrl + (methodAttrib.Path ?? "");
var finalMethod = methodAttrib.Method;
PathExecutionInfo exeInfo = new PathExecutionInfo
{
Type = typ,
Method = method
};
AddExecutionInfo(finalMethod, finalUrl, exeInfo);
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
19
Source : KissManga.cs
with GNU General Public License v3.0
from 9vult
with GNU General Public License v3.0
from 9vult
public override Chapter[] GetSetPrunedChapters(bool overrideDlc)
{
chapters.Clear();
List<Chapter> result = new List<Chapter>();
String[] dlc = GetDLChapters();
bool doFullSetup;
if (!overrideDlc)
{
doFullSetup = true;
}
else // override
{
doFullSetup = false;
}
foreach (string chapterUrl in KissMangaHelper.GetChapterUrls(KissMangaHelper.KISS_URL + "/manga/" + mangaRoot.Name))
{
string[] urlSplits = chapterUrl.Split('/');
string chapID = urlSplits[urlSplits.Length - 1];
string chapNum = chapID.Substring(8); // remove "chapter_"
if ((!doFullSetup) || (doFullSetup && dlc == null) || (doFullSetup && dlc[0].Equals("-1")) || (doFullSetup && dlc.Contains(chapNum)))
{
DirectoryInfo chapDir = null; // Only create folder if doing full setup
if (doFullSetup)
chapDir = FileHelper.CreateFolder(mangaRoot, chapID);
Chapter newchapter = new Chapter(chapDir, chapID, chapNum, doFullSetup);
chapters.Add(newchapter);
result.Add(newchapter);
}
}
chapters = result;
return result.ToArray();
}
19
Source : KissManga.cs
with GNU General Public License v3.0
from 9vult
with GNU General Public License v3.0
from 9vult
public override Chapter[] GetUpdates()
{
List<Chapter> result = new List<Chapter>();
String[] dlc = GetDLChapters();
bool doFullSetup = true;
foreach (string chapterUrl in KissMangaHelper.GetChapterUrls(KissMangaHelper.KISS_URL + "/manga/" + mangaRoot.Name))
{
string[] urlSplits = chapterUrl.Split('/');
string chapID = urlSplits[urlSplits.Length - 1];
string chapNum = chapID.Substring(8); // remove "chapter_"
if ((!doFullSetup) || (doFullSetup && dlc == null) || (doFullSetup && dlc[0].Equals("-1")) || (doFullSetup && dlc.Contains(chapNum)))
{
if (!Directory.Exists(Path.Combine(mangaRoot.FullName, chapID)))
{
DirectoryInfo chapDir = FileHelper.CreateFolder(mangaRoot, chapID);
Chapter newchapter = new Chapter(chapDir, chapID, chapNum, doFullSetup);
chapters.Add(newchapter);
result.Add(newchapter);
}
}
}
return result.ToArray();
}
19
Source : MangaDex.cs
with GNU General Public License v3.0
from 9vult
with GNU General Public License v3.0
from 9vult
public override Chapter[] GetSetPrunedChapters(bool overrideDlc)
{
chapters.Clear();
List<Chapter> result = new List<Chapter>();
string jsonText = MangaDexHelper.GetMangaJSON(id);
JObject jobj = JObject.Parse(jsonText);
String[] dlc = GetDLChapters();
bool doFullSetup;
if (!overrideDlc)
{
doFullSetup = true;
}
else // override
{
doFullSetup = false;
}
foreach (JProperty p in jobj["chapter"])
{
JToken value = p.Value;
if (value.Type == JTokenType.Object)
{
JObject o = (JObject)value;
string chapNum = (String)o["chapter"];
if (usergroup == "^any-group")
{
if (((string)o["lang_code"]).Equals(userlang))
{
if ((!doFullSetup) || (doFullSetup && dlc == null) || (doFullSetup && dlc[0].Equals("-1")) || (doFullSetup && dlc.Contains(chapNum)))
{
string chapID = ((JProperty)value.Parent).Name;
DirectoryInfo chapDir = null; // Only create folder if doing full setup
if (doFullSetup)
chapDir = FileHelper.CreateFolder(mangaRoot, chapID);
Chapter newchapter = new Chapter(chapDir, chapID, chapNum, doFullSetup);
chapters.Add(newchapter);
result.Add(newchapter);
}
}
}
else
{
if (((string)o["lang_code"]).Equals(userlang) && ((string)o["group_name"]).Equals(usergroup))
{
if ((!doFullSetup) || (doFullSetup && dlc == null) || (doFullSetup && dlc[0].Equals("-1")) || (doFullSetup && dlc.Contains(chapNum)))
{
string chapID = ((JProperty)value.Parent).Name;
DirectoryInfo chapDir = FileHelper.CreateFolder(mangaRoot, chapID);
Chapter newchapter = new Chapter(chapDir, chapID, chapNum, doFullSetup);
chapters.Add(newchapter);
result.Add(newchapter);
}
}
}
}
}
chapters = result;
return result.ToArray();
}
19
Source : MangaDex.cs
with GNU General Public License v3.0
from 9vult
with GNU General Public License v3.0
from 9vult
public override Chapter[] GetUpdates()
{
List<Chapter> result = new List<Chapter>();
string jsonText = MangaDexHelper.GetMangaJSON(MangaDexHelper.GetMangaUrl(GetID()));
JObject jobj = JObject.Parse(jsonText);
String[] dlc = GetDLChapters();
bool doFullSetup = true;
foreach (JProperty p in jobj["chapter"])
{
JToken value = p.Value;
if (value.Type == JTokenType.Object)
{
JObject o = (JObject)value;
string chapNum = (String)o["chapter"];
if (usergroup == "^any-group")
{
if (((string)o["lang_code"]).Equals(userlang))
{
if ((!doFullSetup) || (doFullSetup && dlc == null) || (doFullSetup && dlc[0].Equals("-1")) || (doFullSetup && dlc.Contains(chapNum)))
{
string chapID = ((JProperty)value.Parent).Name;
if (!Directory.Exists(Path.Combine(mangaRoot.FullName, chapID)))
{
DirectoryInfo chapDir = FileHelper.CreateFolder(mangaRoot, chapID);
Chapter newchapter = new Chapter(chapDir, chapID, chapNum, doFullSetup);
chapters.Add(newchapter);
result.Add(newchapter);
}
}
}
}
else
{
if (((string)o["lang_code"]).Equals(userlang) && ((string)o["group_name"]).Equals(usergroup))
{
// Console.WriteLine(chapNum);
string chapID = ((JProperty)value.Parent).Name;
if (!Directory.Exists(Path.Combine(mangaRoot.FullName, chapID)))
{
if ((!doFullSetup) || (doFullSetup && dlc == null) || (doFullSetup && dlc[0].Equals("-1")) || (doFullSetup && dlc.Contains(chapNum)))
{
DirectoryInfo chapDir = FileHelper.CreateFolder(mangaRoot, chapID);
Chapter newchapter = new Chapter(chapDir, chapID, chapNum, doFullSetup);
chapters.Add(newchapter);
result.Add(newchapter);
}
}
}
}
}
}
return result.ToArray();
}
19
Source : UserCenterController.cs
with Apache License 2.0
from 91270
with Apache License 2.0
from 91270
[HttpPost]
[Authorization]
public IActionResult AvatarUpload([FromForm(Name = "file")] IFormFile file)
{
try
{
if (Convert.ToBoolean(AppSettings.Configuration["AppSettings:Demo"]))
{
return toResponse(StatusCodeType.Error, "当前为演示模式 , 您无权修改任何数据");
}
var fileExtName = Path.GetExtension(file.FileName).ToLower();
var fileName = DateTime.Now.Ticks.ToString() + fileExtName;
string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".jpeg" };
int MaxContentLength = 1024 * 1024 * 4;
if (!AllowedFileExtensions.Contains(fileExtName))
{
return toResponse(StatusCodeType.Error, "上传失败,未经允许上传类型");
}
if (file.Length > MaxContentLength)
{
return toResponse(StatusCodeType.Error, "上传图片过大,不能超过 " + (MaxContentLength / 1024).ToString() + " MB");
}
var filePath = $"/{DateTime.Now:yyyyMMdd}/";
var avatarDirectory = $"{AppSettings.Configuration["AvatarUpload:AvatarDirectory"]}{filePath}";
if (!Directory.Exists(avatarDirectory))
{
Directory.CreateDirectory(avatarDirectory);
}
using (var stream = new FileStream($"{avatarDirectory}{fileName}", FileMode.Create))
{
file.CopyTo(stream);
}
var avatarUrl = $"{AppSettings.Configuration["AvatarUpload:AvatarUrl"]}{filePath}{fileName}";
var userSession = _tokenManager.GetSessionInfo();
#region 更新用户信息
var response = _usersService.Update(m => m.UserID == userSession.UserID, m => new Sys_Users
{
AvatarUrl = avatarUrl,
UpdateID = userSession.UserID,
UpdateName = userSession.UserName,
UpdateTime = DateTime.Now
});
#endregion
#region 更新登录会话记录
_tokenManager.RefreshSession(userSession.UserID);
#endregion
return toResponse(avatarUrl);
}
catch (Exception)
{
throw;
}
}
19
Source : SpatializerUtilities.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static bool CheckSettings()
{
// Check to see if the count of installed spatializers has changed
if (!CheckSpatializerCount())
{
// A spatializer has been added or removed.
return false;
}
string spatializerName = CurrentSpatializer;
// Check to see if an audio spatializer is configured.
if (string.IsNullOrWhiteSpace(spatializerName))
{
// The user chose to not initialize a spatializer so we are set correctly
return true;
}
string[] installedSpatializers = InstalledSpatializers;
// Check to see if the configured spatializer is installed.
if (!installedSpatializers.Contains(spatializerName))
{
// The current spatializer has been uninstalled.
return false;
}
// A spatializer is correctly configured.
return true;
}
19
Source : SpatializerUtilities.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static void SaveSettings(string spatializer)
{
if (string.IsNullOrWhiteSpace(spatializer))
{
Debug.LogWarning("No spatializer was specified. The application will not support Spatial Sound.");
}
else if (!InstalledSpatializers.Contains(spatializer))
{
Debug.LogError($"{spatializer} is not an installed spatializer.");
return;
}
SerializedObject audioMgrSettings = MixedRealityOptimizeUtils.GetSettingsObject("AudioManager");
SerializedProperty spatializerPlugin = audioMgrSettings.FindProperty("m_SpatializerPlugin");
if (spatializerPlugin == null)
{
Debug.LogError("Unable to save the spatializer settings. The field could not be located into the Audio Manager settings object.");
return;
}
AudioSettings.SetSpatializerPluginName(spatializer);
spatializerPlugin.stringValue = spatializer;
audioMgrSettings.ApplyModifiedProperties();
// Cache the count of installed spatializers
MixedRealityProjectPreferences.AudioSpatializerCount = InstalledSpatializers.Length;
}
19
Source : CreateInvertedIndex.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public static IList<string> GetTerms(string text)
{
text = text.ToLower();
text = new Regex(@"\W").Replace(text, " ");
var words = text.Split(' ').Where(x => x != "").Where(word => !_stopWords.Contains(word)).ToArray();
var tokenizer = new NGramTokenizer();
var terms = words
.Select(tokenizer.Tokenize)
.SelectMany(strings => strings.SelectMany(inner => inner))
.Select(sb => sb.ToString())
.Where(s => !string.IsNullOrEmpty(s) && s.Length > 1)
.ToList();
return terms;
}
19
Source : CreateInvertedIndex.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private static string GetSourceCodeFromExample(Example example)
{
var description = example.SourceFiles;
var uiCodeFiles = description.Where(x => x.Key.EndsWith(".xaml")).ToList();
var sb = new StringBuilder();
foreach (var uiFile in uiCodeFiles)
{
var xml = XDoreplacedent.Parse(uiFile.Value);
foreach (var node in xml.Root.Nodes())
{
if (node is XComment)
{
continue;
}
var xElements = ((XElement)node).Descendants();
foreach (var element in xElements)
{
if (!_codeStopWords.Contains(element.Name.LocalName))
{
sb.AppendFormat("{0} ", element.Name.LocalName);
foreach (var attribute in element.Attributes())
{
sb.AppendFormat("{0} ", attribute.Name.LocalName);
}
}
}
}
}
var lines = sb.ToString();
return lines;
}
19
Source : Program.cs
with MIT License
from acandylevey
with MIT License
from acandylevey
static void Main(string[] args)
{
Log.Active = true;
Host = new MyHost();
Host.SupportedBrowsers.Add(ChromiumBrowser.GoogleChrome);
Host.SupportedBrowsers.Add(ChromiumBrowser.MicrosoftEdge);
if (args.Contains("--register"))
{
Host.GenerateManifest(Description, AllowedOrigins);
Host.Register();
}
else if (args.Contains("--unregister"))
{
Host.Unregister();
}
else
{
Host.Listen();
}
}
19
Source : FileLocatorExtensions.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
public static FileType GetFileType(this FileLocator fileLocator)
{
if (fileLocator == null || string.IsNullOrWhiteSpace(fileLocator.FileName)) return default;
var extension = Path.GetExtension(fileLocator.FileName);
var fileExtension = string.IsNullOrEmpty(extension) ? string.Empty : extension.Substring(1);
return (from item in FileTypeMapping where item.Value.Contains(fileExtension) select item.Key).FirstOrDefault();
}
19
Source : Program_DbUpdates.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
private static void PatchDatabase(string dbType, string host, uint port, string username, string preplacedword, string database)
{
var updatesPath = $"DatabaseSetupScripts{Path.DirectorySeparatorChar}Updates{Path.DirectorySeparatorChar}{dbType}";
var updatesFile = $"{updatesPath}{Path.DirectorySeparatorChar}applied_updates.txt";
var appliedUpdates = Array.Empty<string>();
var containerUpdatesFile = $"/ace/Config/{dbType}_applied_updates.txt";
if (IsRunningInContainer && File.Exists(containerUpdatesFile))
File.Copy(containerUpdatesFile, updatesFile, true);
if (File.Exists(updatesFile))
appliedUpdates = File.ReadAllLines(updatesFile);
Console.WriteLine($"Searching for {dbType} update SQL scripts .... ");
foreach (var file in new DirectoryInfo(updatesPath).GetFiles("*.sql").OrderBy(f => f.Name))
{
if (appliedUpdates.Contains(file.Name))
continue;
Console.Write($"Found {file.Name} .... ");
var sqlDBFile = File.ReadAllText(file.FullName);
var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection($"server={host};port={port};user={username};preplacedword={preplacedword};database={database};DefaultCommandTimeout=120");
switch (dbType)
{
case "Authentication":
sqlDBFile = sqlDBFile.Replace("ace_auth", database);
break;
case "Shard":
sqlDBFile = sqlDBFile.Replace("ace_shard", database);
break;
case "World":
sqlDBFile = sqlDBFile.Replace("ace_world", database);
break;
}
var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);
Console.Write($"Importing into {database} database on SQL server at {host}:{port} .... ");
try
{
script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
var count = script.Execute();
//Console.Write($" {count} database records affected ....");
Console.WriteLine(" complete!");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
Console.WriteLine($" error!");
Console.WriteLine($" Unable to apply patch due to following exception: {ex}");
}
File.AppendAllText(updatesFile, file.Name + Environment.NewLine);
}
if (IsRunningInContainer && File.Exists(updatesFile))
File.Copy(updatesFile, containerUpdatesFile, true);
Console.WriteLine($"{dbType} update SQL scripts import complete!");
}
19
Source : ConversionModule.cs
with MIT License
from acid-chicken
with MIT License
from acid-chicken
[Command(""), Summary("現在のレートで通貨を換算します。")]
public async Task ConvertAsync([Summary("換算元の通貨")] string before, [Summary("換算先の通貨")] string after, [Summary("換算額")] decimal volume = decimal.One, [Remainder] string comment = null)
{
var result = volume;
var route = string.Empty;
var afterL = after.ToLower();
var beforeL = before.ToLower();
var afterU = after.ToUpper();
var beforeU = before.ToUpper();
var isAfterBTC = afterL == "bitcoin" || afterU == "BTC";
var isAfterUSD = afterU == UnitedStatesDollar;
var isAfterC = Convertable.Contains(afterU);
var isBeforeUSD = beforeU == UnitedStatesDollar;
var isBeforeC = Convertable.Contains(beforeU);
if (isAfterUSD)
{
if (isBeforeUSD)
{
route = "USD > USD";
}
else if (isBeforeC)
{
var beforeD = await ApiManager.GetTickerAsDictionaryAsync("bitcoin", beforeU).ConfigureAwait(false);
result *= decimal.Parse(beforeD[$"price_usd"]) / decimal.Parse(beforeD[$"price_{beforeL}"]);
route = $"{beforeU} > BTC > USD";
}
else
{
var afterDs = await ApiManager.GetTickersAsDictionaryAsync().ConfigureAwait(false);
var afterBD = afterDs.First(x => x["id"] == beforeL || x["name"] == before || x["symbol"] == beforeU);
result *= decimal.Parse(afterBD[$"price_usd"]);
route = $"{beforeU} > USD";
}
}
else if (isAfterC)
{
if (isBeforeUSD)
{
var afterD = await ApiManager.GetTickerAsDictionaryAsync("bitcoin", afterU).ConfigureAwait(false);
result *= decimal.Parse(afterD[$"price_{afterL}"]) / decimal.Parse(afterD[$"price_usd"]);
route = $"USD > BTC > {afterU}";
}
else if (isBeforeC)
{
var afterD = await ApiManager.GetTickerAsDictionaryAsync("bitcoin", afterU).ConfigureAwait(false);
var beforeD = await ApiManager.GetTickerAsDictionaryAsync("bitcoin", beforeU).ConfigureAwait(false);
result *= decimal.Parse(afterD[$"price_{afterL}"]) / decimal.Parse(beforeD[$"price_{beforeL}"]);
route = $"{beforeU} > BTC > {afterU}";
}
else
{
var afterDs = await ApiManager.GetTickersAsDictionaryAsync(afterU).ConfigureAwait(false);
var afterBD = afterDs.First(x => x["id"] == beforeL || x["name"] == before || x["symbol"] == beforeU);
result *= decimal.Parse(afterBD[$"price_{afterL}"]);
route = $"{beforeU} > {afterU}";
}
}
else
{
if (isBeforeUSD)
{
var beforeDs = await ApiManager.GetTickersAsDictionaryAsync().ConfigureAwait(false);
var beforeBD = beforeDs.First(x => x["id"] == afterL || x["name"] == after || x["symbol"] == afterU);
result /= decimal.Parse(beforeBD[$"price_usd"]);
route = $"USD > {afterU}";
}
else if (isBeforeC)
{
var beforeDs = await ApiManager.GetTickersAsDictionaryAsync(beforeU).ConfigureAwait(false);
var beforeBD = beforeDs.First(x => x["id"] == afterL || x["name"] == after || x["symbol"] == afterU);
result /= decimal.Parse(beforeBD[$"price_{beforeL}"]);
route = $"{beforeU} > {afterU}";
}
else
{
var afterDs = await ApiManager.GetTickersAsDictionaryAsync().ConfigureAwait(false);
var afterBD = afterDs.First(x => x["id"] == beforeL || x["name"] == before || x["symbol"] == beforeU);
if (isAfterBTC)
{
result *= decimal.Parse(afterBD["price_btc"]);
route = $"{beforeU} > BTC";
}
else
{
var beforeDs = await ApiManager.GetTickersAsDictionaryAsync().ConfigureAwait(false);
var beforeBD = beforeDs.First(x => x["id"] == afterL || x["name"] == after || x["symbol"] == afterU);
result *= decimal.Parse(afterBD["price_usd"]) / decimal.Parse(beforeBD["price_usd"]);
route = $"{beforeU} > BTC > {afterU}";
}
}
}
await ReplyAsync
(
message: Context.User.Mention,
embed:
new EmbedBuilder()
.Withreplacedle("換算結果")
.WithDescription(route)
.WithCurrentTimestamp()
.WithColor(Colors.Blue)
.WithFooter(EmbedManager.CurrentFooter)
.WithAuthor(Context.User)
.AddInlineField("換算前", $"{volume} {beforeU}")
.AddInlineField("換算後", $"{result} {afterU}")
).ConfigureAwait(false);
}
19
Source : LocalizationSymbols.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
private (ImmutableArray<ISymbol>, ImmutableArray<ISymbol>) GetMethods(IEnumerable<ISymbol> membersToreplacedyze,
IEnumerable<string> simpleMethodNames, IEnumerable<string> formatMethodNames)
{
List<ISymbol> simpleMethods = new List<ISymbol>();
List<ISymbol> formatMethods = new List<ISymbol>();
foreach (ISymbol m in membersToreplacedyze)
{
if (m.Kind != SymbolKind.Method)
continue;
if (simpleMethodNames.Contains(m.MetadataName))
{
simpleMethods.Add(m);
}
else if (formatMethodNames.Contains(m.MetadataName))
{
formatMethods.Add(m);
}
}
return (simpleMethods.ToImmutableArray(), formatMethods.ToImmutableArray());
}
19
Source : Program.cs
with Apache License 2.0
from adamralph
with Apache License 2.0
from adamralph
public static int Main(string[] args)
{
if (args.Contains("unicode"))
{
Console.OutputEncoding = Encoding.Unicode;
args = args.Concat(new[] { "Pi (\u03a0)" }).ToArray();
}
var input = args.Contains("in")
? Console.In.ReadToEnd()
.Replace("\r", "\\r", StringComparison.Ordinal)
.Replace("\n", "\\n", StringComparison.Ordinal)
: null;
Console.Out.WriteLine($"SimpleExecTester (stdin): {input}");
Console.Out.WriteLine($"SimpleExecTester (stdout): {string.Join(" ", args)}");
Console.Error.WriteLine($"SimpleExecTester (stderr): {string.Join(" ", args)}");
if (args.Contains("large"))
{
Console.Out.WriteLine(new string('x', (int)Math.Pow(2, 12)));
Console.Error.WriteLine(new string('x', (int)Math.Pow(2, 12)));
}
var exitCode = 0;
if (args.FirstOrDefault(arg => int.TryParse(arg, out exitCode)) != null)
{
return exitCode;
}
if (args.Contains("sleep"))
{
Thread.Sleep(Timeout.Infinite);
return 0;
}
Console.WriteLine($"foo={Environment.GetEnvironmentVariable("foo")}");
return 0;
}
19
Source : SettingsReader.cs
with GNU General Public License v3.0
from AdamWhiteHat
with GNU General Public License v3.0
from AdamWhiteHat
public static bool SettingExists(string SettingName)
{
try
{
if (string.IsNullOrWhiteSpace(SettingName))
{
return false;
}
else if (!ConfigurationManager.AppSettings.AllKeys.Contains(SettingName))
{
return false;
}
else if (string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings[SettingName]))
{
return false;
}
return true;
}
catch (Exception ex)
{
Logging.LogException(ex, $"{nameof(SettingsReader)}.{nameof(SettingExists)} threw an exception.");
return false;
}
}
19
Source : ApplicationRestartPortalBusMessage.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public virtual bool Validate(PluginMessage message)
{
IEnumerable<string> patterns;
if (message.Target == null
|| string.IsNullOrWhiteSpace(message.Target.LogicalName)
|| !_enreplacediesToRestart.TryGetValue(message.Target.LogicalName, out patterns))
{
return false;
}
return patterns.Contains(".*")
|| (!string.IsNullOrWhiteSpace(message.Target.Name)
&& patterns.Any(pattern => Regex.IsMatch(message.Target.Name, pattern)));
}
19
Source : MetadataHelper.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static AttributeTypeCode? GetAttributeTypeCode(OrganizationServiceContext serviceContext, string enreplacedyLogicalName, string attributeLogicalName)
{
var enreplacedyMetadata = GetEnreplacedyMetadata(serviceContext, enreplacedyLogicalName);
if (enreplacedyMetadata == null)
{
return null;
}
if (!enreplacedyMetadata.Attributes.Select(a => a.LogicalName).Contains(attributeLogicalName))
{
return null;
}
var attribute = enreplacedyMetadata.Attributes.FirstOrDefault(a => a.LogicalName == attributeLogicalName);
return attribute == null ? null : attribute.AttributeType;
}
19
Source : MetadataHelper.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static bool IsAttributeLogicalNameValid(OrganizationServiceContext serviceContext, string enreplacedyLogicalName, string attributeLogicalName)
{
var enreplacedyMetadata = GetEnreplacedyMetadata(serviceContext, enreplacedyLogicalName);
return enreplacedyMetadata != null && enreplacedyMetadata.Attributes.Select(a => a.LogicalName).Contains(attributeLogicalName);
}
19
Source : CookieInspector.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private HttpCookie CheckCookie(string key)
{
if (this.Context == null)
{
return null;
}
// Attempt to find this key in the Response, if not there search the request
return this.Context.Response.Cookies.AllKeys.Contains(key)
? this.Context.Response.Cookies.Get(key)
: this.Context.Request.Cookies.AllKeys.Contains(key)
? this.Context.Request.Cookies.Get(key)
: null;
}
19
Source : FetchXmlIndexDocumentFactory.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private void AddDefaultWebRoleToAllDoreplacedentsNotUnderCMS(Doreplacedent doreplacedent, string enreplacedyLogicalName)
{
var cmsEnreplacedies = new[]
{
"adx_blog", "adx_blogpost",
"adx_communityforum", "adx_communityforumthread", "adx_communityforumpost",
"adx_idea", "adx_ideaforum",
"adx_webpage",
"adx_webfile"
};
if (!cmsEnreplacedies.Contains(enreplacedyLogicalName))
{
doreplacedent.Add(
new Field(this._index.WebRoleFieldName, this._index.WebRoleDefaultValue, Field.Store.NO, Field.Index.NOT_replacedYZED));
}
}
19
Source : FetchXMLConditionalOperators.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static ConditionOperator GetKeyByValue(string value)
{
var keyValue = ConditionOperatorToTextFromLookUp.First(pair => pair.Value.Contains(value));
return keyValue.Key;
}
19
Source : CacheDependencyCalculator.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static bool IsContentRequest(OrganizationRequest request)
{
return request != null && CachedRequestsContent.Contains(request.RequestName);
}
19
Source : CrmOnlineReadTransientErrorDetectionStrategy.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static bool IsTransientWebException(Exception ex)
{
var we = ex as WebException;
return we != null && _transientWebExceptions.Contains(we.Message);
}
19
Source : CdnUrlExpressionBuilder.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static string GetValueByIndexOrName(this NameValueCollection collection, int index, string name)
{
if (collection.AllKeys.Contains(name)) return collection[name];
if (collection.Count > index && collection.AllKeys[index] == "_{0}".FormatWith(index)) return collection[index];
return null;
}
19
Source : CdnUrlExpressionBuilder.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static string[] GetValuesByIndexOrName(this NameValueCollection collection, int index, string name)
{
if (collection.AllKeys.Contains(name)) return collection.GetValues(name);
if (collection.Count > index && collection.AllKeys[index] == "_{0}".FormatWith(index)) return collection.GetValues(index);
return null;
}
19
Source : CacheDependencyCalculator.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static bool IsMetadataRequest(OrganizationRequest request)
{
return request != null && CachedRequestsMetadata.Contains(request.RequestName);
}
19
Source : StyleExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static IEnumerable<string> ContentStyles(IPortalViewContext portalViewContext, SiteMapNode node, IDictionary<string, object> cache, IEnumerable<string> except, IEnumerable<KeyValuePair<string, string>> only)
{
var styles = ContentStyles(portalViewContext, node, cache).ToArray();
string[] allDisplayModes;
string[] availableDisplayModes;
if (TryGetDisplayModes(out allDisplayModes, out availableDisplayModes))
{
var partialUrlTrie = new FileNameTrie(styles);
var displayModeComparer = new DisplayModeComparer(availableDisplayModes);
var groups = GetDisplayModeFileGroups(partialUrlTrie, allDisplayModes);
if (only != null)
{
return only.Select(o =>
{
var extensionless = Path.GetFileNameWithoutExtension(o.Key);
var matchGroup = groups.FirstOrDefault(s => string.Equals(s.Prefix, extensionless, StringComparison.OrdinalIgnoreCase));
if (matchGroup == null)
{
return o.Value;
}
var file = matchGroup.Where(f => availableDisplayModes.Contains(f.DisplayModeId))
.OrderBy(f => f, displayModeComparer)
.FirstOrDefault();
return file == null ? o.Value : file.Name.Item1;
});
}
if (except != null)
{
return groups
.Where(group => !except.Any(e => string.Equals(Path.GetFileNameWithoutExtension(e), group.Prefix, StringComparison.OrdinalIgnoreCase)))
.Select(group => group.Where(f => availableDisplayModes.Contains(f.DisplayModeId))
.OrderBy(f => f, displayModeComparer)
.FirstOrDefault())
.Where(f => f != null)
.Select(f => f.Name.Item1);
}
return groups
.Select(group => group.Where(f => availableDisplayModes.Contains(f.DisplayModeId))
.OrderBy(f => f, displayModeComparer)
.FirstOrDefault())
.Where(f => f != null)
.Select(f => f.Name.Item1);
}
if (only != null)
{
return only.Select(o =>
{
var match = styles.FirstOrDefault(s => string.Equals(s.Item2, o.Key, StringComparison.InvariantCultureIgnoreCase));
return match == null ? o.Value : match.Item1;
});
}
if (except != null)
{
return styles
.Where(s => !except.Any(e => string.Equals(e, s.Item2, StringComparison.InvariantCultureIgnoreCase)))
.Select(s => s.Item1);
}
return styles.Select(s => s.Item1);
}
19
Source : FilterOptionGroup.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static FilterOption ToFilterOption(EnreplacedyMetadata enreplacedyMetadata, Enreplacedy enreplacedy, string labelColumn, IEnumerable<string> selected)
{
if (string.IsNullOrEmpty(labelColumn))
{
labelColumn = enreplacedyMetadata.PrimaryNameAttribute;
}
var id = string.Format("{{{0}}}", enreplacedy.Id);
return new FilterOption
{
Id = id,
Type = "dynamic",
Label = enreplacedy.GetAttributeValueOrDefault(labelColumn, string.Empty),
Checked = selected.Contains(id)
};
}
19
Source : CrmContactRoleProvider.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public override bool IsUserInRole(string username, string roleName)
{
var rolesForUser = GetRolesForUser(username);
return rolesForUser.Contains(roleName);
}
19
Source : FilterOptionGroup.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static FilterOption ToFilterOption(OptionMetadata optionMetadata, IEnumerable<string> selected)
{
var id = string.Empty + optionMetadata.Value;
return new FilterOption
{
Id = id,
Type = "dynamic",
Label = optionMetadata.Label.GetLocalizedLabelString(),
Checked = selected.Contains(id)
};
}
19
Source : SavedQueryView.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static ViewColumn ConvertLayoutCellToViewColumn(OrganizationServiceContext serviceContext, EnreplacedyMetadata enreplacedyMetadata, string cellName, Dictionary<string, int> cellWidths, IEnumerable<string> disabledSortCellNames, XElement fetchXml, int languageCode, string aliasColumnNameStringFormat)
{
var label = GetLabel(serviceContext, enreplacedyMetadata, cellName, fetchXml, languageCode, aliasColumnNameStringFormat);
var metadata = GetMetadata(serviceContext, enreplacedyMetadata, cellName, fetchXml);
var sortDisabled = disabledSortCellNames.Contains(cellName);
var width = cellWidths[cellName];
return new ViewColumn(cellName, label, metadata, width, sortDisabled);
}
19
Source : UrlHistoryRedirectProvider.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static IMatch FindPage(OrganizationServiceContext context, Enreplacedy website, string path)
{
var mappedPageResult = UrlMapping.LookupPageByUrlPath(context, website, path);
if (mappedPageResult.Node != null)
{
return new NonHistoryMatch(mappedPageResult.Node);
}
var historyMatchPage = FindHistoryMatchPage(context, website, path);
if (historyMatchPage != null)
{
return new HistoryMatch(historyMatchPage);
}
// find the last slash in the path
var lastSlash = path.LastIndexOf('/');
if (lastSlash != -1)
{
// we found a slash
var pathBeforeSlash = path.Substring(0, lastSlash);
var pathAfterSlash = path.Substring(lastSlash + 1);
var parentMatch = (string.IsNullOrWhiteSpace(pathBeforeSlash) || _homePaths.Contains(pathBeforeSlash))
// do a final traversal against the home page
? GetHomePage(context, website)
// see if we can find a path for the parent url
: FindPage(context, website, pathBeforeSlash);
if (parentMatch.Success)
{
var foundParentPageID = parentMatch.WebPage.ToEnreplacedyReference();
var fetch = new Fetch
{
Enreplacedy = new FetchEnreplacedy("adx_webpage")
{
Filters = new List<Filter>
{
new Filter
{
Conditions = new[]
{
new Condition("statecode", ConditionOperator.Equal, 0),
new Condition("adx_parentpageid", ConditionOperator.Equal, foundParentPageID.Id),
new Condition("adx_partialurl", ConditionOperator.Equal, pathAfterSlash)
}
}
}
}
};
// we found a parent path, now rebuild the path of the child
var child = context.RetrieveSingle(fetch);
if (child != null)
{
return new SuccessfulMatch(child, parentMatch.UsedHistory);
}
var parentPath = context.GetApplicationPath(parentMatch.WebPage);
if (parentPath == null)
{
return new FailedMatch();
}
if (parentPath.AppRelativePath.TrimEnd('/') == path)
{
// prevent stack overflow
return new FailedMatch();
}
var newPath = parentPath.AppRelativePath + (parentPath.AppRelativePath.EndsWith("/") ? string.Empty : "/") + pathAfterSlash;
if (newPath == path)
{
return new FailedMatch();
}
var childMatch = FindPage(context, website, newPath);
if (childMatch.Success)
{
return new HistoryMatch(childMatch.WebPage);
}
}
}
return new FailedMatch();
}
19
Source : EntityExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static bool HasLogicalName(this Enreplacedy enreplacedy, params string[] expectedEnreplacedyName)
{
return enreplacedy != null && expectedEnreplacedyName.Contains(enreplacedy.LogicalName);
}
19
Source : EntityExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static void SetAttributeStringTruncatedToMaxLength(this Enreplacedy enreplacedy, EnreplacedyMetadata enreplacedyMetadata, string attributeLogicalName, string value)
{
if (!string.IsNullOrEmpty(value))
{
if (enreplacedyMetadata == null)
{
throw new ApplicationException("Unable to retrieve the enreplacedy metadata for {0}.".FormatWith(enreplacedy.LogicalName));
}
if (!enreplacedyMetadata.Attributes.Select(a => a.LogicalName).Contains(attributeLogicalName))
{
throw new ApplicationException("Attribute {0} could not be found in enreplacedy metadata for {1}.".FormatWith(attributeLogicalName, enreplacedy.LogicalName));
}
var attribute = enreplacedyMetadata.Attributes.FirstOrDefault(a => a.LogicalName == attributeLogicalName);
if (attribute == null || attribute.AttributeType != AttributeTypeCode.String)
{
throw new ApplicationException("Attribute {0} is not of type string.".FormatWith(attributeLogicalName));
}
var stringAttributeMetadata = attribute as StringAttributeMetadata;
if (stringAttributeMetadata != null)
{
var maxLength = stringAttributeMetadata.MaxLength ?? 0;
if (maxLength > 0 && value.Length > maxLength)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format(@"String length ({0}) is greater than attribute ""{1}"" max length ({2}). String has been truncated.", value.Length, attributeLogicalName, maxLength));
value = value.Truncate(maxLength);
}
}
}
enreplacedy.SetAttributeValue<string>(attributeLogicalName, value);
}
19
Source : EntityReferenceExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static bool HasLogicalName(this EnreplacedyReference enreplacedyReference, params string[] expectedLogicalName)
{
return enreplacedyReference != null && expectedLogicalName.Contains(enreplacedyReference.LogicalName);
}
19
Source : SavedQueryColumnsGenerator.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public ICollection GenerateFields(Control control)
{
var layoutXml = XElement.Parse(SavedQuery.GetAttributeValue<string>("layoutxml"));
var cellNames = layoutXml.Element("row").Elements("cell").Select(cell => cell.Attribute("name")).Where(name => name != null);
var disabledSortCellNames = layoutXml.Element("row").Elements("cell")
.Where(cell => cell.Attribute("disableSorting") != null && cell.Attribute("disableSorting").Value == "1")
.Where(cell => cell.Attribute("name") != null)
.Select(cell => cell.Attribute("name").Value);
var fetchXml = XElement.Parse(SavedQuery.GetAttributeValue<string>("fetchxml"));
var enreplacedyName = fetchXml.Element("enreplacedy").Attribute("name").Value;
var response = (RetrieveEnreplacedyResponse)ServiceContext.Execute(new RetrieveEnreplacedyRequest
{
LogicalName = enreplacedyName,
EnreplacedyFilters = EnreplacedyFilters.Attributes
});
if (response == null || response.EnreplacedyMetadata == null)
{
return new DataControlFieldCollection();
}
if (LanguageCode == 0)
{
LanguageCode = HttpContext.Current?.GetCrmLcid() ?? CultureInfo.CurrentCulture.LCID;
}
var fields =
from name in cellNames
let label = GetLabel(ServiceContext, response.EnreplacedyMetadata, name.Value, fetchXml, LanguageCode)
where label != null
select new BoundField
{
DataField = name.Value,
SortExpression = disabledSortCellNames.Contains(name.Value) ? string.Empty : name.Value,
HeaderText = label
};
return fields.ToArray();
}
19
Source : OrganizationServiceCache.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static bool IsMetadataRequest(OrganizationRequest request)
{
return request != null && _cachedRequestsMetadata.Contains(request.RequestName);
}
19
Source : CrmOrganizationServiceContext.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static bool IsReadOnlyEnreplacedyProperty(object resource, string propertyName)
{
return !(resource is Enreplacedy) || !_readOnlyProperties.Contains(propertyName);
}
19
Source : WSFederationAuthenticationModuleExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static IEnumerable<KeyValuePair<string, string>> GetParameters(this WSFederationMessage message)
{
return GetParameters(message, key => _federationParameters.Contains(key));
}
19
Source : WSFederationAuthenticationModuleExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static IEnumerable<KeyValuePair<string, string>> GetUnknownParameters(this WSFederationMessage message)
{
return GetParameters(message, key => !_federationParameters.Contains(key));
}
19
Source : OrganizationServiceCache.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static bool IsContentRequest(OrganizationRequest request)
{
return request != null && _cachedRequestsContent.Contains(request.RequestName);
}
19
Source : EntityExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static void replacedertEnreplacedyName(this Enreplacedy enreplacedy, params string[] expectedEnreplacedyName)
{
// accept null values
if (enreplacedy == null) return;
var enreplacedyName = enreplacedy.LogicalName;
if (!expectedEnreplacedyName.Contains(enreplacedyName))
{
throw new ArgumentException(
"The extension method expected an enreplacedy object of the type {0} but was preplaceded an enreplacedy object of the type {1} instead.".FormatWith(
string.Join(" or ", expectedEnreplacedyName),
enreplacedyName));
}
}
19
Source : FederationAuthenticationHandler.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
protected IEnumerable<KeyValuePair<string, string>> ToAttributes(IEnumerable<KeyValuePair<string, string>> signInContext)
{
var attributeFilterEnabled = RegistrationSettings.SignUpAttributes != null && RegistrationSettings.SignUpAttributes.Any();
var attributes = attributeFilterEnabled
? signInContext.Where(item => RegistrationSettings.SignUpAttributes.Contains(item.Key))
: signInContext.Where(item => !new[] { ReturnUrlKey, InvitationCodeKey, ChallengeAnswerKey }.Contains(item.Key));
return attributes;
}
19
Source : CmsDataServiceCrmEntityEditingMetadataProvider.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public virtual void AddEnreplacedyMetadata(string portalName, IEditableCrmEnreplacedyControl control, Control container, Enreplacedy enreplacedy)
{
if (control == null || container == null || enreplacedy == null)
{
return;
}
if (enreplacedy.LogicalName == "adx_weblinkset")
{
// Output the service reference for the web link set itself.
AddEnreplacedyServiceReference(control, enreplacedy, enreplacedy.GetAttributeValue<string>("adx_name"), container);
// Output the service reference for the child web links of the set.
AddEnreplacedyreplacedocationSetServiceReferenceForWebLinkSet(control, enreplacedy, "adx_weblinkset_weblink".ToRelationship(), container);
AddEnreplacedyreplacedocationSetServiceReference(portalName, control, enreplacedy, "adx_weblinkset_weblink".ToRelationship(), container, "xrm-enreplacedy-{0}-update-ref");
AddEnreplacedySetSchemaMap(control, "adx_weblink", container);
// Output the service reference and schema map for site web pages (required to create new web links).
AddEnreplacedySetServiceReference(control, "adx_webpage", container);
AddEnreplacedySetSchemaMap(control, "adx_webpage", container);
string weblinkDeleteUriTemplate;
if (TryGetCrmEnreplacedyDeleteDataServiceUriTemplate(control, "adx_weblink", out weblinkDeleteUriTemplate))
{
AddServiceReference(control, weblinkDeleteUriTemplate, "xrm-uri-template xrm-enreplacedy-adx_weblink-delete-ref", container);
}
return;
}
string serviceUri;
if (!TryGetDataServiceEnreplacedyUri(control, enreplacedy, out serviceUri))
{
return;
}
// Add the service reference to the bound enreplacedy.
container.Controls.Add(new HyperLink { CssClreplaced = "xrm-enreplacedy-ref", NavigateUrl = VirtualPathUtility.ToAbsolute(serviceUri), Text = string.Empty });
string enreplacedyUrlServiceUri;
// Add the service reference for getting the URL of the bound enreplacedy.
if (TryGetCrmEnreplacedyUrlDataServiceUri(control, enreplacedy, out enreplacedyUrlServiceUri))
{
AddServiceReference(control, enreplacedyUrlServiceUri, "xrm-enreplacedy-url-ref", container, "GetEnreplacedyUrl");
}
var crmEnreplacedyName = enreplacedy.LogicalName;
AddEnreplacedySetSchemaMap(control, crmEnreplacedyName, container);
// If the enreplacedy is "deletable", add a service reference for soft-delete of the enreplacedy.
if (DeletableEnreplacedyNames.Contains(crmEnreplacedyName))
{
string deleteServiceUri;
if (TryGetCrmEnreplacedyDeleteDataServiceUri(control, enreplacedy, out deleteServiceUri))
{
AddServiceReference(control, deleteServiceUri, "xrm-enreplacedy-delete-ref", container);
}
}
if (FileAttachmentEnreplacedyNames.Contains(crmEnreplacedyName))
{
string fileAttachmentServiceUri;
if (TryGetCrmEnreplacedyFileAttachmentDataServiceUri(control, enreplacedy, out fileAttachmentServiceUri))
{
AddServiceReference(control, fileAttachmentServiceUri, "xrm-enreplacedy-attachment-ref", container);
}
}
// Add the service references on which the creation of various enreplacedies are dependent.
foreach (var dependencyEnreplacedyName in DependencyEnreplacedyNames)
{
AddEnreplacedySetServiceReference(control, dependencyEnreplacedyName, container);
AddEnreplacedySetSchemaMap(control, dependencyEnreplacedyName, container);
}
// Add the service reference URI Templates for the notes replacedociated with given enreplacedy types.
foreach (var fileAttachmentEnreplacedy in FileAttachmentEnreplacedyNames)
{
string uriTemplate;
if (TryGetCrmEnreplacedyFileAttachmentDataServiceUriTemplate(control, fileAttachmentEnreplacedy, out uriTemplate))
{
AddServiceReference(control, uriTemplate, "xrm-uri-template xrm-enreplacedy-{0}-attachment-ref".FormatWith(fileAttachmentEnreplacedy), container);
}
}
// Add the service reference URI Templates for getting URLs for specific enreplacedy types.
foreach (var urlEnreplacedyName in UrlEnreplacedyNames)
{
string uriTemplate;
if (TryGetCrmEnreplacedyUrlDataServiceUriTemplate(control, urlEnreplacedyName, out uriTemplate))
{
AddServiceReference(control, uriTemplate, "xrm-uri-template xrm-enreplacedy-{0}-url-ref".FormatWith(urlEnreplacedyName), container, "GetEnreplacedyUrl");
}
}
IEnumerable<Relationship> childreplacedociations;
if (ChildreplacedociationsByEnreplacedyName.TryGetValue(crmEnreplacedyName, out childreplacedociations))
{
foreach (var childreplacedociation in childreplacedociations)
{
AddEnreplacedyreplacedocationSetServiceReference(portalName, control, enreplacedy, childreplacedociation, container);
}
}
Relationship parentalRelationship;
// Output the URL path of parent enreplacedy to the DOM (mostly to be read if the enreplacedy is deleted--the user
// will then be redirected to the parent).
if (_parentalRelationshipsByEnreplacedyName.TryGetValue(crmEnreplacedyName, out parentalRelationship))
{
var context = PortalCrmConfigurationManager.GetServiceContext(PortalName);
enreplacedy = context.MergeClone(enreplacedy);
var parent = enreplacedy.GetRelatedEnreplacedy(context, parentalRelationship);
var dependencyProvider = PortalCrmConfigurationManager.CreateDependencyProvider(PortalName);
if (dependencyProvider == null)
{
throw new InvalidOperationException("Unable to create {0} for current portal configuration.".FormatWith(typeof(IDependencyProvider).FullName));
}
var urlProvider = dependencyProvider.GetDependency<IEnreplacedyUrlProvider>();
if (urlProvider == null)
{
throw new InvalidOperationException("Unable to create {0} for current portal configuration.".FormatWith(typeof(IEnreplacedyUrlProvider).FullName));
}
var parentPath = urlProvider.GetApplicationPath(context, parent ?? enreplacedy);
if (parentPath != null)
{
AddServiceReference(control, parentPath.AbsolutePath, "xrm-enreplacedy-parent-url-ref", container);
}
}
// Output the sitemarkers of the current web page into the DOM.
if (crmEnreplacedyName == "adx_webpage")
{
var context = PortalCrmConfigurationManager.GetServiceContext(PortalName);
enreplacedy = context.MergeClone(enreplacedy);
foreach (var siteMarker in enreplacedy.GetRelatedEnreplacedies(context, "adx_webpage_sitemarker"))
{
var siteMarkerRef = new HtmlGenericControl("span");
siteMarkerRef.Attributes["clreplaced"] = "xrm-enreplacedy-adx_webpage_sitemarker";
siteMarkerRef.Attributes["replacedle"] = siteMarker.GetAttributeValue<string>("adx_name");
container.Controls.Add(siteMarkerRef);
}
AddEnreplacedySetSchemaMap(control, "adx_webfile", container);
}
}
See More Examples