Monday, October 10, 2011

Suppress WPF Webbrowser Control Script Errors VB.NET

Since the WPF browser control has no suppress script error function and adding a windows form host is just overhead I found a solution in C# and posting the VB version here.

'Add this sub

 Public Sub HideScriptErrors(wb As WebBrowser, Hide As Boolean)
        Dim fiComWebBrowser As FieldInfo = GetType(WebBrowser).GetField("_axIWebBrowser2"BindingFlags.Instance Or BindingFlags.NonPublic)
        If fiComWebBrowser Is Nothing Then
            Return
        End If
        Dim objComWebBrowser As Object = fiComWebBrowser.GetValue(wb)
        If objComWebBrowser Is Nothing Then
            Return
        End If
        objComWebBrowser.[GetType]().InvokeMember("Silent"BindingFlags.SetProperty, Nothing, objComWebBrowser, New Object() {Hide})
    End Sub
 
In WebBrowser1 (or whatever the name of your browser control is)
add this to the Navigated event

 HideScriptErrors(WebBrowser1True)
 
It should look as such

Private Sub WebBrowser1_Navigated(sender As Object, e As System.Windows.Navigation.NavigationEventArgsHandles WebBrowser1.Navigated
        HideScriptErrors(WebBrowser1, True)
End Sub

Saturday, June 25, 2011

Asp.net with Uploadify Sample Project. VB

 Download Source code. 

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="PictureUpload._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
 
    <script src="scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
    <script src="scripts/jquery.uploadify.v2.1.4.js" type="text/javascript"></script>
    <script src="scripts/swfobject.js" type="text/javascript"></script>
    <link href="css/uploadify.css" rel="stylesheet" type="text/css" />
    <script type = "text/javascript">
     $(window).load(

    function () {

        $("#<%=FileUpload1.ClientID %>").uploadify({

            'uploader': 'scripts/uploadify.swf',

            'cancelImg': 'images/cancel.png',

            'buttonText': 'Browse Files',

            'script': 'UploadVB.ashx',

            'folder': 'uploads',

            'fileDesc': 'Image Files',

            'fileExt': '*.jpg;*.jpeg;*.gif;*.png',

            'multi': true,

            'auto': true

        });

    }

);

</script> 

</head>
<body>
    <form id="form1" runat="server">
    <div>
    <div style = "padding:40px">

        <asp:FileUpload ID="FileUpload1" runat="server" />
     
    </div>
    </div>
    </form>
    <p>
       </p>
</body>
</html>


The upload handler

Imports System.Web
Imports System.Web.Services
Imports System

Imports System.IO
Public Class UploadVB
    Implements System.Web.IHttpHandler

    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

        Dim postedFile As HttpPostedFile = context.Request.Files("Filedata")



        Dim savepath As String = ""

        Dim tempPath As String = ""

        tempPath = System.Configuration.ConfigurationManager.AppSettings("FolderPath")

        savepath = context.Server.MapPath(tempPath)

        Dim filename As String = postedFile.FileName

        If Not Directory.Exists(savepath) Then

            Directory.CreateDirectory(savepath)

        End If



        postedFile.SaveAs((savepath & "\") + filename)

        context.Response.Write((tempPath & "/") + filename)

        context.Response.StatusCode = 200

    End Sub



    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable

        Get

            Return False

        End Get

    End Property

End Class






Tuesday, April 19, 2011

Search Bing Through Silverlight C#

Search Bing with silverlight.   Download The Code

First step. Head over to http://www.bing.com/developers/ to get your free api key. It only takes a second and the app will not work without it.
This is for the API version 2.0.  The latest version as of this writing.  If you try other samples out there calling the old service api you will just end  up pulling your hair out like I did.   Microsoft is not issuing any new keys for the old live api search so most of the code examples on the web are worthless.

I'm short of time so I am just going to post the working project and briefly go over the concepts. You will have access to the documentation once you get your key.  BEWARE. Much of the documentation will not work with silverlight.  The examples I saw from Microsoft were JSON or REST.  They forgot to go over the best method, SOAP.  This project uses SOAP to simplify things.

General concept is as follows.
Create a silverlight with asp.net application.

Create a service reference to the Bing API.  http://api.bing.net/search.wsdl
Add a textbox, a button and a datagrid.  The textbox will hold the search term, the button calls the service and the grid displays the results.

Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using CSSearchBing.BingSearch; //This is the service to bing.
namespace CSSearchBing
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
//construct the call
            BingSearch.SearchRequest request = new BingSearch.SearchRequest();
 // Enter you api key.   Should be put in config file for security reasons. 
          request.AppId = "CC37A72C372AA66EA3BEB42292DDDDDDDDD";

          request.Version="2.2";
          request.Adult = AdultOption.Off;
          request.AdultSpecified = true;
          request.Query = txtSearch.Text; // search for what is in the textbox
          request.Sources = new BingSearch.SourceType[] { BingSearch.SourceType.Web };
          request.Web =new BingSearch.WebRequest();
         request.Web.Count = 10; //Ten results.  Read the documentation on how to get more.
          request.Web.CountSpecified = true;
          BingSearch.BingPortTypeClient client = new BingSearch.BingPortTypeClient("BingPort"); // BingPort is needed as is. Endpoint
          client.SearchCompleted += new EventHandler<SearchCompletedEventArgs>(client_SearchCompleted);
          client.SearchAsync(request);
        }
// our search complete handler.  Required for silverlight.
        void client_SearchCompleted(object sender, SearchCompletedEventArgs e)
        {
            SearchResponse response = e.Result;
            if (response.Web.Results.Count() > 0)
            {
                var results = from result in response.Web.Results
                              select new SearchResult
                              {
                                  SearchResultTitle = result.Title,
                                  SearchResultUri = result.Url,
                                  SearchResultDescription = result.Description
                              };

                dataGrid1.ItemsSource = results.ToList();
            }
        }
// class holds result values to pass on
        public class SearchResult
        {
            public string SearchResultTitle { get; set; }
            public string SearchResultDescription { get; set; }
            public string SearchResultUri { get; set; }
        }
  
  
    }
  
    }










