Possible to set values of RegEx? - c#

I'm just wondering if its possible to set my "set of values" to put to RegEx (Or any other methods if there is)...?
Here's what I need to do...
string myString = "Hello<<Prefix>> <<surname>>!!";
My PROBLEM:
I need to replace those strings with "<<....>>" to a value in my database.
I'm thinking of getting all those "<<....>>" and put it in a List but if you have other simpler/easier way, please help me.
Thank you in advance!

It sounds more like you need to use String.Format method. Given:
public class User
{
public string Prefix {get; set;}
public string Surname {get; set;}
}
The output should be constructed like:
var message = String.Format("Hello {0} {1}!!", user.Prefix, user.Surname);

A keyword you might want to search on is templating. One way to do it would be something like this:
var dict = new Dictionary<string,string>()
// Populate the dictionary with your key values
dict.Add("PREFIX", "Mr");
dict.Add("SURNAME", "Prescott");
string myString = "Hello<<PREFIX>> <<SURNAME>>!!";
foreach(item in dict)
{
myString = myString.Replace("<<" + item.Key + ">>", item.Value);
}
Note this is a bit naive, it will loop through an entire dictionary you load even if there is only one element to replace.

Related

Can I get the locator string from a By?

At the moment, I'm storing references to page elements as Bys:
public By showAllCheckbox = By.Id("show-all");
public By addArticleButton = By.CssSelector("a[id='add-article-btn']");
public By exampleEventCategoryEntityPickerPlusButton = By.XPath("//*[#id='j1_1']/i");
public By exampleEventReasonEntityPickerEntity = By.CssSelector("a[id='7603_anchor']");
Using selenium (or some other witchcraft) is it possible to get that selector string back out of the By? For example, for the add article button above I would want to get "a[id='add-article-btn']".
Thanks!
I think you can do it as follows, You can use toString()
By addArtclBtn = By.CssSelector("a[id='add-article-btn']");
String selector = addArtclBtn.toString();
selector value will be something like this "By.cssSelector: a[id='add-article-btn']", Then what you can do is, just spliit the value by ": ".
String[] splittedValues = selector.split(": ");
String value = splittedValues[1];

What is the efficient way to get only first Lookupvalue from SpFieldLookupValueCollection in SharePoint 2010?

I want to Access only first Lookupvalue of SpFieldLookupValueCollection presently I am doing something like this
string abc = string.Empty;
foreach (SPFieldLookupValue value in SpFieldLookupValueCollection)
{
abc = value.LookupValue;
break;
}
Am Fresher to sharepoint please tell me better and faster way to access lookup Values
Thank you
SPFieldLookupValue fieldValue=SpFieldLookupValueCollection.FirstOrDefault();
and
SpFieldLookupValueCollection.First();
this will give the desired result.
You can simply use Linq query as follows,
var firstElement = SpFieldLookupValueCollection.FirstOrDefault();
Note: you will have to include System.Linq; namespace
It's better to get the value of a specific column rather than retrieveing all columns.The following code should work for you.
string fieldValue = "";
if (item["fieldname"] != null)
{
var val= (SPFieldLookupValue)item["fieldname"];
fieldValue = fieldValue .LookupValue;
}

How to remove a specific string from list<strings>

