Here are the examples of the csharp api System.Text.RegularExpressions.Regex.Replace(string, string, string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1915 Examples
19
Source : MessageController.cs
with Apache License 2.0
from 0nise
with Apache License 2.0
from 0nise
public static string executeCodeReplace(string message) {
message = Regex.Replace(message,"随.{2}程","随机教程");
message = Regex.Replace(message, "随.{2}章", "随机文章");
message = Regex.Replace(message, "最.{2}章", "最新文章");
message = Regex.Replace(message, "最.{2}程", "最新教程");
message = message.Replace("余额查询",MessageConstant.SELECT_MONEY);
return message;
}
19
Source : XmlCommandsProvider.cs
with Apache License 2.0
from 1448376744
with Apache License 2.0
from 1448376744
private string ReplaceVariable(Dictionary<string, string> variables, string text)
{
var matches = Regex.Matches(text, @"\${(?<key>.*?)}");
foreach (Match item in matches)
{
var key = item.Groups["key"].Value;
if (variables.ContainsKey(key))
{
var value = variables[key];
text = text.Replace("${" + key + "}", value);
}
}
return Regex.Replace(text, @"\s+", " ").Trim(' ');
}
19
Source : ConnectionStringBuilder.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static ConnectionStringBuilder Parse(string connectionString)
{
var ret = new ConnectionStringBuilder();
if (string.IsNullOrEmpty(connectionString)) return ret;
//支持密码中带有逗号,将原有 split(',') 改成以下处理方式
var vs = Regex.Split(connectionString, @"\,([\w \t\r\n]+)=", RegexOptions.Multiline);
ret.Host = vs[0].Trim();
for (var a = 1; a < vs.Length; a += 2)
{
var kv = new[] { Regex.Replace(vs[a].ToLower().Trim(), @"[ \t\r\n]", ""), vs[a + 1] };
switch (kv[0])
{
case "ssl": if (kv.Length > 1 && kv[1].ToLower().Trim() == "true") ret.Ssl = true; break;
case "protocol": if (kv.Length > 1 && kv[1].ToUpper().Trim() == "RESP3") ret.Protocol = RedisProtocol.RESP3; break;
case "userid":
case "user": if (kv.Length > 1) ret.User = kv[1].Trim(); break;
case "preplacedword": if (kv.Length > 1) ret.Preplacedword = kv[1]; break;
case "database":
case "defaultdatabase": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var database) && database > 0) ret.Database = database; break;
case "prefix": if (kv.Length > 1) ret.Prefix = kv[1].Trim(); break;
case "name":
case "clientname": if (kv.Length > 1) ret.ClientName = kv[1].Trim(); break;
case "encoding": if (kv.Length > 1) ret.Encoding = Encoding.GetEncoding(kv[1].Trim()); break;
case "idletimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var idleTimeout) && idleTimeout > 0) ret.IdleTimeout = TimeSpan.FromMilliseconds(idleTimeout); break;
case "connecttimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var connectTimeout) && connectTimeout > 0) ret.ConnectTimeout = TimeSpan.FromMilliseconds(connectTimeout); break;
case "receivetimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var receiveTimeout) && receiveTimeout > 0) ret.ReceiveTimeout = TimeSpan.FromMilliseconds(receiveTimeout); break;
case "sendtimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var sendTimeout) && sendTimeout > 0) ret.SendTimeout = TimeSpan.FromMilliseconds(sendTimeout); break;
case "poolsize":
case "maxpoolsize": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var maxPoolSize) && maxPoolSize > 0) ret.MaxPoolSize = maxPoolSize; break;
case "minpoolsize": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var minPoolSize) && minPoolSize > 0) ret.MinPoolSize = minPoolSize; break;
case "retry": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var retry) && retry > 0) ret.Retry = retry; break;
}
}
return ret;
}
19
Source : RazorModel.cs
with MIT License
from 2881099
with MIT License
from 2881099
public string GetCsName(string name)
{
name = Regex.Replace(name.TrimStart('@', '.'), @"[^\w]", "_");
name = char.IsLetter(name, 0) ? name : string.Concat("_", name);
if (task.OptionsEnreplacedy01) name = UFString(name);
if (task.OptionsEnreplacedy02) name = UFString(name.ToLower());
if (task.OptionsEnreplacedy03) name = name.ToLower();
if (task.OptionsEnreplacedy04) name = string.Join("", name.Split('_').Select(a => UFString(a)));
return name;
}
19
Source : RazorModel.cs
with MIT License
from 2881099
with MIT License
from 2881099
public string UFString(string text)
{
text = Regex.Replace(text, @"[^\w]", "_");
if (text.Length <= 1) return text.ToUpper();
else return text.Substring(0, 1).ToUpper() + text.Substring(1, text.Length - 1);
}
19
Source : RazorModel.cs
with MIT License
from 2881099
with MIT License
from 2881099
public string GetCsName(string name) {
name = Regex.Replace(name.TrimStart('@', '.'), @"[^\w]", "_");
name = char.IsLetter(name, 0) ? name : string.Concat("_", name);
if (task.OptionsEnreplacedy01) name = UFString(name);
if (task.OptionsEnreplacedy02) name = UFString(name.ToLower());
if (task.OptionsEnreplacedy03) name = name.ToLower();
if (task.OptionsEnreplacedy04) name = string.Join("", name.Split('_').Select(a => UFString(a)));
return name;
}
19
Source : RazorModel.cs
with MIT License
from 2881099
with MIT License
from 2881099
public string UFString(string text) {
text = Regex.Replace(text, @"[^\w]", "_");
if (text.Length <= 1) return text.ToUpper();
else return text.Substring(0, 1).ToUpper() + text.Substring(1, text.Length - 1);
}
19
Source : RazorModel.cs
with MIT License
from 2881099
with MIT License
from 2881099
public string LFString(string text) {
text = Regex.Replace(text, @"[^\w]", "_");
if (text.Length <= 1) return text.ToLower();
else return text.Substring(0, 1).ToLower() + text.Substring(1, text.Length - 1);
}
19
Source : RazorModel.cs
with MIT License
from 2881099
with MIT License
from 2881099
public string LFString(string text)
{
text = Regex.Replace(text, @"[^\w]", "_");
if (text.Length <= 1) return text.ToLower();
else return text.Substring(0, 1).ToLower() + text.Substring(1, text.Length - 1);
}
19
Source : StringMethods.cs
with MIT License
from 8T4
with MIT License
from 8T4
internal static string GenerateSlug(this string phrase)
{
var str = phrase.RemoveAccent().ToLower(CultureInfo.InvariantCulture);
str = Regex.Replace(str, @"[^a-z0-9\s-]", "");
str = Regex.Replace(str, @"\s+", " ").Trim();
str = Regex.Replace(str, @"\s", "-"); // hyphens
return str;
}
19
Source : MangaDexDownload.cs
with GNU General Public License v3.0
from 9vult
with GNU General Public License v3.0
from 9vult
private string ConvertToNumericFileName(string input)
{
string[] parts = input.Split('.'); // x34.png -> {x34 , png}
string name = Regex.Replace(parts[0], "[^0-9.]", "");
return name + "." + input[1]; // -> 34.png
}
19
Source : NhentaiHelper.cs
with GNU General Public License v3.0
from 9vult
with GNU General Public License v3.0
from 9vult
public static int GetPageCount(string hUrl)
{
HtmlDoreplacedent doreplacedent;
if (hUrl.EndsWith("/"))
doreplacedent = new HtmlWeb().Load(hUrl.Substring(0, hUrl.Length - 2));
else
doreplacedent = new HtmlWeb().Load(hUrl.Substring(0, hUrl.Length - 1));
int startIndex = doreplacedent.DoreplacedentNode.InnerHtml.IndexOf("\"num_pages\":") + 12;
int length = 7;
string crop = doreplacedent.DoreplacedentNode.InnerHtml.Substring(startIndex, length);
string pages = Regex.Replace(crop, "[^0-9.]", "");
return int.Parse(pages);
}
19
Source : MicroVM.Assembler.cs
with MIT License
from a-downing
with MIT License
from a-downing
bool Preprocess(string code) {
var lines = code.Split(new[] {"\r\n", "\r", "\n"}, StringSplitOptions.None);
for(int i = 0; i < lines.Length; i++) {
lines[i] = code = Regex.Replace(lines[i].Trim() ,@"\s+"," ");
if(lines[i].Length > 0) {
if(lines[i][0] == '#') {
continue;
}
var args = lines[i].Split(' ');
if(args.Length > 0) {
statements.Add(new Statement {
lineNum = i,
line = args,
tokens = new Token[args.Length]
});
}
}
}
return true;
}
19
Source : TypeReferencePropertyDrawer.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private static void DrawTypeSelectionControl(Rect position, SerializedProperty property, GUIContent label, SystemTypeAttribute filter)
{
try
{
Color restoreColor = GUI.color;
bool restoreShowMixedValue = EditorGUI.showMixedValue;
bool typeResolved = string.IsNullOrEmpty(property.stringValue) || ResolveType(property.stringValue) != null;
EditorGUI.showMixedValue = property.hasMultipleDifferentValues;
GUI.color = enabledColor;
if (typeResolved)
{
property.stringValue = DrawTypeSelectionControl(position, label, property.stringValue, filter, true);
}
else
{
if (SelectRepairedTypeWindow.WindowOpen)
{
GUI.color = disabledColor;
DrawTypeSelectionControl(position, label, property.stringValue, filter, false);
}
else
{
Rect dropdownPosition = new Rect(position.x, position.y, position.width - 90, position.height);
Rect buttonPosition = new Rect(position.x + position.width - 75, position.y, 75, position.height);
Color defaultColor = GUI.color;
GUI.color = errorColor;
property.stringValue = DrawTypeSelectionControl(dropdownPosition, label, property.stringValue, filter, false);
GUI.color = defaultColor;
if (GUI.Button(buttonPosition, "Try Repair", EditorStyles.miniButton))
{
string typeNameWithoutreplacedembly = property.stringValue.Split(new string[] { "," }, StringSplitOptions.None)[0];
string typeNameWithoutNamespace = System.Text.RegularExpressions.Regex.Replace(typeNameWithoutreplacedembly, @"[.\w]+\.(\w+)", "$1");
Type[] repairedTypeOptions = FindTypesByName(typeNameWithoutNamespace, filter);
if (repairedTypeOptions.Length > 1)
{
SelectRepairedTypeWindow.Display(repairedTypeOptions, property);
}
else if (repairedTypeOptions.Length > 0)
{
property.stringValue = SystemType.GetReference(repairedTypeOptions[0]);
}
else
{
EditorUtility.DisplayDialog("No types found", "No types with the name '" + typeNameWithoutNamespace + "' were found.", "OK");
}
}
}
}
GUI.color = restoreColor;
EditorGUI.showMixedValue = restoreShowMixedValue;
}
finally
{
ExcludedTypeCollectionGetter = null;
}
}
19
Source : ConsultaSintegraDF.cs
with MIT License
from ACBrNet
with MIT License
from ACBrNet
private static ACBrEmpresa ProcessResponse(string retorno)
{
const string tableExpression = "<table.*?>(.*?)</table>";
const string trPattern = "<tr(.*?)</tr>";
const string tdPattern = "<td.*?>(.*?)</td>";
var result = new ACBrEmpresa();
try
{
var dadosRetorno = new List<string>();
var tableContents = GetContents(retorno, tableExpression);
foreach (var tableContent in tableContents)
{
var trContents = GetContents(tableContent, trPattern);
foreach (var trContent in trContents)
{
var tdContents = GetContents(trContent, tdPattern);
foreach (var item in tdContents)
{
dadosRetorno.AddText((Regex.Replace(item, "<.*?>", string.Empty).Trim()));
}
}
}
result.CNPJ = LerCampo(dadosRetorno, "CNPJ/CPF");
result.InscricaoEstadual = LerCampo(dadosRetorno, "CF/DF");
result.RazaoSocial = LerCampo(dadosRetorno, "RAZÃO SOCIAL");
result.Logradouro = LerCampo(dadosRetorno, "LOGRADOURO");
result.Numero = LerCampo(dadosRetorno, "Número:");
result.Complemento = LerCampo(dadosRetorno, "Complemento:");
result.Bairro = LerCampo(dadosRetorno, "BAIRRO");
result.Municipio = LerCampo(dadosRetorno, "MUNICÍPIO");
result.UF = (ConsultaUF)Enum.Parse(typeof(ConsultaUF), LerCampo(dadosRetorno, "UF").ToUpper());
result.CEP = LerCampo(dadosRetorno, "CEP").FormataCEP();
result.Telefone = LerCampo(dadosRetorno, "Telefone");
result.AtividadeEconomica = LerCampo(dadosRetorno, "ATIVIDADE PRINCIPAL");
result.DataAbertura = LerCampo(dadosRetorno, "DATA DESSA SITUAÇÃO CADASTRAL").ToData();
result.Situacao = LerCampo(dadosRetorno, "SITUAÇÃO CADASTRAL");
result.DataSituacao = LerCampo(dadosRetorno, "DATA DESSA SITUAÇÃO CADASTRAL").ToData();
result.RegimeApuracao = LerCampo(dadosRetorno, "REGIME DE APURAÇÃO");
result.DataEmitenteNFe = LerCampo(dadosRetorno, "Emitente de NFe desde:").ToData();
}
catch (Exception exception)
{
throw new ACBrException(exception, "Erro ao processar retorno.");
}
return result;
}
19
Source : WorldManager.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
private static string AppendLines(params string[] lines)
{
var result = "";
foreach (var line in lines)
if (!string.IsNullOrEmpty(line))
result += $"{line}\n";
return Regex.Replace(result, "\n$", "");
}
19
Source : SheetFilter.cs
with GNU Lesser General Public License v3.0
from acnicholas
with GNU Lesser General Public License v3.0
from acnicholas
private static string FirstDigitOfLastNumberInString(string s)
{
var onlyNumbers = Regex.Replace(s, "[^0-9]", @" ");
string[] numberParts = onlyNumbers.Split(new[] { @" " }, StringSplitOptions.RemoveEmptyEntries);
var n = numberParts.Where(v => v.Length > 1);
if (n.Count() > 0) {
return n.Last().Substring(0, 1);
}
return null;
}
19
Source : RenameManager.cs
with GNU Lesser General Public License v3.0
from acnicholas
with GNU Lesser General Public License v3.0
from acnicholas
public static string RegexReplace(string val, string search, string replace)
{
return Regex.Replace(val, search, replace);
}
19
Source : SheetFilter.cs
with GNU Lesser General Public License v3.0
from acnicholas
with GNU Lesser General Public License v3.0
from acnicholas
public Predicate<object> GetFilter()
{
string properyName = FilterPropertyName;
switch (FilterPropertyName)
{
case "Export Name":
var m = FirstDigitOfLastNumberInString(FilterValue);
if (m == null)
{
return null;
}
return item => m == FirstDigitOfLastNumberInString((item as ExportSheet).FullExportName);
case "Number":
var n = FirstDigitOfLastNumberInString(FilterValue);
if (n == null)
{
return null;
}
return item => n == FirstDigitOfLastNumberInString((item as ExportSheet).SheetNumber);
case "Name":
properyName = "SheetDescription";
var noNumbers = Regex.Replace(FilterValue, "[0-9-]", @" ");
string[] parts = noNumbers.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
return item => parts.Any(item.GetType().GetProperty(properyName).GetValue(item, null).ToString().Contains);
case "Revision":
properyName = "SheetRevision";
break;
case "Revision Description":
properyName = "SheetRevisionDescription";
break;
case "Revision Date":
properyName = "SheetRevisionDate";
break;
case "Scale":
properyName = "Scale";
break;
case "North Point":
properyName = "NorthPointVisibilityString";
break;
default:
return null;
}
return item => item.GetType().GetProperty(properyName).GetValue(item, null).ToString().Equals(FilterValue, StringComparison.InvariantCulture);
}
19
Source : Utility.cs
with MIT License
from ADefWebserver
with MIT License
from ADefWebserver
public static string StripTags(string HTML, bool RetainSpace)
{
//Set up Replacement String
string RepString;
if (RetainSpace)
{
RepString = " ";
}
else
{
RepString = "";
}
//Replace Tags by replacement String and return mofified string
return System.Text.RegularExpressions.Regex.Replace(HTML, "<[^>]*>", RepString);
}
19
Source : POGeneratorTest.cs
with MIT License
from adams85
with MIT License
from adams85
[Fact]
public void GenerateSkipComments()
{
var generator = new POGenerator(new POGeneratorSettings { SkipComments = true });
string result;
using (var ms = new MemoryStream())
{
generator.Generate(ms, s_catalog);
result = Encoding.UTF8.GetString(ms.ToArray());
}
// Encoding.GetString keeps BOM
var expected = new StreamReader(new MemoryStream(Resources.SamplePO)).ReadToEnd();
expected = Regex.Replace(expected, @"(^|\r\n)(#[^\r]*\r\n)+", "$1");
replacedert.Equal(expected, result);
}
19
Source : Utility.cs
with MIT License
from ADefWebserver
with MIT License
from ADefWebserver
public static string FormatText(string HTML, bool RetainSpace)
{
//Match all variants of <br> tag (<br>, <BR>, <br/>, including embedded space
string brMatch = "\\s*<\\s*[bB][rR]\\s*/\\s*>\\s*";
//Replace Tags by replacement String and return mofified string
return System.Text.RegularExpressions.Regex.Replace(HTML, brMatch, Environment.NewLine);
}
19
Source : Settings.cs
with MIT License
from adlez27
with MIT License
from adlez27
public void LoadRecList()
{
if (init && File.Exists(RecListFile))
{
RecList.Clear();
HashSet<string> uniqueStrings = new HashSet<string>();
Encoding e;
if (ReadUnicode)
{
e = Encoding.UTF8;
}
else
{
e = CodePagesEncodingProvider.Instance.GetEncoding(932);
}
var ext = Path.GetExtension(RecListFile);
if (ext == ".txt")
{
if (Path.GetFileName(RecListFile) == "OREMO-comment.txt")
{
var rawText = File.ReadAllLines(RecListFile, e);
foreach(string rawLine in rawText)
{
var line = rawLine.Split("\t");
if (!uniqueStrings.Contains(line[0]))
{
RecList.Add(new RecLisreplacedem(this, line[0], line[1]));
uniqueStrings.Add(line[0]);
}
}
}
else
{
string[] textArr;
if (SplitWhitespace)
{
var rawText = File.ReadAllText(RecListFile, e);
rawText = Regex.Replace(rawText, @"\s{2,}", " ");
textArr = Regex.Split(rawText, @"\s");
}
else
{
textArr = File.ReadAllLines(RecListFile, e);
}
foreach (string line in textArr)
{
if (!uniqueStrings.Contains(line))
{
RecList.Add(new RecLisreplacedem(this, line));
uniqueStrings.Add(line);
}
}
}
}
else if (ext == ".arl")
{
var rawText = File.ReadAllText(RecListFile, e);
var deserializer = new Deserializer();
var tempDict = deserializer.Deserialize<Dictionary<string, string>>(rawText);
foreach (var item in tempDict)
{
RecList.Add(new RecLisreplacedem(this, item.Key, item.Value));
}
}
else if (ext == ".csv")
{
using (TextFieldParser parser = new TextFieldParser(RecListFile))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
string[] line = parser.ReadFields();
var text = line[0].Substring(0,line[0].Length - 4);
if (!uniqueStrings.Contains(text))
{
RecList.Add(new RecLisreplacedem(this, text, line[1]));
uniqueStrings.Add(text);
}
}
}
CopyIndex();
}
else if (ext == ".reclist")
{
var rawText = File.ReadAllText(RecListFile, e);
var deserializer = new Deserializer();
var reclist = deserializer.Deserialize<WCTReclist>(rawText);
foreach(var line in reclist.Files)
{
if (!uniqueStrings.Contains(line.Filename))
{
RecList.Add(new RecLisreplacedem(this, line.Filename, line.Description));
uniqueStrings.Add(line.Filename);
}
}
}
else if (ext == ".ust"){
var rawText = File.ReadAllLines(RecListFile, e);
foreach (var line in rawText)
{
if (line.StartsWith("Lyric="))
{
var lyric = line.Substring(6);
if (lyric != "R" && lyric != "r" && lyric != "" && !uniqueStrings.Contains(lyric))
{
RecList.Add(new RecLisreplacedem(this, lyric));
uniqueStrings.Add(lyric);
}
}
}
}
}
}
19
Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static string CreateInvitationCode(this OrganizationServiceContext context)
{
//If any changes to this implementation,should also
//go to "..\Portals\Framework\Adxstudio.Xrm.Workflow.Invitation\Adxstudio.Xrm.Workflow.Invitation\UpdateInvitationCode.cs"
byte[] code = new byte[128];
using (RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider())
{
rngCsp.GetBytes(code);
}
string invitationCode = Convert.ToBase64String(code);
return Regex.Replace(invitationCode, @"[+/=]", "-");
}
19
Source : VCalendar.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static string EncodeValue(string value)
{
if (value == null) throw new ArgumentNullException("value");
// Replace illegal characters with escaped versions.
value = Regex.Replace(value, @"([\\;,])", @"\$1");
// Replace line breaks with escaped version.
value = Regex.Replace(value, "(\n|\r|\r\n)", "\\n");
return value;
}
19
Source : IdeaForumDataAdapter.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static string GetDefaultIdeaPartialUrl(string replacedle)
{
if (string.IsNullOrWhiteSpace(replacedle))
{
throw new ArgumentException("Value can't be null or whitespace.", "replacedle");
}
string replacedleSlug;
try
{
// Encoding the replacedle as Cyrillic, and then back to ASCII, converts accented characters to their
// unaccented version. We'll try/catch this, since it depends on the underlying platform whether
// the Cyrillic code page is available.
replacedleSlug = Encoding.ASCII.GetString(Encoding.GetEncoding("Cyrillic").GetBytes(replacedle)).ToLowerInvariant();
}
catch
{
replacedleSlug = replacedle.ToLowerInvariant();
}
// Strip all disallowed characters.
replacedleSlug = Regex.Replace(replacedleSlug, @"[^a-z0-9\s-]", string.Empty);
// Convert all runs of multiple spaces to a single space.
replacedleSlug = Regex.Replace(replacedleSlug, @"\s+", " ").Trim();
// Cap the length of the replacedle slug.
replacedleSlug = replacedleSlug.Substring(0, replacedleSlug.Length <= 50 ? replacedleSlug.Length : 50).Trim();
// Replace all spaces with hyphens.
replacedleSlug = Regex.Replace(replacedleSlug, @"\s", "-").Trim('-');
return replacedleSlug;
}
19
Source : IssueForumDataAdapter.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static string GetDefaultIssuePartialUrl(string replacedle)
{
if (string.IsNullOrWhiteSpace(replacedle))
{
throw new ArgumentException("Value can't be null or whitespace.", "replacedle");
}
string replacedleSlug;
try
{
// Encoding the replacedle as Cyrillic, and then back to ASCII, converts accented characters to their
// unaccented version. We'll try/catch this, since it depends on the underlying platform whether
// the Cyrillic code page is available.
replacedleSlug = Encoding.ASCII.GetString(Encoding.GetEncoding("Cyrillic").GetBytes(replacedle)).ToLowerInvariant();
}
catch
{
replacedleSlug = replacedle.ToLowerInvariant();
}
// Strip all disallowed characters.
replacedleSlug = Regex.Replace(replacedleSlug, @"[^a-z0-9\s-]", string.Empty);
// Convert all runs of multiple spaces to a single space.
replacedleSlug = Regex.Replace(replacedleSlug, @"\s+", " ").Trim();
// Cap the length of the replacedle slug.
replacedleSlug = replacedleSlug.Substring(0, replacedleSlug.Length <= 50 ? replacedleSlug.Length : 50).Trim();
// Replace all spaces with hyphens.
replacedleSlug = Regex.Replace(replacedleSlug, @"\s", "-").Trim('-');
return replacedleSlug;
}
19
Source : Extensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static Folder AddOrGetExistingFolder(this ClientContext context, string listUrl, string folderUrl)
{
// Ensure safe folder URL - it cannot begin or end with dot, contain consecutive dots, or any of ~ " # % & * : < > ? \ { | }
var spSafeFolderUrl = Regex.Replace(folderUrl, @"(\.{2,})|([\~\""\#\%\&\*\:\<\>\?\\\{\|\}])|(^\.)|(\.$)", string.Empty);
var trimmedFolderUrl = spSafeFolderUrl.Trim('/');
Folder folder;
if (TryGetFolder(context, listUrl + "/" + trimmedFolderUrl, out folder))
{
return folder;
}
var list = context.GetListByUrl(listUrl);
return context.CreateFolderPath(list.RootFolder, trimmedFolderUrl);
}
19
Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static T AddOrGetExistingDoreplacedentLocation<T>(this OrganizationServiceContext context, Enreplacedy sharePointSite, Enreplacedy enreplacedy, string relativeUrl)
where T : Enreplacedy, new()
{
if (sharePointSite == null) throw new ArgumentNullException("sharePointSite");
if (enreplacedy == null) throw new ArgumentNullException("enreplacedy");
sharePointSite.replacedertEnreplacedyName(_sharepointsite);
// Replace the following invalid characters ~ " # % & * : < > ? / \ { | } . with hyphens (Same as what CRM does).
var spSafeRelativeUrl = Regex.Replace(relativeUrl, @"[\~\""\#\%\&\*\:\<\>\?\/\\\{\|\}\.]", "-");
var siteName = sharePointSite.GetAttributeValue<string>("name");
var locationName = "Doreplacedents on {0}".FormatWith(siteName);
var folderStructureEnreplacedy = sharePointSite.GetAttributeValue<string>("folderstructureenreplacedy");
if (folderStructureEnreplacedy == "contact" && enreplacedy.LogicalName != "contact")
{
// <site>/contact/<contact name>/<enreplacedy name>/<record name>
var related = context.GetRelatedForEnreplacedyCentricFolderStructure(enreplacedy, folderStructureEnreplacedy);
if (related != null)
{
return context.AddOrGetEnreplacedyCentricDoreplacedentLocation<T>(locationName, spSafeRelativeUrl, enreplacedy, related, sharePointSite);
}
}
if (folderStructureEnreplacedy == "account" && enreplacedy.LogicalName != "account")
{
// <site>/account/<account name>/<enreplacedy name>/<record name>
var related = context.GetRelatedForEnreplacedyCentricFolderStructure(enreplacedy, folderStructureEnreplacedy);
if (related != null)
{
return context.AddOrGetEnreplacedyCentricDoreplacedentLocation<T>(locationName, spSafeRelativeUrl, enreplacedy, related, sharePointSite);
}
}
// <site>/<enreplacedy name>/<record name>
var enreplacedySetLocation = sharePointSite
.GetRelatedEnreplacedies(context, _sharepointdoclocationsiterelationship)
.FirstOrDefault(loc => loc.GetAttributeValue<string>("relativeurl") == enreplacedy.LogicalName);
if (enreplacedySetLocation == null)
{
enreplacedySetLocation = context.CreateDoreplacedentLocation<T>(locationName, enreplacedy.LogicalName, sharePointSite, _sharepointdoclocationsiterelationship);
return context.CreateDoreplacedentLocation<T>(locationName, spSafeRelativeUrl, enreplacedySetLocation, _sharepointdoclocationparentrelationship, enreplacedy.ToEnreplacedyReference());
}
return context.CreateOrUpdateRecordDoreplacedentLocation<T>(locationName, spSafeRelativeUrl, enreplacedySetLocation, enreplacedy);
}
19
Source : Mask.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
protected virtual string ReplaceAttributesWithNamedCaptures(string escapedMask)
{
return Regex.Replace(escapedMask, @"\\\[([^\[\]]+)]", @"(?<$1>[^\/]+)");
}
19
Source : CmsEntityServiceProvider.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static string GetDefaultBlogPostPartialUrl(DateTime date, string replacedle)
{
if (string.IsNullOrWhiteSpace(replacedle))
{
throw new ArgumentException("Value can't be null or whitespace.", "replacedle");
}
string replacedleSlug;
try
{
// Encoding the replacedle as Cyrillic, and then back to ASCII, converts accented characters to their
// unaccented version. We'll try/catch this, since it depends on the underlying platform whether
// the Cyrillic code page is available.
replacedleSlug = Encoding.ASCII.GetString(Encoding.GetEncoding("Cyrillic").GetBytes(replacedle)).ToLowerInvariant();
}
catch
{
replacedleSlug = replacedle.ToLowerInvariant();
}
// Strip all disallowed characters.
replacedleSlug = Regex.Replace(replacedleSlug, @"[^a-z0-9\s-]", string.Empty);
// Convert all runs of multiple spaces to a single space.
replacedleSlug = Regex.Replace(replacedleSlug, @"\s+", " ").Trim();
// Cap the length of the replacedle slug.
replacedleSlug = replacedleSlug.Substring(0, replacedleSlug.Length <= 50 ? replacedleSlug.Length : 50).Trim();
// Replace all spaces with hyphens.
replacedleSlug = Regex.Replace(replacedleSlug, @"\s", "-").Trim('-');
return "{0:yyyy}-{0:MM}-{0:dd}-{1}".FormatWith(date, replacedleSlug);
}
19
Source : EmbeddedResourceFileSystem.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private bool TryGetFullPath(string templatePath, out string fullPath)
{
fullPath = null;
if (templatePath == null || !Regex.IsMatch(templatePath, @"^[a-zA-Z0-9_][a-zA-Z0-9_\/]*$"))
{
return false;
}
try
{
var basePath = templatePath.Contains("/")
? Path.Combine(Root, Path.GetDirectoryName(templatePath))
: Root;
var fileName = "{0}.liquid".FormatWith(Path.GetFileName(templatePath));
fullPath = Regex.Replace(Path.Combine(basePath, fileName), @"\\|/", ".");
return true;
}
catch (System.ArgumentException)
{
return false;
}
}
19
Source : EntityRouteHandler.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
protected override bool TryCreateHandler(OrganizationServiceContext context, string logicalName, Guid id, out IHttpHandler handler)
{
if (string.Equals(logicalName, "annotation", StringComparison.InvariantCulture))
{
var annotation = context.CreateQuery(logicalName).FirstOrDefault(e => e.GetAttributeValue<Guid>("annotationid") == id);
if (annotation != null)
{
var regarding = annotation.GetAttributeValue<EnreplacedyReference>("objectid");
if (regarding != null && string.Equals(regarding.LogicalName, "knowledgearticle", StringComparison.InvariantCulture))
{
// Access to a note replacedociated to a knowledge article requires the CMS Security to grant read of the annotation and the related knowledge article.
// Additionally, if CAL or Product filtering is enabled and the CAL and/or Product providers reject access to the knowledge article
// then access to the note is denied. If CAL and Product filtering are NOT enabled or CAL and/or Product Provider replacedertion preplaceded,
// we must continue to check the Enreplacedy Permissions. If the Enreplacedy Permission Provider grants read to the knowledge article then the
// note can be accessed, otherwise access will be denied.
// replacedert CMS Security on the annotation and knowledge article.
if (TryreplacedertByCrmEnreplacedySecurityProvider(context, annotation.ToEnreplacedyReference()) && TryreplacedertByCrmEnreplacedySecurityProvider(context, regarding))
{
// replacedert CAL and/or Product Filtering if enabled.
var contentAccessLevelProvider = new ContentAccessLevelProvider();
var productAccessProvider = new ProductAccessProvider();
if (contentAccessLevelProvider.IsEnabled() || productAccessProvider.IsEnabled())
{
if (!replacedertKnowledgeArticleCalAndProductFiltering(annotation, context, contentAccessLevelProvider, productAccessProvider))
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, $"Access to {EnreplacedyNamePrivacy.GetEnreplacedyName(annotation.LogicalName)} was denied. Id:{id} RegardingId={regarding.Id} RegardingLogicalName={EnreplacedyNamePrivacy.GetEnreplacedyName(regarding.LogicalName)}");
handler = null;
return false;
}
}
// replacedert Enreplacedy Permissions on the knowledge article.
if (TryreplacedertByCrmEnreplacedyPermissionProvider(context, regarding))
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, $"Access to {EnreplacedyNamePrivacy.GetEnreplacedyName(annotation.LogicalName)} was granted. Id:{id} RegardingId={regarding.Id} RegardingLogicalName={EnreplacedyNamePrivacy.GetEnreplacedyName(regarding.LogicalName)}");
handler = CreateAnnotationHandler(annotation);
return true;
}
}
ADXTrace.Instance.TraceInfo(TraceCategory.Application, $"Access to {EnreplacedyNamePrivacy.GetEnreplacedyName(annotation.LogicalName)} was denied. Id:{id} RegardingId={regarding.Id} RegardingLogicalName={EnreplacedyNamePrivacy.GetEnreplacedyName(regarding.LogicalName)}");
handler = null;
return false;
}
// replacedert CMS security on the regarding enreplacedy or replacedert enreplacedy permission on the annotation and the regarding enreplacedy.
if (TryreplacedertByCrmEnreplacedySecurityProvider(context, regarding) || TryreplacedertByCrmEnreplacedyPermissionProvider(context, annotation, regarding))
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, $"Access to {EnreplacedyNamePrivacy.GetEnreplacedyName(annotation.LogicalName)} was granted. Id={id} RegardingId={regarding?.Id} RegardingLogicalName={EnreplacedyNamePrivacy.GetEnreplacedyName(regarding?.LogicalName)}");
handler = CreateAnnotationHandler(annotation);
return true;
}
}
}
if (string.Equals(logicalName, "salesliteratureitem", StringComparison.InvariantCulture))
{
var salesliteratureitem = context.CreateQuery(logicalName).FirstOrDefault(e => e.GetAttributeValue<Guid>("salesliteratureitemid") == id);
if (salesliteratureitem != null)
{
//Currently salesliteratureitem.iscustomerviewable is not exposed to CRM UI, therefore get the parent and check visibility.
//var isCustomerViewable = salesliteratureitem.GetAttributeValue<bool?>("iscustomerviewable").GetValueOrDefault();
var salesliterature =
context.CreateQuery("salesliterature")
.FirstOrDefault(
e =>
e.GetAttributeValue<Guid>("salesliteratureid") ==
salesliteratureitem.GetAttributeValue<EnreplacedyReference>("salesliteratureid").Id);
if (salesliterature != null)
{
var isCustomerViewable = salesliterature.GetAttributeValue<bool?>("iscustomerviewable").GetValueOrDefault();
if (isCustomerViewable)
{
handler = CreateSalesAttachmentHandler(salesliteratureitem);
return true;
}
}
}
}
if (string.Equals(logicalName, "sharepointdoreplacedentlocation", StringComparison.InvariantCulture))
{
var location = context.CreateQuery(logicalName).FirstOrDefault(e => e.GetAttributeValue<Guid>("sharepointdoreplacedentlocationid") == id);
if (location != null)
{
var httpContext = HttpContext.Current;
var regardingId = location.GetAttributeValue<EnreplacedyReference>("regardingobjectid");
// replacedert CMS access to the regarding enreplacedy or replacedert enreplacedy permission on the enreplacedy
if (TryreplacedertByCrmEnreplacedySecurityProvider(context, regardingId) || TryreplacedertByCrmEnreplacedyPermissionProvider(context, location, location.GetAttributeValue<EnreplacedyReference>("regardingobjectid")))
{
var locationUrl = context.GetDoreplacedentLocationUrl(location);
var fileName = httpContext.Request["file"];
// Ensure safe file URL - it cannot begin or end with dot, contain consecutive dots, or any of ~ " # % & * : < > ? \ { | }
fileName = Regex.Replace(fileName, @"(\.{2,})|([\~\""\#\%\&\*\:\<\>\?\/\\\{\|\}])|(^\.)|(\.$)", string.Empty); // also removes solidus
var folderPath = httpContext.Request["folderPath"];
Uri sharePointFileUrl;
if (!string.IsNullOrWhiteSpace(folderPath))
{
// Ensure safe folder URL - it cannot begin or end with dot, contain consecutive dots, or any of ~ " # % & * : < > ? \ { | }
folderPath = Regex.Replace(folderPath, @"(\.{2,})|([\~\""\#\%\&\*\:\<\>\?\\\{\|\}])|(^\.)|(\.$)", string.Empty).Trim('/');
sharePointFileUrl = new Uri("{0}/{1}/{2}".FormatWith(locationUrl.OriginalString, folderPath, fileName));
}
else
{
sharePointFileUrl = new Uri("{0}/{1}".FormatWith(locationUrl.OriginalString, fileName));
}
handler = CreateSharePointFileHandler(sharePointFileUrl, fileName);
return true;
}
if (!httpContext.Request.IsAuthenticated)
{
httpContext.Response.ForbiddenAndEndResponse();
}
else
{
// Sending Forbidden gets caught by the Application_EndRequest and throws an error trying to redirect to the Access Denied page.
// Send a 404 instead with plain text indicating Access Denied.
httpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
httpContext.Response.ContentType = "text/plain";
httpContext.Response.Write("Access Denied");
httpContext.Response.End();
}
}
}
if (string.Equals(logicalName, "activitymimeattachment", StringComparison.InvariantCulture))
{
var attachment = context.CreateQuery(logicalName).FirstOrDefault(e => e.GetAttributeValue<Guid>("attachmentid") == id);
if (attachment != null)
{
// retrieve the parent object for the annoation
var objectId = attachment.GetAttributeValue<EnreplacedyReference>("objectid");
// replacedert CMS access to the regarding enreplacedy or replacedert enreplacedy permission on the enreplacedy
if (TryreplacedertByCrmEnreplacedySecurityProvider(context, objectId) || TryreplacedertByCrmEnreplacedyPermissionProvider(context, attachment, attachment.GetAttributeValue<EnreplacedyReference>("objectid")))
{
handler = CreateActivityMimeAttachmentHandler(attachment);
return true;
}
}
}
handler = null;
return false;
}
19
Source : BlogSiteMapProvider.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
protected virtual bool TryGetAuthorArchiveNode(OrganizationServiceContext serviceContext, EnreplacedyReference website, string path, out CrmSiteMapNode node)
{
node = null;
var pathMatch = AuthorArchivePathRegex.Match(path);
if (!pathMatch.Success)
{
return false;
}
var archiveRootPath = Regex.Replace(path, @"author/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/$", string.Empty);
var blogAggregationArchivePageQuery = from page in serviceContext.CreateQuery("adx_webpage")
join siteMarker in serviceContext.CreateQuery("adx_sitemarker") on page.GetAttributeValue<Guid>("adx_webpageid") equals siteMarker.GetAttributeValue<EnreplacedyReference>("adx_pageid").Id
where siteMarker.GetAttributeValue<EnreplacedyReference>("adx_pageid") != null && siteMarker.GetAttributeValue<string>("adx_name") == AggregationArchiveSiteMarkerName
where page.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == website
select page;
var blogAggregationArchivePageMatch = blogAggregationArchivePageQuery.ToArray().FirstOrDefault(e => EnreplacedyHasPath(serviceContext, e, archiveRootPath));
Guid authorId;
if (blogAggregationArchivePageMatch != null && Guid.TryParse(pathMatch.Groups["author"].Value, out authorId))
{
node = GetBlogAggregationAuthorArchiveNode(serviceContext, blogAggregationArchivePageMatch, authorId);
return true;
}
var blogsByAuthorArchivePathMatch = from blog in serviceContext.CreateQuery("adx_blog")
where blog.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == website
where blog.GetAttributeValue<string>("adx_partialurl") == pathMatch.Groups["blog"].Value
select blog;
var contextLanguageInfo = HttpContext.Current.GetContextLanguageInfo();
if (contextLanguageInfo.IsCrmMultiLanguageEnabled)
{
blogsByAuthorArchivePathMatch = blogsByAuthorArchivePathMatch.Where(
blog => blog.GetAttributeValue<EnreplacedyReference>("adx_websitelanguageid") == null ||
blog.GetAttributeValue<EnreplacedyReference>("adx_websitelanguageid").Id == contextLanguageInfo.ContextLanguage.EnreplacedyReference.Id);
}
var blogByAuthorArchivePathMatch = blogsByAuthorArchivePathMatch.ToArray().FirstOrDefault(e => EnreplacedyHasPath(serviceContext, e, archiveRootPath));
if (blogByAuthorArchivePathMatch != null && Guid.TryParse(pathMatch.Groups["author"].Value, out authorId))
{
node = GetBlogAuthorArchiveNode(serviceContext, blogByAuthorArchivePathMatch, authorId);
return true;
}
return false;
}
19
Source : BlogSiteMapProvider.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
protected virtual bool TryGetTagArchiveNode(OrganizationServiceContext serviceContext, EnreplacedyReference website, string path, out CrmSiteMapNode node)
{
node = null;
var pathMatch = TagArchivePathRegex.Match(path);
if (!pathMatch.Success)
{
return false;
}
var archiveRootPath = Regex.Replace(path, @"tags/[^/]+$", string.Empty);
var tagSlug = pathMatch.Groups["tag"].Value;
var blogAggregationArchivePageQuery = from page in serviceContext.CreateQuery("adx_webpage")
join siteMarker in serviceContext.CreateQuery("adx_sitemarker") on page.GetAttributeValue<Guid>("adx_webpageid") equals siteMarker.GetAttributeValue<EnreplacedyReference>("adx_pageid").Id
where siteMarker.GetAttributeValue<EnreplacedyReference>("adx_pageid") != null && siteMarker.GetAttributeValue<string>("adx_name") == AggregationArchiveSiteMarkerName
where page.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == website
select page;
var blogAggregationArchivePageMatch = blogAggregationArchivePageQuery.ToArray().FirstOrDefault(e => EnreplacedyHasPath(serviceContext, e, archiveRootPath));
if (blogAggregationArchivePageMatch != null)
{
node = GetBlogAggregationTagArchiveNode(serviceContext, blogAggregationArchivePageMatch, tagSlug);
return true;
}
var blogsByTagArchivePathMatch = from blog in serviceContext.CreateQuery("adx_blog")
where blog.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == website
where blog.GetAttributeValue<string>("adx_partialurl") == pathMatch.Groups["blog"].Value
select blog;
var contextLanguageInfo = HttpContext.Current.GetContextLanguageInfo();
if (contextLanguageInfo.IsCrmMultiLanguageEnabled)
{
blogsByTagArchivePathMatch = blogsByTagArchivePathMatch.Where(
blog => blog.GetAttributeValue<EnreplacedyReference>("adx_websitelanguageid") == null ||
blog.GetAttributeValue<EnreplacedyReference>("adx_websitelanguageid").Id == contextLanguageInfo.ContextLanguage.EnreplacedyReference.Id);
}
var blogByTagArchivePath = blogsByTagArchivePathMatch.ToArray().FirstOrDefault(e => EnreplacedyHasPath(serviceContext, e, archiveRootPath));
if (blogByTagArchivePath != null)
{
node = GetBlogTagArchiveNode(serviceContext, blogByTagArchivePath, tagSlug);
return true;
}
return false;
}
19
Source : BlogSiteMapProvider.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
protected virtual bool TryGetMonthArchiveNode(OrganizationServiceContext serviceContext, EnreplacedyReference website, string path, out CrmSiteMapNode node)
{
node = null;
var pathMatch = MonthArchivePathRegex.Match(path);
if (!pathMatch.Success)
{
return false;
}
DateTime date;
try
{
date = new DateTime(
int.Parse(pathMatch.Groups["year"].Value),
int.Parse(pathMatch.Groups["month"].Value),
1, 0, 0, 0,
DateTimeKind.Utc);
}
catch
{
return false;
}
var archiveRootPath = Regex.Replace(path, @"\d{4}/\d{2}/$", string.Empty);
var blogAggregationArchivePageQuery = from page in serviceContext.CreateQuery("adx_webpage")
join siteMarker in serviceContext.CreateQuery("adx_sitemarker") on page.GetAttributeValue<Guid>("adx_webpageid") equals siteMarker.GetAttributeValue<EnreplacedyReference>("adx_pageid").Id
where siteMarker.GetAttributeValue<EnreplacedyReference>("adx_pageid") != null && siteMarker.GetAttributeValue<string>("adx_name") == AggregationArchiveSiteMarkerName
where page.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == website
select page;
var blogAggregationArchivePageMatch = blogAggregationArchivePageQuery.ToArray().FirstOrDefault(e => EnreplacedyHasPath(serviceContext, e, archiveRootPath));
if (blogAggregationArchivePageMatch != null)
{
node = GetBlogAggregationMonthArchiveNode(serviceContext, blogAggregationArchivePageMatch, date);
return true;
}
var blogsByMonthArchivePathMatch = from blog in serviceContext.CreateQuery("adx_blog")
where blog.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == website
where blog.GetAttributeValue<string>("adx_partialurl") == pathMatch.Groups["blog"].Value
select blog;
var contextLanguageInfo = HttpContext.Current.GetContextLanguageInfo();
if (contextLanguageInfo.IsCrmMultiLanguageEnabled)
{
blogsByMonthArchivePathMatch = blogsByMonthArchivePathMatch.Where(
blog => blog.GetAttributeValue<EnreplacedyReference>("adx_websitelanguageid") == null ||
blog.GetAttributeValue<EnreplacedyReference>("adx_websitelanguageid").Id == contextLanguageInfo.ContextLanguage.EnreplacedyReference.Id);
}
var blogByMonthArchivePath = blogsByMonthArchivePathMatch.ToArray().FirstOrDefault(e => EnreplacedyHasPath(serviceContext, e, archiveRootPath));
if (blogByMonthArchivePath != null)
{
node = GetBlogMonthArchiveNode(serviceContext, blogByMonthArchivePath, date);
return true;
}
return false;
}
19
Source : SurveyReporter.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public void Write(HtmlTextWriter writer)
{
writer.RenderBeginTag(HtmlTextWriterTag.Table);
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
writer.RenderBeginTag(HtmlTextWriterTag.Th);
writer.Write("Submission name");
writer.RenderEndTag();
writer.RenderBeginTag(HtmlTextWriterTag.Th);
writer.Write("Visitor ID");
writer.RenderEndTag();
writer.RenderBeginTag(HtmlTextWriterTag.Th);
writer.Write("Contact Name");
writer.RenderEndTag();
foreach (var question in _surveyChoiceQuestions)
{
writer.RenderBeginTag(HtmlTextWriterTag.Th);
writer.Write(question.GetAttributeValue<string>("adx_name"));
writer.RenderEndTag();
writer.RenderBeginTag(HtmlTextWriterTag.Th);
writer.Write(question.GetAttributeValue<string>("adx_question"));
writer.RenderEndTag();
}
foreach (var question in _surveyTextQuestions)
{
writer.RenderBeginTag(HtmlTextWriterTag.Th);
writer.Write(question.GetAttributeValue<string>("adx_name") + " : " + question.GetAttributeValue<string>("adx_question"));
writer.RenderEndTag();
}
writer.RenderEndTag();
if (_surveySubmissions == null)
{
writer.RenderEndTag();
return;
}
for (int i = 0; i < _surveySubmissions.Count; i++)
{
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
writer.RenderBeginTag(HtmlTextWriterTag.Td);
writer.Write(_surveySubmissions[i].GetAttributeValue<string>("adx_name"));
writer.RenderEndTag();
var contact = _surveyContacts[i];
if (contact != null)
{
writer.RenderBeginTag(HtmlTextWriterTag.Td);
writer.Write(@" ");
writer.RenderEndTag();
writer.RenderBeginTag(HtmlTextWriterTag.Td);
writer.Write(contact.GetAttributeValue<string>("fullname"));
writer.RenderEndTag();
}
else
{
writer.RenderBeginTag(HtmlTextWriterTag.Td);
writer.Write(_surveySubmissions[i].GetAttributeValue<string>("adx_visitorid"));
writer.RenderEndTag();
writer.RenderBeginTag(HtmlTextWriterTag.Td);
writer.Write(@" ");
writer.RenderEndTag();
}
var thisSubmissionTextAnswers = _submissionTextAnswers[i];
var thisSubmissionChoiceAnswers = _submissionChoiceAnswers[i];
var crm = CrmConfigurationManager.CreateContext(ContextName);
foreach (var question in _surveyChoiceQuestions)
{
bool answered = false;
foreach (var answer in thisSubmissionChoiceAnswers)
{
var anses = crm.CreateQuery("adx_surveychoiceanswer");
Enreplacedy answer1 = answer;
var ans = anses.Where(a => a.GetAttributeValue<Guid>("adx_surveychoiceanswerid") == answer1.GetAttributeValue<Guid>("adx_surveychoiceanswerid")).First();
if (ans.GetRelatedEnreplacedy(crm, "adx_choicequestion_choiceanswer").GetAttributeValue<Guid?>("adx_surveychoicequestionid")
== question.GetAttributeValue<Guid?>("adx_surveychoicequestionid"))
{
string partialChoiceList = string.Empty;
var choices = ans.GetRelatedEnreplacedies(crm, "adx_surveychoiceanswer_surveychoice");
foreach (var enreplacedy in choices)
{
partialChoiceList = partialChoiceList + enreplacedy.GetAttributeValue<string>("adx_name") + "|";
}
string pattern = @"\|$";
string replacement = " ";
writer.RenderBeginTag(HtmlTextWriterTag.Td);
if (partialChoiceList != null)
{
string result = Regex.Replace(partialChoiceList, pattern, replacement);
writer.Write(result);
}
else
{
writer.Write(partialChoiceList);
}
writer.RenderEndTag();
writer.RenderBeginTag(HtmlTextWriterTag.Td);
string input = ans.GetAttributeValue<string>("adx_answer");
if (input != null)
{
string result = Regex.Replace(input, pattern, replacement);
writer.Write(result);
}
else
{
writer.Write(input);
}
writer.RenderEndTag();
answered = true;
}
}
if (!answered)
{
writer.RenderBeginTag(HtmlTextWriterTag.Td);
writer.Write(@" ");
writer.RenderEndTag();
}
}
foreach (var question in _surveyTextQuestions)
{
bool answered = false;
foreach (var answer in thisSubmissionTextAnswers)
{
var anses = crm.CreateQuery("adx_surveytextanswer");
Enreplacedy answer1 = answer;
var ans = anses.Where(a => a.GetAttributeValue<Guid>("adx_surveytextanswerid") == answer1.GetAttributeValue<Guid>("adx_surveytextanswerid")).First();
if (ans.GetRelatedEnreplacedy(crm, "adx_textareaquestion_textanswer").GetAttributeValue<Guid?>("adx_surveytextareaquestionid")
== question.GetAttributeValue<Guid?>("adx_surveytextareaquestionid"))
{
writer.RenderBeginTag(HtmlTextWriterTag.Td);
if (string.IsNullOrEmpty(ans.GetAttributeValue<string>("adx_answer")))
{
writer.Write(@" ");
}
else
{
writer.Write(ans.GetAttributeValue<string>("adx_answer"));
}
//writer.Write(answer.GetAttributeValue<string>("adx_answer"));
writer.RenderEndTag();
answered = true;
}
}
if (!answered)
{
writer.RenderBeginTag(HtmlTextWriterTag.Td);
writer.Write(@" ");
writer.RenderEndTag();
}
}
writer.RenderEndTag();
}
writer.RenderEndTag();
writer.Flush();
}
19
Source : StringUtilities.cs
with MIT License
from AdrianWilczynski
with MIT License
from AdrianWilczynski
public static string RemoveInterfacePrefix(this string text)
=> Regex.Replace(text, InterfacePrefixRegex, string.Empty);
19
Source : StringUtilities.cs
with MIT License
from AdrianWilczynski
with MIT License
from AdrianWilczynski
public static string EscapeBackslashes(this string text)
=> Regex.Replace(text, @"\\", @"\\");
19
Source : StringUtilities.cs
with MIT License
from AdrianWilczynski
with MIT License
from AdrianWilczynski
public static string ToCamelCase(this string text)
=> !string.IsNullOrEmpty(text) ?
Regex.Replace(text, "^[A-Z]", char.ToLowerInvariant(text[0]).ToString())
: text;
19
Source : StringUtilities.cs
with MIT License
from AdrianWilczynski
with MIT License
from AdrianWilczynski
public static string ToKebabCase(this string text)
=> Regex.Replace(text, "(?<![A-Z]|^)([A-Z])", "-$1").ToLowerInvariant();
19
Source : StringUtilities.cs
with MIT License
from AdrianWilczynski
with MIT License
from AdrianWilczynski
public static string SquashWhistespace(this string text)
=> Regex.Replace(text, @"\s+", " ");
19
Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public void Edit<T>(IreplacedetData replacedet)
{
Monitor.Log("Editing replacedet " + replacedet.replacedetName);
if (replacedet.replacedetNameEquals("Data/Events/HaleyHouse"))
{
IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
data["195012/f Haley 2500/f Emily 2500/f Penny 2500/f Abigail 2500/f Leah 2500/f Maru 2500/o Abigail/o Penny/o Leah/o Emily/o Maru/o Haley/o Shane/o Harvey/o Sebastian/o Sam/o Elliott/o Alex/e 38/e 2123343/e 10/e 901756/e 54/e 15/k 195019"] = Regex.Replace(data["195012/f Haley 2500/f Emily 2500/f Penny 2500/f Abigail 2500/f Leah 2500/f Maru 2500/o Abigail/o Penny/o Leah/o Emily/o Maru/o Haley/o Shane/o Harvey/o Sebastian/o Sam/o Elliott/o Alex/e 38/e 2123343/e 10/e 901756/e 54/e 15/k 195019"], "(pause 1000/speak Maru \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-female")}$h\"/emote Haley 21 true/emote Emily 21 true/emote Penny 21 true/emote Maru 21 true/emote Leah 21 true/emote Abigail 21").Replace("/dump girls 3", "");
data["choseToExplain"] = Regex.Replace(data["choseToExplain"], "(pause 1000/speak Maru \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-female")}$h\"/emote Haley 21 true/emote Emily 21 true/emote Penny 21 true/emote Maru 21 true/emote Leah 21 true/emote Abigail 21").Replace("/dump girls 4", "");
data["lifestyleChoice"] = Regex.Replace(data["lifestyleChoice"], "(pause 1000/speak Maru \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-female")}$h\"/emote Haley 21 true/emote Emily 21 true/emote Penny 21 true/emote Maru 21 true/emote Leah 21 true/emote Abigail 21").Replace("/dump girls 4", "");
}
else if (replacedet.replacedetNameEquals("Data/Events/Saloon"))
{
IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
string aData = data["195013/f Shane 2500/f Sebastian 2500/f Sam 2500/f Harvey 2500/f Alex 2500/f Elliott 2500/o Abigail/o Penny/o Leah/o Emily/o Maru/o Haley/o Shane/o Harvey/o Sebastian/o Sam/o Elliott/o Alex/e 911526/e 528052/e 9581348/e 43/e 384882/e 233104/k 195099"];
data["195013/f Shane 2500/f Sebastian 2500/f Sam 2500/f Harvey 2500/f Alex 2500/f Elliott 2500/o Abigail/o Penny/o Leah/o Emily/o Maru/o Haley/o Shane/o Harvey/o Sebastian/o Sam/o Elliott/o Alex/e 911526/e 528052/e 9581348/e 43/e 384882/e 233104/k 195099"] = Regex.Replace(aData, "(pause 1000/speak Sam \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-male")}$h\"/emote Shane 21 true/emote Sebastian 21 true/emote Sam 21 true/emote Harvey 21 true/emote Alex 21 true/emote Elliott 21").Replace("/dump guys 3", "");
aData = data["choseToExplain"];
data["choseToExplain"] = Regex.Replace(aData, "(pause 1000/speak Sam \\\")[^$]+.a\\\"", $"$1{PHelper.Translation.Get("confrontation-male")}$h\"/emote Shane 21 true/emote Sebastian 21 true/emote Sam 21 true/emote Harvey 21 true/emote Alex 21 true/emote Elliott 21").Replace("/dump guys 4", "");
aData = data["crying"];
data["crying"] = Regex.Replace(aData, "(pause 1000/speak Sam \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-male")}$h\"/emote Shane 21 true/emote Sebastian 21 true/emote Sam 21 true/emote Harvey 21 true/emote Alex 21 true/emote Elliott 21").Replace("/dump guys 4", "");
}
else if (replacedet.replacedetNameEquals("Strings/StringsFromCSFiles"))
{
IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
data["NPC.cs.3985"] = Regex.Replace(data["NPC.cs.3985"], @"\.\.\.\$s.+", $"$n#$b#$c 0.5#{data["ResourceCollectionQuest.cs.13681"]}#{data["ResourceCollectionQuest.cs.13683"]}");
Monitor.Log($"NPC.cs.3985 is set to \"{data["NPC.cs.3985"]}\"");
}
else if (replacedet.replacedetNameEquals("Data/animationDescriptions"))
{
IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
List<string> sleepKeys = data.Keys.ToList().FindAll((s) => s.EndsWith("_Sleep"));
foreach(string key in sleepKeys)
{
if (!data.ContainsKey(key.ToLower()))
{
Monitor.Log($"adding {key.ToLower()} to animationDescriptions");
data.Add(key.ToLower(), data[key]);
}
}
}
else if (replacedet.replacedetNameEquals("Data/EngagementDialogue"))
{
IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
if (!config.RomanceAllVillagers)
return;
Farmer f = Game1.player;
if (f == null)
{
return;
}
foreach (string friend in f.friendshipData.Keys)
{
if (!data.ContainsKey(friend+"0"))
{
data[friend + "0"] = "";
}
if (!data.ContainsKey(friend+"1"))
{
data[friend + "1"] = "";
}
}
}
else if (replacedet.replacedetName.StartsWith("Characters/schedules") || replacedet.replacedetName.StartsWith("Characters\\schedules"))
{
IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
List<string> keys = new List<string>(data.Keys);
foreach (string key in keys)
{
if(!data.ContainsKey($"marriage_{key}"))
data[$"marriage_{key}"] = data[key];
}
}
}
19
Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public void Edit<T>(IreplacedetData replacedet)
{
Monitor.Log("Editing replacedet " + replacedet.replacedetName);
if (replacedet.replacedetNameEquals("Data/Events/HaleyHouse"))
{
IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
data["195012/f Haley 2500/f Emily 2500/f Penny 2500/f Abigail 2500/f Leah 2500/f Maru 2500/o Abigail/o Penny/o Leah/o Emily/o Maru/o Haley/o Shane/o Harvey/o Sebastian/o Sam/o Elliott/o Alex/e 38/e 2123343/e 10/e 901756/e 54/e 15/k 195019"] = Regex.Replace(data["195012/f Haley 2500/f Emily 2500/f Penny 2500/f Abigail 2500/f Leah 2500/f Maru 2500/o Abigail/o Penny/o Leah/o Emily/o Maru/o Haley/o Shane/o Harvey/o Sebastian/o Sam/o Elliott/o Alex/e 38/e 2123343/e 10/e 901756/e 54/e 15/k 195019"], "(pause 1000/speak Maru \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-female")}$h\"/emote Haley 21 true/emote Emily 21 true/emote Penny 21 true/emote Maru 21 true/emote Leah 21 true/emote Abigail 21").Replace("/dump girls 3", "");
data["choseToExplain"] = Regex.Replace(data["choseToExplain"], "(pause 1000/speak Maru \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-female")}$h\"/emote Haley 21 true/emote Emily 21 true/emote Penny 21 true/emote Maru 21 true/emote Leah 21 true/emote Abigail 21").Replace("/dump girls 4", "");
data["lifestyleChoice"] = Regex.Replace(data["lifestyleChoice"], "(pause 1000/speak Maru \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-female")}$h\"/emote Haley 21 true/emote Emily 21 true/emote Penny 21 true/emote Maru 21 true/emote Leah 21 true/emote Abigail 21").Replace("/dump girls 4", "");
}
else if (replacedet.replacedetNameEquals("Data/Events/Saloon"))
{
IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
string aData = data["195013/f Shane 2500/f Sebastian 2500/f Sam 2500/f Harvey 2500/f Alex 2500/f Elliott 2500/o Abigail/o Penny/o Leah/o Emily/o Maru/o Haley/o Shane/o Harvey/o Sebastian/o Sam/o Elliott/o Alex/e 911526/e 528052/e 9581348/e 43/e 384882/e 233104/k 195099"];
data["195013/f Shane 2500/f Sebastian 2500/f Sam 2500/f Harvey 2500/f Alex 2500/f Elliott 2500/o Abigail/o Penny/o Leah/o Emily/o Maru/o Haley/o Shane/o Harvey/o Sebastian/o Sam/o Elliott/o Alex/e 911526/e 528052/e 9581348/e 43/e 384882/e 233104/k 195099"] = Regex.Replace(aData, "(pause 1000/speak Sam \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-male")}$h\"/emote Shane 21 true/emote Sebastian 21 true/emote Sam 21 true/emote Harvey 21 true/emote Alex 21 true/emote Elliott 21").Replace("/dump guys 3", "");
aData = data["choseToExplain"];
data["choseToExplain"] = Regex.Replace(aData, "(pause 1000/speak Sam \\\")[^$]+.a\\\"", $"$1{PHelper.Translation.Get("confrontation-male")}$h\"/emote Shane 21 true/emote Sebastian 21 true/emote Sam 21 true/emote Harvey 21 true/emote Alex 21 true/emote Elliott 21").Replace("/dump guys 4", "");
aData = data["crying"];
data["crying"] = Regex.Replace(aData, "(pause 1000/speak Sam \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-male")}$h\"/emote Shane 21 true/emote Sebastian 21 true/emote Sam 21 true/emote Harvey 21 true/emote Alex 21 true/emote Elliott 21").Replace("/dump guys 4", "");
}
else if (replacedet.replacedetNameEquals("Strings/StringsFromCSFiles"))
{
IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
data["NPC.cs.3985"] = Regex.Replace(data["NPC.cs.3985"], @"\.\.\.\$s.+", $"$n#$b#$c 0.5#{data["ResourceCollectionQuest.cs.13681"]}#{data["ResourceCollectionQuest.cs.13683"]}");
Monitor.Log($"NPC.cs.3985 is set to \"{data["NPC.cs.3985"]}\"");
}
else if (replacedet.replacedetNameEquals("Data/animationDescriptions"))
{
IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
List<string> sleepKeys = data.Keys.ToList().FindAll((s) => s.EndsWith("_Sleep"));
foreach(string key in sleepKeys)
{
if (!data.ContainsKey(key.ToLower()))
{
Monitor.Log($"adding {key.ToLower()} to animationDescriptions");
data.Add(key.ToLower(), data[key]);
}
}
}
else if (replacedet.replacedetNameEquals("Data/EngagementDialogue"))
{
if (!config.RomanceAllVillagers)
return;
IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
Farmer f = Game1.player;
if (f == null)
{
return;
}
foreach (string friend in f.friendshipData.Keys)
{
if (!data.ContainsKey(friend+"0"))
{
data[friend + "0"] = "";
}
if (!data.ContainsKey(friend+"1"))
{
data[friend + "1"] = "";
}
}
}
else if (replacedet.replacedetName.StartsWith("Characters/schedules") || replacedet.replacedetName.StartsWith("Characters\\schedules"))
{
IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
List<string> keys = new List<string>(data.Keys);
foreach (string key in keys)
{
if(!data.ContainsKey($"marriage_{key}"))
data[$"marriage_{key}"] = data[key];
}
}
}
19
Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public void Edit<T>(IreplacedetData replacedet)
{
if (replacedet.replacedetNameEquals("Data/NPCDispositions"))
{
IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
if (config.EnableGeralt)
data["Elliott"] = Regex.Replace(data["Elliott"],@"/[^/]+$", "/Geralt");
if(config.EnableYennifer)
data["Abigail"] = Regex.Replace(data["Abigail"],@"/[^/]+$", "/Yennifer");
if (config.EnableTriss)
data["Penny"] = Regex.Replace(data["Penny"],@"/[^/]+$", "/Triss");
}
else if (replacedet.replacedetName.StartsWith("Characters/Dialogue/") || replacedet.replacedetName.StartsWith("Characters\\Dialogue\\"))
{
IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
List<string> keys = new List<string>(data.Keys);
foreach (string key in keys)
{
if (config.EnableGeralt)
data[key] = Regex.Replace(data[key], @"Elliott", "Geralt");
if (config.EnableYennifer)
{
data[key] = Regex.Replace(data[key], @"Abigail", "Yennifer");
data[key] = Regex.Replace(data[key], @"Abby", "Yenn");
}
if (config.EnableTriss)
data[key] = Regex.Replace(data[key], @"Penny", "Triss");
}
}
}
19
Source : NPCPatches.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public static void Character_displayName_Getter_Postfix(ref Child __instance, ref string __result)
{
try
{
if (__instance.Name == null || !(__instance is Child))
return;
string[] names = __instance.Name.Split(' ');
if (names.Length < 2 || names[names.Length - 1].Length < 3)
{
return;
}
if (!Config.ShowParentNames && __instance.Name.EndsWith(")"))
{
__result = Regex.Replace(string.Join(" ", names), @" \([^)]+\)", "");
//Monitor.Log($"set child display name to: {__result}");
}
}
catch (Exception ex)
{
Monitor.Log($"Failed in {nameof(Child_reloadSprite_Postfix)}:\n{ex}", LogLevel.Error);
}
}
19
Source : NPCPatches.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public static void Child_reloadSprite_Postfix(ref Child __instance)
{
try
{
if (__instance.Name == null)
return;
string[] names = __instance.Name.Split(' ');
string parent;
if (names.Length > 1 && __instance.displayName.EndsWith(")"))
{
parent = names[names.Length - 1].Substring(1, names[names.Length - 1].Length - 2);
__instance.modData["aedenthorn.MultipleSpouses/OtherParent"] = parent;
}
if (!__instance.modData.ContainsKey("aedenthorn.MultipleSpouses/OtherParent"))
return;
parent = __instance.modData["aedenthorn.MultipleSpouses/OtherParent"];
if (!Config.ShowParentNames && __instance.displayName.EndsWith(")"))
{
__instance.displayName = Regex.Replace(string.Join(" ", names), @" \([^)]+\)", "");
}
if (!Config.ChildrenHaveHairOfSpouse)
return;
__instance.Sprite.textureName.Value += $"_{parent}";
Monitor.Log($"set child {__instance.name}, parent {parent} texture to: {__instance.Sprite.textureName.Value}");
}
catch (Exception ex)
{
Monitor.Log($"Failed in {nameof(Child_reloadSprite_Postfix)}:\n{ex}", LogLevel.Error);
}
}
19
Source : ItemFactory.cs
with MIT License
from afaniuolo
with MIT License
from afaniuolo
private string RemoveInvalidChars(string itemName)
{
string invalidItemNameChars = _appSettings.invalidItemNameChars;
if (string.IsNullOrEmpty(invalidItemNameChars)) return itemName;
var invalidItemNameCharsDecoded = HttpUtility.HtmlDecode(invalidItemNameChars);
var invalidItemNameCharsEscaped = invalidItemNameCharsDecoded.Replace("[", @"\[").Replace("]", @"\]");
var replaceRegex = string.Format("[" + invalidItemNameCharsEscaped + "]");
return Regex.Replace(itemName, replaceRegex, "");
}
19
Source : ContainerAttributeUtils.cs
with Apache License 2.0
from agoda-com
with Apache License 2.0
from agoda-com
public static string GetFriendlyName(Attribute attr)
{
var attrName = attr.GetType().Name;
return Regex.Replace(attrName, "Attribute$", "");
}
19
Source : ArrayData.cs
with GNU Affero General Public License v3.0
from aianlinb
with GNU Affero General Public License v3.0
from aianlinb
public static ArrayData<TypeOfValueInArray> FromString(string value, DatContainer dat, FieldType typeOfarrayInArray) {
value = typeOfarrayInArray == FieldType.String || typeOfarrayInArray == FieldType.ValueString ? value : Regex.Replace(value, @"\s", "").Replace(",", ", ");
if (dat.ReferenceDataOffsets.TryGetValue(value, out long offset) && dat.ReferenceDatas.TryGetValue(offset, out IReferenceData rd) && rd is ArrayData<TypeOfValueInArray> a)
return a;
var ad = new ArrayData<TypeOfValueInArray>(dat, typeOfarrayInArray);
ad.FromString(value);
return ad;
}
See More Examples