ページ

Wednesday, February 2, 2011

Original Captcha System in an ASP.NET Web Pages on WebMatrix/IIS Express or IIS.

ReCaptcha is great to use Captcha system on a website easily, but if need to customize the sytem, then we'd better create another new one.
So I tried creating the system.


Captcha.cs
put dll file in bin folder after doing build the project on vs2010.

This requires the following resources in the project.
 Font as File (*** The font has to be used under the EULA(End User License Agreement) or something. anyway, you should ask the font vender or the copyright owner. ***)
 SESSION_KEY_NAME as string (ex. value = "CaptchaSessionKey")
 CAPTCHA_CODE_STRING as string (ex. value = "1234567890")

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Web;
using System.Web.SessionState;


namespace CaptchaLibrary
{
    public sealed class Captcha : IDisposable
    {
        private readonly Random _random = new Random();
        private bool _disposed = false;

        private Bitmap Image { get; set; }
        private PrivateFontCollection PFC { set; get; }
        private IntPtr Ptr { set; get; }

        public Captcha(int width, int height)
        {
            string text = GenerateCaptchaCode(5);
            if (width > 0 && height > 0)
            {
                HttpContext.Current.Session[Properties.Resources.SESSION_KEY_NAME] = text;
                this.CreateBitmapImage(text, width, height);
            }
        }

        ~Captcha()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            lock (this)
            {
                if (!this._disposed)
                {
                    if (disposing)
                    {
                        if (this.Image != null)
                        {
                            this.Image.Dispose();
                            this.Image = null;
                        }
                        if (this.PFC != null)
                        {
                            this.PFC.Dispose();
                            this.PFC = null;
                        }
                        if (this.Ptr != IntPtr.Zero)
                        {
                            Marshal.FreeHGlobal(this.Ptr);
                            this.Ptr = IntPtr.Zero;
                        }
                    }
                }
                _disposed = true;
            }
        }

        public static bool Validate(string tagName)
        {
            bool isValid = false;
            ValidationErrorMessage = null;

            if (string.IsNullOrEmpty(tagName))
                throw new ArgumentNullException("tagName", "対象となるタグ名が指定されていません。");

            string paramValue = HttpContext.Current.Request.Form[tagName];
            if (string.IsNullOrEmpty(paramValue))
                ValidationErrorMessage = "認証コードを入力してください。";

            string sessionValue = HttpContext.Current.Session[Properties.Resources.SESSION_KEY_NAME].ToString();
            if (string.IsNullOrEmpty(sessionValue))
                ValidationErrorMessage = "タイムアウトです。再読み込みして、認証コードを生成しなおしてください。";

            if (string.IsNullOrEmpty(ValidationErrorMessage))
            {
                if (sessionValue.Equals(paramValue))
                    isValid = true;
                else
                    ValidationErrorMessage = "認証コードが違います。";
            }
            HttpContext.Current.Session.Remove(Properties.Resources.SESSION_KEY_NAME);
            return isValid;
        }

