Outlook Find/Restrict with contain - c#

is there anyway I can use Find or Restrict with something like outlookfield.contains(mystring)?
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook._items.restrict%28v=office.14%29.aspx

According to the documentation you linked to, no there is no way to do it.
Additional Notes
If you are trying to use the Find or Restrict methods with
user-defined fields, the fields must be defined in the folder,
otherwise an error will occur. There is no way to perform a "contains"
operation. For example, you cannot use Find or Restrict to search for
items that have a particular word in the Subject field. Instead, you
can use the AdvancedSearch method, or you can loop through all of the
items in the folder and use the InStr function to perform a search
within a field. You can use the Restrict method to search for items
that begin within a certain range of characters. For example, to
search for all contacts with a last name beginning with the letter M,
use this filter:
sFilter = "[LastName] > 'LZZZ' And [LastName] < 'N'"
It isn't clear from your question exactly what you are trying to do so to give some more context I am trying to count all the emails that have a subject containing a certain string (I've called it mystring to match your example).
Here is the code I started with:
string mystring = "Such String";
int count = inboxFolder.Items.Restrict("[Subject] = " + mystring).Count;
Debug.WriteLine("{0} email(s) contain '{1}'", count, mystring);
This would work so long as the subject of the email was an exact match to mystring which isn't good enough, I needed it to count if the string was contained anywhere in the subject.
I tried Axel Kemper's answer of adding * symbols as a wildcard but it didn't work for me.
Rather than use the AdvancedSeach method (its rather cryptic documentation here) I opted to perform a loop through each item and check manually if it contained the string of interest:
string mystring = "Such String";
int count = 0;
foreach (var item in inboxFolder.Items)
{
if (item is Outlook.MailItem)
{
Outlook.MailItem mailItem = item as Outlook.MailItem;
if (mailItem.Subject != null && mailItem.Subject.Contains(mystring))
{
count++;
}
}
}
Debug.WriteLine("{0} email(s) contain '{1}'", count, mystring);
I've left the code unrefactored to ease readability and understanding but this can also be made into a one liner LINQ expression:
string mystring = "Such String";
int count = inboxFolder.Items.OfType<Outlook.MailItem>().Count(mailItem => mailItem.Subject != null && mailItem.Subject.Contains(mystring));
Debug.WriteLine("{0} email(s) contain '{1}'", count, mystring);
Output from both:
42 email(s) contain 'Such String'

You can specify fields in squared brackets like shown in the following snippets:
Set contact = objContacts.Items.Find("[Email1Address]=" & Chr(34) & .SenderEmailAddress & Chr(34))
Set contact = objContacts.Items.Find("[FileAs] = ""Smith, Jeff"" and [FirstName] = ""Jeff""")
The fieldnames are described in the MSDN documentation or can be inspected using the VBA object catalog viewer.
To implement Contains, you can use * as wildcard before and after the string you are looking for (eg "*myString*"). To search the field for a literal *, you have to use ~*.

Related

counting a string with special characters in a string in c#

