follow me

Deep Zoom - Mouse wheel to zoom in & zoom out.

There are a lot of ways how to manipulate Deep Zoom depending on your needs. Before anything else I give you a short description of what is Deep Zoom. Deep Zoom provides the ability to interactively view high-resolution images in Silverlight. You can zoom in and out of images rapidly without affecting the performance of your application. This Quickstart shows you how to create a Deep Zoom image, load a Deep Zoom image, and add interactivity. Learn More

In order to build Deep Zoom applications, you need to download Microsoft's Deep Zoom Composer . And before we going into the mouse interactive code we should first have a short steps on how to create/build a Deep Zoom Application. So lets say you already has the DeepZoom Composer, open and create a new project.

1. Create new Project and Import Images
You see it has three different parts: Import, Compose and Export. The first thing we do is to import our images. See on the right side there is an Add Image button.



2. Compose the Imported Images
Click on the composed tab then just drag and drop all the images you had imported into the canvas. You see also all of it on the right side.



To arrange all of those, select all images and right click to bring up "Arrange Into Grid" dialog.



Define the number of rows and padding.



Once you click OK on that dialog, Deep Zoom Composer will arrange the images exactly like they're supposed to be.



3. Export Deep Zoom Project
Export them so that we can used it in our Silverlight application.



It generates a couple of different things. First it will create a folder called "GeneratedImages". This folder contains hundreds of images that Silverlight will request and combine when a user is using the Deep Zoom application. Inside this folder is also a file called "dzc_output.xml". This file will be the actual source of the MultiScaleImage object that will be used when building our app.

4. Silverlight Application
Locate the file where you saved your exported Deep Zoom project, and get the GeneratedImages folder and add it in the ClientBin forder of the ASP.net project.



The first piece of code we need to write will create the multiscale image object and set it's source to our Deep Zoom Composer output.

<UserControl x:Class="deepZoom.MainPage"
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:DesignWidth="640" d:DesignHeight="480">
<Grid x:Name="LayoutRoot" Background="Black">
<MultiScaleImage x:Name="msi" Source="../GeneratedImages/dzc_output.xml"/>
</Grid>
</UserControl>


If you run the application you can actually see the the images..how they we're arranged. However there is no mouse interaction happen, you cant zoom in and zoom out those images using your mouse. Now we're down to the good stuff..the code behind of it.