        public static string ValidationErrorMessage { private set; get; }
        public void OutputAsJpg()
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "image/jpg";
            HttpContext.Current.Response.Flush();
            if (Image != null)
                this.Image.Save(HttpContext.Current.Response.OutputStream, ImageFormat.Jpeg);
            HttpContext.Current.Response.End();
        }

        private void CreateBitmapImage(string code, int width, int height)
        {
            this.Image = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            try
            {
                using (Graphics g = Graphics.FromImage(this.Image))
                {
                    g.SmoothingMode = SmoothingMode.AntiAlias;
                    Rectangle rect = new Rectangle(0, 0, width, height);

                    DrawBackground(g, rect);
                    DrawText(g, rect, code, true);
                    DrawRandomNoise(g, rect);
                    DrawRandomLines(g, rect, 2);
                }
            }
            catch (Exception)
            {
                this.Image = null;
            }
        }

        private void DrawBackground(Graphics g, Rectangle rect)
        {
            using (HatchBrush brush = new HatchBrush(HatchStyle.SmallConfetti, Color.LightGray, Color.WhiteSmoke))
                g.FillRectangle(brush, rect);
        }

        private void DrawText(Graphics g, Rectangle rect, string code, bool isWarp)
        {
            Font font = null;
            try
            {
                using (GraphicsPath path = new GraphicsPath())
                using (HatchBrush brush = new HatchBrush(HatchStyle.LargeConfetti, Color.LightGray, Color.DarkGray))
                {
                    SizeF size;
                    float fontSize = rect.Height + 1;
                    FontFamily ff = GetFontFamily();
                    do
                    {
                        fontSize--;
                        font = new Font(ff, fontSize, FontStyle.Bold);
                        size = g.MeasureString(code, font);
                    } while (size.Width > rect.Width);
                    if (ff != null)
                    {
                        ff.Dispose();
                        ff = null;
                    }

                    StringFormat format = new StringFormat();
                    format.Alignment = StringAlignment.Center;
                    format.LineAlignment = StringAlignment.Center;
                    path.AddString(code, font.FontFamily, (int)font.Style, font.Size, rect, format);

                    if (isWarp)
                    {
                        PointF[] points =
                            {
                                new PointF(this._random.Next(rect.Width) / 5F, this._random.Next(rect.Height) / 5F),
                                new PointF(rect.Width - this._random.Next(rect.Width) / 5F, this._random.Next(rect.Height) / 5F),
                                new PointF(this._random.Next(rect.Width) / 5F, rect.Height - this._random.Next(rect.Height) / 5F),
                                new PointF(rect.Width - this._random.Next(rect.Width) / 5F, rect.Height - this._random.Next(rect.Height) / 5F)
                            };
                        Matrix matrix = new Matrix();
                        matrix.Translate(0F, 0F);
                        path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);
                    }

                    g.FillPath(brush, path);
                }
            }
            finally
            {
                if (font != null)
                {
                    font.Dispose();
                    font = null;
                }
            }
        }

        private void DrawRandomNoise(Graphics g, Rectangle rect)
        {
            using (HatchBrush brush = new HatchBrush(HatchStyle.SmallConfetti, Color.LightGray, Color.DarkGray))
            {
                int max = Math.Max(rect.Width, rect.Height);
                for (int i = 0; i < (int)(rect.Width * rect.Height / 10F); i++)
                {
                    int x = this._random.Next(rect.Width);
                    int y = this._random.Next(rect.Height);
                    int w = this._random.Next(max / 50);
                    int h = this._random.Next(max / 50);
                    g.FillEllipse(brush, x, y, w, h);
                }
            }
        }

        private void DrawRandomLines(Graphics g, Rectangle rect, int lines)
        {
            using (HatchBrush brush = new HatchBrush(HatchStyle.LargeConfetti, Color.LightGray, Color.DarkGray))
            using (Pen pen = new Pen(brush, 2))
            {
                for (int i = 0; i < lines; i++)
                {
                    float x = 0L;
                    float y = _random.Next(rect.Height);
                    PointF points = new PointF(x, y);
                    PointF pointe = new PointF(rect.Width - x, rect.Height - y);
                    g.DrawLine(pen, points, pointe);
                }
            }
        }

        private string GenerateCaptchaCode(int length)
        {
            string captchaCode = Properties.Resources.CAPTCHA_CODE_STRING;
            if (length < 0)
                length = 5;
            string code = "";
            for (int i = 0; i < length; i++)
                code = String.Concat(code, captchaCode.Substring(_random.Next(captchaCode.Length), 1));
            return code;
        }

        private FontFamily GetFontFamily()
        {
            try
            {
                byte[] bytes = Properties.Resources.Font;
                this.PFC = new PrivateFontCollection();
                this.Ptr = Marshal.AllocHGlobal(Marshal.SizeOf(bytes[0]) * bytes.Length);
                Marshal.Copy(bytes, 0, this.Ptr, bytes.Length);
                this.PFC.AddMemoryFont(this.Ptr, bytes.Length);
                return this.PFC.Families[0];
            }
            catch (Exception)
            {
                return System.Drawing.FontFamily.GenericSerif;
            }
        }
    }

}


CaptchaImage.cshtml

@using CaptchaLibrary;
@{
    var captchaImg = new Captcha(240,50);
    captchaImg.OutputAsJpg();
    captchaImg.Dispose();
}


CaptchaControlPanel.cshtml
Put this file in App_Code folder

@helper Show(string tagName, string errorMsg ){
<div id="captcha">
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.4.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function(){
        $('#captcha_inputtag_reloadbutton').click(function(){
            $.ajax({
                type: 'GET',
                cache: false,
                success: function(msg, status){
                    $('#captcha_imgtag_captchaimage').attr('src', '@Href"~/CaptchaImage")?' + new Date().getTime());
                    return false;
                }
            });
        });
    });
</script>
<fieldset style="width: 320px;height: 120px;background-color: #ffffe0;position: relative; top: 0px;left: 0px;">
    <legend title="認証コード(CAPTCHA)">画像認証(CAPTCHA)</legend>
    <div align="left" style="width:320px;height: 60px;background-color: transparent;position: relative;top: -15px;left: 5px;">
        <img id="captcha_imgtag_captchaimage" src="@Href("~/CaptchaImage")" alt="CAPTCHA IMAGE" title="認証用画像(CAPTCHA IMAGE)" />
        <input type="image" src="[Image path for reload button]" id="captcha_inputtag_reloadbutton" alt="再読込ボタン" title="再読込ボタン" onclick="return false;" style="width:50px;height:50px;position:relative;top:auto;left:5pt;" /><br />
        <strong>上の画像に表示されているコードを入力してください。</strong>
    </div>
    <div align="left" style="width: 320px;height: 60px;background-color: transparent;position: relative;top: 0px;left: 5px;">
        <input type="text" name="@tagName" title="画像認証コード(CAPTCHA Code)入力ボックス" @if(!errorMsg.IsEmpty()){<text>class="error-field"</text>} />
        @if (!errorMsg.IsEmpty()) {
        <label for="@tagName" class="validation-error" style="position: relative;top: 0px;left: 0px;">
            @errorMsg
        </label>
        }
    </div>
