drupal hit counter
Jerry Huang | All posts by jerry

Jerry Huang apps and developing apps

share on facebook with blogengine

18. June 2011 12:56 by Jerry in BlogEngine

The original post is here: http://blog.sumantdubey.com/post/Share-your-posts-on-Facebook-and-Retweet-them-on-Twitter-with-TWITBOOKSHARE-e28093-BlogEngineNET-Extension.aspx

Unfortunately, the extension class is not working with my latest blogengine 2.0, so I enhanced it a little bit, and now it's working.

download here

  1. place the cs file at App_Code\Extensions
  2. add the css (with notepad) at the end of \themes\the-theme-your-blog-using\style.css
  3. go to extension settings page to enable sharing

IP cameras reviews from the point of view of a developer

11. June 2011 09:48 by Jerry in IP CAM

During the last few months, I had been working with various ip cameras from different brands and types. This review is not focus on functionality but mainly from a developer's angle how the invisible quality of a camera inside is.

 

  • ACTi
    ACTi is recently supported by IP CAM Controller, but this brand actually has a very long history. They provide comprehensive SDK document but most seems only in C++, not very helpful for me though.

    The user who drawn my attention to support this type of cameras, possess both ACM-1231 and ACM-5601 (both are not PTZ camera BTW). At the beginning, my program is just not working with user’s camera, but working with vendor’s demo one. Then I realized user was using “Web Configurator - Version v2.6”, it’s normal, since he probably brought the cameras a few years ago. After he upgraded to latest v3.0 version, problem gone.

    During my testing, I felt ACTi is a kind of old style, I guess probably because its history. There isn’t too much to say about the functionality since I only tested with these 2 fixed cameras.
  • AirLink
    AirLink is not a big manufacturer I guess, their website is pretty informative for consumer but not for developer. For IP camera, their product line is simple which is good for me since I don’t need to handle different scenarios in coding.

    I worked out for this camera without API documentation, but doing some searching on Google. Later on I accessed to user’s camera and implemented the tap-to-center support. It uses the settings as Ipux, maybe their firmware are the same.

    AirLink is fully supported by IP CAM Controller except zooming, but the camera itself doesn’t support optical zooming neither. As a small brand with reasonable price, it’s a nice choice.
  • Axis
    In my opinion, Axis is more popular for business users. They have various products and full solutions for commercial usages. I guess it also have a high reputation in its market, since it’s top tier cameras in terms of price. I will recommend this if you care about quality while concern less on money.

    Axis is a large and mature vendor; they publish full and different SDK documents for different developing purpose. In my case, I only need the HTTP API which can be easily downloaded from their website.

    Axis is completely supported by IP CAM Controller, including regular PTZ, also tap-to-center. Although they have many product lines, but their HTTP API is consistent in all products. This prove that they are good and mature, since only good API could be well designed at the beginning, then future releases could rely on the steady infrastructure.

    Recently received an inquiry that not working on 207W, after some investigation, turn out that 207W is working on Digest Authentication (while others are working on Basic Authentication). Thanks to Tommy who is the owner of 207W, the IP CAM Controller starts to support digest auth (not only Axis, but all other types as well) since v1.9.
  • Canon
    Canon is one of the biggest and best digital camera providers in the world. Most of their IP cameras are not for home users however. I had tested a few advanced models from a local electric appliances shop. VB-C50Fi for example, equipped with 26x Optical Zoom Lens, this give me excellent experience that I could see everything very clearly. Even after done my programming works, I connected to this camera from time to time just for playing around the zooming:) naughty, huh? As a result, If you want something professional, you must have a look at this.

    As a big vendor, I didn’t get too many troubles during development, except for tap-to-center function. Unlike Axis to provide a straightforward API for this, there is no direct support for this purpose. Nevertheless, I found a walk-around that requesting a dummy still image by specifying the direct coordinate, tricky!
  • D-Link
    Well, D-Link is a kind of suck I have to say. It has several product lines, such as Box, fixed and PTZ types. For different types of D-Link, they have the same web interface (the web page after log on), but I can’t believe that the commands using for similar types of camera are different. For example, 1130L is using a set of commands while 5605 is using another set.

    Another problem I found with DCS-2121 is that tiny difference in firmware version may result of big difference in compatibility. A user from Italy told me that 2121 is working on desktop version but failed in phone version. After comparison between vendor’s demo camera with user’s, it turns out that demo camera is using “1.05_patch01” while user is using “1.05”. What kind of version is that? Patch 01? It’s so un-professional, looks like some kind of productions of personal workshop. I guess this is the reason they don’t publish their SDK document. Maybe they don’t have standard at the moment. It’s really mass.

    Anyway, the reason why 1.05 not working in phone is because the web server in 1.05 cannot retrieve the authentication information, ie. username and password from requests that sent via Windows Phone 7, although from the sniffing software, the credential is already passed to remote 1.05 web server. This could be either D-Link’s problem or Microsoft’s fault (probably the latter in my opinion, ha). Anyway, I worked this out by make up my own authentication header. The IP CAM Controller should be compatible with both 1.05 and 1.05_patch01 firmware since v1.9.

    As for ordinary camera functions, I don’t see particular differences from others, just fair I think. The best supported type with IP CAM controller for D-Link is DCS-5605, PTZ, pan/tilt scan and tap-to-center.
  • Foscam
    Foscam surprises me because this cheap but cool camera has so many users from US and Euro, considering the vendor is a small manufactory base in Shenzhen China mainland. You can find many info regarding this brand on Google, API, consumer reviewers, and guess what, I found someone make a robot with Foscam! (check here), I bet they have very strong sale channel in those regions.

    Latest API is available on request, you can send an email to the support email to get one, they response very fast. Actually I doubt that they are using some sort of open source web server in the Foscam, because I found many small brands are compatible with Foscam’s API, such as Solwise, 7Links.

    The only 2 things a bit annoying me is that 1) Foscam is a bit weird on pan and tilt control. Once the camera is moving, it will not stop until you send a stop command. I only found Sony is a company of that at the moment. 2) No tap-to-center support, their web interface support this feature, but not providing in the API. I reported to vendor, but I don’t think they took my opinion seriously. Anyway, to sum up, if you are looking for something cheap and cool, Foscam was born for you.
  • Lorex
    Lorex is a surveillance solution provider, looks like a pretty big one, listed in Canada. I only tested with LNE3003, a fixed camera. There wasn’t too much difficulty for me, since I only implement view function at the moment.

    It’s not a camera I like though, the camera supports still image, motion JPEG (MJPEG), 3gp and MP4. The camera look like support these format concurrently, ie. viewing MJPEG and MP4 at the same time, but actually it is NOT. You need to setup different port numbers for different streaming format, e.g. 8070 is used by default for MJPEG, 560 is for MP4, etc, And more stupid is that another port (says 85) is using for accessing the web interface via HTTP. I don’t see the point why it has to be like this.

    MJPEG must be connected via HTTP and it’s not sharing with the port of web interface. For example, you visit your camera via http://192.1.168.121:85, but when you open the live video page, your browser is actually using 8070 to retrieve image. Why not share the same port as other cameras do?

    Besides, although you had set different formats corresponding different ports, you have to choose one and one only for the current image stream format. In other word, your camera is either working on MJPEG format or MP4 at the same time. Then why I have to set those stupid separated port numbers?

    Hopefully I’m wrong above, otherwise it just doesn’t make sense. Or maybe those ports are working exclusively for their DVR.
  • Mobotix
    Mobotix has more than 10 years history. Very good documentation, they host a website for developer and publish the APIs in HTML format. It’s open and professional. With this support, it’s very easy to implement everything. IP CAM Controller supports PTZ and tap-to-center for Mobotix, tested with M12D-S.

    More considerately, if you send something wrong to the camera, it will tell you the possible reason. For example, if you don’t pass a parameter, the camera responses that which parameter is missing. It’s perfect camera for developer.

    For consumer, Mobotix has all functionalities that other brands have, so if the price is reasonable, it's a nice camera to go with.
  • Panasonic
    This is the camera I am using as well as the first camera supported in IP CAM Controller. I had been using BL-C131 for almost 3 years. It comes with 1 year warranty, when my first BL-C131 broken (wifi chip broken, still can work in wired mode) in the second year, I have to buy another one, same type. I’m quite surprise Panasonic didn’t release successive new camera after years.

    In my case, Panasonic is too easy to broken although it’s continuously running 24*7 in my apartment.  (But is this what IP Camera designed for?) And BL-C131 is one of the most expensive cameras. In addition, comparing with other cameras, the viewing angle is too small, only 149° horizontally (some bands could even extend to 270°). The reason I still brought the same type is because I could re-use the parts inside the broken one if the new one broken again. Plus I didn’t have time for shopping and I have to keep an eye on my baby when working.

    Apart from these, it’s a good camera. Support MPEG-4 and MJPEG concurrently (unlike Lorex). Quite stable, contains audio, motion detection, recording, etc, basically everything an IP camera suppose to have. For developer, one set API compatible almost all Panasonic cameras. And I’m impressive for that the new firmware backward compatible with old version. In BL-C131, with latest firmware, there are actually 2 set of commands I could use. This is important and considerate.
  • Sony
    Similar to Canon, not really suitable for home usage. Some types also support 18x even 26x optical zooming.

    I don’t have too much trouble during development for Sony. Comprehensive SDK document, standard API as others, and more importantly, no varieties API for different kinds of products.

    Same as Canon, recommend for professionals. But I don’t like its “foscam-like” pan tilt control.
  • Toshiba
    Another old Japanese brand, fully supported by IP CAM Controller, but tap-to-center seems not working for some types.

    Toshiba looks a bit “high-tech” for me, from its API, it’s not following simply design principle. The streaming path contains too many parameters. It seems trying to be perfect, since you need to encrypt your user name and password to BASE64 format before sending over HTTP. But BASE64 is not for encryption unfortunately. There is no difference for hacker between BASE64 string and plain text. Toshiba provides a direct-move-api which is to implement the tap-to-center functionality, but by using this, you have to understand its “unlike-others” coordinate system. The API accepts only one passing in parameter which is calculated by X and Y via a formula: V = X*256 + Y.
    I’m glad that I’m Chinese, as Chinese are good at maths! LOL

    Anyway, Toshiba maybe not a developer friendly camera, but it seems quite good for consumer, good image quality, easy to use. But I’m not really sure if this is suitable for home usage. The types (IK-WB21A and IK-WB15A) I tested are both seem to be expensive.
  • TRENDnet
    TRENDnet is also a company with long history; at least I received many TRENDnet camera owner enquiries. I’m not sure if TRENDnet has API, I can’t find one on the website. But I found much information from Google, probably a benefit for a large brand with long history.

    Actually it was quite painful when working on TRENDnet. When I published my very early version on marketplace, I received a user’s email saying that IP600 not working for him. This brand has the same problem as D-Link. It cannot accept the user name and password I passed, but instead of replying 401 unauthorized request, it returns a 502 bad gateway error. This misleading me and caused that I spent a lot of time (from Apr to Jun) for this issue. And secondly, different products use different commands, even for similar types IP612P and IP600.

    To sum up, it's definitely not a developer-friendly camera, but maybe good for consumers, otherwise it couldn't survived for that long
  • VivoTek
    Maybe it’s because VivoTek is a Taiwan company, it seems VivoTek is not so popular in US. Actually VivoTek is one of the major brands in Asia.

    I worked out the VivoTek support in desktop version a few months ago, but I haven’t published to phone version until lately. For 7000 series, there are 2 versions of API, the latest one call “V2”. The problem in phone version could be solved by upgrading to latest firmware which is supported V2 API commands. The APIs are available after log on to their website, free registration.
  • Y-Cam
    All Y-Cam at the moment are fixed camera, this is a small UK company I guess. They haven’t published their SDK, but it will be available on request, after you signed the Non-Disclosure Agreement with them. The SDK is informative, even containing some sample codes in C++.

    Actually before I received their SDK, I already figured out the viewing command, I just want to PTZ command from their document. However, later I realized that Y-Cam is not a PTZ camera.

    Their website prodives many live demo in many countries, which is good for both developers and consumers. You can actually have a look before purchase.