5. Code Behind. Zoom In and Zoom Out
Most of it was being provided by Microsoft I guess, but there are lots of versions on this code it depends what version of Silverlight your using. There are plenty of code but aint working for me. The code-behind for this application:


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 deepZoom
{
public partial class MainPage : UserControl
{

//
// Based on prior work done by Lutz Gerhard, Peter Blois, and Scott Hanselman
//
Point lastMousePos = new Point();

double _zoom = 1;
bool mouseButtonPressed = false;
bool mouseIsDragging = false;
Point dragOffset;
Point currentPosition;

public double ZoomFactor
{
get { return _zoom; }
set { _zoom = value; }
}


public MainPage()
{
InitializeComponent();
this.MouseMove += delegate(object sender, MouseEventArgs e)
{
if (mouseButtonPressed)
{
mouseIsDragging = true;
}
this.lastMousePos = e.GetPosition(this.msi);
};

this.MouseLeftButtonDown += delegate(object sender, MouseButtonEventArgs e)
{
mouseButtonPressed = true;
mouseIsDragging = false;
dragOffset = e.GetPosition(this);
currentPosition = msi.ViewportOrigin;
};

this.msi.MouseLeave += delegate(object sender, MouseEventArgs e)
{
mouseIsDragging = false;
};

this.MouseLeftButtonUp += delegate(object sender, MouseButtonEventArgs e)
{
mouseButtonPressed = false;
if (mouseIsDragging == false)
{
bool shiftDown = (Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift;

ZoomFactor = 2.0;
if (shiftDown) ZoomFactor = 0.5;
Zoom(ZoomFactor, this.lastMousePos);
}
mouseIsDragging = false;
};

this.MouseMove += delegate(object sender, MouseEventArgs e)
{
if (mouseIsDragging)
{
Point newOrigin = new Point();
newOrigin.X = currentPosition.X - (((e.GetPosition(msi).X - dragOffset.X) / msi.ActualWidth) * msi.ViewportWidth);
newOrigin.Y = currentPosition.Y - (((e.GetPosition(msi).Y - dragOffset.Y) / msi.ActualHeight) * msi.ViewportWidth);
msi.ViewportOrigin = newOrigin;
}
};

new MouseWheelHelper(this).Moved += delegate(object sender, MouseWheelEventArgs e)
{
e.Handled = true;
if (e.Delta > 0)
ZoomFactor = 1.2;
else
ZoomFactor = .80;

Zoom(ZoomFactor, this.lastMousePos);
};
}

public void Zoom(double zoom, Point pointToZoom)
{
Point logicalPoint = this.msi.ElementToLogicalPoint(pointToZoom);
this.msi.ZoomAboutLogicalPoint(zoom, logicalPoint.X, logicalPoint.Y);
}
}
}



Create a new class MouseWheelHelper.cs and have this code.


using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;

namespace deepZoom
{
// Courtesy of Pete Blois
public class MouseWheelEventArgs : EventArgs
{
private double delta;
private bool handled = false;

public MouseWheelEventArgs(double delta)
{
this.delta = delta;
}

public double Delta
{
get { return this.delta; }
}

// Use handled to prevent the default browser behavior!
public bool Handled
{
get { return this.handled; }
set { this.handled = value; }
}
}

public class MouseWheelHelper
{

public event EventHandler<MouseWheelEventArgs> Moved;
private static Worker worker;
private bool isMouseOver = false;

public MouseWheelHelper(FrameworkElement element)
{

if (MouseWheelHelper.worker == null)
MouseWheelHelper.worker = new Worker();

MouseWheelHelper.worker.Moved += this.HandleMouseWheel;

element.MouseEnter += this.HandleMouseEnter;
element.MouseLeave += this.HandleMouseLeave;
element.MouseMove += this.HandleMouseMove;
}

private void HandleMouseWheel(object sender, MouseWheelEventArgs args)
{
if (this.isMouseOver)
this.Moved(this, args);
}

private void HandleMouseEnter(object sender, EventArgs e)
{
this.isMouseOver = true;
}

private void HandleMouseLeave(object sender, EventArgs e)
{
this.isMouseOver = false;
}

private void HandleMouseMove(object sender, EventArgs e)
{
this.isMouseOver = true;
}

private class Worker
{

public event EventHandler<MouseWheelEventArgs> Moved;

public Worker()
{

if (HtmlPage.IsEnabled)
{
HtmlPage.Window.AttachEvent("DOMMouseScroll", this.HandleMouseWheel);
HtmlPage.Window.AttachEvent("onmousewheel", this.HandleMouseWheel);
HtmlPage.Document.AttachEvent("onmousewheel", this.HandleMouseWheel);
}

}

private void HandleMouseWheel(object sender, HtmlEventArgs args)
{
double delta = 0;

ScriptObject eventObj = args.EventObject;

if (eventObj.GetProperty("wheelDelta") != null)
{
delta = ((double)eventObj.GetProperty("wheelDelta")) / 120;


if (HtmlPage.Window.GetProperty("opera") != null)
delta = -delta;
}
else if (eventObj.GetProperty("detail") != null)
{
delta = -((double)eventObj.GetProperty("detail")) / 3;

if (HtmlPage.BrowserInformation.UserAgent.IndexOf("Macintosh") != -1)
delta = delta * 3;
}

if (delta != 0 && this.Moved != null)
{
MouseWheelEventArgs wheelArgs = new MouseWheelEventArgs(delta);
this.Moved(this, wheelArgs);

if (wheelArgs.Handled)
args.PreventDefault();
}
}
}
}
}




ciao. Read More...

Add Silverlight in Web page .aspx

I just had my training about Silverlight, and one of the few important things i have learned and want to share it with you all is to how to add/integrate your silverlight application in the web page.

You can embed the Silverlight plug-in in your Web page in two ways:

● Using the HTML object element.
● Using JavaScript, Silverlight.js helper file.

I never try to used JavaScript but i found a very simple way on how to do it. See How to: Add Silverlight to a Web Page by Using JavaScript. For more information about Silverlight.js, see Silverlight.js Reference. So we have to focus more on HTML object element.


The HTML object element is the simplest way to embed the Silverlight plug-in, and is the recommended way. This is the default approach that is used by Visual Studio when you create a new Silverlight-based application and choose to host it in a dynamically generated HTML page.

You can use the object element to integrate Silverlight with JavaScript code in your Web page. However, JavaScript is not required to embed the control. This is useful if JavaScript is disabled on the client or prohibited on the server.

Question is where to find object element that being generated. You can find those in your Testpage both in .aspx and .html



In silverlight 2.0 Testpage.aspx has a different code, it never uses object but still you can make used of those, either way. Code looks like this.


<asp:ScriptManager runat="server" ID="ScriptManager" />
<asp:Silverlight runat="server" ID="silverlightLayout" InstallationMode="Inline"
Version="1.1" Source="MVC_silverlight.xap" EnableHtmlAccess="true" Windowless="true"
Width="844" Height="472" PluginBackColor="Transparent" />


And the object element im preferring too is this:


<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
<param name="source" value="ClientBin/MVC_silverlight.xap"/>
<param name="onError" value="onSilverlightError" />
<param name="background" value="white" />
<param name="minRuntimeVersion" value="3.0.40818.0" />
<param name="autoUpgrade" value="true" />
<a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40818.0" style="text-decoration:none">
<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style:none"/>
</a>
</object>
<iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe>



NOTE: You have to build your project in order to have those object.
Take a look on the first param, name="source" value="ClientBin/MVC_silverlight.xap" it pointed to the xap file. Xap file is the compressed output file for the Silverlight application. The .xap file includes AppManifest.xaml, compiled output assembly of the Silverlight project (.dll) and any other resource files referred by the Silverlight application.

You can actually just add that xap file in your Web project and point it right on the param source value.



For more information, see How to: How to: Add Silverlight to a Web Page by Using HTML

Read More...

Submit a form using asp.net MVC

Ok well..there a lot of ways on how to submit your forms depending on your needs.
I'm gonna show few of those..and its up to you what you gonna used.

The normal way of submitting forms.

Views File (Register.aspx)


<% using (Html.BeginForm()) { %>


Account Information



<%= Html.TextBox("username") %>


// more code in here



<% } %>


Controller File (Home.cs)


[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Register(string username,...)
{

if (string.IsNullOrEmpty(username))
{
return View();
}
// more code in here for checking
}


Submit a form using Javascript


<% using (Html.BeginForm(null, null, FormMethod.Post, new { id="myForm"}))
{ %>
//code here
<% } %>

and then:

 $("#myForm").submit(); 


and do not forget to include jquery-1.2.6.js that comes with mvc (or use a higher version).
The Home.cs file is same as the above code.

If you want to do a client side checking before submitting your data on the server..you have to do the more complex way.

   
<% using (Html.BeginForm("Register", "Home", FormMethod.Post, new { id="myForm", onsubmit="return !stopThis();", enctype="multipart/form-data" }))
{%>
//code here
<% } %>

and then:
   
function stopThis() {
//Mandatory fuction where u can check all ur data if it was all correct and fill up
if (Mandatory()) {
// let say we have a notification element name notify_msg
document.getElementById('notify_msg').innerHTML = 'Pls. Fill up all the Required Fields';
return true;
}
return false; // require fields are all correct
}


Home.cs

   
public ActionResult SubmitCareerForm(FormCollection frm)
{
// no more checking on the field
// code here
}


Take a look on the Home.cs file, see the [AcceptVerbs(HttpVerbs.Post)] it was removed on the last sample. No need for that since we are already
pointing the funtion on the Home file using (Html.BeginForm("Register", "Home",.....

Theres also an elegant way to ajaxify you forms (with jquery) . Never try that one though.

ciao.

Read More...

Installing and Include new module for Joomla

I just had a project using Joomla 1.5 , it was my first time to used it and i find it very difficult to use the new module i added. It took me almost half a day to do research how to include the ninja shadow box module i installed for me to use it in my images. So i decided to post this blog for all joomla starter like me. This tutorial will explain how to install and include the module, we'll gonna use joomla 1.5.

So to start with will have a sample module, lets use Ninja Shadow Box more likely a jquery lightbox. Shadowbox is a cross-browser, cross-platform, cleanly-coded and fully-documented media viewer application written entirely in JavaScript. Using Shadowbox, website authors can display a wide assortment of media in all major browsers without navigating away from the linking page.
Lets say we already had the zip file of the module so the next to do is to install it in our joomla application.

1. Install the Module
Extension -> Install/Uninstall



2. Add a position in templateDetails.xml ( \templates\[template used] Read More...

Problem in Jquery Virtual Tour when place inside a pop-up div.

jQuery virtual tour - an extension to the simple panorama viewer that allows you to play a little bit more with jQuery by adding interactivity to transform some panoramic views into a virtual tour! FREE - released under the GPL licence.

No need for Flash, Quicktime ou Java. Your visitors will not have to install any software to experiment your virtual tour.

Advanced Panorama
This virtual tour plugin has the particularity to be accessible and can run even if javascript has not been activated - navigation uses the standard html tags <map> and <area> in accordance with w3c.

jQuery virtual tour DEMO / jQuery virtual tour Article

jQuery Virtual Tour Script

Simple Pandora Viewer
This small plugin for jQuery offers display as an interactive panorama, all images of your page containing the class 'panorama'

simple pandora viewer DEMO / simple pandora viewer Article


Well, both article sample had there image on a page none of them show how to do it in a pop-up/lightbox image where you can do like this:



So how to do it? Take these simple steps.
1.) Choose what viewer to used. In this case we will just used Simple Pandora Viewer.
2.) Follow the Installation on how to used pandora viewer on this article
3.) Create a pop-up div where you can place your image. See this sample.
Place your image inside <div class="divTextHolder">. Just adjust the css of class divTextHolder to fit the image.

As you try to test your application it works well in Firefox and other browsers but in IE the image won't appear and u will be having trouble in your jquery.js or jquery-1.3.2.js

The following error will occur:
Ln 32 Col 4414 Invalid Argument
fx.elem.style[fx.prop]=fx.now+fx.unit


Ln 24 Col 1337 Invalid Argument
elem[name]=value


To resolve those ERROR you need to do the ff:
on the css of #light need to comment/remove display:none and write this scripts




In this scenario you have to display the div that holds image after the page is ready, coz when you have to display none on div the scripts can't fine the current position of image, but well you know this error will only appeared in IE. IE sucks.

-
Read More...

CrossSlide image a Jquery plugin

CrossSlide is a neat plugin for JQuery that allows you to fade in from one image to the next, and even using some cool visual effects like panning. So I thought I would see how hard it is to set up and what sort of limitations is has (if any).

CrossSlide can do a few different things, depending on how it's called:

Slide + cross-fade
This is the kind of animation from which the plugin takes its name. Here is the jQuery code to set it up:


$(function() {
$('#test1').crossSlide({
speed: 45,
fade: 1
}, [
{ src: 'lib/sand-castle.jpeg', dir: 'up' },
{ src: 'lib/sunflower.jpeg', dir: 'down' },
{ src: 'lib/flip-flops.jpeg', dir: 'up' },
{ src: 'lib/rubber-ring.jpeg', dir: 'down' }
]);
});

Static cross-fade
Pretty simple effect, whose invocation is just as simple:

$(function() {
$('#test2').crossSlide({
sleep: 2,
fade: 1
}, [
{ src: 'lib/sand-castle.jpeg' },
{ src: 'lib/sunflower.jpeg' },
{ src: 'lib/flip-flops.jpeg' },
{ src: 'lib/rubber-ring.jpeg' }
]);
});
Notice how the sleep parameter has taken the place of speed, as there can be no speed in an image that's not moving. fade is still expressed in seconds and is additional to the sleep time. You cannot use both speed and sleep at the same time, because they mean different effects.

Ken Burns effect
Finally, CrossSlide can be brought up to the full visual power of a Ken Burns effect: panning, zooming and fading to specific points, to guide the eye of the viewer and convey meaning:

$(function() {
$('#test3').crossSlide({
fade: 1
}, [
{
src: 'lib/sand-castle.jpeg',
href: 'http://flickr.com/photos/spacetrucker/94209642/',
from: '100% 80% 1x',
to: '100% 0% 1.7x',
time: 3
}, {
src: 'lib/sunflower.jpeg',
href: 'http://flickr.com/photos/hichako/1125341449/',
from: 'top left',
to: 'bottom right 1.5x',
time: 2
}, {
src: 'lib/flip-flops.jpeg',
href: 'http://flickr.com/photos/jayniebell/1125216143/',
from: '100% 80% 1.5x',
to: '80% 0% 1.1x',
time: 2
}, {
src: 'lib/rubber-ring.jpeg',
href: 'http://flickr.com/photos/ruminatrix/1125292682/',
from: '100% 50%',
to: '30% 50% 1.5x',
time: 2
}
]);
});


jquery.cross-slide.js(size: 11K; license: GPL; last updated on 14 May 2009)

See the jQuery documentation for more info.
Also visit gruppo4 for a nice sample demo.
Read More...

Email to Friend script and design for Asp.net

It's obviously important to give your readers a way to tell their friends and colleagues about your site - it's free advertising after all. That's why it is important to put the Email to Friends or Tell your Friends link at the top of every page of the site.

What we have here is just a link Email to Friend which open a pop-up div where user can enter their email address, the email addresses of his friends and a note(optional).


First thing we will do is to create the div.



<body>
<%--the link that will appear in the page--%>

<%--the div that will pop-up--%>



Email a Friend
close

Please enter a valid email address.


<%--onsubmit="send_thisEmail();return false;"--%>






255 character limit










</body>



Second is to put a css for the div that pop-up.



#popUpDivEmail
{
border: 8px solid #5E5E5E;
font-size:12px;
left:50%;
margin:-185px auto 0 -155px;
padding:10px;
position:absolute;
top:50%;
width:300px;
z-index:10000001;
display:none;
}
.emailPopUp
{
color:#333333;
font-family:arial,helvetica,tahoma,verdana,sans-serif;
font-size:11px;
}
#EmailContainer
{
background:#FFFFFF none repeat scroll 0 0;
border:1px solid #CCCCCC;
height:370px;
position:static;
text-align:left;
width:298px;
}
#EmailTitleContainer
{
background:#F2F2F2 none repeat scroll 0 0;
height:13px;
padding:5px 10px;
position:relative;
}
#EmailTitleContainer a
{
color:#4C4C4C;
position:absolute;
right:10px;
text-decoration:none;
top:5px;
}
#the_form input, #the_form textarea
{
background:#FFFFFF none repeat scroll 0 0;
border:1px solid #BBBBBB;
color:#333333;
font-family:arial,helvetica,tahoma,verdana,sans-serif;
font-size:11px;
font-weight:normal;
line-height:1.4em;
margin:0 0 8px;
padding:3px;
width:272px;
}
.btn
{
background:#FFFFFF none repeat scroll 0 0;
border:1px solid #B5B5B5;
color:#333333;
cursor:pointer;
font-size:11px ;
font-weight:bold;
margin:0 2px;
padding:2px 4px;
width:60px;
}

#addthis-pop-email-btns .btn:hover
{
color:#41BBFF;
border: 1px solid #ececec;
}

#errorEmail
{
background:#F26D7D none repeat scroll 0 0;
border-bottom:1px solid #DF5666;
color:#FFFFFF;
padding:5px 10px;
display:none;
}




So have this script in the header







To get the latest js that we exported on the header just copy and paste this latest.js and create a new js file and save it as jquery.js.

The function openThis() and closeThis() are for opening and closing the pop-up div respectively.
In the sendThis() function notice the variable emailRegex, its a regular expression for email. We check first the email enter before we call the server side function EmailToFriend. Another thing is the variable emails = Toemail.split(/[;?,?]/) in function GetAllEmail() this variable will split all the Email To either the user input semicolon ; or comma , to separate the multiple emails. The last function will limit the user number of character inputed on the notes to 255 only.


Basically the form will look like this:

Email To Friend


And last part is the sever side function EmailToFriend where sending of email will take place. This is just a simple asp.net C# code, you can have your own code in here depending on your scope and limitation on how you will have it.



public JsonResult EmailToFriend(string[] To_Email, string From_Email, string msg)
{
for (int i = 0; i < To_Email.Count(); i++)
{
MailMessage message = new MailMessage();

//subject
message.Subject = From_Email + " has shared something with you at Chenz101Tutorials";
string url = HttpContext.Request.UrlReferrer.ToString();

string body = msg + " " + url;
body += "P.S. This message was sent by" + From_Email + "via chenz101tutorials.blogspot.com";

//body
message.Body = body;
message.IsBodyHtml = true;
//from
message.From = new MailAddress(From_Email);
try
{
message.To.Add(To_Email[i]);
//Set SMTP Client
SmtpClient SmtpHost = new SmtpClient();
SmtpHost.EnableSsl = true;
SmtpHost.Host = "smtp.gmail.com";
SmtpHost.Port = 587;
NetworkCredential netCred = new NetworkCredential("username", "password");

SmtpHost.Credentials = netCred;

//Send Email
SmtpHost.Send(message);
}
catch (Exception ex)
{
return Json(false);
}
}

return Json(true);
}


Read More...

Customize lightbox for div element

Lots of thread i read about Lightbox says it wont work on the div element only on images. So i tried to customize some of the lighbox jqueries and its css, and ending up creating a new lightbox.js that adopts div element.

To have a customize lighbox for div element simply:
1. Create the css file for the lightbox [ lightbox.css ].
2. Create the js file[ gsp_lightbox.js ].
3. Import the two file in your page header.
4. Have your html body. And on your hyperlink event ONCLICK add "showLightBox(); return false;" which will open the div lightbox. The div id="light" will contains all the information inside the popup div. Refer html body.

Below contains all the code you will be needed. { copy and paste }



lightbox.css


#fade
{
display: none;
background-color:#3E3E3E;
position: absolute;
top: 0%;
left: 0%;
z-index: 90;
width: 100%;
height: 500px;
-moz-opacity: 0.8;
opacity: 0.8;
filter : alpha(opacity=80);
}

#light
{
display: none;
position: absolute;
top: 0%;
left: 0%;
z-index: 100;
text-align: left;
width:100%;
}

.white_innerContent
{
background-color: #fff;
position: relative;
width: 560px;
height: 500px;
margin: 0 auto;
color:#333333;
}

.lightfoot
{
font-family:Arial,Helvetica,sans-serif;
background-color:#AD7032;
height:32px;
color:#fff;
font-weight:bold;
font-size:12px;
}

.divTextHolder
{
border: 15px solid #B2AD94;
overflow:auto;
width: 510px;
height: 440px;
padding:10px;
}



gsp_lightbox.js



/**
* customized lightbox for div element
* GSP
* http://chenz101tutorials.blogspot.com/
*/

function showLightbox() {

// Get page sizes
var arrPageSizes = currentPageSize();
// Get page scroll
var arrPageScroll = currentPageScroll();

// Style overlay and show it
$('#fade').css({
width: arrPageSizes[0] + 'px',
height: (arrPageSizes[1] + 100) + 'px'
}).fadeIn();
// calculate top and left offset for the jquery-lightbox div object and show it
$('#light').css({
top: (arrPageScroll[1] + (arrPageSizes[3] / 10)) + 'px',
left: arrPageScroll[0] + 'px'
}).show();


$(window).resize(function() {
// Get page sizes
var arrPageSizes = currentPageSize();
// Get page scroll
var arrPageScroll = currentPageScroll();

// Style overlay and show it
$('#fade').css({
width: arrPageSizes[0] + 'px',
height: (arrPageSizes[1] + 100) + 'px'
});
// Calculate top and left offset for the jquery-lightbox div object and show it
$('#light').css({
top: (arrPageScroll[1] + (arrPageSizes[3] / 10)) + 'px',
left: arrPageScroll[0] + 'px'
});

});

//Enable a support to keyboard navigation
$(document).keydown(function(objEvent) {
_keyboard_action(objEvent);
});
}


//get PageSize
function currentPageSize() {
var xScroll, yScroll;
if (window.innerHeight && window.scrollMaxY) {
xScroll = window.innerWidth + window.scrollMaxX;
yScroll = window.innerHeight + window.scrollMaxY;
} else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
xScroll = document.body.scrollWidth;
yScroll = document.body.scrollHeight;
} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
xScroll = document.body.offsetWidth;
yScroll = document.body.offsetHeight;
}
var windowWidth, windowHeight;
if (self.innerHeight) { // all except Explorer
if (document.documentElement.clientWidth) {
windowWidth = document.documentElement.clientWidth;
} else {
windowWidth = self.innerWidth;
}
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
windowWidth = document.documentElement.clientWidth;
windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
windowWidth = document.body.clientWidth;
windowHeight = document.body.clientHeight;
}
// for small pages with total height less then height of the viewport
if (yScroll < windowHeight) {
pageHeight = windowHeight;
} else {
pageHeight = yScroll;
}
// for small pages with total width less then width of the viewport
if (xScroll < windowWidth) {
pageWidth = xScroll;
} else {
pageWidth = windowWidth;
}
arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight);
return arrayPageSize;
};