</fieldset>
</div>
}

Register.cshtml

@using CaptchaLibrary;
@{
    if(WebSecurity.IsAuthenticated)
    {
        Response.Redirect(Href("~/"));
    }
    Response.CacheControl = "no-cache";
    
    Layout = "~/_SiteLayout.cshtml";
    Page.Title = "アカウントの登録";
    Page.Description = "新規登録フォーム";
    var email = "";
    var password = "";
    var confirmPassword = "";
    
    var isValid = true;
    var emailErrorMessage = "";
    var passwordErrorMessage = "";
    var confirmPasswordMessage = "";
    var accountCreationErrorMessage = "";
    var captchaTextErrorMessage = "";
    
    if (IsPost) {
        email = Request.Form["email"];
        password = Request.Form["password"];
        confirmPassword = Request.Form["confirmPassword"];
        
        if (email.IsEmpty()) {
            emailErrorMessage = "電子メール アドレスを入力してください。";
            isValid = false;
        }
        if (password.IsEmpty()) {
            passwordErrorMessage = "パスワードを空白にすることはできません。";
            isValid = false;
        }
        if (password != confirmPassword) {
            confirmPasswordMessage = "新しいパスワードと確認のパスワードが一致しません。";
            isValid = false;
        }
        if(!Captcha.Validate("captchaText"))
        {
            captchaTextErrorMessage = Captcha.ValidationErrorMessage;
            isValid = false;
        }
        if (isValid) {
            var db = Database.Open([db name(w/o ".sdf"]);
            var user = db.QuerySingle("SELECT Email FROM UserProfile WHERE LOWER(Email) = LOWER(@0)", email);
            if (user == null) {
                db.Execute("INSERT INTO UserProfile (Email) VALUES (@0)", email);
                try {
                    bool requireEmailConfirmation = !WebMail.SmtpServer.IsEmpty();
                    var token = WebSecurity.CreateAccount(email, password, requireEmailConfirmation);
                    if (requireEmailConfirmation) {
                        var hostUrl = Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
                        var confirmationUrl = hostUrl + VirtualPathUtility.ToAbsolute("~/Account/Confirm?confirmationCode=" + HttpUtility.UrlEncode(token));
                        WebMail.Send(
                            to: email, 
                            subject: "アカウントを確認してください", 
                            body: "確認コード:  " + token + "。<a href=\"" + confirmationUrl + "\">" + confirmationUrl + "</a> にアクセスしてアカウントを有効にしてください。"
                        ); 
                    }
                    if (requireEmailConfirmation) {
                        Response.Redirect("~/Account/Thanks");
                    } else {
                        WebSecurity.Login(email, password);
                        Response.Redirect("~/");
                    }
                } catch (System.Web.Security.MembershipCreateUserException e) {
                    isValid = false;
                    accountCreationErrorMessage = e.ToString();
                }
            } else {
                isValid = false;
                accountCreationErrorMessage = "電子メール アドレスは既に使用中です。";
            }
        }    
    }
}
<p>
   新しいアカウントを作成するには、以下のフォームを使用してください。 
</p>
@if (!isValid) {
   <p class="message error">
    @if (accountCreationErrorMessage.IsEmpty()) {
        @:エラーを修正し、再試行してください。
    } else {
        @accountCreationErrorMessage
    }
   </p>
}
<form method="post" action="">
    <fieldset>
        <legend>申し込みフォーム</legend>
        <ol>
            <li class="email">
                <label for="email">電子メール:</label>
                <input type="text" id="email" name="email" title="Email address" value="@email" @if(!emailErrorMessage.IsEmpty()){<text>class="error-field"</text>} />
                @if (!emailErrorMessage.IsEmpty()) {
                    <label for="email" class="validation-error">@emailErrorMessage</label>
                }
            </li>
            <li class="password">
                <label for="password">パスワード:</label>
                <input type="password" id="password" name="password" title="パスワード" @if(!passwordErrorMessage.IsEmpty()){<text>class="error-field"</text>} />
                @if (!passwordErrorMessage.IsEmpty()) {
                    <label for="password" class="validation-error">@passwordErrorMessage</label>
                }
            </li>
            <li class="confirm-password">
                <label for="confirmPassword">パスワードの確認入力:</label>
                <input type="password" id="confirmPassword" name="confirmPassword" title="パスワードの確認入力" @if(!confirmPasswordMessage.IsEmpty()){<text>class="error-field"</text>} />
                @if (!confirmPasswordMessage.IsEmpty()) {
                    <label for="confirmPassword" class="validation-error">@confirmPasswordMessage</label>
                }
            </li>
            <li class="recaptcha">
                <!-- CAPTCHA Control Panel -->
                <p>
                    @CaptchaControlPanel.Show("captchaText", @captchaTextErrorMessage)
                </p>
                <!-- CAPTCHA Control Panel -->
            </li>
        </ol>
        <p class="form-actions">
            <input type="submit" value="登録" title="登録" />
        </p>
    </fieldset>
</form>


Register.cshtml




Error Message 1











Error Message 2


Silverlight RSS Reader ( Out Of Browser Version )

I posted Silverlight RSS Reader before, but that requires the proxy server to get RSS feeds.
( See Simple Silverlight RSS Reader. (MVVM Pattern) )
So I was wondering if I create the application with OOB(out of browser).

* Out-of-Browser Settings on Visual Studio
Check "Require elevated trust when running outside the browser".


* Install PFX file on the silverlight project.

1-1.Create a self-signed SSL certificate ( use for text, i.e. non trusted )

makecert.exe( Visual studio pro or windows sdk. )
http://msdn.microsoft.com/en-US/library/bfsktky3(v=VS.100).aspx


(1) Create a root certificate authority.
makecert -n "CN=Dummy Certificate Authority" -r -a sha1 -sr LocalMachine -sky signature -sv OOBRootCA.pvk OOBRootCA.cer

(2) Create a code-signing certificate.
makecert -sv OOBCodeSigningCA.pvk -iv OOBRootCA.pvk -n "CN=OOB Code Signing CA" -ic OOBRootCA.cer OOBCodeSigningCA.cer

(3) Convert the certificate and key to pfx file.
pvk2pfx -pvk OOBCodeSigningCA.pvk -spc OOBCodeSigningCA.cer -pfx DummyOOBCodeSigningCA.pfx -po <password>


1-2. Install the file on the project.

(1) In solution explorer, right-click the project name, and then click Properties. In the Properties Pages dialog box, click the Signing tab.
























(2) Click "Select from File" button and Select the pfx file.






















(3) Enter the password.














(4) Save Properties, then it's done.






* Coding Consideration on OOB

1. Check network status and Download itself if updated.

App.xaml.cs
public App()
{
   .
   .
   .
 NetworkChange.NetworkAddressChanged += NetworkChange_NetworkAddressChanged;


        if (this.IsRunningOutOfBrowser)
            this.CheckAndDownloadUpdateCompleted += App_CheckAndDownloadUpdateCompleted;
   .
   .
   .

}

private void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
{
    if (NetworkInterface.GetIsNetworkAvailable())
    {
        // something
    }
    else
    {
        // something
    }
}

private void App_CheckAndDownloadUpdateCompleted(
                     object sender,
                     CheckAndDownloadUpdateCompletedEventArgs e)
{
    if (e.UpdateAvailable)
    {
        MessageBox.Show("The update has been downloaded. Please restart the application.", 
                        "Application Update",MessageBoxButton.OK);
    }
}



2. Custom Windows Control bar for Silverlight OOB.

WindowControlBar.xaml
<UserControl x:Class="RSSReaderOOB.WindowControlBar"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="26" d:DesignWidth="300">

    <Grid Background="LightGray" Height="26" MaxHeight="26" MinHeight="26">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="100" />
        </Grid.ColumnDefinitions>
        <Image x:Name="IconImage" Source="/Images/IconSL16.png" Width="16" Height="16" Stretch="Uniform" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="3,0,0,0" />
        <TextBlock x:Name="TitleTextBlock" Margin="22,0,0,0" FontSize="13" Text="Silverlight OOB Application" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Left" />
        <StackPanel x:Name="WindowControlBarRoot" Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Top"
                        Margin="0,0,0,0" HorizontalAlignment="Right">
            <Canvas Width="30" x:Name="wcbMinimizeButton" Cursor="Hand" Background="#00000000"
                        Visibility="Visible" Height="20" ToolTipService.ToolTip="Minimize">
                <Border Width="30" Height="20" Background="#FF939393" BorderBrush="#FF000000"
                            BorderThickness="1,1,0,1" CornerRadius="0,0,0,5">
                    <Border BorderThickness="1.5,1.5,1.5,1.5" CornerRadius="0,0,0,5">
                        <Border.Background>
                            <LinearGradientBrush EndPoint="0.514,0.623"
                                                     StartPoint="0.514,0.191">
                                <GradientStop Color="#FF828282" Offset="0"/>
                                <GradientStop Color="#FF262626" Offset="1"/>
                            </LinearGradientBrush>
                        </Border.Background>
                        <Rectangle Margin="6,9,6,3" Fill="#FFD6D5D5" Stroke="#FF000000"
                                       StrokeThickness="0.5"/>
                    </Border>
                </Border>
            </Canvas>
            <Canvas Width="30" x:Name="wcbMaximizeButton" Cursor="Hand" Background="#00000000"
                        Visibility="Visible" Height="20" ToolTipService.ToolTip="Maximize">
                <Border Width="30" Height="20" Background="#FF939393" BorderBrush="#FF000000"
                            BorderThickness="1,1,0,1">
                    <Border BorderThickness="1.5,1.5,1.5,1.5" CornerRadius="0,0,0,0" Width="29"
                                Height="18">
                        <Border.Background>
                            <LinearGradientBrush EndPoint="0.514,0.623"
                                                     StartPoint="0.514,0.191">
                                <GradientStop Color="#FF828282" Offset="0"/>
                                <GradientStop Color="#FF262626" Offset="1"/>
                            </LinearGradientBrush>
                        </Border.Background>
                        <Border Background="#FFD6D5D5" Margin="6,2,6,2" BorderBrush="#FF000000"
                                    BorderThickness="0.5,0.5,0.5,0.5">
                            <Rectangle Stroke="#FF000000" Margin="2,2,2,2"
                                           StrokeThickness="0.5">
                                <Rectangle.Fill>
                                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                                        <GradientStop Color="#FF828282" Offset="0"/>
                                        <GradientStop Color="#FF262626" Offset="1"/>
                                    </LinearGradientBrush>
                                </Rectangle.Fill>
                            </Rectangle>
                        </Border>
                    </Border>
                </Border>
            </Canvas>
            <Canvas Width="40" x:Name="wcbCloseButton" Cursor="Hand" Background="#00000000"
                        Opacity="1" Height="20" ToolTipService.ToolTip="Close">
                <Border Width="40" Height="20" Background="#FF939393" BorderBrush="#FF000000"
                            BorderThickness="1,1,1,1" CornerRadius="0,0,5,0">
                    <Border BorderThickness="1,1,1,1" CornerRadius="0,0,5,0" Width="37"
                                Height="16" x:Name="border">
                        <Border.Background>
                            <LinearGradientBrush EndPoint="0.514,0.623"
                                                     StartPoint="0.514,0.191">
                                <GradientStop Color="#FF956161" Offset="0"/>
                                <GradientStop Color="#FF490E0E" Offset="1"/>
                            </LinearGradientBrush>
                        </Border.Background>
                        <TextBlock Text="X" TextWrapping="Wrap" Foreground="#FFECECEC"
                                       HorizontalAlignment="Center" VerticalAlignment="Center"
                                       x:Name="textBlock"/>
                    </Border>
                </Border>
            </Canvas>
        </StackPanel>

    </Grid>
</UserControl>

WindowControlBar.xaml.cs
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace RSSReaderOOB
{
    public partial class WindowControlBar : UserControl
    {
        public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(WindowControlBar), new PropertyMetadata(OnTitleChanged));
        public static readonly DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(Uri), typeof(WindowControlBar), new PropertyMetadata(OnIconChanged));

        public string Title
        {
            get { return (string)GetValue(TitleProperty); }
            set { SetValue(TitleProperty, value); }
        }

        public Uri Icon
        {
            get { return (Uri)GetValue(IconProperty); }
            set { SetValue(IconProperty, value); }
        }

        private static void OnTitleChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue != null)
            {
                string newTitle = e.NewValue as string;
                WindowControlBar wcb = sender as WindowControlBar;
                wcb.TitleTextBlock.Text = newTitle;
            }
        }

        private static void OnIconChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue != null)
            {
                if (e.NewValue is Uri)
                {
                    WindowControlBar wcb = sender as WindowControlBar;
                    wcb.IconImage.Source = new System.Windows.Media.Imaging.BitmapImage(e.NewValue as Uri);
                }
            }
        }

        public WindowControlBar()
        {
            InitializeComponent();
            if (Application.Current.IsRunningOutOfBrowser)
            {
                this.Visibility = Visibility.Visible;
                this.wcbMaximizeButton.MouseLeftButtonDown += new MouseButtonEventHandler(wcbMaximizeButton_MouseLeftButtonDown);
                this.wcbMinimizeButton.MouseLeftButtonDown += new MouseButtonEventHandler(wcbMinimizeButton_MouseLeftButtonDown);
                this.wcbCloseButton.MouseLeftButtonDown += new MouseButtonEventHandler(wcbCloseButton_MouseLeftButtonDown);
                this.MouseLeftButtonDown += new MouseButtonEventHandler(WindowControlBar_MouseLeftButtonDown);
            }
            else
                this.Visibility = Visibility.Collapsed;
        }

        void WindowControlBar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Application.Current.MainWindow.DragMove();
        }

        void wcbCloseButton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Application.Current.MainWindow.Close();
        }

        void wcbMinimizeButton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Application.Current.MainWindow.WindowState = WindowState.Minimized;
        }

        void wcbMaximizeButton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (Application.Current.MainWindow.WindowState == WindowState.Normal)
                Application.Current.MainWindow.WindowState = WindowState.Maximized;
            else
                Application.Current.MainWindow.WindowState = WindowState.Normal;
        }
    }
}


