C# } For Loop Issues [duplicate] - c#

This question already has answers here:
Value getting changed in the iteration before the call begins
(3 answers)
Closed 6 years ago.
Hello so my school has records that i needed to access but i forgot my user id, so i made a program that would download any possible PDF and search them for my name. If it found mine it would alert me however when the program was down and said "We found a file containing Sean File Name is : xxxxxx.pdf" The actual number part would be off by however much the for loop is incremented by even though this was on a separate method! BTW School name will be starred out!
*B y the way! In Search() I used i-10 as a temporary fix, but I was thinking their must be a better way *
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using BitMiracle.Docotic.Pdf; // pdf parser / viewer
using System.IO;
using System.Threading;
namespace XXXXXXX_TEMP
{
class Program
{
static void Main(string[] args)
{
Program p1 = new Program();
p1.Start();
}
private void Start()
{
WebClient wc = new WebClient();
for (int i = 200000; i < 999999999; i = i + 10)
{
try
{
wc.DownloadFile("XXXXXXXXXXXXXXXXXXXXXX/" + i + ".pdf", i + ".pdf");
}
catch (WebException) {
continue;
}
PdfDocument pdf = new PdfDocument(i + ".pdf");
Thread a = new Thread(() => Search(i, pdf));
a.Start();
if (i == 999999) {
Console.ReadLine();
}
}
}
private void Search(int i, PdfDocument pdf)
{
i = i - 10;
String html = pdf.GetText();
if (html.ToLower().Contains("sean"))
{
Console.WriteLine("Found File Containing Sean! File Name Is : " + i + ".pdf\n");
Console.WriteLine("PDF Text = " + html);
}
}
}
}

What you've run into is called closing over the loop variable. You should carefully study the linked answer as well as the blog entry it links to.
The immediate solution to your problem is to pass a copy of i to the thread. That is:
int index = i;
Thread a = new Thread(() => Search(index, pdf));
However, you might find that starting all those threads seriously bogs down your system, and leaving all those threads hanging could potentially eat up resources and lead to an out of memory exception. A cleaner way to do it is to call ThreadPool.QueueUserWorkItem, like this:
ThreadPool.QueueUserWorkItem(o => Search(index, pdf));
Or, in newer versions of .NET:
Task.Run(() => Search(index, pdf));
See Simplest way to do a fire and forget method in C#? for more information about fire-and-forget threads.

Related

To do searching in an array with some keyword

I have an array which is like
books={'java 350','Photoshop 225','php 210','JavaScript 80','python 180','jquery 250'}
my input for search as be like "ph2" it retrieve both Photoshop 225,php 210 in drop-down menu what is the exact string function to do this task or any set codes available to do this task.
I'm using some build in function like
if (array.Any(keyword.Contains))
and
if (array.Contains(keyword))
it's doesn't help what exactly i want any one pls help me to solve this thanks in advance.....
More flexible approach:
using Microsoft.VisualBasic; // add reference
using Microsoft.VisualBasic.CompilerServices;
using System.Linq;
namespace ConsoleApplication
{
class Program
{
static void Main (string[] args)
{
string[] books = { "java 350", "Photoshop 225", "php 210", "JavaScript 80", "python 180", "jquery 250" };
string input = "*" + string.Join ("*", "ph2".ToArray ()) + "*"; // will be *p*h*2*
var matches = books.Where (x => LikeOperator.LikeString (x, input, CompareMethod.Text));
}
}
}

XmlReader testing of string returned for newline

I am writing a C# class to use for generating email lists to use when a process either succeeds or fails. In running through XmlReader examples from the web, I found that validating the Read() is tougher than it looks.
I can use string.IsNullOrEmpty(x) to test for a null value or and empty node, but it will still blow by that test showing a "\n " in the tooltip for x. Testing for "\n ", '\n ', '\n'. "\n" or char(13) all fail. If I use x.Contains((char)13), it always find it and goes into the code trying to build the email address list. So far, it either always fails or always succeeds.
I found some old posts on stackoverflow where it seemed like the question was the same, but my results don't match with the answers. My environment is Windows 8.1 running Visual Studio 2013 with .Net Framework 4.51. The example from the web I was trying to make work before using the solution in my class is at Microsoft.com
My conversion is below:
using System;
using System.Text;
using System.Linq;
using System.Xml;
using System.Xml.Schema;
using System.IO;
using System.Collections.Generic;
namespace XMLDemo
{
public class project
{
public static void Main()
{
string uri = #"C:\\events\items.xml";
string process_state = "Item";
string emails = StreamEmailAddress(uri, process_state);
}
private static string StreamEmailAddress(string uri, string process_state)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
XmlReader reader = XmlReader.Create(uri, settings);
string returnValue = "";
reader.MoveToContent();
while (reader.Read())
{
string x = reader.Value;
if ((string.IsNullOrEmpty(x) == false) && (x.Contains((char)13)))
{
returnValue = returnValue + x + "; ";
}
}
Console.WriteLine("Made it to the end: " + returnValue);
return returnValue;
}
}
}
You should use string.IsNullOrWhiteSpace
SOLVED: After futzing with it all day, I looked at it with slightly fresher eyes after posting and saw the blatant error. I was using the incorrect function and trying to resolve line feeds by myself. By replacing IsNullOrEmpty(x) with IsNullOrWhiteSpace(x), I got the string of data as expected. Doing the code with email addresses will be easy now.