I would like to count a string (search term) in another string (logfile).
Splitting the string with the method Split and searching the array afterwards is too inefficient for me, because the logfile is very large.
In the net I found the following possibility, which worked quite well so far. However,
count = Regex.Matches(_editor.Text, txtLookFor.Text, RegexOptions.IgnoreCase).Count;
I am now running into another problem there, that I get the following error when I count a string in the format of "Nachricht erhalten (".
Errormessage:
System.ArgumentException: "Nachricht erhalten (" analysed - not enough )-characters.
You need to escape the ( symbol as it has a special function in regular expressions:
var test = Regex.Matches("Nachricht erhalten (3)", #"Nachricht erhalten \(", RegexOptions.IgnoreCase).Count;
If you do this by user input where the user is not familiar with regular expressions you probably easier off using IndexOf in a while loop, where you keep using the new index found in the last loop. Which might also be a bit better on performance than a regular expression. Example:
var test = "This is a test";
var searchFor = "is";
var count = 0;
var index = test.IndexOf(searchFor, 0);
while (index != -1)
{
++count;
index = test.IndexOf(searchFor, index + searchFor.Length);
}

A composite format string in conjunction with DataTable.Select()

I've got an array with three elements
string[] cat = new string[3] { "XBox360", "PS3", "Wii" };
then my I basically compare the array agianst a DataTable and do some manipulation under certain conditions. The code that (I didn't write) performs match is this:
drResults = dtResults.Select(String.Format("Cat = '{0}' AND Cat_Entries = '{1}'", category, cat[i]));
The category (Cat) varialble contains a category numbers and Cat_Entries the elements of the cat array. And so in the code I perform operations if the drResult.Lenght > 0.
What I don't understand is what does the code inside Format() do? I'm looking at Microsoft's definition but what throws me off is the "AND". Also are the numbers between curly brackets {} like a sequential index designator that tell the runtime that the category element repalces Zero, and cat[i] replaces One?
All this is of course inside a loop and other code but I don't think it really adds to the question so I left it out.
The Select method takes a piece of SQL and returns rows that match. In this case you are looking for a row where Cat field = '<category>' AND the Cat_Entries field = '<cat[i]>'
The Format function is a better way of creating the string than doing
"Cat = '" + category + "' AND Cat_Entries = '" + cat[i] + '" as the latter is harder to read and is probably slower due to having to create several interim strings.
The {0} and {1} are just place holders representing the variables that you provide, ie.
category and cat[i]. You can reuse each as many times as you like and in any order,.e.g. it would be valid (albeit stupid) to have
String.Format("Cat_Entries = '{1}' AND Cat = '{0}' AND Cat = '{0}'", category, cat[i])

Code an elegant way to strip strings

I am using C# and in one of the places i got list of all peoples names with their email id's in the format
name(email)\n
i just came with this sub string stuff just off my head. I am looking for more elegant, fast ( in the terms of access time, operations it performs), easy to remember line of code to do this.
string pattern = "jackal(jackal#gmail.com)";
string email = pattern.SubString(pattern.indexOf("("),pattern.LastIndexOf(")") - pattern.indexOf("("));
//extra
string email = pattern.Split('(',')')[1];
I think doing the above would do sequential access to each character until it finds the index of the character. Works ok now since name is short, but would struggle when having a large name ( hope people don't have one)
A dirty hack would be to let microsoft do it for you.
try
{
new MailAddress(input);
//valid
}
catch (Exception ex)
{
// invalid
}
I hope they would do a better job than a custom reg-ex.
Maintaining a custom reg-ex that takes care of everything might involve some effort.
Refer: MailAddress
Your format is actually very close to some supported formats.
Text within () are treated as comments, but if you replace ( with < and ) with > and get a supported format.
The second parameter in Substring() is the length of the string to take, not the ending index.
Your code should read:
string pattern = "jackal(jackal#gmail.com)";
int start = pattern.IndexOf("(") + 1;
int end = pattern.LastIndexOf(")");
string email = pattern.Substring(start, end - start);
Alternatively, have a look at Regular Expression to find a string included between two characters while EXCLUDING the delimiters

Loop Problem: Assign data to different strings when in a loop

I have a string which consists of different fields. So what I want to do is get the different text and assign each of them into a field.
ex: Hello Allan IBM
so what I want to do is:
put these three words in different strings like
string Greeting = "Hello"
string Name = "Allan"
string Company = "IBM"
//all of it happening in a loop.
string data = "Hello Allan IBM"
string s = data[i].ToString();
string[] words = s.Split(',');
foreach (string word in words) {
Console.WriteLine(word);
}
any suggestions?
thanks hope to hear from you soon
If I understand correctly you have a string with place-holders and you want to put different string in those place-holders:
var format="{0}, {1} {2}. How are you?";
//string Greeting = "Hello"
//string Name = "Allan"
//string Company = "IBM"
//all of it happening in a loop.
string data = ...; //I think you have an array of strings separated by ,
foreach( va s in data){
{
//string s = data[i];//.ToString(); - it is already a string array
string[] words = data[i].Split(',');
Console.WriteLine(format, words[0], words[1], words[2]);
}
To me it sound not like a problem that can be solved with a loop. The essential problem is that the loop can only work if you do exactly the same operation on the items within the loop. If your problem doesn't fit, you end up with a dozen of lines of code within the loop to handle special cases, what could have been written in a shorter way without a loop.
If there are only two or three strings you have to set (what should be the case if you have named variables), assign them from the indexes of the split string. An alternative would be using regular expressions to match some patterns to make it more robust, if one of the expected strings is missing.
Another possibility would be to set attributes on members or properties like:
[MyParseAttribute(/*position*/ /*regex*/)]
string Greeting {get;set;}
And use reflexion to populate them. Here you could create a loop on all properties having that attribute, as it sounds to me that you are eager to create a loop :-)

What does the dollar sign and { } mean as a locator selenium c#

Hi I don't understand the locator with the $ sign and the name in braces {name}. Am I right in thinking, using this way you can use the locator as an IList and also a non IList. Here is the locator:
public IList<IWebElement> ResultByName(string name) => dr.FindElements(By.Id($"//div[text() = '{name}']"));
And then its used in the code snippet:
IList<IWebElement> list = _regRep.ResultByName(emailID);
int actualCount = list.Count;
Assert.AreEqual(1, list.Count, "Only one user should match email " + emailID);
There is a flaw in this because even though there is an emailID in the table it still gives a count of 0 which is not what is expected?
This is an interpolated string that allows you to add expressions into your string:
var myValue = "interpolate";
var interpolatedText = $"The dollar sign allows you to {myValue} text and literal C# expressions.";
It was introduced with C# 6.0 and allows you to avoid using String.Format.

Categories

Resources