Here are the examples of the csharp api System.Text.RegularExpressions.Regex.Replace(string, System.Text.RegularExpressions.MatchEvaluator, int, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1290 Examples
19
View Source File : UpdateTest.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
[Test]
public void UpdateDataIn_Test()
{
const int usersCount = 3;
var data = new List<UserData>(usersCount);
for (int i = 0; i < usersCount; i++)
{
data.Add(new UserData
{
UserId = i+1,
FirstName = "First" + i,
LastName = "Last" + i,
EMail = $"user{i}@company.com",
RegDate = new DateTime(2020, 01, 02)
});
}
var tbl = Tables.User();
var expr = UpdateData(tbl, data)
.MapDataKeys(s => s.Set(s.Target.UserId, s.Source.UserId))
.MapData(s => s.Set(s.Target.FirstName, s.Source.FirstName))
.AlsoSet(s => s.Set(s.Target.Modified, GetUtcDate()))
.Done();
var sql = expr.ToMySql();
Regex r = new Regex("t[\\d|\\w]{32}");
sql = r.Replace(sql, "tmpTableName");
replacedert.AreEqual(sql, "CREATE TEMPORARY TABLE `tmpTableName`(`UserId` int,`FirstName` varchar(6) character set utf8,CONSTRAINT PRIMARY KEY (`UserId`));INSERT INTO `tmpTableName`(`UserId`,`FirstName`) VALUES (1,'First0'),(2,'First1'),(3,'First2');UPDATE `user` `A0`,`tmpTableName` `A1` SET `A0`.`FirstName`=`A1`.`FirstName`,`A0`.`Modified`=UTC_TIMESTAMP() WHERE `A0`.`UserId`=`A1`.`UserId`;DROP TABLE `tmpTableName`;");
sql = expr.ToSql();
replacedert.AreEqual(sql, "UPDATE [A0] SET [A0].[FirstName]=[A1].[FirstName],[A0].[Modified]=GETUTCDATE() FROM [dbo].[user] [A0] JOIN (VALUES (1,'First0'),(2,'First1'),(3,'First2'))[A1]([UserId],[FirstName]) ON [A0].[UserId]=[A1].[UserId]");
}
19
View Source File : DbContext.cs
License : Apache License 2.0
Project Creator : 1448376744
License : Apache License 2.0
Project Creator : 1448376744
private void Initialize(IDbCommand cmd, string sql, object parameter, int? commandTimeout = null, CommandType? commandType = null)
{
var dbParameters = new List<IDbDataParameter>();
cmd.Transaction = _transaction;
cmd.CommandText = sql;
if (commandTimeout.HasValue)
{
cmd.CommandTimeout = commandTimeout.Value;
}
if (commandType.HasValue)
{
cmd.CommandType = commandType.Value;
}
if (parameter is IDbDataParameter)
{
dbParameters.Add(parameter as IDbDataParameter);
}
else if (parameter is IEnumerable<IDbDataParameter> parameters)
{
dbParameters.AddRange(parameters);
}
else if (parameter is Dictionary<string, object> keyValues)
{
foreach (var item in keyValues)
{
var param = CreateParameter(cmd, item.Key, item.Value);
dbParameters.Add(param);
}
}
else if (parameter != null)
{
var handler = GlobalSettings.EnreplacedyMapperProvider.GetDeserializer(parameter.GetType());
var values = handler(parameter);
foreach (var item in values)
{
var param = CreateParameter(cmd, item.Key, item.Value);
dbParameters.Add(param);
}
}
if (dbParameters.Count > 0)
{
foreach (IDataParameter item in dbParameters)
{
if (item.Value == null)
{
item.Value = DBNull.Value;
}
var pattern = $@"in\s+([\@,\:,\?]?{item.ParameterName})";
var options = RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline;
if (cmd.CommandText.IndexOf("in", StringComparison.OrdinalIgnoreCase) != -1 && Regex.IsMatch(cmd.CommandText, pattern, options))
{
var name = Regex.Match(cmd.CommandText, pattern, options).Groups[1].Value;
var list = new List<object>();
if (item.Value is IEnumerable<object> || item.Value is Array)
{
list = (item.Value as IEnumerable).Cast<object>().Where(a => a != null && a != DBNull.Value).ToList();
}
else
{
list.Add(item.Value);
}
if (list.Count() > 0)
{
cmd.CommandText = Regex.Replace(cmd.CommandText, name, $"({string.Join(",", list.Select(s => $"{name}{list.IndexOf(s)}"))})");
foreach (var iitem in list)
{
var key = $"{item.ParameterName}{list.IndexOf(iitem)}";
var param = CreateParameter(cmd, key, iitem);
cmd.Parameters.Add(param);
}
}
else
{
cmd.CommandText = Regex.Replace(cmd.CommandText, name, $"(SELECT 1 WHERE 1 = 0)");
}
}
else
{
cmd.Parameters.Add(item);
}
}
}
if (Logging != null)
{
var parameters = new Dictionary<string, object>();
foreach (IDbDataParameter item in cmd.Parameters)
{
parameters.Add(item.ParameterName, item.Value);
}
Logging.Invoke(cmd.CommandText, parameters, commandTimeout, commandType);
}
}
19
View Source File : GetBoundingBox.cs
License : GNU Affero General Public License v3.0
Project Creator : 3drepo
License : GNU Affero General Public License v3.0
Project Creator : 3drepo
void Update () {
if(Input.GetMouseButtonUp(0))
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo = new RaycastHit();
if (Physics.Raycast(ray, out hitInfo, Mathf.Infinity))
{
var meshName = Regex.Replace(hitInfo.collider.name, @"_[\d]+$", ""); ;
var uvCoord = hitInfo.textureCoord2;
var ns = hitInfo.collider.transform.root.name;
var nsArr = ns.Split('.');
GetBoundingBoxInfo(nsArr[1], meshName, (int) uvCoord.y);
}
}
}
19
View Source File : DellFanManagementGuiForm.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley
License : GNU General Public License v3.0
Project Creator : AaronKelley
private void ConsistencyModeTextBoxesChangedEventHandler(Object sender, EventArgs e)
{
// Enforce digits only in these text boxes.
if (Regex.IsMatch(consistencyModeLowerTemperatureThresholdTextBox.Text, "[^0-9]"))
{
consistencyModeLowerTemperatureThresholdTextBox.Text = Regex.Replace(consistencyModeLowerTemperatureThresholdTextBox.Text, "[^0-9]", "");
}
if (Regex.IsMatch(consistencyModeUpperTemperatureThresholdTextBox.Text, "[^0-9]"))
{
consistencyModeUpperTemperatureThresholdTextBox.Text = Regex.Replace(consistencyModeUpperTemperatureThresholdTextBox.Text, "[^0-9]", "");
}
if (Regex.IsMatch(consistencyModeRpmThresholdTextBox.Text, "[^0-9]"))
{
consistencyModeRpmThresholdTextBox.Text = Regex.Replace(consistencyModeRpmThresholdTextBox.Text, "[^0-9]", "");
}
CheckConsistencyModeOptionsConsistency();
}
19
View Source File : SimpleAnimationNodeEditor.cs
License : MIT License
Project Creator : aarthificial
License : MIT License
Project Creator : aarthificial
[MenuItem("replacedets/Create/Reanimator/Simple Animation (From Textures)", false, 400)]
private static void CreateFromTextures()
{
var trailingNumbersRegex = new Regex(@"(\d+$)");
var sprites = new List<Sprite>();
var textures = Selection.GetFiltered<Texture2D>(SelectionMode.replacedets);
foreach (var texture in textures)
{
string path = replacedetDatabase.GetreplacedetPath(texture);
sprites.AddRange(replacedetDatabase.LoadAllreplacedetsAtPath(path).OfType<Sprite>());
}
var cels = sprites
.OrderBy(
sprite =>
{
var match = trailingNumbersRegex.Match(sprite.name);
return match.Success ? int.Parse(match.Groups[0].Captures[0].ToString()) : 0;
}
)
.Select(sprite => new SimpleCel(sprite))
.ToArray();
var replacedet = SimpleAnimationNode.Create<SimpleAnimationNode>(
cels: cels
);
string baseName = trailingNumbersRegex.Replace(textures[0].name, "");
replacedet.name = baseName + "_animation";
string replacedetPath = Path.GetDirectoryName(replacedetDatabase.GetreplacedetPath(textures[0]));
replacedetDatabase.Createreplacedet(replacedet, Path.Combine(replacedetPath ?? Application.dataPath, replacedet.name + ".replacedet"));
replacedetDatabase.Savereplacedets();
}
19
View Source File : ProjectWriter.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public static string WriteProject(Example example, string selectedPath, string replacedembliesPath, bool showMessageBox = true)
{
var files = new Dictionary<string, string>();
var replacedembly = typeof(ProjectWriter).replacedembly;
var names = replacedembly.GetManifestResourceNames();
var templateFiles = names.Where(x => x.Contains("Templates")).ToList();
foreach (var templateFile in templateFiles)
{
var fileName = GetFileNameFromNs(templateFile);
using (var s = replacedembly.GetManifestResourceStream(templateFile))
{
if (s == null) break;
using (var sr = new StreamReader(s))
{
files.Add(fileName, sr.ReadToEnd());
}
}
}
string projectName = "SciChart_" + Regex.Replace(example.replacedle, @"[^A-Za-z0-9]+", string.Empty);
files[ProjectFileName] = GenerateProjectFile(files[ProjectFileName], example, replacedembliesPath);
files[SolutionFileName] = GenerateSolutionFile(files[SolutionFileName], projectName);
files.RenameKey(ProjectFileName, projectName + ".csproj");
files.RenameKey(SolutionFileName, projectName + ".sln");
files[MainWindowFileName] = GenerateShellFile(files[MainWindowFileName], example).Replace("[Examplereplacedle]", example.replacedle);
foreach (var codeFile in example.SourceFiles)
{
files.Add(codeFile.Key, codeFile.Value);
}
WriteProjectFiles(files, Path.Combine(selectedPath, projectName));
if (showMessageBox && Application.Current.MainWindow != null)
{
var message = $"The {example.replacedle} example was successfully exported to {selectedPath + projectName}";
MessageBox.Show(Application.Current.MainWindow, message, "Success!");
}
return projectName;
}
19
View Source File : ProjectWriter.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private static string GenerateProjectFile(string projFileSource, Example example, string replacedembliesPath)
{
var projXml = XDoreplacedent.Parse(projFileSource);
if (projXml.Root != null)
{
var elements = projXml.Root.Elements().Where(x => x.Name.LocalName == "ItemGroup").ToList();
if (elements.Count == 3)
{
// Add appropriate references
var el = new XElement("Reference", new XAttribute("Include", ExternalDependencies.Replace(".dll", string.Empty)));
el.Add(new XElement("HintPath", Path.Combine(replacedembliesPath, ExternalDependencies)));
elements[0].Add(el);
// Add replacedembly references
foreach (var asmName in replacedembliesNames)
{
el = new XElement("Reference", new XAttribute("Include", asmName.Replace(".dll", string.Empty)));
el.Add(new XElement("HintPath", Path.Combine(replacedembliesPath, asmName)));
elements[0].Add(el);
}
// Add package references for specific example NuGet packages
var examplereplacedle = Regex.Replace(example.replacedle, @"\s", string.Empty);
var examplePackages = NuGetPackages.Where(p => p.StartsWith(examplereplacedle));
if (examplePackages.Any())
{
foreach (var package in examplePackages)
{
// Examplereplacedle;PackageName;PackageVersion
var packageAttr = package.Split(';');
if (packageAttr.Length == 3)
{
el = new XElement("PackageReference",
new XAttribute("Include", packageAttr[1]),
new XAttribute("Version", packageAttr[2]));
elements[1].Add(el);
}
}
}
#if NET452
return projXml.ToString().Replace("[PROJECTTARGET]", "net452");
#else
elements[2].Remove(); // Remove 'net452' references
return projXml.ToString().Replace("[PROJECTTARGET]", "netcoreapp3.1");
#endif
}
}
return projFileSource;
}
19
View Source File : Increment.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
private static string GetDestinationNumberreplacedtring(string s, string i)
{
if (string.IsNullOrEmpty(s))
{
s = string.Empty;
}
if (IncrementSettings.Default.UseDestinationSearchPattern)
{
s = Regex.Replace(s, IncrementSettings.Default.DestinationSearchPattern, IncrementSettings.Default.DestinationReplacePattern);
} else
{
s = Regex.Replace(s, IncrementSettings.Default.SourceSearchPattern, IncrementSettings.Default.DestinationReplacePattern);
}
return s.Replace("#VAL#", i);
}
19
View Source File : Increment.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
private static string GetSourceNumberreplacedtring(string s)
{
if (string.IsNullOrEmpty(s))
{
s = string.Empty;
}
return Regex.Replace(s, IncrementSettings.Default.SourceSearchPattern, IncrementSettings.Default.SourceReplacePattern);
}
19
View Source File : PostExportHookCommand.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
public static string FormatConfigurationString(ExportSheet sheet, string value, string extension)
{
string result = value;
result = result.Replace(@"$height", sheet.Height.ToString(CultureInfo.InvariantCulture));
result = result.Replace(@"$width", sheet.Width.ToString(CultureInfo.InvariantCulture));
result = result.Replace(@"$fullExportName", sheet.FullExportName);
result = result.Replace(@"$fullExportPath", sheet.FullExportPath(extension));
result = result.Replace(@"$exportDir", sheet.ExportDirectory);
result = result.Replace(@"$pageSize", sheet.PageSize);
result = result.Replace(@"$projectNumber", sheet.ProjectNumber);
result = result.Replace(@"$sheetDescription", sheet.SheetDescription);
result = result.Replace(@"$sheetNumber", sheet.SheetNumber);
result = result.Replace(@"$sheetRevisionDate", sheet.SheetRevisionDate);
result = result.Replace(@"$sheetRevision", sheet.SheetRevision);
result = result.Replace(@"$sheetRevisionDescription", sheet.SheetRevisionDescription);
result = result.Replace(@"$fileExtension", extension);
// search for, and replace Custom Paramters
string pattern = @"(__)(.*?)(__)";
result = Regex.Replace(
result,
pattern,
m => RoomConverter.RoomConversionCandidate.GetParamValuereplacedtring(sheet.ParamFromString(m.Groups[2].Value)));
return result;
}
19
View Source File : UserView.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
private static string ReplacePatternMatches(Element element, string name)
{
string user = Environment.UserName;
string date = MiscUtilities.GetDateString;
try
{
name = name.Replace(@"$user", user);
name = name.Replace(@"$date", date);
}
catch
{
//// FIXME
}
string pattern = @"(<<)(.*?)(>>)";
name = Regex.Replace(
name,
pattern,
m => RoomConverter.RoomConversionCandidate.GetParamValuereplacedtring(ParamFromString(m.Groups[2].Value, element)));
// Revit wont allow { or } so replace them if they exist
name = name.Replace(@"{", string.Empty).Replace(@"}", string.Empty);
return name;
}
19
View Source File : ServiceControlManager.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public void CalculateServiceName(RunnerSettings settings, string serviceNamePattern, string serviceDisplayNamePattern, out string serviceName, out string serviceDisplayName)
{
Trace.Entering();
serviceName = string.Empty;
serviceDisplayName = string.Empty;
if (string.IsNullOrEmpty(settings.RepoOrOrgName))
{
throw new InvalidOperationException($"Cannot find GitHub repository/organization name from server url: '{settings.ServerUrl}'");
}
// For the service name, replace any characters outside of the alpha-numeric set and ".", "_", "-" with "-"
Regex regex = new Regex(@"[^0-9a-zA-Z._\-]");
string repoOrOrgName = regex.Replace(settings.RepoOrOrgName, "-");
serviceName = StringUtil.Format(serviceNamePattern, repoOrOrgName, settings.AgentName);
if (serviceName.Length > 80)
{
Trace.Verbose($"Calculated service name is too long (> 80 chars). Trying again by calculating a shorter name.");
int exceededCharLength = serviceName.Length - 80;
string repoOrOrgNameSubstring = StringUtil.SubstringPrefix(repoOrOrgName, 45);
exceededCharLength -= repoOrOrgName.Length - repoOrOrgNameSubstring.Length;
string runnerNameSubstring = settings.AgentName;
// Only trim runner name if it's really necessary
if (exceededCharLength > 0)
{
runnerNameSubstring = StringUtil.SubstringPrefix(settings.AgentName, settings.AgentName.Length - exceededCharLength);
}
serviceName = StringUtil.Format(serviceNamePattern, repoOrOrgNameSubstring, runnerNameSubstring);
}
serviceDisplayName = StringUtil.Format(serviceDisplayNamePattern, repoOrOrgName, settings.AgentName);
Trace.Info($"Service name '{serviceName}' display name '{serviceDisplayName}' will be used for service configuration.");
}
19
View Source File : OutputManager.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public void OnDataReceived(object sender, ProcessDataReceivedEventArgs e)
{
var line = e.Data;
// ## commands
if (!String.IsNullOrEmpty(line) &&
(line.IndexOf(ActionCommand.Prefix) >= 0 || line.IndexOf(ActionCommand._commandKey) >= 0))
{
// This does not need to be inside of a critical section.
// The logging queues and command handlers are thread-safe.
if (_commandManager.TryProcessCommand(_executionContext, line, _container))
{
return;
}
}
// Problem matchers
if (_matchers.Length > 0)
{
// Copy the reference
var matchers = _matchers;
// Strip color codes
var stripped = line.Contains(_colorCodePrefix) ? _colorCodeRegex.Replace(line, string.Empty) : line;
foreach (var matcher in matchers)
{
IssueMatch match = null;
for (var attempt = 1; attempt <= _maxAttempts; attempt++)
{
// Match
try
{
match = matcher.Match(stripped);
break;
}
catch (RegexMatchTimeoutException ex)
{
if (attempt < _maxAttempts)
{
// Debug
_executionContext.Debug($"Timeout processing issue matcher '{matcher.Owner}' against line '{stripped}'. Exception: {ex.ToString()}");
}
else
{
// Warn
_executionContext.Warning($"Removing issue matcher '{matcher.Owner}'. Matcher failed {_maxAttempts} times. Error: {ex.Message}");
// Remove
Remove(matcher);
}
}
}
if (match != null)
{
// Reset other matchers
foreach (var otherMatcher in matchers.Where(x => !object.ReferenceEquals(x, matcher)))
{
otherMatcher.Reset();
}
// Convert to issue
var issue = ConvertToIssue(match);
if (issue != null)
{
// Log issue
_executionContext.AddIssue(issue, stripped);
return;
}
}
}
}
// Regular output
_executionContext.Output(line);
}
19
View Source File : FileManager.cs
License : GNU General Public License v3.0
Project Creator : AdamMYoung
License : GNU General Public License v3.0
Project Creator : AdamMYoung
internal static string GetGroupShortcut(GroupViewModel group)
{
var appDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDoreplacedents);
var folderPath = Path.Combine(appDirectory, @"Groupr\Shortcuts\");
Regex illegalInFileName = new Regex(@"[\\/:*?""<>|]");
var fileName = group.Name + " " + DateTime.Now.ToString($"yyyy-MM-dd") + ".lnk";
var sanitizedFileName = illegalInFileName.Replace(fileName, "");
var shortcutPath = Path.Combine(folderPath, sanitizedFileName);
Directory.CreateDirectory(folderPath);
if (!File.Exists(shortcutPath))
CreateGroupShortcut(group, shortcutPath);
return folderPath;
}
19
View Source File : VCalendar.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static string StripHtml(string html)
{
if (string.IsNullOrEmpty(html))
{
return null;
}
var doreplacedent = new HtmlDoreplacedent();
doreplacedent.LoadHtml(html);
return Regex.Replace(doreplacedent.DoreplacedentNode.InnerText, @"[\s\r\n]+", " ").Trim();
}
19
View Source File : FetchXmlIndexDocumentFactory.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public CrmEnreplacedyIndexDoreplacedent GetDoreplacedent(FetchXmlResult fetchXmlResult)
{
var enreplacedyMetadata = _dataContext.GetEnreplacedyMetadata(_fetchXml.LogicalName, _metadataCache);
var attributes = enreplacedyMetadata.Attributes.ToDictionary(a => a.LogicalName, a => a);
var doreplacedent = new Doreplacedent();
var primaryKey = Guid.Empty;
var languageValueAdded = false;
var lcid = 0;
// Store the enreplacedy logical name and the logical name of the primary key attribute in the index doreplacedent, for
// easier later retrieval of the enreplacedy corresponding to this doreplacedent.
doreplacedent.Add(
new Field(_index.LogicalNameFieldName, enreplacedyMetadata.LogicalName, Field.Store.YES, Field.Index.NOT_replacedYZED));
doreplacedent.Add(
new Field(
_index.PrimaryKeyLogicalNameFieldName,
enreplacedyMetadata.PrimaryIdAttribute,
Field.Store.YES,
Field.Index.NOT_replacedYZED));
try
{
var content = new ContentFieldBuilder();
foreach (var fetchXmlField in fetchXmlResult)
{
// Treat the primary key field in a special way.
if (fetchXmlField.Name == enreplacedyMetadata.PrimaryIdAttribute)
{
primaryKey = new Guid(fetchXmlField.Value);
doreplacedent.Add(new Field(_index.PrimaryKeyFieldName, primaryKey.ToString(), Field.Store.YES, Field.Index.NOT_replacedYZED));
doreplacedent.Add(new Field(fetchXmlField.Name, primaryKey.ToString(), Field.Store.YES, Field.Index.NOT_replacedYZED));
// Adding webroles for the webpage to the index.
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.CmsEnabledSearching))
{
if (enreplacedyMetadata.LogicalName == "adx_webpage")
{
ADXTrace.Instance.TraceInfo(TraceCategory.Monitoring, "CMS is enabled. Adding roles for adx_webpage index");
var ruleNames = CmsIndexHelper.GetWebPageWebRoles(this._contentMapProvider, primaryKey);
this.AddWebRolesToDoreplacedent(doreplacedent, ruleNames);
}
if (enreplacedyMetadata.LogicalName == "adx_ideaforum")
{
ADXTrace.Instance.TraceInfo(TraceCategory.Monitoring, "CMS is enabled. Adding roles for adx_ideaforum index");
var ruleNames = CmsIndexHelper.GetIdeaForumWebRoles(this._contentMapProvider, primaryKey);
this.AddWebRolesToDoreplacedent(doreplacedent, ruleNames);
}
if (enreplacedyMetadata.LogicalName == "adx_communityforum")
{
ADXTrace.Instance.TraceInfo(TraceCategory.Monitoring, "CMS is enabled. Adding roles for adx_communityforum index");
var ruleNames = CmsIndexHelper.GetForumsWebRoles(this._contentMapProvider, primaryKey);
this.AddWebRolesToDoreplacedent(doreplacedent, ruleNames);
}
}
continue;
}
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.CmsEnabledSearching))
{
if (fetchXmlField.Name == "adx_ideaforumid" && enreplacedyMetadata.LogicalName == "adx_idea")
{
ADXTrace.Instance.TraceInfo(TraceCategory.Monitoring, "CMS is enabled. Adding roles for adx_idea index");
var ruleNames = CmsIndexHelper.GetIdeaForumWebRoles(
this._contentMapProvider,
new Guid(fetchXmlField.Value));
this.AddWebRolesToDoreplacedent(doreplacedent, ruleNames);
}
// Based off the Parent Web Page get the webroles for each given enreplacedy
if ((fetchXmlField.Name == "adx_parentpageid" && enreplacedyMetadata.LogicalName == "adx_blog")
|| (fetchXmlField.Name == "adx_blog_blogpost.adx_parentpageid" && enreplacedyMetadata.LogicalName == "adx_blogpost")
|| (fetchXmlField.Name == "adx_parentpageid" && enreplacedyMetadata.LogicalName == "adx_webfile"))
{
ADXTrace.Instance.TraceInfo(TraceCategory.Monitoring, string.Format("CMS is enabled. Adding roles for {0} index", fetchXmlField.Name));
var ruleNames = CmsIndexHelper.GetWebPageWebRoles(this._contentMapProvider, new Guid(fetchXmlField.Value));
this.AddWebRolesToDoreplacedent(doreplacedent, ruleNames);
}
if ((fetchXmlField.Name == "adx_forumid" && enreplacedyMetadata.LogicalName == "adx_communityforumthread")
|| (fetchXmlField.Name == "adx_communityforumpost_communityforumthread.adx_forumid" && enreplacedyMetadata.LogicalName == "adx_communityforumpost"))
{
ADXTrace.Instance.TraceInfo(TraceCategory.Monitoring, string.Format("CMS is enabled. Adding roles for {0} index", fetchXmlField.Name));
var ruleNames = CmsIndexHelper.GetForumsWebRoles(
this._contentMapProvider,
new Guid(fetchXmlField.Value));
this.AddWebRolesToDoreplacedent(doreplacedent, ruleNames);
}
if (enreplacedyMetadata.LogicalName == "annotation" && fetchXmlField.Name == "knowledgearticle.knowledgearticleid")
{
var id = new Guid(fetchXmlField.Value);
doreplacedent.Add(new Field("annotation_knowledgearticleid", id.ToString(), Field.Store.YES, Field.Index.NOT_replacedYZED));
}
}
// Store the replacedle of the result in a special field.
if (fetchXmlField.Name == _replacedleAttributeLogicalName && enreplacedyMetadata.LogicalName != "annotation")
{
doreplacedent.Add(new Field(_index.replacedleFieldName, fetchXmlField.Value, Field.Store.YES, Field.Index.replacedYZED));
}
// Store the language locale code in a separate field.
if (_localeConfig.IsLanguageCodeLogicalName(fetchXmlField.Name))
{
doreplacedent.Add(
new Field(
_index.LanguageLocaleCodeFieldName,
fetchXmlField.Value.ToLowerInvariant(),
Field.Store.YES,
Field.Index.NOT_replacedYZED));
languageValueAdded = true;
}
// Store the language locale LCID in a separate field.
if (_localeConfig.IsLCIDLogicalName(fetchXmlField.Name) && int.TryParse(fetchXmlField.Value, out lcid))
{
doreplacedent.Add(
new Field(_index.LanguageLocaleLCIDFieldName, fetchXmlField.Value, Field.Store.YES, Field.Index.NOT_replacedYZED));
}
// Skip metadata parsing for language fields
if (_localeConfig.CanSkipMetadata(fetchXmlField.Name)) continue;
FetchXmlLinkAttribute link;
if (_fetchXml.TryGetLinkAttribute(fetchXmlField, out link))
{
var linkEnreplacedyMetadata = _dataContext.GetEnreplacedyMetadata(link.EnreplacedyLogicalName, _metadataCache);
var linkAttributeMetadata = linkEnreplacedyMetadata.Attributes.FirstOrDefault(a => a.LogicalName == link.LogicalName);
if (linkAttributeMetadata == null)
{
throw new InvalidOperationException("Unable to retrieve attribute metadata for FetchXML result field {0} for enreplacedy {1}.".FormatWith(link.LogicalName, linkEnreplacedyMetadata.LogicalName));
}
var fieldName = fetchXmlResult.Any(f => f.Name == link.LogicalName)
? "{0}.{1}".FormatWith(linkEnreplacedyMetadata.LogicalName, linkAttributeMetadata.LogicalName)
: link.LogicalName;
//Renaming product identifier field to "replacedociated.product"
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.CmsEnabledSearching)
&& (this._fetchXml.LogicalName == "knowledgearticle" && fieldName == "record2id"
|| this._fetchXml.LogicalName == "annotation" && fieldName == "productid"))
{
fieldName = FixedFacetsConfiguration.ProductFieldFacetName;
}
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.CmsEnabledSearching)
&& (this._fetchXml.LogicalName == "knowledgearticle" && (fieldName == "notetext" || fieldName == "filename")))
{
fieldName = "related_" + fieldName;
}
if (fieldName == "related_filename")
{
fetchXmlField.Value = Regex.Replace(fetchXmlField.Value, "[._,-]", " ");
}
if (fieldName == "related_notetext")
{
fetchXmlField.Value = fetchXmlField.Value.Substring(GetNotesFilterPrefix().Length);
}
AddDoreplacedentFields(doreplacedent, fieldName, fetchXmlField, linkAttributeMetadata, content);
}
else
{
AttributeMetadata attributeMetadata;
if (!attributes.TryGetValue(fetchXmlField.Name, out attributeMetadata))
{
throw new InvalidOperationException(
ResourceManager.GetString("Attribute_Metadata_Fetchxml_Retrieve_Exception")
.FormatWith(fetchXmlField.Name, enreplacedyMetadata.LogicalName));
}
if (fetchXmlField.Name == "filename")
{
fetchXmlField.Value = Regex.Replace(fetchXmlField.Value, "[._,-]", " ");
}
if (fetchXmlField.Name == "notetext")
{
fetchXmlField.Value = fetchXmlField.Value.Substring(GetNotesFilterPrefix().Length);
}
AddDoreplacedentFields(doreplacedent, fetchXmlField.Name, fetchXmlField, attributeMetadata, content);
}
}
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.CmsEnabledSearching))
{
// Add the default value for enreplacedies that are not Knowledge articles for the Product filtering field.
if (enreplacedyMetadata.LogicalName != "knowledgearticle")
{
doreplacedent.Add(
new Field(
FixedFacetsConfiguration.ProductFieldFacetName,
this._index.ProductAccessNonKnowledgeArticleDefaultValue,
Field.Store.NO,
Field.Index.NOT_replacedYZED));
doreplacedent.Add(
new Field(FixedFacetsConfiguration.ContentAccessLevel,
"public",
Field.Store.NO,
Field.Index.NOT_replacedYZED));
}
else
{
// If there aren't any products replacedociated to the article add the default value so then at query time
// based on the site setting it will add these to the result or not.
var productsDoreplacedent = doreplacedent.GetField(FixedFacetsConfiguration.ProductFieldFacetName);
if (productsDoreplacedent == null)
{
doreplacedent.Add(
new Field(
FixedFacetsConfiguration.ProductFieldFacetName,
this._index.ProductAccessDefaultValue,
Field.Store.NO,
Field.Index.NOT_replacedYZED));
}
}
}
if (!languageValueAdded)
{
doreplacedent.Add(new Field(_index.LanguageLocaleCodeFieldName, _index.LanguageLocaleCodeDefaultValue, Field.Store.YES, Field.Index.NOT_replacedYZED));
}
// Add the field for the main, replacedyzed, search content.
doreplacedent.Add(new Field(_index.ContentFieldName, content.ToString(), _index.StoreContentField ? Field.Store.YES : Field.Store.NO, Field.Index.replacedYZED));
if (_index.AddScopeField)
{
var scopeField = doreplacedent.GetField(_index.ScopeValueSourceFieldName);
var scopeValue = scopeField == null ? _index.ScopeDefaultValue : scopeField.StringValue;
doreplacedent.Add(new Field(_index.ScopeFieldName, scopeValue, Field.Store.NO, Field.Index.NOT_replacedYZED));
}
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.CmsEnabledSearching))
{
this.AddDefaultWebRoleToAllDoreplacedentsNotUnderCMS(doreplacedent, enreplacedyMetadata.LogicalName);
this.AddUrlDefinedToDoreplacedent(doreplacedent, enreplacedyMetadata.LogicalName, fetchXmlResult);
}
var doreplacedentreplacedyzer = lcid > 0
? _index.GetLanguageSpecificreplacedyzer(lcid)
: _index.replacedyzer;
return new CrmEnreplacedyIndexDoreplacedent(doreplacedent, doreplacedentreplacedyzer, primaryKey);
}
catch (Exception e)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Error: Exception when trying to create the index doreplacedent. {0}", e));
}
return new CrmEnreplacedyIndexDoreplacedent(doreplacedent, _index.replacedyzer, primaryKey);
}
19
View Source File : SimpleHtmlFormatter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static string ReplaceUrlsWithLinks(string text)
{
return UrlReplacementRegex.Replace(text, match =>
{
Uri uri;
return Uri.TryCreate(match.Groups["url"].Value, UriKind.Absolute, out uri)
? @"<a href=""{0}"" rel=""nofollow"">{0}</a>".FormatWith(WebUtility.HtmlEncode(uri.ToString()))
: match.Value;
});
}
19
View Source File : StringHelper.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static string StripHtml(string html)
{
if (string.IsNullOrEmpty(html))
{
return null;
}
var doreplacedent = new HtmlAgilityPack.HtmlDoreplacedent();
doreplacedent.LoadHtml(html);
return Regex.Replace(HttpUtility.HtmlDecode(doreplacedent.DoreplacedentNode.InnerText), @"[\s\r\n]+", " ").Trim();
}
19
View Source File : SearchDataSourceView.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected string GetFilter(DataSourceSelectArguments args, IDictionary parameters)
{
if (string.IsNullOrEmpty(Owner.Filter))
{
return (parameters["Filter"] ?? string.Empty).ToString();
}
return Regex.Replace(Owner.Filter, @"@(?<parameter>\w+)", match =>
{
var value = parameters[match.Groups["parameter"].Value];
return value == null ? match.Value : value.ToString();
});
}
19
View Source File : SearchDataSourceView.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected string GetQueryText(DataSourceSelectArguments args, IDictionary parameters)
{
if (string.IsNullOrEmpty(Owner.Query))
{
return (parameters["Query"] ?? string.Empty).ToString();
}
return Regex.Replace(Owner.Query, @"@(?<parameter>\w+)", match =>
{
var value = parameters[match.Groups["parameter"].Value];
var res = value == null ? match.Value : value.ToString();
return HttpUtility.HtmlDecode(res ?? string.Empty);
});
}
19
View Source File : CacheKeyDependency.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public string GetCacheKey(System.Web.HttpContext context, System.Web.UI.Control control, object container, Converter<string, string> getDefaultKey)
{
string cacheKey = KeyFormat;
if (Parameters != null && Parameters.Count > 0)
{
// use the parameters collection to build the dependency
IOrderedDictionary values = Parameters.GetValues(context, control);
if (container != null)
{
// process CacheItemParameter objects, lookup the value based on the container
foreach (Parameter param in Parameters)
{
if (param is CacheItemParameter)
{
string format = (param as CacheItemParameter).Format;
string propertyName = (param as CacheItemParameter).PropertyName;
string result = DataBinder.Eval(container, propertyName, format);
if (!string.IsNullOrEmpty(result))
{
values[param.Name] = result;
}
}
}
}
if (!string.IsNullOrEmpty(KeyFormat))
{
foreach (DictionaryEntry entry in values)
{
if (entry.Key != null)
{
string key = entry.Key.ToString().Trim();
if (!key.StartsWith("@"))
{
key = "@" + key;
}
cacheKey = Regex.Replace(cacheKey, key, "{0}".FormatWith(entry.Value), RegexOptions.IgnoreCase);
}
}
}
}
else if (!string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(PropertyName))
{
string result = null;
if (container != null)
{
try
{
result = DataBinder.Eval(container, PropertyName, "{0}");
}
catch (Exception e)
{
Tracing.FrameworkError("CacheKeyDependency", "GetCacheKey", "Invalid cache parameter settings.");
Tracing.FrameworkError("CacheKeyDependency", "GetCacheKey", e.ToString());
}
}
// use this object to build the dependency
string key = Name.Trim();
if (!key.StartsWith("@"))
{
key = "@" + key;
}
cacheKey = Regex.Replace(cacheKey, key, result ?? string.Empty, RegexOptions.IgnoreCase);
}
if (string.IsNullOrEmpty(cacheKey))
{
// could not find a suitable cacheKey from the parameters, build a default key
cacheKey = "Adxstudio:{0}:ID={1}".FormatWith(control.GetType().FullName, control.ID);
// provide an opportunity to override this suggested default
if (getDefaultKey != null)
{
cacheKey = getDefaultKey(cacheKey);
}
}
if (VaryByUser)
{
IIdenreplacedy idenreplacedy;
if (TryGetCurrentIdenreplacedy(out idenreplacedy) && idenreplacedy.IsAuthenticated)
{
cacheKey += ":Idenreplacedy={0}".FormatWith(idenreplacedy.Name);
}
}
if (!string.IsNullOrEmpty(VaryByParam))
{
foreach (string section in VaryByParam.Split(_varySeparator))
{
string param = section.Trim();
cacheKey += ":{0}={1}".FormatWith(param, context.Request[param]);
}
}
return cacheKey;
}
19
View Source File : StringUtilities.cs
License : MIT License
Project Creator : AdrianWilczynski
License : MIT License
Project Creator : AdrianWilczynski
public static string NormalizeNewLine(this string text)
=> Regex.Replace(text, @"\r?\n", NewLine);
19
View Source File : TypeExtensions.cs
License : MIT License
Project Creator : adrianoc
License : MIT License
Project Creator : adrianoc
public static string ReflectionTypeName(this ITypeSymbol type, out IList<string> typeParameters)
{
if (type is INamedTypeSymbol namedType && namedType.IsGenericType) //TODO: namedType.IsUnboundGenericType ? Open
{
typeParameters = namedType.TypeArguments.Select(typeArg => typeArg.FullyQualifiedName()).ToArray();
return Regex.Replace(namedType.ConstructedFrom.ToString(), "<.*>", "`" + namedType.TypeArguments.Length );
}
typeParameters = Array.Empty<string>();
return type.FullyQualifiedName();
}
19
View Source File : ConvertEditLinksFilter.cs
License : Apache License 2.0
Project Creator : advanced-cms
License : Apache License 2.0
Project Creator : advanced-cms
private string ReplaceImages(string html)
{
const string pattern = "<img.*?src=[\"'](.+?)[\"'].*?>";
html = Regex.Replace(html, pattern, x =>
{
if (x.Groups.Count == 1)
{
return x.Value;
}
var imgSrc = x.Groups[1];
var editUrl = imgSrc.Value;
var content = _urlResolver.Route(new UrlBuilder(editUrl), ContextMode.Edit);
if (content == null)
{
return x.Value;
}
var viewUrl = _urlResolver.GetUrl(content.ContentLink, content.LanguageBranch(), new VirtualPathArguments
{
ContextMode = ContextMode.Default
});
var groupStart = imgSrc.Index - x.Index;
var groupEnd = groupStart + imgSrc.Length;
return x.Value.Substring(0, groupStart - 1) + viewUrl + x.Value.Substring(groupEnd + 1);
});
return html;
}
19
View Source File : DiscordManager.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public static void UpdateStatus()
{
if (!canUpdate)
{
return;
}
if (!PhotonNetwork.inRoom)
{
if (PhotonNetwork.InsideLobby)
{
_presence.state = "In lobby: " + Regex.Replace(PhotonNetwork.ServerAddress, "app\\-|\\.exitgamescloud\\.com|\\:\\d+", "").ToUpper().Replace("WS://", "").Replace("WSS://", "");
switch (PhotonNetwork.ServerAddress.Split(':')[0])
{
case "142.44.242.29":
_presence.state = "In lobby: USA";
break;
case "135.125.239.180":
_presence.state = "In lobby: Europe";
break;
case "51.79.164.137":
_presence.state = "In lobby: Asia";
break;
case "172.107.193.233":
_presence.state = "In lobby: South America";
break;
default:
break;
}
_presence.partySize = 0;
_presence.partyMax = 0;
_presence.largeImageKey = "anarchyicon";
}
else if (IN_GAME_MAIN_CAMERA.GameType != GameType.Stop)
{
_presence.state = "Solo: " + FengGameManagerMKII.Level.Name;
_presence.partySize = 0;
_presence.partyMax = 0;
_presence.largeImageKey = FengGameManagerMKII.Level.DiscordName;
_presence.largeImageText = FengGameManagerMKII.Level.Name;
}
else
{
_presence.state = "In menu";
_presence.partySize = 0;
_presence.partyMax = 0;
_presence.largeImageKey = "anarchyicon";
}
}
else
{
var text = PhotonNetwork.room.Name.Split('`')[0].RemoveHex();
_presence.state = "Multiplayer: " + ((text.Length > 30) ? (text.Remove(27) + "...") : text);
_presence.partySize = PhotonNetwork.room.PlayerCount;
_presence.partyMax = PhotonNetwork.room.MaxPlayers;
_presence.largeImageKey = FengGameManagerMKII.Level.DiscordName;
_presence.largeImageText = FengGameManagerMKII.Level.Name;
}
DiscordRPC.UpdatePresence(_presence);
}
19
View Source File : DiscordSDK.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public void UpdateStatus()
{
if (!PhotonNetwork.inRoom)
{
if (PhotonNetwork.InsideLobby)
{
_Activity.State = "In lobby: " + Regex.Replace(PhotonNetwork.ServerAddress, "app\\-|\\.exitgamescloud\\.com|\\:\\d+", "").ToUpper().Replace("WS://", "").Replace("WSS://", "");
_Activity.Party.Size.CurrentSize = 0;
_Activity.Party.Size.MaxSize = 0;
_Activity.replacedets.LargeImage = "anarchyicon";
}
else if (IN_GAME_MAIN_CAMERA.GameType != GameType.Stop)
{
_Activity.State = "Solo: " + FengGameManagerMKII.Level.Name;
_Activity.Party.Size.CurrentSize = 0;
_Activity.Party.Size.MaxSize = 0;
_Activity.replacedets.LargeImage = FengGameManagerMKII.Level.DiscordName;
_Activity.replacedets.LargeText = FengGameManagerMKII.Level.Name;
}
else
{
_Activity.State = "In menu";
_Activity.Party.Size.CurrentSize = 0;
_Activity.Party.Size.MaxSize = 0;
_Activity.replacedets.LargeImage = "anarchyicon";
}
}
else
{
var text = PhotonNetwork.room.Name.Split('`')[0].RemoveHex();
_Activity.State = "Multiplayer: " + ((text.Length > 30) ? (text.Remove(27) + "...") : text);
_Activity.Party.Size.CurrentSize = PhotonNetwork.room.PlayerCount;
_Activity.Party.Size.MaxSize = PhotonNetwork.room.MaxPlayers;
_Activity.replacedets.LargeImage = FengGameManagerMKII.Level.DiscordName;
_Activity.replacedets.LargeText = FengGameManagerMKII.Level.Name;
}
_ActivityManager.UpdateActivity(_Activity, (result) =>
{
if (result != SDK.Result.Ok)
{
Debug.Log("Failed to update Activity.");
}
});
}
19
View Source File : Form_SteamID64_Editor.cs
License : MIT License
Project Creator : Aemony
License : MIT License
Project Creator : Aemony
private void textBoxSteamID64_New_TextChanged(object sender, EventArgs e)
{
textBoxSteamID64_New.Text = Regex.Replace(textBoxSteamID64_New.Text, @"[^\d]", "");
if (UInt64.TryParse(textBoxSteamID64_New.Text, out UInt64 unused) == true)
{
toolStripStatusLabel1.Text = lastStatus;
if (textBoxSteamID64_New.Text.Length > 0)
{
// Update the Steam Community link
linkLabelSteamID64_New.Links.Clear();
LinkLabel.Link linkSteamCommunityProfile_New = new LinkLabel.Link(0, 0, "http://steamcommunity.com/profiles/" + textBoxSteamID64_New.Text);
linkLabelSteamID64_New.Links.Add(linkSteamCommunityProfile_New);
linkLabelSteamID64_New.Enabled = true;
}
else
{
linkLabelSteamID64_New.Links.Clear();
linkLabelSteamID64_New.Enabled = false;
}
// Check if a current file is loaded
if (String.IsNullOrWhiteSpace(textBoxSteamID64_New.Text) == false && String.IsNullOrWhiteSpace(filePath) == false && textBoxSteamID64_New.Text != textBoxSteamID64.Text)
{
buttonUpdate.Enabled = true;
}
else
{
buttonUpdate.Enabled = false;
}
} else {
buttonUpdate.Enabled = false;
linkLabelSteamID64_New.Enabled = false;
}
}
19
View Source File : AG0022DoNotExposeBothSyncAndAsyncVersionsOfMethods.cs
License : Apache License 2.0
Project Creator : agoda-com
License : Apache License 2.0
Project Creator : agoda-com
private static void replacedyzeNode(SyntaxNodereplacedysisContext context)
{
if (!(context.Node is MethodDeclarationSyntax methodDeclarationSyntax))
{
return;
}
// ensure public method or interface specification
if (!(methodDeclarationSyntax.Modifiers.Any(SyntaxKind.PublicKeyword)
|| methodDeclarationSyntax.Parent.IsKind(SyntaxKind.InterfaceDeclaration)))
{
return;
}
// ensure method is async in intent
var methodDeclaration = (IMethodSymbol) context.SemanticModel.GetDeclaredSymbol(context.Node);
if (!AsyncHelpers.IsAsyncIntent(methodDeclaration))
{
return;
}
// find other methods with matching names
var targetName = MatchAsyncMethod.Replace(methodDeclarationSyntax.Identifier.Text, "");
var matchingMethods = methodDeclarationSyntax.Parent.ChildNodes()
.OfType<MethodDeclarationSyntax>()
.Where(methodSyntax => methodSyntax != context.Node)
.Where(methodSyntax => methodSyntax.Identifier.Text == targetName);
// if any of these methods are sync then report
foreach (var methodSyntax in matchingMethods)
{
var methodSymbol = context.SemanticModel.GetDeclaredSymbol(methodSyntax);
if (!AsyncHelpers.IsAsyncIntent(methodSymbol))
{
context.ReportDiagnostic(Diagnostic.Create(Descriptor, methodSyntax.GetLocation()));
}
}
}
19
View Source File : TrjMediaProvider.cs
License : MIT License
Project Creator : aguang-xyz
License : MIT License
Project Creator : aguang-xyz
public async Task<IEnumerable<Episode>> GetEpisodesAsync(string word)
{
var html = await GetApi().GetSearchPageAsync(word, string.Empty).AsHtmlAsync();
var vodList = html.SelectNodes(XPaths.Search.VodList).FirstOrDefault();
if (vodList == null)
{
return Array.Empty<Episode>();
}
var items = HtmlNode.CreateNode(vodList.OuterHtml).SelectNodes(XPaths.Search.Item);
if (items == null)
{
return Array.Empty<Episode>();
}
var episodes = new List<Episode>();
foreach (var node in items.Select(item => HtmlNode.CreateNode(item.OuterHtml)))
{
var linkNode = node.SelectSingleNode(XPaths.Search.ItemLink);
if (linkNode == null)
{
continue;
}
var replacedle = linkNode.Attributes["replacedle"].Value;
var url = linkNode.Attributes["href"].Value;
if (!int.TryParse(Regex.Replace(url, @"(^/vod/detail/id/|\.html$)", string.Empty), out var externalId))
{
continue;
}
var imageNode = node.SelectSingleNode(XPaths.Search.ItemImageLink);
if (imageNode == null)
{
continue;
}
var imageUrl = imageNode.Attributes["data-original"].Value;
if (!(imageUrl.StartsWith("http:") || imageUrl.StartsWith("https:")))
{
imageUrl = $"https://{Host}{imageUrl}";
}
episodes.Add(new Episode
{
ProviderId = ProviderId,
ExternalId = externalId.ToString(),
replacedle = replacedle,
ImageUrl = imageUrl
});
}
return episodes;
}
19
View Source File : MainWindow.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb
License : GNU Affero General Public License v3.0
Project Creator : aianlinb
private void OnRecoveryClicked(object sender, RoutedEventArgs e) {
if (new VersionSelector().ShowDialog() != true) return;
var bkg = new BackgroundDialog();
var rtn = (RecordTreeNode)((TreeViewItem)Tree.SelectedItem).Tag;
Task.Run(() => {
try {
string PatchServer = null;
var indexUrl = SelectedVersion switch {
1 => (PatchServer = GetPatchServer()) + "Bundles2/_.index.bin",
2 => (PatchServer = GetPatchServer(true)) + "Bundles2/_.index.bin",
3 => "http://poesmoother.eu/owncloud/index.php/s/1VsY1uYOBmfDcMy/download",
_ => null
};
if (SelectedVersion == 3) {
var outsideBundles2 = true;
var tmp = rtn;
do {
if (tmp == ggpkContainer.FakeBundles2)
outsideBundles2 = false;
tmp = tmp.Parent;
} while (tmp != null);
if (outsideBundles2) {
Dispatcher.Invoke(() => {
MessageBox.Show(this, "Tencent version currently only support recovering files under \"Bundles2\" directory!", "Unsupported", MessageBoxButton.OK, MessageBoxImage.Error);
bkg.Close();
});
return;
}
}
var l = new List<IFileRecord>();
GGPKContainer.RecursiveFileList(rtn, l);
bkg.ProgressText = "Recovering {0}/" + l.Count.ToString() + " Files . . .";
if (http == null) {
http = new() {
Timeout = Timeout.InfiniteTimeSpan
};
http.DefaultRequestHeaders.Add("User-Agent", "VisualGGPK2");
}
IndexContainer i = null;
if (l.Any((ifr) => ifr is BundleFileNode)) {
var br = new BinaryReader(new MemoryStream(http.GetByteArrayAsync(indexUrl).Result));
i = new IndexContainer(br);
br.Close();
}
foreach (var f in l) {
if (f is BundleFileNode bfn) {
var bfr = bfn.BundleFileRecord;
var newbfr = i.FindFiles[bfr.NameHash];
bfr.Offset = newbfr.Offset;
bfr.Size = newbfr.Size;
if (bfr.BundleIndex != newbfr.BundleIndex) {
bfr.BundleIndex = newbfr.BundleIndex;
bfr.bundleRecord.Files.Remove(bfr);
bfr.bundleRecord = ggpkContainer.Index.Bundles[bfr.BundleIndex];
bfr.bundleRecord.Files.Add(bfr);
}
} else {
var fr = f as FileRecord;
var path = Regex.Replace(fr.GetPath(), "^ROOT/", "");
fr.ReplaceContent(http.GetByteArrayAsync(PatchServer + path).Result);
}
bkg.NextProgress();
}
if (i != null)
if (SteamMode)
ggpkContainer.Index.Save("_.index.bin");
else
ggpkContainer.IndexRecord.ReplaceContent(ggpkContainer.Index.Save());
Dispatcher.Invoke(() => {
MessageBox.Show(this, "Recoveried " + l.Count.ToString() + " Files", "Done", MessageBoxButton.OK, MessageBoxImage.Information);
bkg.Close();
OnTreeSelectedChanged(null, null);
});
} catch (Exception ex) {
App.HandledException(ex);
Dispatcher.Invoke(bkg.Close);
}
}
19
View Source File : MainWindow.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb
License : GNU Affero General Public License v3.0
Project Creator : aianlinb
public static void BatchConvertPng(IEnumerable<KeyValuePair<IFileRecord, string>> list, Action ProgressStep = null) {
var regex = new Regex(".dds$");
LibBundle.Records.BundleRecord br = null;
MemoryStream ms = null;
var failBundles = 0;
var failFiles = 0;
foreach (var (record, path) in list) {
Directory.CreateDirectory(Directory.GetParent(path).FullName);
if (record is BundleFileNode bfn) {
if (br != bfn.BundleFileRecord.bundleRecord) {
ms?.Close();
br = bfn.BundleFileRecord.bundleRecord;
br.Read(bfn.ggpkContainer.Reader, bfn.ggpkContainer.RecordOfBundle(br)?.DataBegin);
ms = br.Bundle?.Read(bfn.ggpkContainer.Reader);
if (ms == null)
++failBundles;
}
if (ms == null)
++failFiles;
else {
var bs = DdsToPng(new MemoryStream(bfn.BatchReadFileContent(ms)));
BitmapSourceSave(bs, regex.Replace(path, ".png"));
}
} else {
var bs = DdsToPng(new MemoryStream(record.ReadFileContent()));
BitmapSourceSave(bs, regex.Replace(path, ".png"));
}
ProgressStep?.Invoke();
}
if (failBundles != 0 || failFiles != 0)
throw new GGPKContainer.BundleMissingException(failBundles, failFiles);
}
19
View Source File : APIProxyService.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
public async Task<string> Get(AiurUrl url, bool forceHttp = false, bool autoRetry = true)
{
if (forceHttp && !url.IsLocalhost())
{
url.Address = _regex.Replace(url.Address, "http://");
}
var request = new HttpRequestMessage(HttpMethod.Get, url.ToString())
{
Content = new FormUrlEncodedContent(new Dictionary<string, string>())
};
request.Headers.Add("X-Forwarded-Proto", "https");
request.Headers.Add("accept", "application/json, text/html");
using var response = autoRetry ? await SendWithRetry(request) : await _client.SendAsync(request);
var content = await response.Content.ReadreplacedtringAsync();
if (content.IsValidJson())
{
return content;
}
else
{
if (response.IsSuccessStatusCode)
{
throw new InvalidOperationException($"The {nameof(APIProxyService)} can only handle JSON content while the remote server returned unexpected content: {content.OTake(100)}.");
}
else
{
throw new WebException($"The remote server returned unexpected content: {content.OTake(100)}. code: {response.StatusCode} - {response.ReasonPhrase}.");
}
}
}
19
View Source File : APIProxyService.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
public async Task<string> Post(AiurUrl url, AiurUrl postDataStr, bool forceHttp = false, bool autoRetry = true)
{
if (forceHttp && !url.IsLocalhost())
{
url.Address = _regex.Replace(url.Address, "http://");
}
var request = new HttpRequestMessage(HttpMethod.Post, url.ToString())
{
Content = new FormUrlEncodedContent(postDataStr.Params)
};
request.Headers.Add("X-Forwarded-Proto", "https");
request.Headers.Add("accept", "application/json");
using var response = autoRetry ? await SendWithRetry(request) : await _client.SendAsync(request);
var content = await response.Content.ReadreplacedtringAsync();
if (content.IsValidJson())
{
return content;
}
else
{
if (response.IsSuccessStatusCode)
{
throw new InvalidOperationException($"The {nameof(APIProxyService)} can only handle JSON content while the remote server returned unexpected content: {content.OTake(100)}.");
}
else
{
throw new WebException($"The remote server returned unexpected content: {content.OTake(100)}. code: {response.StatusCode} - {response.ReasonPhrase}.");
}
}
}
19
View Source File : APIProxyService.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
public async Task<string> PostWithFile(AiurUrl url, Stream fileStream, bool forceHttp = false, bool autoRetry = true)
{
if (forceHttp && !url.IsLocalhost())
{
url.Address = _regex.Replace(url.Address, "http://");
}
var request = new HttpRequestMessage(HttpMethod.Post, url.Address)
{
Content = new MultipartFormDataContent
{
{ new StreamContent(fileStream), "file", "file" }
}
};
request.Headers.Add("X-Forwarded-Proto", "https");
request.Headers.Add("accept", "application/json");
using var response = autoRetry ? await SendWithRetry(request) : await _client.SendAsync(request);
var content = await response.Content.ReadreplacedtringAsync();
if (content.IsValidJson())
{
return content;
}
else
{
if (response.IsSuccessStatusCode)
{
throw new InvalidOperationException($"The {nameof(APIProxyService)} can only handle JSON content while the remote server returned unexpected content: {content.OTake(100)}.");
}
else
{
throw new WebException($"The remote server returned unexpected content: {content.OTake(100)}. code: {response.StatusCode} - {response.ReasonPhrase}.");
}
}
}
19
View Source File : ToSlug.cs
License : MIT License
Project Creator : akasarto
License : MIT License
Project Creator : akasarto
public static string ToSlug(this string @this)
{
var wordSepparator = "-";
if (string.IsNullOrWhiteSpace(@this))
{
return @this;
}
var filtered = @this.FilterSpecialChars(replacer: " ").ToLower();
var slug = MultiWhiteSpaces.Replace(filtered, wordSepparator);
return slug.Trim(wordSepparator.ToCharArray());
}
19
View Source File : SplitJsCommandHandler.cs
License : MIT License
Project Creator : akinix
License : MIT License
Project Creator : akinix
public async Task Handle(SplitJsCommand command, CancellationToken cancellationToken)
{
var content = await File.ReadAllTextAsync(command.TempJsName, cancellationToken);
// 获取除香港澳门台湾的省市区
var matches = content.TrimEnd(';').Split("\"A-G\"");
matches = matches[1].Split(";return t=e}(),r=function(t){var e=");
var strProvince = "{\"A-G\"" + matches[0];
var strArear = matches[1].Rtrim("return t=e}(),c=function(t){var e=").Rtrim(";");
// 获取港澳台马其他
matches = matches[1].Split("return t=e}(),h=function(e)");
Regex reg = new Regex(@",[a-zA-Z]=function");
var other = reg.Replace(matches[0].Ltrim("return t=e}(),c=function(t){var e="), ",o=function").Split(";return t=e}(),o=function(t){var e="); // [0]港澳 [1]台湾 [2]马来西亚 [3]欧美
var strGangAo = other[0];
var strTaiwan = other[1];
// 有些城市无区县 但是有街道
var strNoneDistrictCity = matches[1].Ltrim("get(\"district\"),u=").Rtrim(",v=t.inArray");
_areaContextService.SetProvinceString(strProvince);
_areaContextService.SetAreaString(strArear);
_areaContextService.SetGangAoString(strGangAo);
_areaContextService.SetTaiwanString(strTaiwan);
_areaContextService.SetNoneDistrictCityString(strNoneDistrictCity);
// 触发拆分js完成事件
await _mediator.Publish(new SplitJsCompletedEvent(), cancellationToken);
}
19
View Source File : DownloadStreetDataJob.cs
License : MIT License
Project Creator : akinix
License : MIT License
Project Creator : akinix
private string replacedysis(string str)
{
//json不支持引号,去除拼音等
var temp = str.Ltrim("success:true,result:").Rtrim("});");
temp = Regex.Replace(temp, "[a-zA-Z]+", "").Replace(" ", "").Replace(",''", "")
.Replace("'", "\"");
return temp;
}
19
View Source File : TechLogItem.cs
License : MIT License
Project Creator : akpaevj
License : MIT License
Project Creator : akpaevj
private string GetCleanSql(string data)
{
if (string.IsNullOrEmpty(data))
return "";
else
{
// Remove parameters
int startIndex = data.IndexOf("sp_executesql", StringComparison.OrdinalIgnoreCase);
if (startIndex < 0)
startIndex = 0;
else
startIndex += 16;
int e1 = data.IndexOf("', N'@P", StringComparison.OrdinalIgnoreCase);
if (e1 < 0)
e1 = data.Length;
var e2 = data.IndexOf("p_0:", StringComparison.OrdinalIgnoreCase);
if (e2 < 0)
e2 = data.Length;
var endIndex = Math.Min(e1, e2);
// Remove temp table names, parameters and guids
var result = Regex.Replace(data[startIndex..endIndex], @"(#tt\d+|@P\d+|\d{8}-\d{4}-\d{4}-\d{4}-\d{12})", "{RD}", RegexOptions.ExplicitCapture);
return result;
}
}
19
View Source File : MixtureNodeView.cs
License : MIT License
Project Creator : alelievr
License : MIT License
Project Creator : alelievr
protected bool MaterialPropertiesGUI(Material material, bool fromInspector, bool autoLabelWidth = true)
{
if (material == null || material.shader == null)
return false;
if (autoLabelWidth)
{
EditorGUIUtility.wideMode = false;
EditorGUIUtility.labelWidth = nodeTarget.nodeWidth / 3.0f;
}
MaterialProperty[] properties = MaterialEditor.GetMaterialProperties(new []{material});
var portViews = GetPortViewsFromFieldName(nameof(ShaderNode.materialInputs));
MaterialEditor editor;
if (!materialEditors.TryGetValue(material, out editor))
{
foreach (var replacedembly in AppDomain.CurrentDomain.Getreplacedemblies())
{
var editorType = replacedembly.GetType("UnityEditor.MaterialEditor");
if (editorType != null)
{
editor = materialEditors[material] = Editor.CreateEditor(material, editorType) as MaterialEditor;
MixturePropertyDrawer.RegisterEditor(editor, this, owner.graph);
break ;
}
}
}
bool propertiesChanged = CheckPropertyChanged(material, properties);
foreach (var property in properties)
{
if ((property.flags & (MaterialProperty.PropFlags.HideInInspector | MaterialProperty.PropFlags.PerRendererData)) != 0)
continue;
int idx = material.shader.FindPropertyIndex(property.name);
var propertyAttributes = material.shader.GetPropertyAttributes(idx);
if (!fromInspector && propertyAttributes.Contains("ShowInInspector"))
continue;
// Retrieve the port view from the property name
var portView = portViews?.FirstOrDefault(p => p.portData.identifier == property.name);
if (portView != null && portView.connected)
continue;
// We only display textures that are excluded from the filteredOutProperties (i.e they are not exposed as ports)
if (property.type == MaterialProperty.PropType.Texture && nodeTarget is ShaderNode sn)
{
if (!sn.GetFilterOutProperties().Contains(property.name))
continue;
}
// TODO: cache to improve the performance of the UI
var visibleIfAtribute = propertyAttributes.FirstOrDefault(s => s.Contains("VisibleIf"));
if (!string.IsNullOrEmpty(visibleIfAtribute))
{
var match = visibleIfRegex.Match(visibleIfAtribute);
if (match.Success)
{
string propertyName = match.Groups[1].Value;
string[] accpectedValues = match.Groups[2].Value.Split(',');
if (material.HasProperty(propertyName))
{
float f = material.GetFloat(propertyName);
bool show = false;
foreach (var value in accpectedValues)
{
float f2 = float.Parse(value);
if (f == f2)
show = true;
}
if (!show)
continue;
}
else
continue;
}
}
// Hide all the properties that are not supported in the current dimension
var currentDimension = nodeTarget.settings.GetResolvedTextureDimension(owner.graph);
string displayName = property.displayName;
bool is2D = displayName.Contains(MixtureUtils.texture2DPrefix);
bool is3D = displayName.Contains(MixtureUtils.texture3DPrefix);
bool isCube = displayName.Contains(MixtureUtils.textureCubePrefix);
if (is2D || is3D || isCube)
{
if (currentDimension == TextureDimension.Tex2D && !is2D)
continue;
if (currentDimension == TextureDimension.Tex3D && !is3D)
continue;
if (currentDimension == TextureDimension.Cube && !isCube)
continue;
displayName = Regex.Replace(displayName, @"_2D|_3D|_Cube", "", RegexOptions.IgnoreCase);
}
// In ShaderGraph we can put [Inspector] in the name of the property to show it only in the inspector and not in the node
if (property.displayName.ToLower().Contains("[inspector]"))
{
if (fromInspector)
displayName = Regex.Replace(property.displayName, @"\[inspector\]\s*", "", RegexOptions.IgnoreCase);
else
continue;
}
float h = editor.GetPropertyHeight(property, displayName);
// We always display textures on a single line without scale or offset because they are not supported
if (property.type == MaterialProperty.PropType.Texture)
h = EditorGUIUtility.singleLineHeight;
Rect r = EditorGUILayout.GetControlRect(true, h);
if (property.name.Contains("Vector2"))
property.vectorValue = (Vector4)EditorGUI.Vector2Field(r, displayName, (Vector2)property.vectorValue);
else if (property.name.Contains("Vector3"))
property.vectorValue = (Vector4)EditorGUI.Vector3Field(r, displayName, (Vector3)property.vectorValue);
else if (property.type == MaterialProperty.PropType.Range)
{
if (material.shader.GetPropertyAttributes(idx).Any(a => a.Contains("IntRange")))
property.floatValue = EditorGUI.IntSlider(r, displayName, (int)property.floatValue, (int)property.rangeLimits.x, (int)property.rangeLimits.y);
else
property.floatValue = EditorGUI.Slider(r, displayName, property.floatValue, property.rangeLimits.x, property.rangeLimits.y);
}
else if (property.type == MaterialProperty.PropType.Texture)
property.textureValue = (Texture)EditorGUI.ObjectField(r, displayName, property.textureValue, typeof(Texture), false);
else
editor.ShaderProperty(r, property, displayName);
}
return propertiesChanged;
}
19
View Source File : BaseNodeView.cs
License : MIT License
Project Creator : alelievr
License : MIT License
Project Creator : alelievr
internal void SyncSerializedPropertyPathes()
{
int nodeIndex = owner.graph.nodes.FindIndex(n => n == nodeTarget);
// If the node is not found, then it means that it has been deleted from serialized data.
if (nodeIndex == -1)
return;
var nodeIndexString = nodeIndex.ToString();
foreach (var propertyField in this.Query<PropertyField>().ToList())
{
propertyField.Unbind();
// The property path look like this: nodes.Array.data[x].fieldName
// And we want to update the value of x with the new node index:
propertyField.bindingPath = s_ReplaceNodeIndexPropertyPath.Replace(propertyField.bindingPath, m => m.Groups[1].Value + nodeIndexString + m.Groups[3].Value);
propertyField.Bind(owner.serializedGraph);
}
}
19
View Source File : MixtureNode.cs
License : MIT License
Project Creator : alelievr
License : MIT License
Project Creator : alelievr
protected IEnumerable< PortData > GetMaterialPortDatas(Material material)
{
if (material == null)
yield break;
var currentDimension = settings.GetResolvedTextureDimension(graph);
var s = material.shader;
for (int i = 0; i < material.shader.GetPropertyCount(); i++)
{
var flags = s.GetPropertyFlags(i);
var name = s.GetPropertyName(i);
var displayName = s.GetPropertyDescription(i);
var type = s.GetPropertyType(i);
var tooltip = s.GetPropertyAttributes(i).Where(s => s.Contains("Tooltip")).FirstOrDefault();
// Inspector only properties aren't available as ports.
if (displayName.ToLower().Contains("[inspector]"))
continue;
if (tooltip != null)
{
// Parse tooltip:
var m = tooltipRegex.Match(tooltip);
tooltip = m.Groups[1].Value;
}
if ((flags & ShaderPropertyFlags.HideInInspector) != 0
|| (flags & ShaderPropertyFlags.NonModifiableTextureData) != 0
|| (flags & ShaderPropertyFlags.PerRendererData) != 0)
continue;
if (!PropertySupportsDimension(s.GetPropertyName(i), currentDimension))
continue;
// We don't display textures specific to certain dimensions if the node isn't in this dimension.
if (type == ShaderPropertyType.Texture)
{
bool is2D = displayName.EndsWith(MixtureUtils.texture2DPrefix);
bool is3D = displayName.EndsWith(MixtureUtils.texture3DPrefix);
bool isCube = displayName.EndsWith(MixtureUtils.textureCubePrefix);
if (is2D || is3D || isCube)
{
if (currentDimension == TextureDimension.Tex2D && !is2D)
continue;
if (currentDimension == TextureDimension.Tex3D && !is3D)
continue;
if (currentDimension == TextureDimension.Cube && !isCube)
continue;
displayName = Regex.Replace(displayName, @"_2D|_3D|_Cube", "", RegexOptions.IgnoreCase);
}
}
yield return new PortData{
identifier = name,
displayName = displayName,
displayType = GetPropertyType(s, i),
tooltip = tooltip,
};
}
}
19
View Source File : CSharpProjectGenerator.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
protected override bool GenerateProjectFiles(string location)
{
try
{
string templateDir = Path.Combine(Application.StartupPath, "Templates");
string templateFile = Path.Combine(templateDir, "csproj.template");
string projectFile = Path.Combine(location, RelativeProjectFileName);
using (StreamReader reader = new StreamReader(templateFile))
using (StreamWriter writer = new StreamWriter(
projectFile, false, reader.CurrentEncoding))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
line = line.Replace("${RootNamespace}", RootNamespace);
line = line.Replace("${replacedemblyName}", replacedemblyName);
if (line.Contains("${DotNetVersion}"))
{
line = Regex.Replace(line, @"\${DotNetVersion}", EnumExtensions.GetDescription(dotNetVersion));
if (line.Length == 0)
continue;
}
if (line.Contains("${SourceFile}"))
{
foreach (string fileName in FileNames)
{
if ((new Regex(@"\.cs$").IsMatch(fileName)))
{
string newLine = line.Replace("${SourceFile}", fileName);
writer.WriteLine(newLine);
}
}
}
else if (line.Contains("${HbmXmlFile}"))
{
foreach (string fileName in FileNames)
{
if ((new Regex(@"\.hbm\.xml$").IsMatch(fileName)))
{
string newLine = line.Replace("${HbmXmlFile}", fileName);
writer.WriteLine(newLine);
}
}
}
else if (line.Contains("${OtherFile}"))
{
foreach (string fileName in FileNames)
{
if (!(new Regex(@"\.hbm\.xml$|\.cs$").IsMatch(fileName)))
{
string newLine = line.Replace("${OtherFile}", fileName);
writer.WriteLine(newLine);
}
}
}
else
{
writer.WriteLine(line);
}
}
}
return true;
}
catch
{
return false;
}
}
19
View Source File : ReplaceExtensions.cs
License : MIT License
Project Creator : alfa-laboratory
License : MIT License
Project Creator : alfa-laboratory
public static string ReplaceVariables(this VariableController variableController, string str, string pattern, Func<object, string> foundReplace = null!, Func<object, string> notFoundReplace = null!)
{
object val;
var fmt = Regex.Replace(
str ?? string.Empty,
pattern,
m =>
{
if (m.Groups[1].Value.Length <= 0 || m.Groups[1].Value[0] == '(')
{
return $"{m.Groups[1].Value}";
}
var variable = m.Groups[1].Value;
var (methodName, parameters) = ReplaceMethodsExtension.GetFunction(variable);
if (methodName is null)
{
if (variableController.GetVariable(variable) is null)
{
return notFoundReplace != null ? notFoundReplace(variable) : variable;
}
val = variableController.GetVariableValue(variable);
return (foundReplace != null ? foundReplace(val) : val.ToString())!;
}
var _params = Array.Empty<string>();
if(parameters is not null)
{
_params = new string[parameters.Length];
if (parameters.Any())
{
for(var i = 0; i < parameters.Length; i++)
{
if (variableController.GetVariable(parameters[i]) is null)
{
_params[i] = notFoundReplace != null ? notFoundReplace(parameters[i]) : parameters[i];
}
else
{
_params[i] = variableController.GetVariableValueText(parameters[i]);
}
}
}
}
var function = ReplaceMethodsExtension.Check(methodName);
if(function.GetParameters().Length != _params.Length)
{
return notFoundReplace != null ? notFoundReplace(variable) : variable;
}
var funcVal = ReplaceMethodsExtension.Invoke(methodName, _params);
return (foundReplace != null ? foundReplace(funcVal) : funcVal.ToString())!;
}
19
View Source File : LinkHelper.cs
License : Apache License 2.0
Project Creator : allure-framework
License : Apache License 2.0
Project Creator : allure-framework
public static void UpdateLinks(IEnumerable<Link> links, HashSet<string> patterns)
{
foreach (var linkTypeGroup in links
.Where(l => !string.IsNullOrWhiteSpace(l.type))
.GroupBy(l => l.type))
{
var typePattern = $"{{{linkTypeGroup.Key}}}";
var linkPattern = patterns.FirstOrDefault(x =>
x.IndexOf(typePattern, StringComparison.CurrentCultureIgnoreCase) >= 0);
if (linkPattern != null)
{
var linkArray = linkTypeGroup.ToArray();
for (var i = 0; i < linkArray.Length; i++)
{
var replacedLink = Regex.Replace(linkPattern, typePattern, linkArray[i].url ?? string.Empty,
RegexOptions.IgnoreCase);
linkArray[i].url = Uri.EscapeUriString(replacedLink);
}
}
}
}
19
View Source File : StringHelper.cs
License : MIT License
Project Creator : alonsoalon
License : MIT License
Project Creator : alonsoalon
public static string Format(string str, object obj)
{
if (str.IsNull())
{
return str;
}
string s = str;
if (obj.GetType().Name == "JObject")
{
foreach (var item in (Newtonsoft.Json.Linq.JObject)obj)
{
var k = item.Key.ToString();
var v = item.Value.ToString();
s = Regex.Replace(s, "\\{" + k + "\\}", v, RegexOptions.IgnoreCase);
}
}
else
{
foreach (System.Reflection.PropertyInfo p in obj.GetType().GetProperties())
{
var xx = p.Name;
var yy = p.GetValue(obj).ToString();
s = Regex.Replace(s, "\\{" + xx + "\\}", yy, RegexOptions.IgnoreCase);
}
}
return s;
}
19
View Source File : ConverterService.cs
License : GNU General Public License v3.0
Project Creator : alxnbl
License : GNU General Public License v3.0
Project Creator : alxnbl
public string ExtractImagesToResourceFolder(Page page, string mdFileContent, string resourceFolderPath, string mdFilePath, bool joplinResourceRef, bool postProcessingMdImgRef)
{
// Search of <IMG> tags
var pageTxtModified = mdFileContent;
if (postProcessingMdImgRef)
{
pageTxtModified = Regex.Replace(mdFileContent, "<img [^>]+/>", delegate (Match match)
{
// Process an <IMG> tag
string imageTag = match.ToString();
// http://regexstorm.net/tester
string regexImgAttributes = "<img src=\"(?<src>[^\"]+)\".* />";
MatchCollection matchs = Regex.Matches(imageTag, regexImgAttributes, RegexOptions.IgnoreCase);
Match imgMatch = matchs[0];
var padDocImgPath = imgMatch.Groups["src"].Value;
var imgAttach = page.ImageAttachements.Where(img => img.PanDocFilePath == padDocImgPath).FirstOrDefault();
if (imgAttach == null)
{
// Add a new attachmeent to current page
imgAttach = new Attachements(page)
{
Type = AttachementType.Image,
PanDocFilePath = padDocImgPath,
};
imgAttach.ExportFileName = imgAttach.Id + Path.GetExtension(padDocImgPath);
imgAttach.ExportFilePath = Path.Combine(resourceFolderPath, imgAttach.ExportFileName);
page.Attachements.Add(imgAttach);
}
var attachRef = joplinResourceRef ?
$":/{imgAttach.Id}" :
GetImgMdReference(Path.GetRelativePath(Path.GetDirectoryName(mdFilePath), resourceFolderPath), imgAttach.ExportFileName);
return $"";
});
}
// Move attachements file into output ressource folder and delete tmp file
foreach (var attach in page.ImageAttachements)
{
File.Copy(attach.PanDocFilePath, attach.ExportFilePath);
File.Delete(attach.PanDocFilePath);
}
return pageTxtModified;
}
19
View Source File : ShaderMethodGenerator.cs
License : MIT License
Project Creator : Aminator
License : MIT License
Project Creator : Aminator
private static Compilation GetCompilation(Type type)
{
lock (decompiledTypes)
{
if (!decompiledTypes.TryGetValue(type, out Compilation compilation))
{
EnreplacedyHandle handle = MetadataTokenHelpers.TryAsEnreplacedyHandle(type.MetadataToken) ?? throw new InvalidOperationException();
string replacedemblyPath = type.replacedembly.Location;
if (!decompilers.TryGetValue(replacedemblyPath, out CSharpDecompiler decompiler))
{
decompiler = CreateDecompiler(replacedemblyPath);
decompilers.Add(replacedemblyPath, decompiler);
}
string sourceCode = decompiler.Decompilereplacedtring(handle);
sourceCode = AnonymousMethodDeclaringTypeDeclarationRegex.Replace(sourceCode, ShaderGenerator.AnonymousMethodDeclaringTypeName);
sourceCode = AnonymousMethodDeclarationRegex.Replace(sourceCode, $"internal void {ShaderGenerator.AnonymousMethodEntryPointName}");
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sourceCode);
IList<MetadataReference> metadataReferences = GetMetadataReferences(type.replacedembly, type.replacedembly.GetName(), typeof(object).replacedembly.GetName());
compilation = CSharpCompilation.Create("Shaderreplacedembly", new[] { syntaxTree }, metadataReferences);
decompiledTypes.Add(type, compilation);
}
return compilation;
}
}
19
View Source File : CodeGenerator.cs
License : MIT License
Project Creator : Aminator
License : MIT License
Project Creator : Aminator
public CodeCompileUnit RawClreplaced(string fileName, out string clreplacedName)
{
var root = FileSchemas[fileName];
var schemaFile = new CodeCompileUnit();
var schemaNamespace = new CodeNamespace("GltfLoader.Schema");
schemaNamespace.Imports.Add(new CodeNamespaceImport("System.Linq"));
schemaNamespace.Imports.Add(new CodeNamespaceImport("System.Runtime.Serialization"));
clreplacedName = Helpers.ToPascalCase(GltfReplacementRegex.Replace(root.replacedle, "Gltf"));
var schemaClreplaced = new CodeTypeDeclaration(clreplacedName)
{
Attributes = MemberAttributes.Public
};
if (root.AllOf != null)
{
foreach (var typeRef in root.AllOf)
{
if (typeRef.IsReference)
{
throw new NotImplementedException();
}
}
}
if (root.Properties != null)
{
foreach (var property in root.Properties)
{
AddProperty(schemaClreplaced, property.Key, property.Value);
}
}
GeneratedClreplacedes[fileName] = schemaClreplaced;
schemaNamespace.Types.Add(schemaClreplaced);
schemaFile.Namespaces.Add(schemaNamespace);
return schemaFile;
}
19
View Source File : CreditCardValidation.cs
License : MIT License
Project Creator : andrebaltieri
License : MIT License
Project Creator : andrebaltieri
public Contract<T> IsCreditCard(string val, string key, string message)
{
val = Regex.Replace(val, FluntRegexPatterns.OnlyNumbersPattern, "");
if (string.IsNullOrWhiteSpace(val))
{
AddNotification(key, message);
return this;
}
var even = false;
var checksum = 0;
foreach (var digit in val.ToCharArray().Reverse())
{
if (!char.IsDigit(digit))
{
AddNotification(val, message);
return this;
}
var value = (digit - '0') * (even ? 2 : 1);
even = !even;
while (value > 0)
{
checksum += value % 10;
value /= 10;
}
}
if (checksum % 10 != 0)
AddNotification(key, message);
return this;
}
19
View Source File : BreachedEntriesDialog.cs
License : MIT License
Project Creator : andrew-schofield
License : MIT License
Project Creator : andrew-schofield
[STAThread]
private void breachedEntryList_MouseClick(object sender, MouseEventArgs e)
{
if (breachedEntryList.SelectedItems != null && breachedEntryList.SelectedItems.Count == 1)
{
var tag = ((ItemData)breachedEntryList.SelectedItems[0].Tag);
var entry = tag.Enreplacedy;
var breach = tag.Breach;
if (breach != null)
{
var txt = breach.Description;
// "The description may include markup such as emphasis and strong tags as well as hyperlinks"
var regexNewLineHtml = new Regex(@"<\s*br.*?>|<\s*p.*?>");
txt = regexNewLineHtml.Replace(txt, Environment.NewLine);
var regexMarkup = new Regex(@"<.*?>");
txt = regexMarkup.Replace(txt, string.Empty);
// now unencode any html encoded stuff.
txt = System.Web.HttpUtility.HtmlDecode(txt);
this.breachDescriptionText.Text = txt;
}
}
}
See More Examples