Need a default search engine for web browser control - c#

I have created a web browser app for windows phone 7 using web browser control. I want to add a default search engine(i.e, a textBox that is used for Google search or Bing search). And also if the user type anything(words like technology or so on), the search should be redirected to the above default search engine. Can anyone help me with this???
The textBox that I used for entering URL is named as "UrlTextBox" and my web browser control is named as "browsers". The textBox is used for search engine is named as "SearchTextBox".
Thanks in advance for your hard work!!!
public void browsers_Navigating(object sender, NavigatingEventArgs e)
{
UrlTextBox.Text = e.Uri.ToString();
if (navigationcancelled)
{ e.Cancel = true; }
SearchEngine[] availableSearchEngines = new SearchEngine[]
{new SearchEngine(){ Name = "Google", URLPattern = "http://www.google.com/search?q={0}" }};
new SearchEngine(){ Name = "Yahoo", URLPattern = "http://search.yahoo.com/search?p={0}" };
new SearchEngine(){ Name = "Bing", URLPattern = "http://www.bing.com/search?q={0}" };
}
UrlTextBox-:
private void UrlTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
Uri url;
if (Uri.TryCreate(UrlTextBox.Text, UriKind.Absolute, out url))
{
this.urls[this.currentIndex] = UrlTextBox.Text;
this.browsers[this.currentIndex].Navigate(url);
}
if (!Uri.TryCreate(UrlTextBox.Text, UriKind.Absolute, out url))
{
SearchEngine defaultSearchEngine = availableSeachEngines[0];
String URL = String.Format(defaultSearchEngine.URLPattern, UrlTextBox.Text);
}
else
{
Navigate(UrlTextBox.Text);
}
}
}
But there is an error says "availableSeachEngines" --->
The name availableSeachEngines does not exist in the current context.
Now i have added my codes above that i have used in my program and also added Muaz Othman codes into it. But its not working for me and also shows the error. I think am making some mistakes in it. Can anyone correct it??? Thanks in advance!!!

You can create a class like this:
public class SearchEngine {
public string Name {set; get}
public string URLPattern { get; set;}
public override string ToString(){
return Name;
}
}
and in your code you can have this array:
SearchEngine[] availableSearchEngines = new SearchEngine[]{
new SearchEngine(){ Name = "Google", URLPattern = "http://www.google.com/search?q={0}" };
new SearchEngine(){ Name = "Yahoo", URLPattern = "http://search.yahoo.com/search?p={0}" };
new SearchEngine(){ Name = "Bing", URLPattern = "http://www.bing.com/search?q={0}" };
}
but in your code you should have only one SearchEngine object:
SearchEngine defaultSearchEngine;
so when the user enters text and chooses "Go" you check if the entered text is a valid URL (maybe using a regular expression), and if not you do this:
String url = String.Format(defaultSearchEngine.URLPattern, SearchTextBox.Text);

Related

DotNetBrowser: How to use multiple IEngine?

I'm having trouble using multiple DotNetBrowser IEngine instances at once.
Whenever I try to use more than one at a time, they conflict, even though I have already defined different folders for each one.
Follow the code I'm using.
public void initializeBrowser(string guid)
{
string contextDirectory = Application.StartupPath + #"\cache\" + guid;
string pathProxy = ConfigurationManager.AppSettings["pathProxy"];
BrowserView browserView = new BrowserView()
{
Dock = DockStyle.Fill
};
engine = EngineFactory.Create(new EngineOptions.Builder
{
UserDataDirectory = contextDirectory,
SandboxDisabled = true,
RenderingMode = RenderingMode.OffScreen,
}.Build());
browserView.InitializeFrom(browser);
browser = engine.CreateBrowser();
browser.Navigation.FrameLoadFinished += delegate (object sender, FrameLoadFinishedEventArgs e)
{
Console.Out.WriteLine($"FrameLoadFinished: URL = {e.ValidatedUrl},"
+ $" IsMainFrame = {e.Frame.IsMain}");
};
}

Error in creating twitterizer app in asp.net

