Pages

Wednesday, October 24, 2012

Keeping an Images Aspect Ratio when Resizing Window

A project, which I needed to keep an image’s aspect ratio when resizing the browser window. When the browser window is resized, flexible  images displayed in the document window becomes skewed losing its desired aspect ratio.

Incorporating JavaScript, JQuery, CSS 3, the code successfully keeps the image’s aspect ratio when the browser is resized. This helps when designing flexible layouts. Images look good when sized.

One limitation is that I use CSS background-size property, which is CSS3. Therefore, the code below only works with CSS3 supported browser: doesn’t work with IE7/8.

However, I can get this to work without using CSS3, but since I believe, needing to keep the aspect ratio, I would be implementing the script on newer CSS3 compatible browsers/devices.

Supported browsers: IE9+, Firefox 4+, Opera, Chrome, and Safari 5+. 

Sample HTML page:

<body>
<section>
<form id="form1" runat="server">
<h1 class="headerTitle">Folkways Note Books</h1>
<div style="float: left; width: 40%; height: 400px;">
<div class="BGImage img1">&nbsp;</div>
<div class="BGImage img2">&nbsp;</div>
</div>
<div style="float: left; width: 58%; height: 400px;">
<div class="BGImage img3">&nbsp;</div>
<div class="BGImage img16">&nbsp;</div>
</div>
</form>
<span id="start"></span>- <span id="end"></span>
</section>
</body>

CSS

<style>
div.BGImage
{
position: relative;
top: 0px;
left: 0px;
overflow: hidden;
width: 100%;
height: 100%;
background-repeat: no-repeat;
z-index: 1;
}

div.BGImage.img1
{
background: url(media/images/Spiral-BG120603001.jpg);
}

div.BGImage.img2
{
background: url(media/images/Spiral-BG120609002.jpg);
}

div.BGImage.img3
{
background-image: url(media/images/DragonFly003-120608.jpg);
}

div.BGImage.img16
{
background-image: url(media/images/DragonFly016-120605.jpg);
;

}

div.BGImage.img7
{
background-image: url(media/images/DragonFly007-120608.jpg);
}

div.BGImage.img16
{
background-image: url(media/images/DragonFly016-120608.jpg);
}
</style>


JavaScript / JQuery


<script>
var ResizeWindowImgResize = function (Images) {
this.DynamicImages = Images;
}

ResizeWindowImgResize.prototype.SetBoxDimensions = function () {
var DynamicImages = $(".BGImage");
var imgBox;
for (var i = 0; i < DynamicImages.length; i++) {
imgBox = $(DynamicImages[i]);
var obj = this.GetBoxDimensions(imgBox);
imgBox.height(obj.width * this.ratio);
imgBox.css("background-size", "100% 100%");
}
}
ResizeWindowImgResize.prototype.ratio = .625;

ResizeWindowImgResize.prototype.GetBoxDimensions = function (item) {
return { width: item.width(), height: item.height() };
}

window.onload = function () {
var imgResize = new ResizeWindowImgResize();
imgResize.SetBoxDimensions();
}
window.onresize = function () {
var imgResize = new ResizeWindowImgResize();
imgResize.SetBoxDimensions();
};

</script>


This post is for the purpose of my notes only.


“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”


Henry Ford

Wednesday, October 10, 2012

Using Code First (Code Only) approach with Entity Framework - Sergey Barskiy

A very good video by Sergey Barskiy - A must.
This session was recorded live at CodeStock 2011 - http://codestock.org Session will include high level overview of Entity Framework and how various approach...


Saturday, August 18, 2012

Code-First: From UML Class Diagram to Creating MS SQL Database

Over the years designing web applications, I have sketched thoughts onto paper; sketching out c# classes and database table relations. I knew there were great modeling programs to assist me, but I never bothered researching. I didn’t want to learn another language or program.

However, recently I learned of .Net 4.0+ EntityFramework and UML Modeling. These two allow me to create POCO classes, DB tables, and relationships between DB tables.
It is very straight forward, which I show the process I followed below:

My Sloution Explorer shows 4 projects:

DataLayer: a C# class project exposing a DbContext layer.

Model: a UML class diagram is created and C# classes are generated from its packages .
ModelLib: where the C# classes are stored after being generating.

WebApplication1: allows to initiate the Context and possibility create database.




First, Within a black .Net 4.0 solution, I Created a new Modeling Project, I dragged out an UML class diagram and made associations:


After creating class diagram, I right clicked on each package and selected Generate Code:



Clicking Generate Code a new C# class project is created and all modeled classes from the Class Diagram classes are created and saved within a specified folder.
  • The folder’s name, where the derived classes are saved, is derived from their package’s name.
  • The project’s name takes the model project’s name and apppends “Lib”