winform Close self plus another WebBrowserControl

i know i could search proccessId / name of running tasks and kill processes i need .
though till now i was not developing schedualed tasks / self executble Applications,
so i didn't need to know how to make the application close itself after execition
trying to close everything (including WebDriver) via Application.Exit + OR this.Close()
right after i have got what i was looking for. mission Complete .
please close ... no more work for you .
but mr . Program.cs still needs somthing from Form1.
saying somthing about
Cannot access a disposed object.
Object name: 'Form1'.
any combination of both was returning in some point an exeption error
(from program.cs ) even though mission complete . no more code was requested .(?) by me..atleast.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using System.IO;
namespace HT_R_WbBrows2
{
public partial class Form1 : Form
{
public IeEnginGenerator Iengn = new IeEnginGenerator();
public Form1()
{
InitializeComponent();
//setLogView(View.Details);
string extractededVal = Iengn.ExtractPageValue(Iengn.itrfWebEng);
string flnm = #" the directory path to file --> \dolarRate.asp";
File.WriteAllText(fn, extractededVal);
this.Close();
Application.Exit();
}
public class IeEnginGenerator
{
private string directory = Environment.CurrentDirectory;///Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
public IWebDriver IwebEngine;
public List<string> ListElementsInnerHtml = new List<string>();
public HtmlAgilityPack.HtmlDocument Dnetdoc = new HtmlAgilityPack.HtmlDocument();
#region <<=========== setupDriver ============>>
public string ExtractPageValue(IWebDriver DDriver, string url="")
{
if(string.IsNullOrEmpty(url))
url = #"http://www.boi.org.il/he/Markets/ExchangeRates/Pages/Default.aspx";
var service = InternetExplorerDriverService.CreateDefaultService(directory);
service.LogFile = directory + #"\seleniumlog.txt";
service.LoggingLevel = InternetExplorerDriverLogLevel.Trace;
var options = new InternetExplorerOptions();
options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
DDriver = new InternetExplorerDriver(service, options, TimeSpan.FromSeconds(60));
DDriver.Navigate().GoToUrl(url);
Dnetdoc.LoadHtml(DDriver.PageSource);
string Target = Dnetdoc.DocumentNode.SelectNodes("//table//tr")[1].ChildNodes[7].InnerText;
//.Select(tr => tr.Elements("td").Select(td => td.InnerText).ToList())
//.ToList();
return Math.Round(Convert.ToDouble(Target), 2).ToString();
//return "";//Math.Round(Convert.ToDouble( TempTxt.Split(' ')[10]),2).ToString();
}
#endregion
}
}
}
Why use a winform application? A Console application would probably suffice for what you are doing. Once Main() ends your app will close as well. Main() never ends in a winform app because of the applications runloop.
Edit:
Here would be the correct way to do this. You need to register to the forms Load event and run your code there, not in the constructor. You can't close a winform from inside a constructor.
Edit 2: Put this code in the Form1() constructor. Somewhere after InitializeComponent();
this.Load += (sender,args)=>{ /*do all your work here*/
string extractededVal = Iengn.ExtractPageValue(Iengn.itrfWebEng);
string flnm = #" the directory path to file --> \dolarRate.asp";
File.WriteAllText(fn, extractededVal);
Application.Exit();
};

Programming an autoupdater / launcher application in c# that works with any program