I am using Twitterizer dll to post a twit on twitter via oauth method but it give me error.
"Whoa there!
There is no request token for this page. That's the special key we need from applications asking to use your Twitter account. Please go back to the site or application that sent you here and try again; it was probably just a mistake."
And my code is:
using System;
using Twitterizer;
public partial class Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var oauth_consumer_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var oauth_consumer_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
if (Request["oauth_token"] == null)
{
OAuthTokenResponse reqToken = OAuthUtility.GetRequestToken(oauth_consumer_key, oauth_consumer_secret,
Request.Url.AbsoluteUri);
Response.Redirect(string.Format("http://Twitter.com/oauth/authorize?oauth_token+{0}", reqToken.Token));
}
else
{
string requestToken = Request["oauth_token"].ToString();
string pin = Request["oauth_verifier"].ToString();
var tokens = OAuthUtility.GetAccessToken(oauth_consumer_key, oauth_consumer_secret, requestToken, pin);
OAuthTokens accessToken = new OAuthTokens()
{
AccessToken = tokens.Token,
AccessTokenSecret = tokens.TokenSecret,
ConsumerKey = oauth_consumer_key,
ConsumerSecret = oauth_consumer_secret
};
TwitterResponse<TwitterStatus> response = TwitterStatus.Update(accessToken, "Hello everyone, today it's too hot (weather)!!!");
if (response.Result == RequestResult.Success)
{
Response.Write("It's done");
}
else
{
Response.Write("Fail");
}
}
}
}
Please help me..
Seeing no one is giving an answer to your problem, I can suggest the library I am working on.
With Tweetinvi you will be able to do what you want with the following code :
// Step 1 : Redirect user to go on Twitter.com to authenticate
public ActionResult TwitterAuth()
{
var appCreds = new ConsumerCredentials("CONSUMER_KEY", "CONSUMER_SECRET");
// Specify the url you want the user to be redirected to
var redirectURL = "http://" + Request.Url.Authority + "/Home/ValidateTwitterAuth";
var authenticationContext = AuthFlow.InitAuthentication(appCreds, redirectURL);
return new RedirectResult(authenticationContext.AuthorizationURL);
}
// Step 2 : On redirected url
public ActionResult ValidateTwitterAuth()
{
// Get some information back from the URL
var verifierCode = Request.Params.Get("oauth_verifier");
var authorizationId = Request.Params.Get("authorization_id");
// Create the user credentials
var userCreds = AuthFlow.CreateCredentialsFromVerifierCode(verifierCode, authorizationId);
// Do whatever you want with the user now!
ViewBag.User = User.GetAuthenticatedUser(userCreds);
return View();
}
Authentication Documentation : https://github.com/linvi/tweetinvi/wiki/Authentication
I know this is not helping for your Twitterizer but you might want to consider it.

C# application to post on facebook group as regular user