Here are the capture images of the application.

1.Start the application and then click Install button.
The Application on the browser.




















2.Click Install button.
* Security Warning appears because of Non-Trusted SSL.




















3.Enter a RSS feed url in the textbox.


















4. Done.




Thursday, January 20, 2011

Custom CSHTML Helper Class for WebMatrix

I tried creating helper class for WebMatrix on Visual Studio 2010.

 

 

1. Creating a new Class Library (.NET Framework 4)

 

2. Add System.Web.dll to reference.

 

3. Write some code you need, like the following

using System;
using System.Web;

public static class MyWebSite
{
private static string _URL = "http://www.bing.com/";

public static IHtmlString LinkToHome()
{
return LinkTo(_URL, "Home", "_self");
}

public static IHtmlString LinkTo(string url, string str, string target)
{
return new HtmlString("<a href=\"" + url + "\" target=\"" + target + "\">"
+ str + "</a>");
}

}

4. Copy the dll after compiled the above project to "bin" folder in your website on WebMatrix.

 

5. Call the Helper class under the rule of Razor syntax.

@MyWebSite.LinkToHome()

 

* The helper class also works fine for ASP.NET MVC 3 Web Application with Razor as view engine.

Plus, We can even create/use Custom CSHTML helper class directly by adding a C# class file or a CSHTML file in App_Code folder on WebMatrix.

 