IP CAM Controller is ranking top 44 today

9. June 2011 10:26 by Jerry in IP CAM

Although received the first and second bad reviews recently, it raised 10 position since last update in April.

As the Marketplace at the moment is not allowed developer to response user review, not even contact the reviewer via email or anything. So I guess I can only say something here, poor me:(

The first bad review was from US, saying that not working with D-LINK 930L camera and complaining there is no free trail before purchase. Well, first of all, I do provide free trail if you read the app desc. You can try at your computer here. And second, 930L is not in the tested list. For D-Link, I only tested DCS-1130L which is showing in the app desc. In case the reviewer read this blog, you may contact me to arrange a test, to see if there is any problem, or alternative walkaround. As far as I know, some camera by default is not setted to support MJPEG, you may need to change that.

The 2nd one was from Austria that complaining too expensive and something like "no longer stop"? (original comment is not in english, I use translator) Ok, you beat me. I can't comment on price since it's not the cheapest one. But comparing to some competitors' price like $19.99 or $7.99, mine in $3.99 is a kind of economic, isn't it? For "no longer stop", I'm not sure which camera you have, but if you are using foscam, it's a foscam's feature that the camera will keep moving until you tap the direction button again. e.g. tap left button, camera will start moving left until either reach the left end or you tap the left button again.

Anyway, apart from these two bad reviews, all the rest are rating from 4 to 5 stars, 13 rates in total. The average worldwide score is 4 for the time being. Many thanks for those positive reviewers!

If you have purchased IP CAM Controller and not yet rated, I appreciate if you could do me a favor by giving it a rate: in the app list page of your phone, tap and hold "IP CAM Controller", a menu will pop up, select "rate and review" which will lead you to the review page; click the stars to rate and leave a message; It's recommended to say something like what camera brand and type are working for you. Great thanks!yes

ListPicker performance tuning

8. June 2011 22:53 by Jerry in UI, Windows Phone Development

The ListPicker control in Silverlight for Windows Phone Toolkit (Feb 2011 release) has become famous after its poor performance.wink My app IP CAM Controller for example, starts from v1.6, I used ListPicker to accommodate the full list of supported camera types and brands. The total item number is about 20 to 30, while it took 3 to 5 seconds to get response when openning the setup page. It's really a huge lag.

Thanks to Pedro Lamas who solved this problem by changing the source code in a few places. Details please refer to here:

http://www.pedrolamas.com/2011/06/02/listpicker-a-cafeina/

It's not in english, but translator is available on the right up side of the page. He also submitted a patch to the official Toolkit project on CodePlex here:

http://silverlight.codeplex.com/SourceControl/list/patches

patch ID 9632, providing a brief summary in english.

Good news for those lazy people (such as meblush), I attached the compiled binary and source file base on Pedro's blog, feel free to download from here.

Unzip the file and copy the two files (Microsoft.Phone.Controls.Toolkit.dll and Microsoft.Phone.Controls.Toolkit.pdb) to your Toolkit installation folder, e.g.

C:\Program Files\Microsoft SDKs\Windows Phone\v7.0\Toolkit\Feb11\Bin\

 

What make Smart Dial so special?

30. April 2011 13:29 by Jerry in Smart Dial
  • the first app supports "Edit Before Call" in the marketplace
  • the first app supports search Chinese contacts in Pinyin
  • the first app supports import both Live and Gmail contacts from phone (there is one before Smart Dial, but only support Live)
  • hopefully will be the first one to edit contact photo from camera or photo hub (will be available in next release)

click here for more info

Replace TinyMCE with CKEditor and CKFinder in BlogEngine 2.0

24. April 2011 22:23 by Jerry in BlogEngine

From the first day of using BlogEngine, I'm suffering the built-in editor which is the stupid TinyMCE. I finally make up my mind to replace it after upgraded the website to the latest BlogEngine 2.0 version, because it's really slow when typing.

 

  1. download the latest ckeditor and ckfinder for ASP.NET, put CKEditor.NET.dll and CKFinder.dll to the BIN folder of your blogengine website;
    and copy the rest stuff to editors folder, like: editors/ckeditor; editors/ckfinder;
  2. disable any form of http compression, including but not limit to IIS settings (if you had enabled) and blogengine compression, otherwise ckfinder will not working
  3. edit blogengine web.config file, to disable the default http compression, search for "CompressionModule", remove or comment the whole line, i.e.
    <!--add name="CompressionModule" type="BlogEngine.Core.Web.HttpModules.CompressionModule, BlogEngine.Core"/-->
    *BTW, I spent hours to troubleshoot ckfinder, before I disable this setting, I always got an "system error" 1072896748 with ckfinder.

    By now, you should proper config ckeditor and ckfinder, make sure you are able to run those samples. You will need to set folder permission, change config files etc, for details, please refer to ckeditor and ckfinder's documentations.

    From the next step, will start to integrate blogengine with ckeditor and ckfinder.
     
  4. modify admin/HtmlEditor.ascx

[code language=ASPX]

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="htmlEditor.ascx.cs" Inherits="Admin.HtmlEditor" %>
<%@ Register Src="tinyMCE.ascx" TagName="tinyMCE" TagPrefix="uc1" %>
<%--<uc1:tinyMCE ID="TinyMCE1" runat="server" />--%>

<textarea class="ckeditor" ID="TinyMCE1" style="width:100%" rows="40" runat="server"></textarea>

<script src='/editors/ckeditor/ckeditor.js' type='text/javascript'></script>
<script src='/editors/ckfinder/ckfinder.js' type='text/javascript'></script>
<script type= "text/javascript" defer="defer">
/*
var oFCKeditor = new CKeditor( '<%=TinyMCE1.ClientID %>',null,null,"Default" ) ;
oFCKeditor.BasePath = "/editors/ckeditor/" ;
oFCKeditor.filebrowserBrowseUrl = '/editors/ckfinder/ckfinder.html';
oFCKeditor.filebrowserImageBrowseUrl = '/editors/ckfinder/ckfinder.html?type=Images';
oFCKeditor.filebrowserFlashBrowseUrl = '/editors/ckfinder/ckfinder.html?type=Flash';
oFCKeditor.ReplaceTextarea() ;
*/
CKEDITOR.replace( '<%=TinyMCE1.ClientID %>',
{
filebrowserBrowseUrl : '/editors/ckfinder/ckfinder.html',
filebrowserImageBrowseUrl : '/editors/ckfinder/ckfinder.html?type=Images',
filebrowserFlashBrowseUrl : '/editors/ckfinder/ckfinder.html?type=Flash',
filebrowserUploadUrl : '/editors/ckfinder/core/connector/aspx/connector.aspx?command=QuickUpload&type=Files',
filebrowserImageUploadUrl : '/editors/ckfinder/core/connector/aspx/connector.aspx?command=QuickUpload&type=Images',
filebrowserFlashUploadUrl : '/editors/ckfinder/core/connector/aspx/connector.aspx?command=QuickUpload&type=Flash',
filebrowserWindowWidth : '1000',
filebrowserWindowHeight : '700'
});
</script>

[/code]

 

  1. modify admin/HtmlEditor.ascx.cs

[code language=C#]

// --------------------------------------------------------------------------------------------------------------------
// <summary>
//   The admin_html editor.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Admin
{
    using System.Web.UI;

    /// <summary>
    /// The admin_html editor.
    /// </summary>
    public partial class HtmlEditor : UserControl
    {
        #region Properties

        /// <summary>
        /// Gets or sets TabIndex.
        /// </summary>
       
        public short TabIndex
        {
         /*
            get
            {
                return this.TinyMCE1.TabIndex;
            }

            set
            {
                this.TinyMCE1.TabIndex = value;
            }*/
            get { return 0; }
      set { }

        }

        /// <summary>
        /// Gets or sets Text.
        /// </summary>
        public string Text
        {
            get
            {
                return this.TinyMCE1.Value;
            }

            set
            {
                this.TinyMCE1.Value = value;
            }
        }
       
        public string EditorID
        { get{return TinyMCE1.ClientID;}}

        #endregion
    }
}

[/code]

  1. modify admin/Posts/Add_entry.aspx, should be 2 places in AutoSave and SavePost javascript functions
    replace "tinyMCE.activeEditor.getContent();" with "CKEDITOR.instances['<%=txtContent.EditorID %>'].getData()"
  2. modify admin/Posts/EditPage.aspx, similar with above, but only 1 place in SavePage function
    change  var content = tinyMCE.activeEditor.getContent(); to
    var content = CKEDITOR.instances['<%=txtContent.EditorID %>'].getData();
  3. modify CheckAuthentication function in editors/ckfinder/config.ascx
    to integrate the blogengine authentication, otherwise everyone will be able to upload file to your user file folder if you simply return true:
    return Page.User.Identity.IsAuthenticated;
  4. It's not realted to integration, but it's a security issue that most people forgot,
    * to remove all samples in the _samples folder, as well as the _source folder
    * it's a good practice to follow the ckfinder's suggestion: in IIS, set Execute Permissions to "none" in the properties of the user files folder (ie. upload folder)

A WinForm Image Selector Control

24. April 2011 12:35 by Jerry in UI

First of all, I have to point out that the control is far from perfect. So far it's just workable for my Smart Dial Agent. If you want to make use of it, you will need to do your own customization or make it flexible by using control property. You are welcome to send me back an enhanced version if you have done some works on itLaughing

Before going into technical details, let's have a look how it works

The rectangle with black border in the photo is the selector, while the image on the left is the target cropped photo. The selector could move or resize, but it couldn't smaller than 96*96.

The original source code is from a Chinese website (I forgot which one now, sorry) and base on .Net Framework 1.1. It doesn't work probably at the beginning, I'm not sure if relates to the framework. I just fix some problems and make some changes to fit my needs.

Usage:

New a Form in Visual Studio, drap a PictureBox and then place a Selector control on top of the PictureBox. drap another PictureBox as target image. Trigger the Mouse-Up event to retrieve target image. Below is a sample:

[code language=C#]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 SmartDialAgent.Utils;
using SmartDialAgent.Controls;

namespace SmartDialAgent
{
    public partial class CropImage : Form
    {
        public CropImage()
        {
            InitializeComponent();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog dlg = new OpenFileDialog();
                dlg.Filter = "Images|*.jpg;*.jpeg;*.png;*.bmp";
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    LoadImage(dlg.FileName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void LoadImage(string path)
        {
            Image img = Image.FromFile(path);
            if (img.Width > 640 || img.Height > 480)
            {
                //source img too big, adjust size
                int x1, y1;//base on width
                if (img.Width > 640)
                {
                    x1 = 640;
                    y1 = 640 * img.Height / img.Width;
                }
                else
                {
                    x1 = img.Width;
                    y1 = img.Height;
                }
                int x2, y2;//base on height
                if (img.Height > 480)
                {
                    y2 = 480;
                    x2 = 480 * img.Width / img.Height;
                }
                else
                {
                    x2 = img.Width;
                    y2 = img.Height;
                }
                //choose the smaller pairs
                if (x1 > x2)
                {
                    img = img.GetThumbnailImage(x2, y2, null, new IntPtr());
                }
                else
                {
                    img = img.GetThumbnailImage(x1, y1, null, new IntPtr());
                }
            }
            pbImage.Image = img;
            pbImage.Width = img.Width;
            pbImage.Height = img.Height;
            int len;
            if (img.Width > img.Height)
                len = img.Height;
            else
                len = img.Width;
            if ((len / 2) > 96)
            {
                pictureBoxSelection1.Width = len / 2;
                pictureBoxSelection1.Height = pictureBoxSelection1.Width;
            }
            else
            {
                pictureBoxSelection1.Width = 96;
                pictureBoxSelection1.Height = 96;
            }
            pictureBoxSelection1.PictureBox = pbImage;
            groupBox1.Width = pbImage.Width;
            groupBox1.Height = pbImage.Height;
            pictureBoxSelection1.Left = pbImage.Left;
            pictureBoxSelection1.Top = pbImage.Top;
            this.GetTargetImage();

        }


        private void GetTargetImage()
        {
            Image img;
            if (pictureBoxSelection1.SelectedImage == null)
            {
                img = PictureBoxSelector.Crop(pbImage.Image, pictureBoxSelection1.Size, pictureBoxSelection1.Left - pbImage.Left, pictureBoxSelection1.Top - pbImage.Top);
            }
            else
            {
                img = pictureBoxSelection1.SelectedImage;
            }
             if (img != null && img.Width > 96)
                    img = img.GetThumbnailImage(96, 96, null, new IntPtr());
                pbTarget.Image = img;
        }

        private void pictureBoxSelection1_MouseUp(object sender, MouseEventArgs e)
        {
            GetTargetImage();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }
        private Image Image
        {
            get
            {
                return pbTarget.Image;
            }
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;
        }

        public static Image GetCropImage(string path)
        {
            using (CropImage frm = new CropImage())
            {
                frm.LoadImage(path);
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    return frm.Image;
                }
                else
                    return null;
            }
        }

 

    }
}

[/code]

 

Control source code:

[code language=C#]

using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using SmartDialAgent.Utils;
using System.Drawing.Drawing2D;

namespace SmartDialAgent.Controls
{

    public class PictureBoxSelector : System.Windows.Forms.Control
    {

        private Color _BorderColor = new Color();
        //private Color _BackColor = new Color();
        private bool _ReSizeble;
        private Point _SelfLocation = new Point();
        private Point _MouseLocation = new Point();
        private int _SelfWidth;
        private int _SelfHeight;
        private int _SelectSelctedIndex;//0-8,0:SizeAll
        private Rectangle _rectLeftSelector = new Rectangle();
        private Rectangle _rectTopSelector = new Rectangle();
        private Rectangle _rectRightSelector = new Rectangle();
        private Rectangle _rectBottomSelector = new Rectangle();
        private Rectangle _rectLeftTopSelector = new Rectangle();
        private Rectangle _rectRightTopSelector = new Rectangle();
        private Rectangle _rectRightBottomSelector = new Rectangle();
        private Rectangle _rectLeftBottomSelector = new Rectangle();
        private System.ComponentModel.Container components = null;
        public PictureBoxSelector()
        {
            InitializeComponent();
        }
        [DefaultValue("Black"), Description("color of the border"), Category("Appearance")]
        public Color BorderColor
        {
            get
            {
                // Insert code here.
                return _BorderColor;
            }
            set
            {
                _BorderColor = value;
                this.Invalidate();
            }
        }
        //[DefaultValue("Control"), Description("Background color"), Category("Appearance")]
        //public override Color BackColor
        //{
        //    get
        //    {
        //        // Insert code here.
        //        return _BackColor;
        //    }
        //    set
        //    {
        //        _BackColor = value;
        //        this.Invalidate();
        //    }
        //}
        [DefaultValue(false), Description("Indicates the control coud be moved and resized"), Category("Behavior")]
        public bool ReSizeble
        {
            get
            {
                // Insert code here.
                return _ReSizeble;
            }
            set
            {
                _ReSizeble = value;
                this.Invalidate();
            }
        }

        [Description("Selected area"), Category("Behavior")]
        public Rectangle SelectedRectangle
        {
            get
            {
                Rectangle selectRectangler = new Rectangle();
                selectRectangler.X = this.Location.X ;
                selectRectangler.Y = this.Location.Y ;
                selectRectangler.Height = this.Height ;
                selectRectangler.Width = this.Width ;
                return selectRectangler;
            }

        }
        /// <summary>
        /// the selected image
        /// </summary>
        public Image SelectedImage { get; private set; }

        public static Bitmap Crop(Image image, Size targetSize, int x, int y)
        {
            try
            {
                Bitmap bmp = new Bitmap(targetSize.Width, targetSize.Height);//, PixelFormat.Format24bppRgb);
                bmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);

                Graphics gfx = Graphics.FromImage(bmp);
                gfx.SmoothingMode = SmoothingMode.AntiAlias;
                gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
                gfx.PixelOffsetMode = PixelOffsetMode.HighQuality;
                gfx.DrawImage(image, new Rectangle(0, 0, targetSize.Width, targetSize.Height),
                    x, y, targetSize.Width, targetSize.Height, GraphicsUnit.Pixel);

                gfx.Dispose();

                return bmp;
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// repaint the background by copying crop image from parent picturebox
        /// </summary>
        /// <param name="e"></param>
        private void RepaintBackground(PaintEventArgs e)
        {
            if (PictureBox != null && PictureBox.Image!=null)
            {
                Image img = Crop(PictureBox.Image, Size, Left - PictureBox.Left, Top - PictureBox.Top);
                if (img != null)
                    e.Graphics.DrawImage(img, 0, 0, Width, Height);
                SelectedImage = img;
            }
        }
        protected override void OnPaint(PaintEventArgs e)
        {
            RepaintBackground(e);
            ReDrawControl(e.Graphics);
        }
        private void DrawSelector(Graphics graphics)
        {
            SolidBrush SelectorPen = new SolidBrush(Color.White);
            Pen borderPen = new Pen(this._BorderColor, 1);
            try
            {
                //solid
                PointF[] LeftPoints = getPointF(0, this.Height / 2 - 3, 6, 6);
                graphics.FillClosedCurve(SelectorPen, LeftPoints);

                PointF[] TopPoints = getPointF(this.Width / 2 - 3, 0, 6, 6);
                graphics.FillClosedCurve(SelectorPen, TopPoints);

                PointF[] RightPoints = getPointF(this.Width - 7, this.Height / 2 - 3, 6, 6);
                graphics.FillClosedCurve(SelectorPen, RightPoints);

                PointF[] BottomPoints = getPointF(this.Width / 2 - 3, this.Height - 7, 6, 6);
                graphics.FillClosedCurve(SelectorPen, BottomPoints);
               
                //remove the 4 solid resize selectors, I don't need it, if you need to, add them back
                //PointF[] LeftTopPoints = getPointF(0, 0, 6, 6);
                //graphics.FillClosedCurve(SelectorPen, LeftTopPoints);

                //PointF[] RightTopPoints = getPointF(this.Width - 7, 0, 6, 6);
                //graphics.FillClosedCurve(SelectorPen, RightTopPoints);

                //PointF[] RightBottomPoints = getPointF(this.Width - 7, this.Height - 7, 6, 6);
                //graphics.FillClosedCurve(SelectorPen, RightBottomPoints);

                //PointF[] LeftBottomPoints = getPointF(0, this.Height - 7, 6, 6);
                //graphics.FillClosedCurve(SelectorPen, LeftBottomPoints);
                //borders
                int border = 6;
                _rectLeftSelector.X = 0;
                _rectLeftSelector.Y = this.Height / 2 - 3;
                _rectLeftSelector.Height = border;
                _rectLeftSelector.Width = border;
                graphics.DrawRectangle(borderPen, _rectLeftSelector);

                _rectTopSelector.X = this.Width / 2 - 3;
                _rectTopSelector.Y = 0;
                _rectTopSelector.Height = border;
                _rectTopSelector.Width = border;
                graphics.DrawRectangle(borderPen, _rectTopSelector);

                _rectRightSelector.X = this.Width - 7;
                _rectRightSelector.Y = this.Height / 2 - 3;
                _rectRightSelector.Height = border;
                _rectRightSelector.Width = border;
                graphics.DrawRectangle(borderPen, _rectRightSelector);

                _rectBottomSelector.X = this.Width / 2 - 3;
                _rectBottomSelector.Y = this.Height - 7;
                _rectBottomSelector.Height = border;
                _rectBottomSelector.Width = border;
                graphics.DrawRectangle(borderPen, _rectBottomSelector);
               
                //remove the 4 solid resize selectors, I don't need it, if you need to, add them back
                //_rectLeftTopSelector.X = 0;
                //_rectLeftTopSelector.Y = 0;
                //_rectLeftTopSelector.Width = border;
                //_rectLeftTopSelector.Height = border;
                //graphics.DrawRectangle(borderPen, _rectLeftTopSelector);

                //_rectRightTopSelector.X = this.Width - 7;
                //_rectRightTopSelector.Y = 0;
                //_rectRightTopSelector.Width = border;
                //_rectRightTopSelector.Height = border;
                //graphics.DrawRectangle(borderPen, _rectRightTopSelector);

                //_rectRightBottomSelector.X = this.Width - 7;
                //_rectRightBottomSelector.Y = this.Height - 7;
                //_rectRightBottomSelector.Width = border;
                //_rectRightBottomSelector.Height = border;
                //graphics.DrawRectangle(borderPen, _rectRightBottomSelector);

                //_rectLeftBottomSelector.X = 0;
                //_rectLeftBottomSelector.Y = this.Height - 7;
                //_rectLeftBottomSelector.Width = border;
                //_rectLeftBottomSelector.Height = border;
                //graphics.DrawRectangle(borderPen, _rectLeftBottomSelector);
            }
            catch (Exception E)
            {
                throw E;
            }
            finally
            {
                SelectorPen.Dispose();
                borderPen.Dispose();
            }

        }
        private void ReDrawControl(Graphics graphics)
        {

            try
            {

                //draw background
               
                //graphics.Clear(this._BackColor);
                //SolidBrush backPen=new SolidBrush(this._BackColor);
                //PointF point1 = new PointF(1,1);
                //PointF point2 = new PointF(this.Width-2,1);
                //PointF point3 = new PointF(this.Width-2,this.Height-2);
                //PointF point4 = new PointF(1,this.Height-2);
                //PointF[] points = {point1, point2, point3, point4};
                //graphics.DrawImage(ImageUtils.CropImage(this.PictureBox, new Rectangle(Left, Top, Width, Height)),);
                //graphics.FillClosedCurve(backPen, points);
               
                //border
                Rectangle rectBorder = new Rectangle();
                Pen borderPen = new Pen(this._BorderColor, 1);
                rectBorder.X = 0;
                rectBorder.Y = 0;
                rectBorder.Height = this.Height - 1;
                rectBorder.Width = this.Width - 1;
                graphics.DrawRectangle(borderPen, rectBorder);
                //selector
                if (_ReSizeble)
                {
                    DrawSelector(graphics);
                }
            }
            catch (Exception E)
            {
                throw E;
            }
            finally
            {
                graphics.Dispose();
            }
        }
        public PictureBox PictureBox { get; set; }
        protected override void OnPaintBackground(PaintEventArgs e)
        {
            this.RepaintBackground(e);
        }


        private PointF[] getPointF(int x, int y, int Width, int Height)
        {
            PointF point1 = new PointF(x, y);
            PointF point2 = new PointF(x + Width, y);
            PointF point3 = new PointF(x + Width, y + Height);
            PointF point4 = new PointF(x, y + Height);
            PointF[] points = { point1, point2, point3, point4 };
            return points;
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                    components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region generated by Visual Studio

        private void InitializeComponent()
        {
            components = new System.ComponentModel.Container();
            this.Resize += new EventHandler(ShapeEx_Resize);
            this.MouseDown += new MouseEventHandler(ShapeEx_MouseDown);
            this.MouseMove += new MouseEventHandler(ShapeEx_MouseMove);
            this.MouseLeave += new EventHandler(ShapeEx_MouseLeave);
            this.MouseUp += new MouseEventHandler(ShapeEx_MouseUp);
            this.Move += new EventHandler(Selection_Move);
            this._BorderColor = Color.Black;
            //this._BackColor = Color.Transparent;//.FromName("Control");
            this._ReSizeble = false;
            this._SelectSelctedIndex = -1;
            SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);  
            //SetStyle(ControlStyles.OptimizedDoubleBuffer, true);  

        }
        #endregion

        private void ShapeEx_Resize(object sender, EventArgs e)
        {
            //hard code 96, the smallest size could be,
            //will be better if use a Size property
            if (this.Width < 96 || this.Height < 96)
            {
                this.Width = 96;
                this.Height = 96;
            }
            this.Invalidate();
        }

 

        private void ShapeEx_MouseDown(object sender, MouseEventArgs e)
        {
            if (_ReSizeble)
            {
                if (_rectLeftSelector.Contains(e.X, e.Y) || _rectRightSelector.Contains(e.X, e.Y) || _rectTopSelector.Contains(e.X, e.Y) || _rectBottomSelector.Contains(e.X, e.Y) || _rectLeftTopSelector.Contains(e.X, e.Y) || _rectRightTopSelector.Contains(e.X, e.Y) || _rectRightBottomSelector.Contains(e.X, e.Y) || _rectLeftBottomSelector.Contains(e.X, e.Y))
                {
                    if (_rectLeftTopSelector.Contains(e.X, e.Y))
                    {
                        this.Cursor = Cursors.SizeNWSE;
                        this._SelectSelctedIndex = 1;
                    }

                    if (_rectTopSelector.Contains(e.X, e.Y))
                    {
                        this.Cursor = Cursors.SizeNS;
                        this._SelectSelctedIndex = 2;
                    }
                    if (_rectRightTopSelector.Contains(e.X, e.Y))
                    {
                        this.Cursor = Cursors.SizeNESW;
                        this._SelectSelctedIndex = 3;
                    }
                    if (_rectRightSelector.Contains(e.X, e.Y))
                    {
                        this.Cursor = Cursors.SizeWE;
                        this._SelectSelctedIndex = 4;
                    }
                    if (_rectRightBottomSelector.Contains(e.X, e.Y))
                    {
                        this.Cursor = Cursors.SizeNWSE;
                        this._SelectSelctedIndex = 5;
                    }
                    if (_rectBottomSelector.Contains(e.X, e.Y))
                    {
                        this.Cursor = Cursors.SizeNS;
                        this._SelectSelctedIndex = 6;
                    }
                    if (_rectLeftBottomSelector.Contains(e.X, e.Y))
                    {
                        this.Cursor = Cursors.SizeNESW;
                        this._SelectSelctedIndex = 7;
                    }
                    if (_rectLeftSelector.Contains(e.X, e.Y))
                    {
                        this.Cursor = Cursors.SizeWE;
                        this._SelectSelctedIndex = 8;
                    }

                }
                else
                {
                    this.Cursor = Cursors.SizeAll;
                    this._SelectSelctedIndex = 0;
                }
                this._SelfLocation.X = this.Location.X;
                this._SelfLocation.Y = this.Location.Y;
                this._MouseLocation.X = Cursor.Position.X;
                this._MouseLocation.Y = Cursor.Position.Y;
                this._SelfWidth = this.Width;
                this._SelfHeight = this.Height;
            }
        }

        private void ShapeEx_MouseMove(object sender, MouseEventArgs e)
        {
           
            //move and resize
            //since I removed 4 resize selector, it will only fall into cases like 2,4,6,8,etc
            switch (this._SelectSelctedIndex)
            {
                case 0:
                    this.Location = new Point(Cursor.Position.X - (_MouseLocation.X - _SelfLocation.X), Cursor.Position.Y - (_MouseLocation.Y - _SelfLocation.Y));
                    break;
                case 1:
                    this.Height = this._SelfHeight - (Cursor.Position.Y - _MouseLocation.Y);
                    this.Width = this._SelfWidth - (Cursor.Position.X - _MouseLocation.X);
                    this.Location = new Point(Cursor.Position.X - _MouseLocation.X + _SelfLocation.X, Cursor.Position.Y - _MouseLocation.Y + _SelfLocation.Y);
                    break;
                case 2:
                    this.Height = this._SelfHeight - (Cursor.Position.Y - _MouseLocation.Y);
                    this.Width = Height;//remove if Width<> Height
                    this.Location = new Point(_SelfLocation.X, Cursor.Position.Y - _MouseLocation.Y + _SelfLocation.Y);
                    break;
                case 3:
                    this.Height = this._SelfHeight - (Cursor.Position.Y - _MouseLocation.Y);
                    this.Width = this._SelfWidth + (Cursor.Position.X - _MouseLocation.X);
                    this.Location = new Point(_SelfLocation.X, Cursor.Position.Y - (_MouseLocation.Y - _SelfLocation.Y));
                    break;
                case 4:
                    this.Width = this._SelfWidth + (Cursor.Position.X - _MouseLocation.X);
                    Height = Width;//remove if Width<> Height
                    break;
                case 5:
                    this.Height = this._SelfHeight + (Cursor.Position.Y - _MouseLocation.Y);
                    this.Width = this._SelfWidth + (Cursor.Position.X - _MouseLocation.X);
                    break;
                case 6:
                    this.Height = this._SelfHeight + (Cursor.Position.Y - _MouseLocation.Y);
                    Width = Height;//remove if Width<> Height
                    break;
                case 7:
                    this.Height = this._SelfHeight + (Cursor.Position.Y - _MouseLocation.Y);
                    this.Width = this._SelfWidth - (Cursor.Position.X - _MouseLocation.X);
                    this.Location = new Point(Cursor.Position.X - _MouseLocation.X + _SelfLocation.X, _SelfLocation.Y);
                    break;
                case 8:
                    this.Width = this._SelfWidth - (Cursor.Position.X - _MouseLocation.X);
                    Height = Width;//remove if Width<> Height
                    this.Location = new Point(Cursor.Position.X - _MouseLocation.X + _SelfLocation.X, _SelfLocation.Y);
                    break;
            }
 
           
        }

        private void Selection_Move(object sender, EventArgs e)
        {
            Invalidate();
        }

        private void ShapeEx_MouseLeave(object sender, EventArgs e)
        {
            this.Cursor = Cursors.Default;
            this._SelectSelctedIndex = -1;
            Invalidate();
        }

        private void ShapeEx_MouseUp(object sender, MouseEventArgs e)
        {
            this.Cursor = Cursors.Default;
            this._SelectSelctedIndex = -1;
            Invalidate();
        }

    }
}

[/code]

As I stated at the beginning, this is a naive version, below is a list of known issues

  1. when the selector is out of the parent PictureBox, the area of out of PictureBox can't be blank, but some remaining pixes with lagacy color (I don't know how to say, you will see if you run it). Currently I use a groupBox as a container for the PictureBox so that it doesn't look so ugly. Ideally the selector is not allowed to move out size of parent PictureBox
  2. should proper control the PictureBox property, should throw error if the property is null, or force the control parent is PictureBox
  3. current version seems not very efficient, the image is flicking when moving the selector

 

source code also available here:

PictureBoxSelection.cs (19.17 kb)

Smart Dial Agent

20. April 2011 01:40 by Jerry in Smart Dial

finally, Smart Dial Agent now support directly import contacts from Live and Google.Cool

select "Import" from menu

 

Simply input user name and password, then import...

IP CAM Controller is ranking top 54

19. April 2011 11:12 by Jerry in IP CAM

In the Music & Video category. Not bad as a new app just published one monthCool

Live contacts import coming soon

19. April 2011 01:18 by Jerry in Smart Dial

A big progress in directly importing (not via CSV) Live contacts, including both Messenger contacts and Live Address Book contacts!

New Smart Dial Agent is coming very soonCool

Hmmm... maybe provide the same functionality in WP7 as well..