Second, I created a C# class project with only one C# class, which I named: Context.cs. This class is the context layer and will inherit from DbContext.

From MSN (MSDN DbContext):

DbContext Class

Entity Framework 5.0 Represents a combination of the Unit-Of-Work and Repository patterns and enables you to query a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.

DbSet<TEntity> Class

Represents a typed entity set that is used to perform create, read, update, and delete operations. DbSet is not publicly constructible and can only be created from a DbContext instance.


Lastly, I created a Web Application, and in the code behind initiated the Context class. Because of lazy loading, if I was to only initiate the Context class, no DB tables would be created. Therefore, I selected something from the Client table and converted to a List. By converted it to a list, it must make a round trip to the database, and therefore the database tables will be created.
Special Note: Reference:
  • EntityFramework
  • System.Data.Entity
  • Context namespace (dogPedalerEnityMSSQL)
This name was chosen because Entity Framework will name the database after the Context’s Namespace. If no Connection String is found in the web.config, then Entity Framework will create SQLExpress Database named dogPedalerEnityMSSQL.Context (Namespace.Class).

Complete, I found this to be great. Going from Model to Classes to Creating DB tables.
This is only for my notes, and additionally it would be great, if someone receives benefit from my notes.

Monday, August 13, 2012

Below is an example of the Captcha Control

Download the complete solution from CodePlex.

Captcha Control added to ASP.NET Page.

<li>

//Captcha Control
<cc1:CaptchaControl ID="myCaptchaControl" ClientIDMode="Static"
  Width="800"
  Height="75"
  ImageWidth="400"
  ImageHeight="75"
  Minimum="5"
  Maximum="6"
  CaptchaHandlerUrl="~/CaptchaHandler.ashx"
  Overlap="6"
  RefreshButtonPath="~/Images/refresh.png"  runat="server" />

<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

Please enter characters displayed above&nbsp;

<asp:TextBox ID="CaptchaCharacters" ClientIDMode="Static" Text="" Width="100" ToolTip="Enter characters displayed above" runat="server">
</asp:TextBox>

<asp:RequiredFieldValidator runat="server" ValidationGroup="RegisterGroup" ontrolToValidate="CaptchaCharacters" CssClass="field-validation-error" ErrorMessage="*Required" />

</li>
 
Captcha Control will render out a HTML image element (image displaying characters) and a HTML input element of type button (refresh button - retrieving a new set of display characters).
Below the Capthca Control, I added a Textbox, which is where the user would type the Captcha characters and will be verified once the form is submitted.



Code Behind - Verifing Captcha Characters

Note: Captcha control had been place within a CreateUserWizard control. Referencing Captcha Control, I must FindControl within CreateUserWizard control (ID="RegisterUserWizardStep").

 //CreatingUser is raised before the Memebership Provider's CreateUser. Setting LoginCancelEventArgs Cancel property equal to true, the user will not be created.
protected void RegisterUser_CreatingUser(object sender, LoginCancelEventArgs e)
{
    var err = ((Literal)GetControl("ErrorMessage"));
    var parent = err.Parent;
    err.Text = "";

    Page.Validate();
    if (!Page.IsValid)
    {
       err.Text = "Required fields are empty or incorrect information was entered.";
       e.Cancel = true;
     }
     else
     {
       //Initiate the EncodeCaptcha class
       var ec = new EncodeCaptcha(GetCaptchaKey());

       //GetCaptchaCharacters returns clear Captcha characters represented in the displayed image.
       //Test they must be equal
       if (ec.characters != GetCaptchaCharacters())
       {
          err.Text = "Characters incorrectly entered. Please reenter correct characters displayed";
          e.Cancel = true;
       }
      }
}

//Return submited Captcha characters. the characters that the user had entered.
string GetCaptchaCharacters()
{
    return ((TextBox)GetControl("CaptchaCharacters")).Text;
}

//Return encrypted Captcha character string. The encrypted string had be UrlEncode, so the return
//string is UrlDecoded.
string GetCaptchaKey()
{
    var cc = GetControl("myCaptchaControl");
    var captchaCharacters = (HiddenField)cc.FindControl("Captcha-Key");

    return HttpUtility.UrlDecode(Request[captchaCharacters.UniqueID]);
}

//Abstracted findng fields within CreateUserWizard.
Control GetControl(string value)
{
    return RegisterUserWizardStep.ContentTemplateContainer.FindControl(value);
}

Sunday, August 12, 2012

New Update Captcha Image Control

I have updated my captcha image control. I believe it is sleeker and is overall better code wise.