Pattern 1:  Using a C# file

1. creating Helper01.cs

using System;
using System.Collections.Generic;
using System.Web;

/// <Summary>
/// Summary description for Helper01
/// </Summary>
public static class Helper01
{
public static IHtmlString Message(string name)
{
return new HtmlString("Hello " + name);
}
}

 

2. usage:
@Helper01.Message("onamae")

 

 

Pattern 2: Using a CSHTML file

1. creating Helper02.cshtml

@helper Message(string name)
{
<text>Hello @name</text>
}

 

2. usage:
@Helper02.Message("seimei")

 

 

Sunday, August 29, 2010

Simple Silverlight RSS Reader. (MVVM Pattern)

As a little more useful application under MVVM Pattern, I created a silverlight RSS reader.

Silverlight RSS Reader Demo
http://demo.gehintleman.com/RssReader.html


But, as is well known, silverlight application throws System.Security.SecurityException unless the target host has a clientaccesspolicy.xml.
(Because silverlight does not allow corss domain access.)

One of the solution against that, using GAE(Google App Engine) is a workable alternative.

1.Create rssfeed.py

# -*- coding: utf-8 -*-
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import urlfetch

class GetRssFeed(webapp.RequestHandler):
  def get(self):
    u = self.request.get("u")
    if u:
      try:
        result = urlfetch.fetch(u)
        self.response.out.write(result.content)
      except:
        self.error(404)
    else:
      self.error(404)


