Parsing out URLs in email messages - c#

I'm having an issue in some of my code, i cannot seem to think of the best way to do this, all i want to do is extract a URL from a pop3 email message depending on if the domain is in the "to check" array, for example if "stackoverflow.com" is in the email message, i would extract all urls in the message body that contains "stackoverflow.com" in it, and just perform a quick WebClient() request with that url.
Code:
private void BgwEmails_DoWork_1(object sender, DoWorkEventArgs e)
{
try
{
bool finished = false;
Pop3Client pop3 = new Pop3Client();
if (pop3.Connected)
{
pop3.Disconnect();
}
pop3.Connect(txtBoxMailServer.Text, int.Parse(txtBoxPort.Text), chkSSL.Checked);
pop3.Authenticate(txtBoxUsername.Text, txtBoxPassword.Text, AuthenticationMethod.UsernameAndPassword);
int messageCount = pop3.GetMessageCount();
if (messageCount == 0)
{
return;
}
Helpers.ReturnMessage("[ " + messageCount + " ] Message(s) in your inbox.");
int count = 0;
for (int d = 1; d <= messageCount; d++)
{
bgwEmails.WorkerSupportsCancellation = true;
if (bgwEmails.CancellationPending)
{
e.Cancel = true;
Helpers.ReturnMessage($"Cancelling link activator ...");
return;
}
if (finished)
{
return;
}
OpenPop.Mime.Message message = null;
message = pop3.GetMessage(d);
if (null == message || null == message.MessagePart || null == message.MessagePart.MessageParts) {
continue;
}
string textFromMessage = null;
try
{
textFromMessage = message?.MessagePart?.MessageParts[0]?.GetBodyAsText();
} catch (Exception) {
continue;
}
MessagePart messagePart = message.MessagePart.MessageParts[0];
if (null == messagePart || null == messagePart.BodyEncoding || null == messagePart.Body || null == messagePart.BodyEncoding.GetString(messagePart.Body)) {
continue;
}
string linkToCheck;
using (var wc = new WebClient())
{
linkToCheck = wc.DownloadString("https://www.thesite.com/api.php?getActivationLinks=1");
}
var linksToClickArray = linkToCheck.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
//Helpers.ReturnMessage(textFromMessage);
for (var i = 0; i < linksToClickArray.Length; i++)
{
var regex = new Regex(linksToClickArray[i], RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline);
var matches = regex.Matches(textFromMessage);
foreach (Match match in matches)
{
if (match.Success)
{
count++;
Invoke(new MethodInvoker(() => { listBoxEmailsClicked.Items.Add("Clicked: " + match.Value); }));
using (WebClient wc = new WebClient())
{
Helpers.ReturnMessage(match.Value);
wc.DownloadString(match.Value);
}
}
}
}
if (null != textFromMessage)
{
Invoke(new MethodInvoker(() => { txtStatusMessages.AppendText(textFromMessage); }));
}
}
Helpers.ReturnMessage($"Emails downloaded successfully! You clicked [ " + count + " ] activation links.");
} catch (Exception ex) {
Helpers.ReturnMessage($"POP3 Error: " + ex.Message + ".");
}
}
I do a request here: https://www.thesite.com/api.php?getActivationLinks=1 which contains a list of domains to check for in the messages, they just come back one line at a time like:
thesite1.com
thesite2.com
etc
The code works as far as connetcing and downloading, i just cannot seem to think of a way to parse of the urls only if it matches a domain in the target list, any help or advice would be appreciated.

Related

C# Rabbitmq single consumer consume multiple message in single Queue