function currentPageScroll() {
var xScroll, yScroll;
if (self.pageYOffset) {
yScroll = self.pageYOffset;
xScroll = self.pageXOffset;
} else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
yScroll = document.documentElement.scrollTop;
xScroll = document.documentElement.scrollLeft;
} else if (document.body) {// all other Explorers
yScroll = document.body.scrollTop;
xScroll = document.body.scrollLeft;
}
arrayPageScroll = new Array(xScroll, yScroll);
return arrayPageScroll;
};

//close LightBox
function closeLightbox() {
$('#light').css('display','none');
$('#fade').fadeOut(function() { $('#fade').css('display', 'none'); });

// Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
$('embed, object, select').css({ 'visibility': 'visible' });
}



/**
* Perform the keyboard actions
*
*/
function _keyboard_action(objEvent) {
// To ie
if (objEvent == null) {
keycode = event.keyCode;
escapeKey = 27;
// To Mozilla
} else {
keycode = objEvent.keyCode;
escapeKey = objEvent.DOM_VK_ESCAPE;
}
// Get the key in lower case form
key = String.fromCharCode(keycode).toLowerCase();
// Verify the keys to close the ligthBox
if ((key == 'c') || (key == 'x') || (keycode == escapeKey)) {
closeLightbox();
}
}