application = webapp.WSGIApplication([('/RssFeed',GetRssFeed)], debug=False)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()


2. Create clientaccesspolicy.xml

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from>
        <domain uri="*"/>
      </allow-from>
      <grant-to>
        <resource path="/" include-subpaths="true"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>


3. Add the following configurations in app.yaml

- url: /RssFeed
  script: rssfeed.py
- url: /clientaccesspolicy.xml
  static_files: clientaccesspolicy.xml
  upload: clientaccesspolicy.xml


After deploying those files to GAE, silverlight applications can fetch RSS via the python script.

http://<your application name>.appspot.com/RssFeed?u=<target RSS feed url>


* Actually, I didn't use Expression Blend to create the view. so it doesn't look good.
   but, I think, trying to code xaml must be good to deeply understand silverlight.

Wednesday, August 18, 2010

MVVM Pattern for Silverlight 4

I tried creating a simple silverlight application under some of MVVM pattern rules like followings.

・Views can do "CRUD" data only by "Data Binding" from ViewModels. ( CRUD : Create, Read, Update, Delete )
・Any events will be executed on ViewModels by "ICommand" from Views or some Behaviors on Views.
    (which means there is no code behind on the view.)

⇒ "loose coupling" between a view and a viewmodel ( ViewとViewModelの疎結合 )