I have single queue with more than message and i want to consume that message sequencial in
order for another transaction with parse payload foreach message
the problem is when i loop all payload list after get the first paylod why first message
is always still count on list after being loop and always being proceed
and the second message and so on not being consumed
my sample list messsage array is "
first message : ["test123#gmail.com","smtp.email.io","admin","2525","123","Test_200999#yahoo.com","Email Confirmation","Hello World"]
second message :
["test123#gmail.com","smtp.email.io","admin","2525","123","Test_200998#yahoo.com","Email Confirmation","Hello World"]
third message
["test123#gmail.com","smtp.email.io","admin","2525","123","Test_200997#yahoo.com","Email Confirmation","Hello World"]
here's my code
private static async void ExcecutePayload(CancellationToken cancellationToken)
{
var factory = new ConnectionFactory
{
HostName = "localhost"
};
var connection = factory.CreateConnection();
using var channel = connection.CreateModel();
channel.QueueDeclare("email_confirmation_notifications", durable: true, exclusive: false, autoDelete: false,arguments: null);
channel.BasicQos(0, 1, false);
var consumer = new EventingBasicConsumer(channel);
EmailModel _model = new EmailModel();
var s1 = new List<string>();
string s2 = "";
bool
first = false,
second = false;
var random = new Random();
consumer.Received += (model, eventArgs) =>
{
var processingtime = random.Next(1, 10);
var body = eventArgs.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
foreach (char c in message)
{
if (second)
{
s1.Add(s2);
s2 = "";
first = false;
second = false;
}
if (first)
{
if (c == '"')
{
second = true;
}
else
{
s2 += c;
}
}
if (c == '"' && !first && !second)
{
first = true;
}
}
if (second && first)
{
s1.Add(s2);
}
foreach (var item in s1.Select((value, i) => new { i, value }).ToList())
{
var value = item.value;
var index = item.i;
if (index == 0) { _model.Sender = value; };
if (index == 1) { _model.Host = value; };
if (index == 2) { _model.UserName = value; };
if (index == 3) { _model.Port = value; };
if (index == 4) { _model.Password = value; };
if (index == 5) { _model.To = value; };
if (index == 6) { _model.Subject = value; };
if (index == 7) { _model.Body = value; };
}
try
{
InsertTransaction(_model, cancellationToken);
SendEmailAsync(_model, cancellationToken);
}
catch (Exception ex)
{
throw ex;
}
Console.WriteLine($"Notification email has sent to: {string.Join(", ", _model.To)}");
Task.Delay(TimeSpan.FromSeconds(processingtime), cancellationToken).Wait();
channel.BasicAck(deliveryTag: eventArgs.DeliveryTag, multiple: false);
};
await Task.CompletedTask;
channel.BasicConsume(queue: "email_confirmation_notifications", autoAck: false, consumer: consumer);
Console.ReadKey();
}

Get message from FieldDescriptor in protobuf