I am making a program updater / launcher that can be used for any program.
I have a config file on the client and a config file on a http server. I get version numbers from both of them and compare them and if they are are not = then update the client.
I have everything working except for when the update starts. What I need is say if someone downloaded my application and do not use if for say a month and in between that time I have 5 or so updates.
The problem is how to I get my program to download the first update , install it and then download the next update untill they have all been downloaded?
I am new to programming and this is the only kind of app I can think of to work on to learn.
Thanks
My settings.conf on http server XML File.
<Table>
<Product>
<Product_id>1</Product_id>
<Product_name>Infected</Product_name>
<Product_version>1.0.0.1</Product_version>
<Product_Url>http://localhost/update/v1.0.0.1.exe</Product_Url>
<Product_id>2</Product_id>
<Product_name>Infected</Product_name>
<Product_version>1.0.0.2</Product_version>
<Product_Url>http://localhost/update/v1.0.0.2.exe</Product_Url>
<Product_id>3</Product_id>
<Product_name>Infected</Product_name>
<Product_version>1.0.0.3</Product_version>
<Product_Url>http://localhost/update/v1.0.0.3.exe</Product_Url>
<Product_id>4</Product_id>
<Product_name>Infected</Product_name>
<Product_version>1.0.0.4</Product_version>
<Product_Url>http://localhost/update/v1.0.0.4.exe</Product_Url>
<Product_id>5</Product_id>
<Product_name>Infected</Product_name>
<Product_version>1.0.0.5</Product_version>
<Product_Url>http://localhost/update/v1.0.0.5.exe</Product_Url>
</Product>
</Table>
My Client Config XML file.
<Table>
<Product>
<Product_id>1</Product_id>
<Product_name>Infected</Product_name>
<Product_version>1.0.0.0</Product_version>
<Product_Url>http://localhost/update/v1.0.0.1.exe</Product_Url>
</Product>
</Table>
My C# Form.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.Net;
using System.Diagnostics;
using System.Runtime.Remoting;
namespace Launcher
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public string localversion { get; set; }
public string remoteversion { get; set; }
public string UpdateURL { get; set; }
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Navigate("http://www.kceoc.com/");
webBrowser2.Navigate("http://www.kceoc.com/");
button1.Enabled = false; // Disable the launch button untill all updates are completed.
GetLocalXMLFile(); //Run first xml function to start everything off.
}
private void GetLocalXMLFile()
{
try //Start error checking.
{
using (XmlTextReader localxml = new XmlTextReader("settings.conf")) //Load xml file in same folder as launcher.exe
{
while (localxml.Read()) // Start reading the settings.conf file
{
switch (localxml.NodeType) //Get the Node that we will use.
{
case XmlNodeType.Text:
label1.Text = localxml.Value; //Change the text of label1 to value of Node.
string localversion = localxml.Value; // Store Node Value in string localversion for latter use.
GetRemoteXMLFile(localversion, remoteversion); //Everything went ok and got a value from Node so pass this all to our next function witch is get remote xml.
break;
}
}
}
}
catch (FileNotFoundException)
{
label1.Text = "Local Config not found. Reinstall the application"; // Catch error incase file is not there.
}
}
private void GetRemoteXMLFile(string localversion, string remoteversion)
{
try //Start error checking
{
using (XmlTextReader remotexml = new XmlTextReader("http://localhost/update/settings.conf")) //Load up remote xml on web server
{
while (remotexml.Read()) //Start reading xml file from server.
{
switch (remotexml.NodeType)
{
case XmlNodeType.Text:
label2.Text = remotexml.Value; // Change value of label2 to remote xml node value
remoteversion = remotexml.Value; // Set the remoteversion string to remotexml.value
CompareXMLFileVersions(localversion, remoteversion); // Everything went ok so send localversion string and remoteversion string to compare function.
break;
}
}
}
}
catch (FileNotFoundException)
{
label1.Text = "Remote config not found. Maby website id down?"; // Catch error incase file is not there.
}
}
private void CompareXMLFileVersions(string localversion, string remoteversion)
{
label1.Text = localversion; // Just so we can see the value in the lables to konw if they have value or not.
label2.Text = remoteversion; // Just so we can see the value in the lables to konw if they have value or not.
if (localversion == remoteversion) // Comparing the values of localversion and remoteversion and if they have same value then
{ // change label3 to You have latest version.
label3.Text = "You have the latest version";
}
else
{
label3.Text = "There is a new version. Starting update process here"; // If localversion and remoteversion are diffrent then let user know the files are out of date and start the updating process..
GetListOfUpdates(remoteversion); // Starting the updating process function..
}
}
private void GetListOfUpdates(string remoteversion)
{
//WebClient webClient = new WebClient();
//webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
//webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
//webClient.DownloadFileAsync(new Uri(remoteversion), #"v1.0.0.1.exe");
string url = "http://localhost/update/v1.0.0.1.exe";
WebClient downloader = new WebClient();
downloader.DownloadFileCompleted += new AsyncCompletedEventHandler(downloader_DownloadFileCompleted);
downloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloader_DownloadProgressChanged);
downloader.DownloadFileAsync(new Uri(url), "temp.exe");
}
void downloader_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
label1.Text = e.BytesReceived + " " + e.ProgressPercentage;
}
void downloader_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
//if (e.Error != null)
// MessageBox.Show(e.Error.Message);
//else
// MessageBox.Show("Completed!!!");
}
}
}
Thanks
Welcome to SO!
I am new to programming and this is the only kind of app I can think of to work on to learn. Thanks
Depending on how new you are, I'd really recommend you start with something a little easier. Otherwise, the first thing I'd recommend you do is to actually draw a flowchart. Your logic looks a little off, and it looks as if you're huffing it trying to design this system as you write it, which is something you never want to be doing.
There are a lot of solutions for this that provide a better, more reliable systems then anything you can make yourself, but I can understand the educational value of this sort of project. I made my own 'auto-update/launcher' recently for just that reason, and it works reasonably well, albeit on a free webserver with myself an some friends as the only users.
Here's the flowchart I made for it:
Large:http://i.imgur.com/qS1U8.png
This is actually the second iteration of my little project, with the first being less then overwhelming and somewhat disastrous in uncommon circumstances, but it's a good learning experiance. This one also has goofy command files that I can define things like showing messages to the user during an update, which is nice.
If you don't mind looking at terrible and messy code, you can look through the code repo here, although it's not documented and a few part's aren't actually used but haven't been removed from source control. An example application that uses it is here (source, also messy).
Sorry for what looks like a shameless self-plug, but I can't really answer your question directly and hope that you might be able to make use of some of this as an indication of how you should go about doing this, since it's actually a pretty fun project.