html body


<body>

This is the main content. To display a lightbox click here




<%-- overlay --%>

<%-- the pop-up div starts here. --%>



This is the lightbox content.
This is the lightbox content.
This is the lightbox content.
This is the lightbox content.
This is the lightbox content.
This is the lightbox content.
This is the lightbox content.
This is the lightbox content.
This is the lightbox content.
This is the lightbox content.
This is the lightbox content.
This is the lightbox content.
This is the lightbox content.




Amenitites







<%-- the pop-up div ends here. --%>

</body>


well, it looks like this after.

lightbox div Read More...

To use onchange event of dropdownlist on asp.net MVC

Lots of us are still learning the MVC framework. Some are facing difficulties on how to interact the controller and the views. Probably one of the common problems we encounter was dealing with the dropdownlist. In a scenario that you will be having two dropdownlist linking to each other
(dropdown A and dropdown B). And on the onchange event of the dropdown A another set of values will be loaded on the dropdown B.

You don’t want to post the form containing the two dropdown lists back to the server each and every time a user selects a new value from dropdown A. That would create a really bad user experience. Instead, you want to update the list of dropdown B after a new value of dropdown A is selected without a form post.


so probably you be needed cascading drop-downs.

A good sample.

-87
Read More...

Hover effect over a div tag, Jquery