In protobuf (C#) I want to print all fields inside different messages and submessages. How can I get message type and send to function again (recursive walking to lowest child)? More specific: What I must do, that fieldDescriptor is send like a message? I search solution, which is change "???".
private void PrintAllReportableFieldsinMessage(Google.Protobuf.IMessage message)
{
foreach (var fieldDescriptor in message.Descriptor.Fields.InFieldNumberOrder())
{
if (fieldDescriptor.FieldType == Google.Protobuf.Reflection.FieldType.Message)
{
PrintAllReportableFieldsinMessage(???); // What can I send here?
}
else
{
Google.Protobuf.Reflection.FieldOptions options = fieldDescriptor.GetOptions();
if (options != null && options.GetExtension(HelloworldExtensions.Reportable))
{
var fieldValue = fieldDescriptor.Accessor.GetValue(message);
var fieldName = fieldDescriptor.Name;
Dispatcher.Invoke(() =>
{
lReadableResult.Content += fieldName + ":" + fieldValue + "|";
});
}
}
}
}
I found a solition. HasValue return false, if any values inside submessage are not set. Then I must create a new Imessage which have all default values. So then this code works for printing all field names in all messages and submessages.
private void PrintAllReportableFieldsinMessage(Google.Protobuf.IMessage message)
{
foreach (var fieldDescriptor in message.Descriptor.Fields.InFieldNumberOrder())
{
if (fieldDescriptor.FieldType == Google.Protobuf.Reflection.FieldType.Message)
{
if (fieldDescriptor.Accessor.HasValue(message))
{
IMessage submessage = fieldDescriptor.Accessor.GetValue(message) as IMessage;
PrintAllReportableFieldsinMessage(submessage);
}
else {
IMessage cleanSubmessage = fieldDescriptor.MessageType.Parser.ParseFrom(ByteString.Empty);
PrintAllReportableFieldsinMessage(cleanSubmessage);
}
}
else
{
Google.Protobuf.Reflection.FieldOptions options = fieldDescriptor.GetOptions();
if (options != null && options.GetExtension(HelloworldExtensions.Reportable))
{
var fieldValue = fieldDescriptor.Accessor.GetValue(message);
var fieldName = fieldDescriptor.Name;
Dispatcher.Invoke(() =>
{
lReadableResult.Content += fieldName + ":" + fieldValue + "|";
});
}
}
}
}

System.OutOfMemoryException in C# when Generating huge amount of byte[] objects

I'm using this code to modify a pdf tmeplate to add specific details to it,
private static byte[] GeneratePdfFromPdfFile(byte[] file, string landingPage, string code)
{
try
{
using (var ms = new MemoryStream())
{
using (var reader = new PdfReader(file))
{
using (var stamper = new PdfStamper(reader, ms))
{
string _embeddedURL = "http://" + landingPage + "/Default.aspx?code=" + code + "&m=" + eventCode18;
PdfAction act = new PdfAction(_embeddedURL);
stamper.Writer.SetOpenAction(act);
stamper.Close();
reader.Close();
return ms.ToArray();
}
}
}
}
catch(Exception ex)
{
File.WriteAllText(HttpRuntime.AppDomainAppPath + #"AttachmentException.txt", ex.Message + ex.StackTrace);
return null;
}
}
this Method is being called from this Method:
public static byte[] GenerateAttachment(AttachmentExtenstion type, string Contents, string FileName, string code, string landingPage, bool zipped, byte[] File = null)
{
byte[] finalVal = null;
try
{
switch (type)
{
case AttachmentExtenstion.PDF:
finalVal = GeneratePdfFromPdfFile(File, landingPage, code);
break;
case AttachmentExtenstion.WordX:
case AttachmentExtenstion.Word:
finalVal = GenerateWordFromDocFile(File, code, landingPage);
break;
case AttachmentExtenstion.HTML:
finalVal = GenerateHtmlFile(Contents, code, landingPage);
break;
}
return zipped ? _getZippedFile(finalVal, FileName) : finalVal;
}
catch(Exception ex)
{
return null;
}
}
and here is the main caller,
foreach (var item in Recipients)
{
//...
//....
item.EmailAttachment = AttachmentGeneratorEngine.GenerateAttachment(_type, "", item.AttachmentName, item.CMPRCode, _cmpTmp.LandingDomain, _cmpTmp.AttachmentZip.Value, _cmpTmp.getFirstAttachment(item.Language, item.DefaultLanguage));
}
The AttachmentGeneratorEngine.GenerateAttachment method is being called approx. 4k times, because I'm adding a specific PDF file from a PDF template for every element in my List.
recently I started having this exception:
Exception of type 'System.OutOfMemoryException' was thrown. at System.IO.MemoryStream.ToArray()
I already implemented IDisposible in the classes and and I made sure that all of them are being released.
Note: it was running before very smoothely and also I double checked the system's resources - 9 GB is used out of 16 GB, so I had enough memory available.
==========================================
Update:
Here is the code that loops through the list
public static bool ProcessGroupLaunch(string groupCode, int customerId, string UilangCode)
{
CampaignGroup cmpGList = GetCampaignGroup(groupCode, customerId, UilangCode)[0];
_campaigns = GetCampaigns(groupCode, customerId);
List<CampaignRecipientLib> Recipients = GetGroupRcipientsToLaunch(cmpGList.ID, customerId);
try
{
foreach (var item in _campaigns)
item.Details = GetCampaignDetails(item.CampaignId.Value, UilangCode);
Stopwatch stopWatch = new Stopwatch();
#region single-threaded ForEach
foreach (var item in Recipients)
{
CampaignLib _cmpTmp = _campaigns.FirstOrDefault(x => x.CampaignId.Value == item.CampaignId);
bool IncludeAttachment = _cmpTmp.IncludeAttachment ?? false;
bool IncludeAttachmentDoubleBarrel = _cmpTmp.IncludeAttachmentDoubleBarrel ?? false;
if (IncludeAttachment)
{
if (_cmpTmp.AttachmentExtension.ToLower().Equals("doc") || (_cmpTmp.AttachmentExtension.ToLower().Equals("docx")))
_type = AttachmentGeneratorEngine.AttachmentExtenstion.Word;
else if (_cmpTmp.AttachmentExtension.ToLower().Equals("ppt") || (_cmpTmp.AttachmentExtension.ToLower().Equals("pptx")))
_type = AttachmentGeneratorEngine.AttachmentExtenstion.PowePoint;
else if (_cmpTmp.AttachmentExtension.ToLower().Equals("xls") || (_cmpTmp.AttachmentExtension.ToLower().Equals("xlsx")))
_type = AttachmentGeneratorEngine.AttachmentExtenstion.Excel;
else if (_cmpTmp.AttachmentExtension.ToLower().Equals("pdf"))
_type = AttachmentGeneratorEngine.AttachmentExtenstion.PDF;
else if (_cmpTmp.AttachmentExtension.ToLower().Equals("html"))
_type = AttachmentGeneratorEngine.AttachmentExtenstion.HTML;
}
//set "recpient" details
item.EmailFrom = _cmpTmp.EmailFromPrefix + "#" + _cmpTmp.EmailFromDomain;
item.EmailBody = GetChangedPlaceHolders((_cmpTmp.getBodybyLangCode(string.IsNullOrEmpty(item.Language) ? item.DefaultLanguage : item.Language, item.DefaultLanguage)), item.ID, _cmpTmp.CustomerId.Value, _cmpTmp.CampaignId.Value);
if (item.EmailBody.Contains("[T-LandingPageLink]"))
{
//..
}
if (item.EmailBody.Contains("[T-FeedbackLink]"))
{
//..
}
if (item.EmailBody.Contains("src=\".."))
{
//..
}
//set flags to be used by the SMTP Queue and Scheduler
item.ReadyTobeSent = true;
item.PickupReady = false;
//add attachment to the recipient, if any.
if (IncludeAttachment)
{
item.AttachmentName = _cmpTmp.getAttachmentSubjectbyLangCode(string.IsNullOrEmpty(item.Language) ? item.DefaultLanguage : item.Language, item.DefaultLanguage) + "." + _cmpTmp.AttachmentExtension.ToLower();
try
{
if (_type == AttachmentGeneratorEngine.AttachmentExtenstion.PDF || _type == AttachmentGeneratorEngine.AttachmentExtenstion.WordX || _type == AttachmentGeneratorEngine.AttachmentExtenstion.Word)
item.EmailAttachment = AttachmentGeneratorEngine.GenerateAttachment(_type, "", item.AttachmentName, item.CMPRCode, _cmpTmp.LandingDomain, _cmpTmp.AttachmentZip.Value, _cmpTmp.getFirstAttachment(item.Language, item.DefaultLanguage));
else item.EmailAttachment = AttachmentGeneratorEngine.GenerateAttachment(_type, value, item.AttachmentName, item.CMPRCode, _cmpTmp.LandingDomain, _cmpTmp.AttachmentZip.Value);
item.AttachmentName = _cmpTmp.AttachmentZip.Value ? (_cmpTmp.getAttachmentSubjectbyLangCode(string.IsNullOrEmpty(item.Language) ? item.DefaultLanguage : item.Language, item.DefaultLanguage) + ".zip") :
_cmpTmp.getAttachmentSubjectbyLangCode(string.IsNullOrEmpty(item.Language) ? item.DefaultLanguage : item.Language, item.DefaultLanguage) + "." + _cmpTmp.AttachmentExtension.ToLower();
}
catch (Exception ex)
{
}
}
else
{
item.EmailAttachment = null;
item.AttachmentName = null;
}
}
#endregion
stopWatch.Stop();
bool res = WriteCampaignRecipientsLaunch(ref Recipients);
return res;
}
catch (Exception ex)
{
Recipients.ForEach(i => i.Dispose());
cmpGList.Dispose();
Recipients = null;
cmpGList = null;
return false;
}
finally
{
Recipients.ForEach(i => i.Dispose());
cmpGList.Dispose();
Recipients = null;
cmpGList = null;
}
}

Multithreading issue ,Maybe a DeadLock using Foreach

Parallel.ForEach keeps on running and my program does not end. I am unable to trace where it goes after the first iteration. My guess is that gets a deadlock and keeps on doing context switching.
private void ReadInputFile()
{
var collection = new ConcurrentBag<PropertyRecord>();
var lines = System.IO.File.ReadLines(InputFileName);
int i = 0;
int RecordsCount = lines.Count();
Parallel.ForEach(lines, line =>
{
if (string.IsNullOrWhiteSpace(line))
{
return;
}
var tokens = line.Split(',');
var postalCode = tokens[0];
var country = tokens.Length > 1 ? tokens[1] : "england";
SetLabelNotifyTwoText(
string.Format(
"Reading PostCode {0} out of {1}"
i,
lines.Length));
var tempRecord = GetAllAddesses(postalCode, country);
if (tempRecord != null)
{
foreach (PropertyRecord r in tempRecord)
{
collection.Add(r);
}
}
});
}
private List<PropertyRecord> GetAllAddesses(
string postalCode,
string country = "england")
{
SetLabelNotifyText("");
progressBar1.Value = 0;
progressBar1.Update();
var records = new List<PropertyRecord>();
using (WebClient w = new WebClient())
{
var url = CreateUrl(postalCode, country);
var document = w.DownloadString(url);
var pagesCount = GetPagesCount(document);
if (pagesCount == null)
{
return null;
}
for (int i = 0; i < pagesCount; i++)
{
SetLabelNotifyText(
string.Format(
"Reading Page {0} out of {1}",
i,
pagesCount - 1));
url = CreateUrl(postalcode,country, i);
document = w.DownloadString(url);
var collection = Regex.Matches(
document,
"<div class=\"soldDetails\">(.|\\n|\\r)*?class=" +
"\"soldAddress\".*?>(?<address>.*?)(</a>|</div>)" +
"(.|\\n|\\r)*?class=\\\"noBed\\\">(?<noBed>.*?)" +
"</td>|</tbody>");
foreach (var match in collection)
{
var r = new PropertyRecord();
var bedroomCount = match.Groups["noBed"].Value;
if(!string.IsNullOrEmpty(bedroomCount))
{
r.BedroomCount = bedroomCount;
}
else
{
r.BedroomCount = "-1";
}
r.address = match.Groups["address"].Value;
var line = string.Format(
"\"{0}\",{1}",
r.address
r.BedroomCount);
OutputLines.Add(line);
Records.Add(r);
}
}
}
return Records;
}
It runs fine without Parallel.ForEach, but using Parallel.ForEach is in requirements.
I have debugged it and after returning from GetAllAdresses-method first time, Step Next button halts and it just keep on debugging in the background. It doesn't come back on any bookmark I have placed.
As you said in comments, your SetLabelNotifyText and SetLabelNotifyTwoText methods calls Control.Invoke.
For Control.Invoke to work, Main thread has to be free, but in your case you seem to block the main thread by invoking Parallel.ForEach in it.
Here is a minimal reproduction:
private void button1_Click(object sender, EventArgs e)
{
Parallel.ForEach(Enumerable.Range(1, 100), (i) =>
{
Thread.Sleep(10);//Simulate some work
this.Invoke(new Action(() => SetText(i)));
});
}
private void SetText(int i)
{
textBox1.Text = i.ToString();
}
Main thread waits for Parallel.ForEach and worker threads waits for Main thread, and thus results in deadlock.
How to fix: Don't use Invoke simply use BeginInvoke or don't block the MainThread.
If this isn't the case post sscce, that will be helpful for us
Change your code like this, to use async and await. This is the modern alternative to using BeginInvoke and other asynchronous code models.
private async Task ReadInputFile()
{
var collection = new ConcurrentBag<PropertyRecord>();
var lines = System.IO.File.ReadLines(InputFileName);
int i = 0;
int RecordsCount = lines.Count();
Parallel.ForEach(lines, line =>
{
if (string.IsNullOrWhiteSpace(line))
{
return;
}
var tokens = line.Split(',');
var postalCode = tokens[0];
var country = tokens.Length > 1 ? tokens[1] : "england";
SetLabelNotifyTwoText(
string.Format(
"Reading PostCode {0} out of {1}"
i,
lines.Length));
var tempRecord = await GetAllAddesses(postalCode, country);
if (tempRecord != null)
{
foreach (PropertyRecord r in tempRecord)
{
collection.Add(r);
}
}
});
}
private async Task<List<PropertyRecord>> GetAllAddesses(
string postalCode,
string country = "england")
{
SetLabelNotifyText("");
progressBar1.Value = 0;
progressBar1.Update();
var records = new List<PropertyRecord>();
using (WebClient w = new WebClient())
{
var url = CreateUrl(postalCode, country);
var document = await w.DownloadStringTaskAsync(url);
var pagesCount = GetPagesCount(document);
if (pagesCount == null)
{
return null;
}
for (int i = 0; i < pagesCount; i++)
{
SetLabelNotifyText(
string.Format(
"Reading Page {0} out of {1}",
i,
pagesCount - 1));
url = CreateUrl(postalcode,country, i);
document = await w.DownloadStringTaskAsync(url);
var collection = Regex.Matches(
document,
"<div class=\"soldDetails\">(.|\\n|\\r)*?class=" +
"\"soldAddress\".*?>(?<address>.*?)(</a>|</div>)" +
"(.|\\n|\\r)*?class=\\\"noBed\\\">(?<noBed>.*?)" +
"</td>|</tbody>");
foreach (var match in collection)
{
var r = new PropertyRecord();
var bedroomCount = match.Groups["noBed"].Value;
if(!string.IsNullOrEmpty(bedroomCount))
{
r.BedroomCount = bedroomCount;
}
else
{
r.BedroomCount = "-1";
}
r.address = match.Groups["address"].Value;
var line = string.Format(
"\"{0}\",{1}",
r.address
r.BedroomCount);
OutputLines.Add(line);
Records.Add(r);
}
}
}
return Records;
}
Then call it like this
ReadInputFile.Wait();
or, even better, is the caller is async,
await ReadInputFile();

installed apps name verus search name

I will be straight forward and say that I found this code online and therefore is not my own. It works perfectly if I type in the name of the program as shown in Programs and Features but for instance, I want to type Mozilla Firefox and have it find the installed Mozilla Firefox 26.0 (x86 en-US). I tried many times to use .substring and .contains in the line that checks the two strings but each time leads the program to just lock up. Any help is appreciated.
Just for side notes:
I am using a list of programs in a txt file that are read in to check against the installed apps.
I ran a messagebox right after it sets the display name and several of the message boxes show up blank. I tried to limit it with string.length not being 0 and length being equal or greater than the string from the txt file but all still locks up the program.
Code:
private static bool IsAppInstalled(string p_machineName, string p_name)
{
string keyName;
// search in: CurrentUser
keyName = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
if (ExistsInRemoteSubKey(p_machineName, RegistryHive.CurrentUser, keyName, "DisplayName", p_name) == true)
{
return true;
}
// search in: LocalMachine_32
keyName = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
if (ExistsInRemoteSubKey(p_machineName, RegistryHive.LocalMachine, keyName, "DisplayName", p_name) == true)
{
return true;
}
// search in: LocalMachine_64
keyName = #"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall";
if (ExistsInRemoteSubKey(p_machineName, RegistryHive.LocalMachine, keyName, "DisplayName", p_name) == true)
{
return true;
}
return false;
}
private static bool ExistsInRemoteSubKey(string p_machineName, RegistryHive p_hive, string p_subKeyName, string p_attributeName, string p_name)
{
RegistryKey subkey;
string displayName;
using (RegistryKey regHive = RegistryKey.OpenRemoteBaseKey(p_hive, p_machineName))
{
using (RegistryKey regKey = regHive.OpenSubKey(p_subKeyName))
{
if (regKey != null)
{
foreach (string kn in regKey.GetSubKeyNames())
{
using (subkey = regKey.OpenSubKey(kn))
{
displayName = subkey.GetValue(p_attributeName) as string;
MessageBox.Show(displayName);
if (p_name.Equals(displayName, StringComparison.OrdinalIgnoreCase) == true) // key found!
{
return true;
}
}
}
}
}
}
return false;
}
I have tried too many different things to list (or remember)... If it helps this is the majority of the rest of the code calling it:
private void Button_Click(object sender, EventArgs e)
{
string[] lines = new string[250];
string msg = "";
string path = System.Windows.Forms.Application.StartupPath;
if (blah.Checked)
{
try
{
StreamReader filePick = new StreamReader(#path + "\\blah.txt");
int counter = 0;
while ((lines[counter] = filePick.ReadLine()) != null)
{
counter++;
}
filePick.Close();
}
catch (Exception ex)
{
msg += ex.Message;
}
}
else if (blah2.Checked)
{
try
{
StreamReader filePick = new StreamReader(#path + "\\blah2.txt");
int counter = 0;
while ((lines[counter] = filePick.ReadLine()) != null)
{
counter++;
}
filePick.Close();
}
catch (Exception ex)
{
msg += ex.Message;
}
}
string MACHINE_NAME = System.Environment.MachineName;
int counter2 = 0;
string APPLICATION_NAME = "";
string filename = "";
while (lines[counter2] != null)
{
APPLICATION_NAME = lines[counter2];
try
{
bool isAppInstalled = IsAppInstalled(MACHINE_NAME, APPLICATION_NAME);
if (isAppInstalled == true)
{
appsNeedAttention = true;
msg += APPLICATION_NAME + " is still installed.";
}
counter2++;
}
catch (Exception ex)
{
msg += ex.Message;
}
}
if (blah.Checked == true)
{
filename = "blah.txt";
}
else if (blah2.Checked == true)
{
filename = "blah2.txt";
}
if (counter2 == 0 && File.Exists(filename) == true)
{
msg = "There are no programs listed in the file.";
}
if (msg != "")
{
MessageBox.Show(msg, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
Try to change this part :
if (p_name.Equals(displayName, StringComparison.OrdinalIgnoreCase) == true)
{
return true;
}
To this :
//check null to avoid error
if (!string.IsNullOrEmpty(displayName))
{
//convert both string to lower case to ignore case difference
//and use contains to match partially
if (displayName.ToLower().Contains(p_name.ToLower()))
{
return true;
}
}

Categories

Resources