MVVM Pattern for Silverlight 4  Demo
http://demo.gehintleman.com/MVVMPattern.html

・There are 4 Views (including MainView), and all the Views do not have any code behinds.
・Views and ViewModels are managed through ExportAttribute/ImportAttribute.
・Using resource files(*.resx) for the localization.


MVVM Pattern could clearly devide web application development into coding by programmers and designing by designers.

* Differently from WPF, Silverlight cannot assign(bind) ViewModels to Views in Application.Resources in APP.XAML.
   But, Managed Extensibility Framework ( a.k.a. MEF ) is so great that we can easily manage ViewModels and Views.

Sunday, July 18, 2010

Authentication in silverlight 4

Here is a preparation for Very Very Verrrrry simple Login System for Silverlight.


I. Server Side ( XXXXX.Web project )

1. Membership Provider class

namespace XXXXX.Web.Providers
{
    public class CustomMembershipProvider : MembershipProvider
    {
        public override string ApplicationName { set; get; }
        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            return new MembershipUser("CustomMembershipProvider",
                username,
                null,
                null,
                null,
                null,
                false,
                false,
                new DateTime(),
                new DateTime(),
                new DateTime(),
                new DateTime(),
                new DateTime());
        }

        public override bool ValidateUser(string username, string password)
        {
            if(username == "admin")
                return password == "password";
            if(username == "user")
                return password == "password";
            return false;
        }

        public override bool EnablePasswordReset { get { throw new NotImplementedException(); } }

        public override bool EnablePasswordRetrieval { get { throw new NotImplementedException(); } }

        public override bool RequiresQuestionAndAnswer { get { throw new NotImplementedException(); } }

        public override int MaxInvalidPasswordAttempts { get { throw new NotImplementedException(); } }

        public override int PasswordAttemptWindow { get { throw new NotImplementedException(); } }

        public override bool RequiresUniqueEmail { get { throw new NotImplementedException(); } }

        public override MembershipPasswordFormat PasswordFormat { get { throw new NotImplementedException(); } }

        public override int MinRequiredPasswordLength { get { throw new NotImplementedException(); } }

        public override int MinRequiredNonAlphanumericCharacters { get { throw new NotImplementedException(); } }

        public override string PasswordStrengthRegularExpression { get { throw new NotImplementedException(); } }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { throw new NotImplementedException(); }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) { throw new NotImplementedException(); }

        public override string GetPassword(string username, string answer) { throw new NotImplementedException(); }

        public override bool ChangePassword(string username, string oldPassword, string newPassword) { throw new NotImplementedException(); }

        public override string ResetPassword(string username, string answer) { throw new NotImplementedException(); }

        public override void UpdateUser(MembershipUser user) { throw new NotImplementedException(); }

        public override bool UnlockUser(string userName) { throw new NotImplementedException(); }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) { throw new NotImplementedException(); }

        public override string GetUserNameByEmail(string email) { throw new NotImplementedException(); }

        public override bool DeleteUser(string username, bool deleteAllRelatedData) { throw new NotImplementedException(); }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); }

        public override int GetNumberOfUsersOnline() { throw new NotImplementedException(); }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); }
    }
}


2. Profile Provider class

namespace XXXXX.Web.Providers
{
    public class CustomProfileProvider : ProfileProvider
    {
        public override string ApplicationName { set; get; }

        public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection collection)
        {
            var username = context["UserName"];
            var result = new SettingsPropertyValueCollection();

            result.Add(new SettingsPropertyValue(
                new SettingsProperty(
                    "WelcomeMessage",
                    typeof(string),
                    null,
                    true,
                    string.Format("ようこそ {0}さん", username),
                    SettingsSerializeAs.String,
                    null,
                    false,
                    false)));
            return result;
        }

        public override int DeleteProfiles(ProfileInfoCollection profiles) { throw new NotImplementedException(); }

        public override int DeleteProfiles(string[] usernames) { throw new NotImplementedException(); }

        public override int DeleteInactiveProfiles(ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate) { throw new NotImplementedException(); }

        public override int GetNumberOfInactiveProfiles(ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate) { throw new NotImplementedException(); }

        public override ProfileInfoCollection GetAllProfiles(ProfileAuthenticationOption authenticationOption, int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); }

        public override ProfileInfoCollection GetAllInactiveProfiles(ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); }

        public override ProfileInfoCollection FindProfilesByUserName(ProfileAuthenticationOption authenticationOption, string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); }

        public override ProfileInfoCollection FindInactiveProfilesByUserName(ProfileAuthenticationOption authenticationOption, string usernameToMatch, DateTime userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); }

        public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection) { throw new NotImplementedException(); }
    }
}


3. Role Provider class

