I am using SharpDevelop platform and I want to do perform a google search for an expression, then generate a list of all web addresses in the first page, another list on the second page, etc. Using some sample code I found, I can retrieve results from the first page. How can I modify the code to get the results on the second page?
Maybe there are better methods than what I found, for example using google API?
Here is the code:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Net;
using System.Collections.Specialized;
namespace GoogleSearch
{
/// <summary>
/// Description of MainForm.
/// </summary>
public partial class MainForm : Form
{
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
//
// TODO: Add constructor code after the InitializeComponent() call.
//
}
void Button1Click(object sender, EventArgs e)
{
string uriString = "http://www.google.com/search";
string keywordString = "search expression";
WebClient webClient = new WebClient();
NameValueCollection nameValueCollection = new NameValueCollection();
nameValueCollection.Add("q", keywordString);
webClient.QueryString.Add(nameValueCollection);
textBox1.Text = webClient.DownloadString(uriString);
}
}
}
Related
I have to make a program to back up my IDM download list every day, because there is other ones using my computer and they removing my download list.
IDM API only lets me add download to IDM list, so is there any library or other way to back up my IDM download list using C#?
thanks for helping
Thanks to #Setsu found out a solution. there is a key in registry which contains all of the URLs. the key is HKEY_CURRENT_USER\Software\DownloadManager and it contains keys which contains values named Url0 with the URL in it.
As an example HKEY_CURRENT_USER\Software\DownloadManager\85\Url0 contains one of added link to IDM download list.
So I searched all of the HKEY_CURRENT_USER\Software\DownloadManager subkeys for Url0 and saved the values to a list box using this code:
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 Microsoft.Win32;
namespace IDMListSaver
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
RegistryKey key = Registry.CurrentUser.OpenSubKey("Software\\DownloadManager");
string[] keys = key.GetSubKeyNames();
for (int i = 0; i <= key.SubKeyCount-1; i++)
{
key = key.OpenSubKey(keys[i]);
Object o = key.GetValue("Url0");
if (o != null)
{
listBox1.Items.Add(o);
}
key = Registry.CurrentUser.OpenSubKey("Software\\DownloadManager");
}
}
}
}
It definitely can get better, but it solved my problem until here.
So thanks again #Setsu
I'm trying to use the Bing Search API to find images as backgrounds to the tiles inside of my app. I've included the BingSearchContainer.cs in my Project but I can't make it work with the sample code provided here.
Any guidelines for how to use the Bing Search API inside of my Windows Phone 8 app would be appriciated!
Thanks for any answer.
I expect that you already have a AccountKey so I wont tell you have to get one.
Implementation
First of all, add the BingSearchContainer.cs to your project
Implement the sample C# code found in the Bing API Quick Start & Code
Thereafter, right-click References and choose Manage NuGet Packages... and search for, and install, Microsoft.Data.Services.Client.WindowsP.
Modify the sample code so that it work with Windows Phone:
using Bing;
using System;
using System.Data.Services.Client;
using System.Linq;
using System.Net;
namespace StackOverflow.Samples.BingSearch
{
public class Finder
{
public void FindImageUrlsFor(string searchQuery)
{
// Create a Bing container.
string rootUri = "https://api.datamarket.azure.com/Bing/Search";
var bingContainer = new Bing.BingSearchContainer(new Uri(rootUri));
bingContainer.UseDefaultCredentials = false;
// Replace this value with your account key.
var accountKey = "YourAccountKey";
// Configure bingContainer to use your credentials.
bingContainer.Credentials = new NetworkCredential(accountKey, accountKey);
// Build the query.
var imageQuery = bingContainer.Image(query, null, null, null, null, null, null);
imageQuery.BeginExecute(_onImageQueryComplete, imageQuery);
}
// Handle the query callback.
private void _onImageQueryComplete(IAsyncResult imageResults)
{
// Get the original query from the imageResults.
DataServiceQuery<Bing.ImageResult> query =
imageResults.AsyncState as DataServiceQuery<Bing.ImageResult>;
var resultList = new List<string>();
foreach (var result in query.EndExecute(imageResults))
resultList.Add(result.MediaUrl);
FindImageCompleted(this, resultList);
}
public event FindImageUrlsForEventHandler FindImageUrlsForCompleted;
public delegate void FindImageUrlsForEventHandler(object sender, List<string> result);
}
}
Example
And now, let's use the code I provided you with:
using Bing;
using System;
using System.Data.Services.Client;
using System.Linq;
using System.Net;
namespace StackOverflow.Samples.BingSearch
{
public class MyPage
{
private void Button_Click_1(object sender, RoutedEventArgs e)
{
var finder = new Finder();
finder.FindImageUrlsForCompleted += finder_FindImageUrlsForCompleted;
finder.FindImageUrlsFor("candy");
}
void finder_FindImageUrlsForCompleted(object sender, List<string> result)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
foreach (var s in result)
MyTextBox.Text += s + "\n";
});
}
}
}
I'm compiling code on-the-fly using System.CodeDom.Compiler. Everything inside the compiled source works well, whatever I'm putting inside this source. I know how to call my functions:
o = results.CompiledAssembly.CreateInstance("Foo.Bar");
MethodInfo mi = o.GetType().GetMethod("SayHello");
mi.Invoke(o, null);
But let's say I'm using a WebClient to retrieve a string asynchronously using WebClient.DownloadStringAsync. Or any other context where I want my compiled source to tell to the host "Hey, I got a nice string ready for you." For the example, I've used a WebBrowser. Basically, I know how to deal with each of the two instances: My hosting program and the compiled program, but I want my compiled program to communicate with the host. By the way, I'm not a super-experimented programmer, so no obvious method comes to my mind.
What I've tried:
1 . I don't really need to try it because it would work, but I could use a timer reading a strings stack or tasks queue inside the compiled source, but the purpose of my application is to have +- 60 scripts able to execute ponctual tasks, not continuous background processes, so it wouldn't be efficient on the CPU.
2 . I've passed the handler to the compiled source like if it was in the hosting app:
//In the hosting app
MethodInfo mi2 = o.GetType().GetMethod("attachCallbackToHost");
mi2.Invoke(o2, new object[] { new WebBrowserNavigatedEventHandler (wb_navigated) });
//... And the handler
public static void wb_navigated(object sender, WebBrowserNavigatedEventArgs e)
{
string browserHtmlFromCompiledSource = ((WebBrowser)sender).DocumentText;
MessageBox.Show(browserHtmlFromCompiledSource);
}
// Plain text from the compiled source code
public void attachCallbackToHost(WebBrowserNavigatedEventHandler handlerFromTheHost)
{
wb.Navigated += handlerFromTheHost;
}
And it did nothing.
3 . Maybe I could share a class or variable by passing it to the compiled assembly?
So, the question is either this or the other:
How to watch efficiently for change inside a specific variable or property inside the compiled program?
How to attach a callback to the host?
Ok. I got it: In order to access the host from the compiled source, the only thing required is to add the host assembly to the refered assemblies in the compiler parameters:
compilerParams.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
So no need for any special callback or INotifier.
Here's the full code that strictly answers my question and nothing more:
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 Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
namespace MamaProgram
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string source =
#"
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.Net;
using MyMama = MamaProgram;
namespace Baby
{
public class Program
{
public WebBrowser wb = new WebBrowser();
public void navigateTo(string url)
{
wb.Navigated += wb_navigated;
wb.Navigate(url);
}
public void wb_navigated(object sender, WebBrowserNavigatedEventArgs e)
{
MyMama.Form1.getResult(wb.DocumentText);
}
}
}
";
Dictionary<string, string> providerOptions = new Dictionary<string, string>
{
{"CompilerVersion", "v3.5"}
};
CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);
CompilerParameters compilerParams = new CompilerParameters
{
GenerateInMemory = true,
GenerateExecutable = false,
TreatWarningsAsErrors = false
};
compilerParams.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
compilerParams.ReferencedAssemblies.Add("System.Data.dll");
compilerParams.ReferencedAssemblies.Add(typeof(System.Linq.Enumerable).Assembly.Location); // Trick to add assembly without knowing their name
compilerParams.ReferencedAssemblies.Add(typeof(System.ComponentModel.Component).Assembly.Location); // Trick to add assembly without knowing their name
compilerParams.ReferencedAssemblies.Add("System.Windows.Forms.dll");
CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);
if (results.Errors.Count != 0)
throw new Exception("Compilation failed");
object o = results.CompiledAssembly.CreateInstance("Baby.Program");
MethodInfo mi2 = o.GetType().GetMethod("navigateTo");
mi2.Invoke(o, new object[] { "http://www.google.com" });
}
public static void getResult(string result)
{
MessageBox.Show(result);
}
}
}
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();
};
I want to create a simple app that shows me the city of the current application.
When I tried the code that I will paste below it returns empty for city, and it returns for country =US, but I live in Belgium.
According to this link
It says:
The location services provides access to location functionality, such as cell triangulations, WiFi (through IP address), and GPS. Also great many modern devices supports resolving location in some way from mentioned before, application must handle the case where location services cannot resolve the location or user has disabled location services from the Control Panel.
My Laptop does not have GPS, but with the IP, it should know the city and country.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Devices.Geolocation;
using System.Threading.Tasks;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace AlarmPro
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
//InitializeLocationServices();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
TextBlock txt = new TextBlock();
var location = await InitializeLocationServices();
txt.Text = location;
Grid.SetRow(txt, 0);
Grid.SetColumn(txt, 1);
}
private async Task<string> InitializeLocationServices()
{
//Initialize geolocator object
Geolocator geoLocator = new Geolocator();
try
{
//Try resolve the current location
var position = await geoLocator.GetGeopositionAsync();
if (position !=null)
{
string city = position.CivicAddress.City;
string country = position.CivicAddress.Country;
string state = position.CivicAddress.State;
string zip = position.CivicAddress.PostalCode;
string msg = "I am located in " + country;
if (city.Length > 0)
msg += ", city of " + city;
if (state.Length > 0)
msg += ", " + state;
if (zip.Length > 0)
msg += " near zip code " + zip;
return msg;
}
return string.Empty;
}
catch (Exception)
{
//Nothing to do - no GPS signal or some timeout occured.n .
return string.Empty;
}
}
}
}
Fairly certain you'll need to wait for the Geolocator to actually get a position.
The naive way would be to just keep trying in a while loop to see if there's a new update.
You'll want to probably want to attach to the PositionChanged event handler and wait for that to tell you that you have new updates.
Here's some info and code examples straight from the source.
http://msdn.microsoft.com/en-us/library/windows/apps/br225534.aspx
I do believe there's also some accuracy (DesiredAccuracy property) settings in there, perhaps that could be useful as well in making it be a bit more specific.