A hover effect will be applied usually on an image. Others have an image inside a div, its still an image which will be resize every mouse in and mouse out. What i have in here in this post will be a div with different element inside of it. It will expand the div and each element inside of it every mouse in and out.

First thing we need to have a html form which will serves our main page for this example.

What i have here is a div inside a div. The div id=card is the main container. Take a look of the styles i have in every div that holds my card information. It is so important to have that positioning of every element, you will know it on the later part of this post.










Next, we need to have the the latest jQuery library. And this AnimateMyDiv.js that i have below:



/*
-------------------------------------------------
FileName:AnimateMyDiv.js
Author: http://chenz101tutorials.blogspot.com/
-------------------------------------------------
*/


$(document).ready(function() {

DivSmall($(this).find('div.innercontainer').children());

$('ul.thumb li').hover(function() {
$(this).css({ 'z-index': '10' }); /*Add a higher z-index value so this image stays on top*/
DivBig($(this).find('div.innercontainer').children()); // this function call when mouse in
$(this).find('div.container').addClass('hover').stop()
.animate({
width: '500px', /* Set new width */
height: '300px', /* Set new height */
padding: '10px'
}, 100); /* this value of "200" is the speed of how fast/slow this hover animates */

}, function() {
$(this).css({ 'z-index': '0' }); /* Set z-index back to 0 */
$(this).find('div.container').removeClass('hover').stop()
.animate({
width: '250px', /* Set width back to default */
height: '150px', /* Set height back to default */
padding: '5px'
}, 200);
DivSmall($(this).find('div.innercontainer').children()); // this function called when mouse out

});

function DivBig(content) {
for (var i = 0; i < content.length; i++) {
var fontSize = parseFloat($(content[i]).css("font-size"));
var posTop = parseFloat($(content[i]).css("top"));
var posLeft = parseFloat($(content[i]).css("left"));
$(content[i]).css({ 'font-size': fontSize * 2 + 'px', 'top': posTop * 2 + 'px', 'left': posLeft * 2 + 'px' });
}
var contW = parseFloat($('div.innercontainer').width());
var contH = parseFloat($('div.innercontainer').height());
}

function DivSmall(content) {
for (var i = 0; i < content.length; i++) {
var fontSize = parseFloat($(content[i]).css("font-size"));
var posTop = parseFloat($(content[i]).css("top"));
var posLeft = parseFloat($(content[i]).css("left"));
$(content[i]).css({ 'font-size': fontSize / 2 + 'px', 'top': posTop / 2 + 'px', 'left': posLeft / 2 + 'px' });
}
var contW = parseFloat($('div.innercontainer').width());
var contH = parseFloat($('div.innercontainer').height());
$('div.innercontainer').css({ 'width': contW / 2 + 'px', 'height': contH / 2 + 'px' });
}
});