Opening mp3 by not-default program C sharp

How can I open mp3 file with RealPlayer while the default is MediaPlayer
I know Process and ProcessStartInfo method, but I would like to know how to "open program with..."
Can you help me, plz?
Okay, so thought I'd make this possible for you before I clock off for the night. I have thrown together a working console application which loads (known) installed programs from the registry's App Path key. The solution is far from perfect, won't be the safest, fastest, or most reliable solution, and it certainly shouldn't be seen amongst any production code, but it is more than enough to aid you, hopefully, in developing what it is you need:
So, here is the code, minus the namespace...
using System;
using System.IO;
using Microsoft.Win32;
using System.Diagnostics;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
if (args.Length >= 0 && !string.IsNullOrEmpty(args[0]) && File.Exists(args[0]))
{
var programs = new InstalledPrograms();
var programKey = "RealPlay.exe".ToLowerInvariant();
if (programs.ContainsKey(programKey))
{
var programPath = programs[programKey];
if (!string.IsNullOrEmpty(programPath) && File.Exists(programPath))
{
var process = new Process();
process.StartInfo = new ProcessStartInfo(programPath);
process.StartInfo.Arguments = args[0];
if (process.Start())
{
Console.WriteLine("That was easy!");
}
else
{
Console.WriteLine("Hell's bells and buckets of blood, we seem to have hit a snag!");
}
}
}
}
else
{
Console.WriteLine("Specify a file as an argument, silly!");
}
Console.WriteLine();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
class InstalledPrograms : Dictionary<string, string>
{
static string PathKeyName = "Path";
static string RegistryKeyToAppPaths = #"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths";
public InstalledPrograms()
{
Refresh();
}
public void Refresh()
{
Clear();
using (var registryKey = Registry.LocalMachine.OpenSubKey(RegistryKeyToAppPaths))
{
var executableFullPath = string.Empty;
foreach (var registrySubKeyName in registryKey.GetSubKeyNames())
{
using (var registrySubKey = registryKey.OpenSubKey(registrySubKeyName))
{
executableFullPath = registrySubKey.GetValue(string.Empty) as string;
Add(registrySubKeyName.ToLowerInvariant(), executableFullPath);
}
}
}
}
}
}
Though we check for file existence, and other minor but necessary checks are made, you would still need to tighten this up further when plugged into the environment of your own code, including, among other things, exception handling for, but not limited to, registry access issues.

Categories