I am trying to convert this code from C# to VB. Tried to use third party tools, but not successful. Can some one help me .Thanks
private static string RemoveInvalidHtmlTags(this string text)
{
return HtmlTagExpression.Replace(text, new MatchEvaluator((Match m) =>
{
if (!ValidHtmlTags.ContainsKey(m.Groups["tag"].Value))
return String.Empty;
string generatedTag = String.Empty;
System.Text.RegularExpressions.Group tagStart = m.Groups["tag_start"];
System.Text.RegularExpressions.Group tagEnd = m.Groups["tag_end"];
System.Text.RegularExpressions.Group tag = m.Groups["tag"];
System.Text.RegularExpressions.Group tagAttributes = m.Groups["attr"];
generatedTag += (tagStart.Success ? tagStart.Value : "<");
generatedTag += tag.Value;
foreach (Capture attr in tagAttributes.Captures)
{
int indexOfEquals = attr.Value.IndexOf('=');
// don't proceed any futurer if there is no equal sign or just an equal sign
if (indexOfEquals < 1)
continue;
string attrName = attr.Value.Substring(0, indexOfEquals);
// check to see if the attribute name is allowed and write attribute if it is
if (ValidHtmlTags[tag.Value].Contains(attrName))
generatedTag += " " + attr.Value;
}
// add nofollow to all hyperlinks
//if (tagStart.Success && tagStart.Value == "<" && tag.Value.Equals("a", StringComparison.OrdinalIgnoreCase))
// generatedTag += " rel=\"nofollow\"";
if (tag.Value.ToString() == "object")
{
generatedTag += (tagEnd.Success ? " height=\"374\" width=\"416\"" + tagEnd.Value : ">");
}
else
{
generatedTag += (tagEnd.Success ? tagEnd.Value : ">");
}
return generatedTag;
}));
}
The problem converting this code is that you have a lambda expression with a multi-line statement body:
(Match m) =>
{
...a lot of code
}
Since VB9 doesn't support this, you'll want to put the code in brackets into its own function instead:
Private Function GetValue(m As Match) As String
....a lot of code
End Function
Then your RemoveInvalidHtmlTags code will look like this:
Return HtmlTagExpression.Replace(text, new MatchEvaluator(AddressOf GetValue))
You can use free tools to translate the rest of the code.
Have you tried this free tool?
Related
So I would like to read out all occurrences in C# in one string and work with it. Means I need the position of the part string, but I don't know how. Example:
The main string can look like this:
Currently there are %count{"only_groups":"1, 2, 3","ignore_channels":"1, 2, 3"}% supporters online, %count{"ignore_channels":"1, 2, 3","querys":"false"}% of them are afk. These are the active supporters: %list{"querys":"false","only_groups":"1, 2, 3"}%
Contentwise this string makes no sense, but I think you can understand what I mean by these strings. There are also more possible variables besides %count% and %list%
Now I want to keep all these variables and replace something instead.
I already have the following code, but it would only replace one variable and it would only recognize the %count% variable if it is completely lower case:
int pFrom = channel_name.IndexOf("%count{") + "%count{".Length;
int pTo = channel_name.LastIndexOf("}%");
string result = channel_name.Substring(pFrom, pTo - pFrom);
Logger.Info(result);
string json2 = #"{" + result + "}";
JObject o2 = JObject.Parse(json2);
foreach (JProperty property in o2.Properties())
{
var pname = property.Name;
if (pname == "only_groups")
{
only_groups = property.Value.ToString();
}
else if (pname == "ignore_groups")
{
ignore_groups = property.Value.ToString();
}
else if (pname == "only_channels")
{
only_channels = property.Value.ToString();
}
else if (pname == "ignore_channels")
{
ignore_channels = property.Value.ToString();
}
else if (pname == "away")
{
away = property.Value.ToString();
}
else if (pname == "querys")
{
query = property.Value.ToString();
}
}
var serverVar = (await fullClient.GetServerVariables()).Value;
if (query.Equals("only"))
{
channel_name = "User online: " + serverVar.QueriesOnline;
}
else if (query.Equals("ignore"))
{
channel_name = "User online: " + (serverVar.ClientsOnline - serverVar.QueriesOnline);
}
else
{
channel_name = "User online: " + serverVar.ClientsOnline;
}
I hope people understand what I'm about to do. My English is not the best
Use Regex.Matches() to get a list of all occurences.
This pattern will find all variables including configuration json:
(?s)%.*?%
Then you just need to extract the 2 parts out of the matched value.
This will find only the variable name within the matched value:
(?s)(?<=%).+?(?=({|%))
This will find the JSON configuration within the matched value if there is any:
(?s){.*}
Only caveat is you can't use % character anywhere in text outside of variables.
My requirement is to create a web api in c# that will create another API According to the document.
User will send api name, action method name , Request and type of operation that need to be performed by the new api and our api will create the required api and return response that contain API url and request/response type.
I have searched in lot of different website but i did't found anything related to it. if anyone have solution of it or any close idea please share. i need to do this in asp.net MVC
I have a sample program that uses CodeDomCompiler that generates a standard Telemetry implementation for any given interface. The code is compiled to memory and loaded into the address space. This sounds like what you are trying to do. If so, take stab at generating some code using the samples and ask questions as you encounter problems.
This may help you get started.
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using TelemeterFactory;
namespace ConsoleTelemeter
{
/// <summary>Generate a CSharp Telemeter that calls Console.WriteLine as its output.</summary>
public class Factory : FactoryBase
{
public override string[] GenerateSource(SourceGenerationOptions options)
{
var generatedClassName = options.Type.Name + "_" + options.FactoryOptions.ClassName;
var text = this.CSharpTemplate()
.Replace("<codeGenerationTool>", $"{nameof(ConsoleTelemeter)} {Assembly.GetExecutingAssembly().GetName().Version} {DateTimeOffset.UtcNow:yyyy-MM-dd HH:mm:ss zzz}")
.Replace("<generatedNamespace>", options.FactoryOptions.Namespace)
.Replace("<generatedClassName>", generatedClassName)
.Replace("<interfaceImplemented>", options.Type.FullName)
.Replace("//<privateFields>", "private const string Null = \"<null>\";")
.Replace("//<publicMethodImplementations>", Methods(options.Methods))
.Replace("\t", " ")
;
return new[] { text, $"{options.FactoryOptions.Namespace}.{generatedClassName}" };
}
private string Methods(IReadOnlyList<MethodInfo> methods)
{
var sb = new StringBuilder(4096);
foreach (var method in methods)
{
// method start
sb.AppendFormat("\n\t\tpublic {0} {1} (", method.ReturnType, method.Name);
var comma = string.Empty;
foreach (ParameterInfo parameter in method.GetParameters())
{
sb.AppendFormat("{0}{1} {2}", comma, parameter.ParameterType, parameter.Name);
comma = ", ";
}
sb.Append(") {\n");
sb.Append("\t\t\tvar result = $\"{DateTimeOffset.UtcNow:yyyy-MM-dd HH:mm:ss.ffffff} ");
sb.Append("{nameof(");
sb.Append(method.Name);
sb.Append(")}: ");
comma = string.Empty;
foreach (ParameterInfo parameter in method.GetParameters())
{
var t = parameter.ParameterType;
sb.AppendFormat("{0}{{nameof({1})}}={{", comma, parameter.Name);
// special case for boolean parameters to be coerced to strings below. Not strictly necessary for this Telemeter but show how one could do it if necessary.
sb.AppendFormat("{1}{0}", parameter.Name, t == typeof(Boolean) ? "(" : string.Empty);
if (t == typeof(string))
{
sb.Append(" ?? Null");
}
else if (t == typeof(Int32)
|| t == typeof(float)
|| t == typeof(double)
|| t == typeof(Int64)
|| t == typeof(decimal)
|| t == typeof(Int16))
{
sb.Append(":#0");
}
else if (t.BaseType == typeof(Enum))
{
sb.Append(":D");
}
else if (t == typeof(Boolean))
{
sb.Append("? \"1\" : \"0\")");
}
else
{
sb.Append(".ToString() ?? Null");
}
sb.Append("}");
comma = ",";
}
sb.Append("\";\n\t\t\treturn result;\n");
// method end
sb.Append("\t\t}\n");
}
return sb.ToString();
}
}
}
I'm trying to check if any string entered after a certain message I do have a working version in SQL that I want to use almost the same one in C#
Usage in SQL:
ELSE IF #Msg LIKE '/Message %'
Usage in C#:
else if (Msg == "/Message ")
I want the tool to check if any string entered right after /Message.
Thanks in advance :)
You can use the following string functions:
var Msg = "A message to check";
For LIKE 'SomeText%':
if (Msg.StartsWith("SomeText"))
For LIKE '%SomeText':
if (Msg.EndsWith("SomeText"))
For LIKE '%SomeText%':
if (Msg.Contains("SomeText"))
Here is how the TSQL LIKE keyword works.
using System;
namespace SqlLike
{
class Program
{
static void Main(string[] args)
{
var findMe = "ABCHelloXYZ";
// LIKE '......%'
if (findMe.StartsWith("ABC"))
{
Console.WriteLine("Yay");
}
// LIKE '%......'
if (findMe.EndsWith("XYZ"))
{
Console.WriteLine("Woohoo");
}
// LIKE '%......%'
if (findMe.Contains("Hello"))
{
Console.WriteLine("JackPot!!");
}
Console.ReadLine();
}
}
}
Your requirements are a little vague, but this should get you there (with a little adjustment as needed).
String Msg = "/Message somethingelse";
if (Msg.Contains("/Message ") && (Msg.Length > 9) )
{
String str = Msg.Substring(9);
Console.Write("str: " + str);
}
As #Scott suggested you can also use:
if (Msg.StartsWith("/Message ") && (Msg.Length > 9))
{
String str = Msg.Substring(9);
Console.Write("str: " + str);
}
I have created a regex function and called it when the data is being saved.
public static bool CheckSpecialCharacter(string value)
{
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(#"[~`!##$%^*()=|\{}';.,<>]");
if (regex.IsMatch(value))
{
return false;
}
else
{
return true;
}
}
Used here:
if (ClassName.CheckSpecialCharacter(txt_ExpName1.Text)==false)
{
lblErrMsg.Text = "Special characters not allowed";
return;
}
Now instead of writing "Special characters not allowed", I want to attach the 1st special character that was entered in the textbox, so
if # was entered, the message should be read as "Special character # not allowed"
Is it possible to do this? please help.Thanks.
Try following code.
public static string CheckSpecialCharacter(string value)
{
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(#"[~`!##$%^*()=|\{}';.,<>]");
var match = regex.Match(value);
if (match.Success)
{
return match.Value;
}
else
{
return string.empty;
}
}
usage:
var value = ClassName.CheckSpecialCharacter(txt_ExpName1.Text);
if (!string.IsNullOrEmpty(value ))
{
lblErrMsg.Text = value + " Special characters not allowed";
return;
}
OR you can do it by returning bool and adding one out parameter in the function, but i will not suggest that.. check this link
EDIT - To do the same thing in Javascript
function CheckSpecialCharacter(value)
{
var res = value.match(/[~`!##$%^*()=|\{}';.,<>]/g);
return res == null ? "" : res[0];
}
usage:
var value = CheckSpecialCharacter(document.getElementById("txt_ExpName1").value);
if(value != "")
{
document.getElementById("lblErrMsg").innerHTML = value + " Special characters not allowed";
}
Try this:
public static bool CheckSpecialCharacter(string value, out string character)
{
var regex = new System.Text.RegularExpressions.Regex(#"[~`!##$%^*()=|\{}';.,<>]");
var match = regex.Match(value);
character = regex.Match(value).Value;
return match.Length == 0;
}
and then
string character;
if (ClassName.CheckSpecialCharacter(txt_ExpName1.Text, out character) == false)
{
lblErrMsg.Text = character + " Special characters not allowed";
return;
}
You can just use the Matches(string) function from Regex to get the matches then check the first element like this :
var regex = new Regex(#"[~`!##$%^*()=|\{}';.,<>]");
var matches = regex.Matches("This contains # two b#d characters");
if (matches.Count > 0)
{
var firstBadCharacter = matches[0];
}
Then you can wrap the result of your check in an Exception :
throw new ArgumentException("Special character '" + firstBadCharacter + "' not allowed.");
Is there a way to do this in C# without making a new method to overload for every var type there is?
$box = !empty($toy) : $toy ? "";
The only ways I can think of to do it is either:
if (toy != null)
{
box += toy;
}
or this:
public string emptyFilter(string s) ...
public int emptyFilter(int i) ...
public bool emptyFilter(bool b) ...
public object emptyFilter(object o)
{
try
{
if (o != null)
{
return o.ToString();
}
else
{
return "";
}
}
catch (Exception ex)
{
return "exception thrown":
}
}
box += this.emptyFilter(toy);
I basically wanna check to make sure that the variable/property is set/not empty/exists/has value/etc... and return it or "" without some ridiculous about of code like above.
You could use the conditional operator (?:):
string box = (toy != null) ? toy.ToString() : "";
return variable ?? default_value;
That what you're going for? I'm a little confused considering you're showing PHP code and tag this with C#.
There's also the Nullable<T> type you can use.
How bout an extender class?
public static class ToStringExtender
{
public static String ToStringExt(this Object myObj)
{
return myObj != null ? myObj.ToString() : String.Empty;
}
}
var myobject = foo.ToStringExt()
DEMO
I'm not sure of what he wants, BUT:
string str = String.Empty;
str += true;
str += 5;
str += new object();
str += null;
This is perfectly legal. For each one adition the ToString() will be called. For null, simply nothing will be added.
The value of str at the end: True5System.Object
or,
var s = (toy?? "").ToString();
or
var s = (toy?? string.Empty).ToString();
i think there may be a slight misunderstanding about how var is used; but that's a separate topic.
maybe this below will help:
box += (toy ?? "").ToString();