Copy the codes above and paste it in a js templates name the file AnimateMyDiv.js.
Import both JS in the <head> of the Info.aspx.






Take a look on the function DivBig() and function DivSmall(), see how important the positioning of each element. It may be tricky but thats the real score, it makes every element go small and big.

To make it complete heres the CSS:









Read More...

Customize reCaptcha, remove theme. ASP.net

It was my first time to use reCaptcha, and i found out that there is a default theme plugin to it, where all i need to get is just the image, with the link reload captcha and link to play audio, similar to the facebook and twitter. Set the reCaptcha theme to "clean" ( theme: 'clean' ) still looks bad. And it took me a while to configure the API inorder to blend in and work good to the website we have.

Well, custom theming API allows you to do the same thing that Facebook has done. Unfortunately, this customization can't be done without javascript.

In order to use custom theming, you must first set the theme property of the RecaptchaOptions to 'custom'. This tells reCAPTCHA that it should not create a user interface of its own. reCAPTCHA will rely on the presence of HTML elements with the following IDs to display the CAPTCHA to the user:

* An empty div with ID recaptcha_image. This is where the actual image will be placed. The div will be 300x57 pixels.
* A text input with ID and name both set to recaptcha_response_field. This is where the user can enter their answer.
* Optionally, a div which contains the entire reCAPTCHA widget. This ID div should be placed into the custom_theme_widget and the style of the div should be set to display:none. After the reCAPTCHA theming code has fully loaded, it will make the div visible. This element avoids making the page flicker while it loads.






Note: dont forget to export the recaptcha.js before the above code.

On the page you will have this html code:



Incorrect please try again







<%--an empty div with ID recaptcha_image --%>


Get another CAPTCHA
Get an audio CAPTCHA


<%--a text input with ID and name both set to recaptcha_response_field --%>





So its kinda look like this( is use asp.net MVC ):

custom_recaptcha


Have this script also to check if the inputed text is same as the image recaptcha that generated.


$(function() {
$('#submitLink').click(function() {
$.ajax({
type: "POST",
url: "/Home/isCaptchaValid",
async: false,
data: { "challenge": Recaptcha.get_challenge(), "response": Recaptcha.get_response() },
success: function(data) {
alert(data);
},
error: function() { alert('error'); }
});
});
});


Take a look at the URL i call it will go on the HOME controller (as i used the MVC). The code behind for this application:


//be reminded that i use ASP.net MVC
//it will return a JSON boolean.

[AcceptVerbs(HttpVerbs.Post)]
public bool isCaptchaValid(string challenge,string response)
{

// Add your operation implementation here
Recaptcha.RecaptchaValidator validator = new Recaptcha.RecaptchaValidator
{
PrivateKey = "6LcouQcAAAAAAOjcmhymXE9M7jTHAmV9VsIm1UFy",
RemoteIP=Request.UserHostAddress,
Challenge=challenge,
Response=response

};
Recaptcha.RecaptchaResponse Cresponse = validator.Validate();
return Cresponse.IsValid;
}


The parameters Recaptcha.get_challenge() and Recaptcha.get_response() are the helper functions that return the reCAPTCHA challenge string and the response that the user has typed in to the response field. They return null if the widget isn't showing. Can be used with the AJAX API to retrieve the answers so that an XMLHttpRequest can be used to post the reCAPTCHA solution.

View the demo.

For more info visit: ASP.NET CAPTCHA Library for reCAPTCHA


ciao

Read More...

101 Free Twitter Buttons, Badges and Widget to Show Off Your Tweets


One of the best ways to find new followers for your Twitter account is to provide any other online profile that you might already have. If you have a website, blog or other social media account linking to your Twitter account is a great way to do this.

There are a number of ways to promote your Twitter (Twitter) account. You can add yourself to one of the many growing Twitter directories, Twitter directories, or, have an eye catching button, widget or counter can be even more effective. Well, of course there are some Official Twitter Badges available...but what if you want something a little different(considering the color, format and sizes)?

So below are the list of links where you can download a buttons, embed badges and widgets that you can customize to include your tweets for your website:

Cute Twitter Bird Vector Art - by Smashing Magazine. The set is available as a free download and can be used for any purpose without any restrictions whatsoever. You can freely use it for both your private and commercial projects, including software, online services, templates and themes. The set may not be resold, sub-licensed, rented, transferred or otherwise made available for use. Please link to this article if you would like to spread the word.

Spread the word on Twitter!


TwitStamp – TwitStamp lets you set up an easy, attractive, and customizable badge that displays your latest tweet. You can select the badge’s size, background and so on. You can also set up a TwitCard that will show your name, avatar, bio, latest tweet, number of followers and more.

twitstamp.com


U Stand Out Twitter Badges – U Stand Out offers up a nice selection of badges you can use for your site or blog that range from artsy to straight-to-the-point.

Twitter Button - Blue Theme Twitter Button - Black Theme Twitter Button - Purple Theme


SayTweet – SayTweet allows you to upload a picture of your own, tag the Twitter users shown, and their tweets will show up in speech bubbles on the image as they publish them.

Siah Design - Free Twitter Buttons - 42 Twitter buttons - some of them animated. You can download the graphics by right clicking the image and downloading the link. Just place the image on your site and link to your Twitter profile.

animated twitter button TWITTER BUTTONS animated twitter button


TwitterSalt – allows you to customize your widget on their site and then just by using a single line of HTML code you can post your updates on sites, on message boards, in emails and more.

Twignature - Another Japanese creation that allows you to enter your account name and have a personalized twitter button with your account name on it. Lots of sizes and a few different styles to choose from.

twitter / chenzdenmark


Twitt-Twoo - WordPress plugin Widget for your blog’s sidebar. There’s another WP sidebar widget plugin here.

twitt-1.gif


MilkAddict - Twitter button - 2 simple round buttons.

twitter-button-small.png


Follow me on Twitter badges - 36 colorful Twitter badges. There are also some backgrounds to go with these badges.

Follow me on Twitter badge twitter-blue.png twitter-red-plaid.png


31 Logos et boutons pour Twitter - 31 great buttons. The blog might not be in English but the buttons are. Some great designs here.



Web Design by mt - 10 Twitter Buttons for Free (German).

twitter-button.png


Randa Clay - Free Twitter Graphics - 18 different Twitter buttons like this one.

twitter badge 2 twitter badge 9


TwiBadge – is a WordPress plugin widget that allows you to easily add the official Twitter widget to your site. This allows you to show a group of your most recent tweets, your user name and number of followers, but best of all, it will also enable your readers to login and follow you so they can do everything right from your sidebar.

widgetnest twitter widget


-87

Read More...

A fancy style for search suggestion

Apple is known to create beautiful products (next to the needed functionality of course).

The website from Apple isn't less: The layout is simple yet beautiful. Yet, one of the most awesome things about the website is the search functionality. It gives you suggestions (with images) about the several products they offer, making it really user-friendly.

Today, we're trying to recreate the effect from that website by creating a fancy apple.com-style search suggestion. Make sure you check out the demo (or visit Apple.com) to see this awesome effect work.


A fancy Apple.com-style search suggestion



This example makes use of several techniques: MySQL (for the database), HTML/CSS for styling, PHP for retrieving the data and jQuery for the AJAX request. How about that for some nice way of combining powerful techniques to create something nice like this. You do need some basic knowledge about these techniques to fully understand this tutorial.