namespace XXXXX.Web.Providers
{
    public class CustomRoleProvider : RoleProvider
    {
        public override string ApplicationName { set; get; }

        public override string[] GetRolesForUser(string username)
        {
            if (username == "admin")
                return new[] { "Administrators", "Users" };
            if (username == "user")
                return new[] { "Users" };
            return null;
        }

        public override bool IsUserInRole(string username, string roleName)
        {
            if(username == "admin")
                return roleName == "Administrators" || roleName == "Users";
            if(username == "user")
                return roleName == "Users";
            return false;
        }

        public override void CreateRole(string roleName) { throw new NotImplementedException(); }

        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { throw new NotImplementedException(); }

        public override bool RoleExists(string roleName) { throw new NotImplementedException(); }

        public override void AddUsersToRoles(string[] usernames, string[] roleNames) { throw new NotImplementedException(); }

        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { throw new NotImplementedException(); }

        public override string[] GetUsersInRole(string roleName) { throw new NotImplementedException(); }

        public override string[] GetAllRoles() { throw new NotImplementedException(); }

        public override string[] FindUsersInRole(string roleName, string usernameToMatch) { throw new NotImplementedException(); }
    }
}


4. User class

namespace XXXXX.Web.Providers
{
    public class User : UserBase
    {
        public string WelcomeMessage { set; get; }
    }
}


5. Authentication Domain Service class

    [EnableClientAccess]
    public class AuthenticationService : AuthenticationBase<User> { }


6. Web.Config

  <system.web>
    <authentication mode="Forms" />
    <membership defaultProvider="customProvider">
      <providers>
        <clear />
        <add name="customProvider" type="XXXXX.Web.Providers.CustomMembershipProvider"/>
      </providers>
    </membership>
    <profile enabled="true" defaultProvider="customProvider">
      <properties>
        <add name="WelcomeMessage" allowAnonymous="false"/>
      </properties>
      <providers>
        <clear />
        <add name="customProvider" type="XXXXX.Web.Providers.CustomProfileProvider"/>
      </providers>
    </profile>
    <roleManager enabled="true" defaultProvider="customProvider">
      <providers>
        <clear />
        <add name="customProvider" type="XXXXX.Web.Providers.CustomRoleProvider"/>
      </providers>
    </roleManager>
  </system.web>



II. Client side ( XXXXX project )

7. App.xaml.cs

        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();

            WebContext webcontext = new WebContext();
            webcontext.Authentication = new FormsAuthentication();
            this.ApplicationLifetimeObjects.Add(webcontext);
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            this.Resources.Add("WebContext", WebContext.Current);
            //this.RootVisual = new MainPage();
            this.RootVisual = new BasePage();
        }


Here is the pages for the simple login system.

8. BasePage.xaml

<UserControl x:Class="XXXXX.BasePage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

</UserControl>


9.BasePage.xaml.cs

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;

namespace XXXXX
{
    using XXXXX.Web;

    public partial class BasePage : UserControl
    {
        public BasePage()
        {
            InitializeComponent();
            if (this.Content == null)
            {
                this.Content = new LoginPage();
            }
            else
            {
                var user = WebContext.Current.User;
                if (user.IsAuthenticated)
                    ((BasePage)Parent).ShowMainPage();
                else
                    ((BasePage)Parent).ShowLoginPage();
            }
        }

        public void ShowLoginPage()
        {
            this.Content = new LoginPage();
        }

        public void ShowMainPage()
        {
            this.Content = new MainPage();
        }
    }
}



** [IMPORTANT] **

10. MainPage.xaml.cs

add following code in the constructor.

var user = WebContext.Current.User;
if (!user.IsAuthenticated)
    ((BasePage)Parent).ShowLoginPage();




I know that using "business application template" is easier than the above way, but I hope it would be more customizable.

Change UserAgent on UIWebView ( Undocumented method )

I was looking for how to change the User Agent on UIWebView for iPhone/iPad.
then I found the solution... but it's undocumented method, which means it would be quite hard to get the approval from app store.


UIWebView+UserAgent.h

@interface UIWebView(UserAgent)
    -(void)setUserAgent:(NSString *)userAgent;
@end


UIWebView+UserAgent.m

#import "UIWebView+UserAgent.h"
#import <objc/runtime.h>

@implementation UIWebView(UserAgent)
-(void)setUserAgent:(NSString *)userAgent
{
    id webDocumentView;
    id newWebView;
    webDocumentView = objc_msgSend(self, @selector(_documentView));
    object_getInstanceVariable(webDocumentView, "_webView", (void**)&newWebView);
    objc_msgSend(newWebView, @selector(setCustomUserAgent:),userAgent);
}
@end


This would make the log analysis simpler by distinguishing precisely between Safari and the application on iPhone/iPad.
Plus, Providing some special services only for the application users on website is available by use of the UserAgent.