Wednesday, April 6, 2011

VB,NET to Wordpress Example

Been trying to wrap my head around manipulating a php wordpress install with a .NET client.

Not much clear cut info out there so I figured I would post a quick example to give those interested a starting point.

First things first.  You need the  CookComputing.XmlRpc library. You can download the latest version here.

You need to extract the zip file using winzip, winrar or another non system extractor. 

For some reason the bin directory is not visible if using the system extractor even if you are running as Admin and have all folder view options on.

Next, start up visual studio and create a new standard windows forms application.  You should not target a compact framework. I had problems with the .net 4 client profile framework so I changed the framework to standard .net 4.0

Now you will need to add two references to the project.  Click add reference from visual studio and select browse.  You need to browse to the bin directory of the xml-rpc.net.2.5.0 directory you previously extracted.  Add a reference to   CookComputing.XmlRpcV2.dll  and IStateName.dll

Go back to your form and add a single button. View the form code window and add the following.

Imports CookComputing.XmlRpc
Imports System

Public Class Form1 'your form name
    Public Structure category
        Public categoryId As Object
        Public parentId As Object
        Public description As Object
        Public categoryName As Object
        Public htmlUrl As Object
        Public rssUrl As Object
    End Structure
 '// important to have the correct wordpress xmlrpc.php path.  If in doubt, use your browser and navigate to it '//first.

 <XmlRpcUrl("http://yoursite.com/wordpress/xmlrpc.php")> _
    Public Interface IWP
        Inherits IXmlRpcProxy

        <XmlRpcMethod("wp.getCategories")> _
        Function getCategories(ByVal args() As String) As category()
    End Interface
'// your button1 code....
 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim proxy As IWP = XmlRpcProxyGen.Create(Of IWP)()
        Dim args() As String = {"http:/yoursite.com", _
                                  "AdminUserName", "AdminPassword"}
        Dim categories() As category
        categories = proxy.getCategories(args)
        For Each category In categories
            Debug.Print(category.categoryId)
            Debug.Print(category.categoryName)
            Debug.Print(category.description)
            Debug.Print(category.htmlUrl)
            Debug.Print(category.rssUrl)
        Next

    End Sub
End Class


That should do it. 

There is another great blog that defines more functions step by step in C# and VB.net here















Saturday, March 19, 2011

Flashbuilder Timer Sample

import flash.utils.Timer;
import flash.events.TimerEvent;
private var t:Timer;
function init():void{
  t = new Timer(10000);
  t.addEventListener(TimerEvent.TIMER, functName);
  t.start();
}
function functName(e:TimerEvent):void {
    trace(" update ");
  t.start();
}

Tuesday, February 22, 2011

Get html query string with Flashbuilder 4

In the html page that hosts the swf object. Required addition.  located in c:\.....\html-template folder.
 <script type="text/javascript" src="swfobject.js"></script>
        <script type="text/javascript">
            <!-- For version detection, set to min. required Flash Player version, or 0 (or 0.0.0), for no version detection. -->
            var swfVersionStr = "${version_major}.${version_minor}.${version_revision}";
            <!-- To use express install, set to playerProductInstall.swf, otherwise the empty string. -->
            var xiSwfUrlStr = "${expressInstallSwf}";
            var flashvars = {};
var queryString = window.location.search.substring(1);
if (queryString != null & queryString.length > 0)
{
    var keyValuePairs = queryString.split("&");
    for (var i = 0; i < keyValuePairs.length; i++)
    {
        var keyValuePair = keyValuePairs[i].split("=");

        if (keyValuePair.length == 2)
        {
            flashvars[keyValuePair[0]] = keyValuePair[1];
        }
    }
}

            var params = {};
            params.quality = "high";
            params.bgcolor = "${bgcolor}";
            params.allowscriptaccess = "sameDomain";
            params.allowfullscreen = "true";
            var attributes = {};
            attributes.id = "${application}";
            attributes.name = "${application}";
            attributes.align = "middle";
            swfobject.embedSWF(
                "${swf}.swf", "flashContent",
                "${width}", "${height}",
                swfVersionStr, xiSwfUrlStr,
                flashvars, params, attributes);
            <!-- JavaScript enabled so display the flashContent div in case it is not replaced with a swf object. -->


//in the mxml file
protected function lblTest_mouseOverHandler(event:MouseEvent):void
            {
                // TODO Auto-generated method stub
                var someVariable:String = this.parameters["url"];
            lblTest.text=someVariable;
            }

Wednesday, February 16, 2011

VB.NET Webrequest with useragent

 Private Function readHtmlPage(ByVal url As String) As String
        Try
            Dim result As String
            Dim objResponse As WebResponse
            Dim objRequest As WebRequest = System.Net.HttpWebRequest.Create(url)
            DirectCast(objRequest, System.Net.HttpWebRequest).UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.38) Gecko/20101203 Firefox/3.6.13 (.NET CLR 3.5.26529)"

            objResponse = objRequest.GetResponse()
            Using sr As New StreamReader(objResponse.GetResponseStream())
                result = sr.ReadToEnd()
                'Close and clean up the StreamReader
                sr.Close()
            End Using
            Return result
        Catch ex As Exception
            'lblStatus.Text = ex.Message
            Return ex.Message.ToString
            Exit Function
        End Try
    End Function