So here`s the nice and originally design search suggestion from Marcofolio.net


Type rest of the post here
Read More...

Redirecting Page using Jquery Timer

First and foremost, you might wondering whats the use of having these when we can use the predefine Response.Redirect([url]) method. Well, the main purpose of having this in Jquery is to allows you to set timer that fire an event after a certain amount of time. Asp.net equivalent has 'Application_BeginRequest' event where you can record the url path of the page and a Meta refesh TAG where you can set a time. But i feel more comfortable using this jquery timer, since i can also use this when im working on MVC. I will be creating a very simple example of how i do Jquery timer in redirecting page.

To begin with we need to have the the latest jQuery [compressed, 19kB] and Jquery timer inorder to work on timer.

We will be having two pages a Home.aspx and Info.aspx. The most common way in redirecting page with timer happens when you need to notify user and redirect her/him to a particular page. Or when an error occur while doing something you need to redirect the user.

Import both JS in the <head> of the Info.aspx.







Info.aspx page will hold the notification for the user. After 3 seconds it will be redirected to Home.aspx.

Here's the scripts how to use timer in redirecting a page.





On the form of Info.aspx, we just have the notification.




Successfully created a new account.


You will be redirected to Home page after 3 seconds






87
Read More...

Add and Remove a element dynamically in jQuery

What i have in here is a very simple add and remove textfield element. One has to click on the Add link and another textfield will be added. You can also use these if you need to add another element like a button or a dropdownlist at the same time remove it dynamically.

So first thing we need to have these files to begin:

- the latest jQuery [compressed, 19kB]
- jQuery Plugin: highlightFade [8kB] this is optional just to give a little highlight effect when adding elements)

Now we gonna import both JS in the <head> of my html doc.






Then, create a table with a <div> nested inside the <td> . Also create an <a> tag that will be used to generate the form. The <input type=”hidden”> is required in order to ensure a unique id is assigned to every newly generated form elements.



<table>
<tr>
<td/>
<td colspan="3">
Add
</td>
</tr>
<tr>
<td> Blog(s): </td>
<td>
//target div were blog dynamic fields added
</td>
</tr>
<tr>
<td/>
<td colspan="3">
Add
</td>
</tr>
<tr>
<td> Social Network(s): </td>
<td>
//target div were social dynamic fields added
</td>
</tr>
</table>




Next, the JS code for adding the form. The form element being added is wrapped inside a <p> with an id corresponding each row. Actually we can use <td> and create a table inside a <div>, but right now we just stick on the <p>.
The simple jQuery function used here is $().append(). At the same time, we also create a ‘Remove’ anchor right next to the elements we added. These anchor will be used to invoke the function to remove the particular row. Next, a nice little highlight effect is added to the <p> using highlightFade jQuery plugin and finally the value of <input type=”hidden” id=”id”> is incremented. I had an IF statment to check if that field is for the blog or for the social network.



function addFormField(type) {
var id = document.getElementById("id").value;
if (type == "blog") {
$("#divTxt").append("

Remove

");
}
else {
$("#divSocial").append("

Remove

");
}

$("#brow" + id).highlightFade({
speed: 1000
});
$("#srow" + id).highlightFade({
speed: 1000
});

id = (id-1) + 2;
document.getElementById("id").value = id;
}


Finally, the JS code for removing form elements. Basically, what this function does is remove the

that wrapped the form elements, using jQuery function $().remove(). As a result, everything will be removed safely (not hidden) from the form. This can be seen when you submit the form; only values from the visible text fields are sent to the browser.


function removeFormField(id) {
$(id).remove();
}




-87
Read More...

Drag and Drop in javascript, and Save persisting position using ASP.net

Drag and Drop are one of the few jQuery's UI Library. jQuery UI provides abstractions for low-level interaction and animation, advanced effects and high-level, themeable widgets, built on top of the jQuery JavaScript Library, that you can use to build highly interactive web applications.

To make use of Draggables, you need to download the UI library and then use the ui.core and ui.draggable files along with jquery:


<script src="script/jquery-1.3.1.min.js" type="text/javascript"></script>
<script src="script/ui.core.min.js" type="text/javascript"></script>
<script src="script/ui.draggable.min.js" type="text/javascript"></script>

There are lots of demos you can see in some site about this drag and drop interactions of the elements but i think only few can give on how to save the persisting position of the dragged item across Postbacks, or even sessions.

So we need to have a simple example of asp.net form.


<form id="form1" runat="server">
<div id="div1" style="border: 1px solid blue; text-align: center; width: 100px; height: 20px;">
Move this text
</div>
</form>


Basically it looks like this:



The Javascript that makes the div draggable:


<script type="text/javascript">
$(function() {
$("#div1").draggable({
drag: function(event, ui) {
$("#div1").css("opacity", "0.6"); // Additional css. Transparency when drag.
},
stop: function(event, ui) {
saveCoords(ui.absolutePosition.left, ui.absolutePosition.top, ui.helper.attr('id'));
$("#div1").css("opacity", "1.0"); // Additional css. Full opacity when stopped
},
cursor: "move"
});
});
</script>


Take a look on the stop callback event a saveCoords() function will be called with 3 arguments are supplied: the x coordinate, y coordinate and the id of the current draggable - ui.helper.attr('id'). And here what that function does:


function saveCoords(x, y, el, id) {

$.ajax({
type: "POST",
url: "Coordinates.asmx/SaveCoords", // the function inside the handler
data: "{x: '" + x + "', y: '" + y + "', element: '" + el + "', userid: '1'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
if (response.d != '1') {
alert('Not Saved!');
}
},
error: function(response) {
alert(response.responseText);
}
});
}


This function makes a call to a Web Service called Coordinates, invoking its method, [url:]SaveCoords(). It passes [data:] in the x and y coordinates, the id of the element and a user ID (hardcoded for thos example, bit could be provided by a session variable, for instance). Here's the Web Service:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Data.SqlClient;
using System.Data;

///
/// Summary description for Coordinates
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

//[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]

[ScriptService]
public class Coordinates : WebService
{
private String conString = System.Configuration.ConfigurationManager.ConnectionStrings["dragCon"].ConnectionString;

[WebMethod]
public int SaveCoords(int x, int y, string element, int userid)
{
int result = 0;
using (SqlConnection conn = new SqlConnection(conString))
{
string query = "UPDATE Coords SET xPos = @xPos, yPos = @yPos WHERE Element = @Element AND UserID = @UserID";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("xPos", x);
cmd.Parameters.AddWithValue("yPos", y);
cmd.Parameters.AddWithValue("Element", element);
cmd.Parameters.AddWithValue("UserID", userid);
conn.Open();
result = (int)cmd.ExecuteNonQuery();
}
}
return result;
}


Note: in this sample i already had a database Drag in my server and a table name Coords with four fields xPos, yPos, Element and a UserID.

The WebMethod simply takes the arguments passed to it and saves them to the database. It returns the number of rows affected for error checking. Great. So the position of the element is saved. How does that get translated to a draggable being positioned where it was left when the page is next requested by the user with the ID of 1? We need another Web Method:


[WebMethod]
public DataSet GetSavedCoords(int userid)
{
DataSet dt = new DataSet();

string query = "SELECT xPos, yPos, Element FROM Coords WHERE UserID = '" + userid + "'";
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(query, con);
con.Open();

SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);

return dt;
}


Taking the User ID as an argument, this method returns a DataSet filled with the positions of all elements saved against the user, and it is invoked in the Page_Load() event in the Code Behind:


protected void Page_Load(object sender, EventArgs e)
{
Coordinates coords = new Coordinates();
DataSet dt = coords.GetSavedCoords(1);
using(DataTableReader reader = dt.CreateDataReader())
{
while (reader.Read())
{
HtmlGenericControl ctl = (HtmlGenericControl)this.FindControl(reader["element"].ToString());
if (ctl != null)
{
ctl.Style.Add("left", reader["xPos"].ToString() + "px");
ctl.Style.Add("top", reader["yPos"].ToString() + "px");

}
}
}
}



The Web Service class is instantiated and its GetSavedCoords() method is called. For each row in the returned DataSet, an element on the page is sought with the same id as one saved in the database. If it is found, it has a dash of CSS applied to it through Attributes.Add(). These set the CSS top and left values. When the page is rendered again, the text is exactly where it was left last time.

-
Read More...