I've just developed my first c# app to post on facebook. Currently, I have no problems to post on my wall, but what I want to do is to post on group's wall, but not as admin, but as regular user. When I changed ID to post with group one instead of my profile, I get auth error. It seems I am missing some permissions. Please take a look at my code and tell me what I am missing to post on given group's wall, and again to underline, I want to post as regular user of the group, not as admin.
So I use this when I am getting the permissions.
private const string ExtendedPermissionsNeeded = "publish_actions";
I am using this to generate Login Url
private string GenerateLoginUrl()
{
dynamic parameters = new ExpandoObject();
parameters.client_id = app_id;
parameters.redirect_uri = "https://www.facebook.com/connect/login_success.html";
parameters.response_type = "token";
parameters.display = "popup";
if (!string.IsNullOrWhiteSpace(ExtendedPermissionsNeeded))
parameters.scope = ExtendedPermissionsNeeded;
var fb = new FacebookClient();
Uri loginUri = fb.GetLoginUrl(parameters);
return loginUri.AbsoluteUri;
}
And finally here is what i am using to post on facebook:
private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
string accessToken;
bool authorized;
if (webBrowser1.Visible)
{
var fb = new FacebookClient();
FacebookOAuthResult oauthResult;
if (fb.TryParseOAuthCallbackUrl(e.Url, out oauthResult))
{
if (oauthResult.IsSuccess)
{
accessToken = oauthResult.AccessToken;
authorized = true;
}
else
{
accessToken = "";
authorized = false;
}
if (authorized)
{
fb = new FacebookClient(accessToken);
dynamic result = fb.Get("me");
fb.Post("/100000853192437/feed", new { message = "test " });
}
else
{
MessageBox.Show("Couldn't log into Facebook!", "Login unsuccessful", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
}
With API v2.4, you can not post into regular groups any more as a normal user.
user_groups permission has been removed (and will be removed for all apps, whatever API version they are using, on Oct. 6, 2015), and only user_managed_groups is available now – and that only gives access (read/write) to the groups the user is an admin of.
https://developers.facebook.com/docs/graph-api/reference/v2.4/group/feed#publish
https://developers.facebook.com/docs/apps/changelog#v2_4_deprecations

Reading out Edge Browser Title & Url with System.Windows.Automation

I'm trying to read out the TITLE & URL from the Microsoft EDGE Browser.
Doing this with System.Windows.Automation most preferably since the code base already uses this for other problems.
Is it possible with System.Windows.Automation?
How to access the URL?
I'm currently this far:
AutomationId "TitleBar"
ClassName "ApplicationFrameWindow"
Name = [string]
=> Reading out this element gives me the TITLE
=> Walking it's children, I find the item "addressEditBox":
AutomationId "addressEditBox"
ClassName "RichEditBox"
Name "Search or enter web address"
=> I always get back the string "Search or enter web address"
=> This is the control where the url is in, though it isn't updated as the user goes to a website, it always returns a fixed string.
In code:
var digger1 = AutomationElement.FromHandle(process.MainWindowHandle).RootElement.FindAll(TreeScope.Children, Condition.TrueCondition);
foreach(AutomationElement d1 in digger1 {
if(d1.Current.ClassName.Equals("ApplicationFrameWindow")) {
var digger2 = d1.FindAll(TreeScope.Children, Condition.TrueCondition);
foreach(AutomationElement d2 in digger2) {
if(d2.Current.ClassName.Equals("Windows.Ui.Core.CoreWindow")) {
var digger3 = d2.FindAll(TreeScope.Children, Condition.TrueCondition);
foreach(AutomationElement d3 in digger3) {
if(d3.Current.AutomationId.Equals("addressEditBox")) {
var url = d3.Current.Name;
return url;
}
}
}
}
}
}
You're almost there. You just need to get the TextPattern from the addressEditBox element. Here is a full sample Console app that dumps out all currently running Edge's windows on the desktop:
class Program
{
static void Main(string[] args)
{
AutomationElement main = AutomationElement.FromHandle(GetDesktopWindow());
foreach(AutomationElement child in main.FindAll(TreeScope.Children, PropertyCondition.TrueCondition))
{
AutomationElement window = GetEdgeCommandsWindow(child);
if (window == null) // not edge
continue;
Console.WriteLine("title:" + GetEdgeTitle(child));
Console.WriteLine("url:" + GetEdgeUrl(window));
Console.WriteLine();
}
}
public static AutomationElement GetEdgeCommandsWindow(AutomationElement edgeWindow)
{
return edgeWindow.FindFirst(TreeScope.Children, new AndCondition(
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window),
new PropertyCondition(AutomationElement.NameProperty, "Microsoft Edge")));
}
public static string GetEdgeUrl(AutomationElement edgeCommandsWindow)
{
var adressEditBox = edgeCommandsWindow.FindFirst(TreeScope.Children,
new PropertyCondition(AutomationElement.AutomationIdProperty, "addressEditBox"));
return ((TextPattern)adressEditBox.GetCurrentPattern(TextPattern.Pattern)).DocumentRange.GetText(int.MaxValue);
}
public static string GetEdgeTitle(AutomationElement edgeWindow)
{
var adressEditBox = edgeWindow.FindFirst(TreeScope.Children,
new PropertyCondition(AutomationElement.AutomationIdProperty, "TitleBar"));
return adressEditBox.Current.Name;
}
[DllImport("user32")]
public static extern IntPtr GetDesktopWindow();
}

Changing properties on FB's User object

Can I change properties on FB's User object? Can I change "work" and "education"? I need to add information to these collections. I have user_work_history permission all right.
I used CS-Canvas-AspNetWebForms-WithoutJsSdk as a basis. Server replies "true" (in the id variable) but nothing gets changed. "100002852727242" is id on my app's fake test user, Dorothy Ambhebgbgbdb Liman. Tried also post to "me" instead with same effect (= zilch).
Here's my code:
protected void btnPostToWall_Click(object sender, EventArgs e)
{
if (CanvasAuthorizer.Authorize())
{
var fb = this.CurrentClient;
var parameters = new
{
work = new []
{
new
{
employer = new
{
id = "20528438720",
name = "Microsoft"
},
location = new
{
id = "109738839051539",
name = "Redmond, Washington"
},
position = new
{
id = "131108890265554",
name = "SDE"
},
start_date = "1991-01"
}
}
};
try
{
dynamic id = fb.Post("100002852727242", parameters);
lblPostMessageResult.Text = "Message posted successfully";
txtMessage.Text = string.Empty;
}
catch (FacebookApiException ex)
{
lblPostMessageResult.Text = ex.Message;
}
}
}
Original sample code was posting something on the Dorothy's wall, no probs there. Maybe I can't post to "http://graph.facebook.com/me?"? Couldn't find anything useful anywhere. Any ideas?
Thanks in advance!!
Currently, you cannot POST to /USER_ID, only to connections on the User object, e.g. /USER_ID/feed. Hence, you cannot change properties on the User object via a POST.

Categories