Initiates an asynchronous call, and the returned result, will be a single image of alphanumeric characters. Image’s characters are presented in various font sizes and or (+/-) rotated in some degree.

This project offers the complete Visual Studio 2012 solution within a compressed zip file. Download the complete solution from CodePlex.

Shown below is the Captcha type which generates randomly selected characters and draws an image displaying those specific random characters.

Two files are involved rendering the Captcha image:
  • CaptchaControl.cs and CaptchaHandler.ashx
  • CaptchaControl.cs is a generic control rendering out an image and an Image Button. The rendered image’s ImageUrl property is dynamically set, and calls CaptchaHandler.ashx with an attached query string. The query string has a particular name/value pair specifying the particular Captcha characters.
CaptchaControl.cs generates and encodes characters appending the generated string to the rendering image’s query string.

CaptchaHandler.ashx returns a HTTPResponse bitmap and is displayed on the client side webpage.


CaptchaControl Class

Namespace: Captcha.Control
Assembly: CaptchaControl.dll

Syntax
public CaptchaControl : WebControl

Constructors
CaptchaControl(): base(HtmlTextWriterTag.Fieldset) Initializes a new instance of the CaptchaControl class

Properties
string RefreshButtonPath Absolute path to the Image Button’s image
string CaptchaHandlerUrl Absolute path to the Captcha Handler
int Minimum Minimum number of characters to be selected
int Maximum Maximum number of characters to be selected
int Overlap Amount of overlap between character placement.
int ImageWidth Captcha image’s width
int ImageHeight Captcha image’s height
string CharacterSet The character domain to select from. Default character set: ABDEGHMNQRTabdeghmnqr3456789#@&$%

Monday, July 9, 2012

Visual Studio Development Web Server, mp4 isn’t part of the set of built in known Mime types.

With HTML5 video element, I found the video missing when using Internet Explorer 9. IE9 supports the HTML5 video element, but the video was just missing.

Correcting the problem

Because Visual Studio’s Development Web Server is missing mp4 mime type, and to my knowledge there isn’t a way to add a missing mime type to Visual Studio’s Development Web Server built in know Mime types.

I added to the applications config.sys file:

<system.webServer>
  <staticContent>
    <mimeMap fileExtension=".mp4" mimeType="video/mp4" />
  </staticContent>
</system.webServer>


This adds it to the IIS server, so now I need to switch from using the Development Web Server to Local IIS Server.


Within Visual Studio, I must be administrator when working under Local IIS. The process opening Visual Studio as Administrator:

Right click on Visual Studio’s shortcut icon > properties > shortcut tab > advanced button > check run as administrator checkbox.


Now when I open Visual Studio, I will be running Visual Studio as administrator.


Now set the application properties:


project > properties > Web > click Use Local IIS Server radio button. Project URL should be set to the application’s virtual directory path.


Now HTML5 videos should work using mp4. 


The purpose is solely for my notes.

Thursday, July 5, 2012

Adding #region to Visual Studio 2012 CSS page



I do like regions, because it seems to add an abstraction to the CSS page by the ability to collapse sections narrowing the viewing area.

This show how to wrap a region around CSS declarations:

Begin wrapping with: /*#region Fieldset Styling */

End with: /*#endregion*/

Below is CSS formatting a form section within a fieldset element:

Each HTML input element has a title label and is wrapped in a HTML div element. The HTML div element has a class attribute value equal to fields.




/*#region Fieldset Styling */

fieldset {

    margin: 8px;

    padding: 12px 0px 20px;

    font-size: 1.1em;

    background-color: #fff;

}

 

    fieldset > div {

        margin-top: 8px;

    }

 

.fields {

}

 

    .fields span {

        display: inline-block;

        text-align: right;

    }

 

        .fields span.RecoverEmail {

            width: 100%;

            text-align: left;

        }

 

        .fields span:not(:first-child) {

            font-size: 0.8em;

        }

 

        .fields span.UniqueStatus {

            display: none;

            text-align: left;

        }

 

            .fields span.UniqueStatus input {

                margin-bottom: -3px;

            }

 

            .fields span.UniqueStatus.show {

                display: inline;

            }

 

    .fields input {

        width: 50%;

        border: medium solid #c0c0c0;

        height: 24px;

        line-height: 28px;

        font-size: 13px;

    }

 

        .fields input:focus {

            border: medium solid #4d90fe;

            outline-style: none;

            outline-color: invert;

        }

 

        .fields input.smaller {

            width: 30%;

        }

 

        .fields input.medium {

            width: 40%;

        }

/*#endregion*/










These are my notes for later use.