I've got a list of strings called xyz the string has this structure iii//abcd, iii//efg. how can I loop through this list and remove only iii// ?
I have tried this but it remove everything. thanks
string mystring = "iii//";
xyz.RemoveAll(x=> x.Split ('//')[0].ToString().Equals (mystring));
Removing all the strings who start with iii//:
xyz.RemoveAll(x => x.StartsWith(#"iii//"));
Removing the iii// from all strings:
var newList = xyz.Select(x => x.Replace(#"iii//", string.Empty)).ToList();
You can try this also which will remove the string from list if it starts with "iii/" other wise not.
string mystring = "iii//";
xyz.RemoveAll(x=>x.StartsWith(mystring));
I believe OP wants something to remove iii// from all strings:
string prefix = "iii///";
List<string> xyz = ...;
var result = xyz.Select(x => x.Substring(prefix.Length)).ToList();
Note: this of course assumes that each string really starts with prefix.

print all variables in class C#

To start I would prefer not to use reflection to accomplish this.
I have a class lets say
public class exampleClass
{
public string var1 = "one";
public string var2 = "two";
public int var3 = 3;
public string var4 = "four";
etc. etc..
}
I want to dynamically be able to iterate through that class and print out the variables. I thought about serialization but wasn't exactly sure how to implement it for this case (the only examples I could find were to XML and I don't want that) also I don't really want to change the structure of the class in any way.
The reason I'm doing that is because I'm constructing an HTML table and want to do:
for(int i = 0; i < exampleClass.Count; i++)
tbl_row = "<td>" + exampleClass[i] + "</td>";
or something similar. Any suggestions?
The easisets way would be using reflection. This should be enough :
var example = new exampleClass();
var allPublicFields = example.GetType().
GetFields(BindingFlags.Public | BindingFlags.Instance );
Use a dictionary, instead of fields: Dictionary<fieldName, fieldValue> , but this is
kind over engineering the simple a streghtforward solution: reflection over clear and maintanable structure of your strong typed class.
Complete same for building HTML with TagBuilder.
var tagBuilder = new TagBuilder("tr");
var exampleClass = new exampleClass();
tagBuilder.InnerText += "<td>Field</td><td>Value</td>";
foreach(var field in typeof(exampleClass)
.GetFields(BindingFlags.Public | BindingFlags.Instance))
{
var nameBuilder = new TagBuilder("td");
var valueBuilder = new TagBuilder("td");
nameBuilder.InnerHtml = field.Name;
valueBuilder.InnerHtml = field.GetValue(exampleClass).ToString();
tagBuilder.InnerHtml += string.Format("{0}{1}",
nameBuilder.ToString(),
valueBuilder.ToString());
}
outputs:
<tr>
<td>Field</td><td>Value</td>
<td>var1</td><td>one</td>
<td>var2</td><td>two</td>
<td>var3</td><td>3</td>
<td>var4</td><td>four</td>
<tr>
If you don't want to use reflection, how about storing the data in a dictionary, rather than in a custom class? That way you can simply iterate over the keys or values as required.
Personally, I think you're better off with reflection. You could achieve what you're trying to do if you're using .NET 4 or later and derive exampleClass from DynamicObject.
The example on this page is pretty similar to what you're looking to do.

Variable in the dynamic string in C#

I have a module to send message with the SMS. I can put the variable in the string if the message is a static, but the user request the message can be changed whatever their want.
I created this variable
CompanyName
CustomerName
BillNumber
Payment
Example :
From {Company}. Hi Mr/Mrs {CustomerName}, your bill number is
{BillNumber} with a total payment of {Payment}. We want to inform you
the items has been completed and ready for collection.
My current code is work for static message,
string messageSms = "From " +Company+ ". Hi Mr/Mrs "+{CustomerName}+", your bill number is "+{BillNumber}+" with a total payment of "+{Payment}+". We want to inform you the items has been completed and ready for collection.";
But how can be done with dynamic message? How can I detect the variable in the string and set the data on the variable?
I also following with this article but not help so much.
var newString = messageSms.Replace("{Company}", CompanyName)
.Replace("{CustomerName}", CustomerName) // ...etc
Should do it.
Assuming I'm understanding, i think the String.Inject class could be helpful. Picture a named String.Format:
"Hello, {company}!".Inject(new { company = "StackOverflow" });
// "Hello, StackOverflow!"
The other benefit is you can have a hard-coded model and reference direct properties of it. e.g.
class Contact
{
string FirstName;
string LastName;
}
String greeting = "Mr. {FirstName} {LastName}, Welcome to the site ...";
String result = greeting.Inject(new Contact
{
FirstName = "Brad",
LastName = "Christie"
});
You could also use interpolated strings using C# 6.0
var messageSms = $"From {companyName}. Hi {customerName}, your bill number is {billNumber} with a total payment of {payment}.";
I would approach with the following :
string Company;
string CustomerName;
string BillNumber;
string Payment;
string messageSms = $#"
From {Company}. Hi Mr/Mrs {CustomerName}, your bill number is {BillNumber}
with a total payment of {Payment}. We want to inform you the items has been
completed and ready for collection.
";
Try String.Format Method, for example:
string messageSms = String.Format("From {0}. Hi ..{1}, Your..{2} with..{3}. We..",
CompanyName, CustomerName, BillNumber, Payment);
I assume that the easiest way to achieve this (you did not clarify your question) is to use string.Format().
Just use it like this:
string company = ...;
string name= ...;
string billNr= ...;
string payment= ...;
string output = string.Format("From {0}. Hi Mr/Mrs {1}, your bill number is {2} with a total payment of {3}. We want to inform you the items has been completed and ready for collection.", company, name, billNr, payment);
Why not use a StringBuilder instead?
StringBuilder stringBuilder = new StringBuilder("From {Company}.Hi Mr/Mrs {CustomerName}, your bill number is {BillNumber} with a total payment of {Payment}. We want to inform you the items has been completed and ready for collection.");
stringBuilder.Replace("{Company}",CompanyName);
stringBuilder.Replace("{CustomerName}",CustomerName);
stringBuilder.Replace("{BillNumber}",BillNumber);
stringBuilder.Replace("{Payment}",Payment);
string messageSms = stringBuilder.ToString();
To make a reusable solution you could start by declaring an object that contains the replacement values as properties. In this case I simply declare an anonymous object but a normal class would work just as well:
var data = new {
Company = "Stack Overflow",
CustomerName = "Martin Liversage",
BillNumber = 123456,
Payment = 1234.567M.ToString("N2")
};
Notic how I "cheat" and assign a string to Payment. Number and date/time formatting is always a complex issue and I have decided to do the formatting up-front when I declare the data object. You could instead build some more or less elaborate formatting rules into the formatting engine.
Having a data object with properties I can build a dictionary of name/value pairs:
var dictionary = data
.GetType()
.GetProperties()
.ToDictionary(
propertyInfo => propertyInfo.Name,
propertyInfo => propertyInfo.GetValue(data, null)
);
Assuming that format contains the formatting template it is simply a matter of looping over the elements in the dictionary to create the replacement string:
var buffer = new StringBuilder(format);
foreach (var name in dictionary.Keys) {
var value = dictionary[name].ToString();
buffer.Replace("{" + name + "}", value);
}
var message = buffer.ToString();

Categories