Entries Tagged as ''

Javascript from flash script Accessing javascript from flash getUrl flash

Creating pop-up browser windows in flash

Flash can trigger a browser pop-up in many ways, this sample explains how to do this by JavaScript.We can use javascript in flash in very simple way.Just create a function in javascript and place that in header.In flash file you have only to use getUrl function for accessing that javascript function.

<!–adsencestart–>

Code to write in the flash file

Create a new flash file, create a simple button in it, click the button and type this code on the flash button:

on (release) {
getURL("javascript:openNewWindow('http://www.macromedia.com','thewin',
'height=400,width=400,toolbar=no,scrollbars=yes')");
} Code to write in the html page:-

Now open the html page that contains the swf button and place this code between <head>…</head> area of the html code:

<script language="JavaScript">
function openNewWindow(URLtoOpen, windowName, windowFeatures) {
newWindow=window.open(URLtoOpen, windowName, windowFeatures); }
</script>

Now you are done. When the flash button is clicked then the flash button will trigger the JavaScript from the html page.

Options

You can adjust the first code (the on on the flash button) in order to adjust pop-up window options as follows: url to open, window name, height, width, toolbars (yes/no) and scroll bars (yes/no).

or also you have another like choice:-Code to go in html page top

<script language=”javascript”>
function redirect_now()
{
window.location=”yahoo.com”;
}
</script>

Now code for flash button:-

on (release) {
getURL(“javascript:redirect_now()”);
}


Flash and PHP contact form actionscript Creating contact mail form in flash

About php and flash contact form

This is a contact form made in flash and php, it can be used on ‘contact us’ pages.
A flash file contains the form items and when the ‘send’ button is pressed it sends the values to mailer.php, this mailer.php sends the email to the receiver.

Few of the benefits of using a flash form instead of a html contact form are:
better user interface
less junk messages (automated scripts cannot send emails through a flash form unless it is decompiled)
Usage details

Upload mailer.php and form.swf on your server in same directory.
In mailer.php you will have to replace ‘email@yourserver.com’ with your email address. Make sure this is an email hosted on that server where you are testing (most server requires this).
Preview

This is a preview of how the contact form looks, you try sending an email to see how form reacts, email will not be sent. It shows a warning if some of the fields are not filled.

<?php
/* —————————
php and flash contact form.
by www.MacromediaHelp.com
—————————
Note: most servers require that one of the emails (sender or receiver)
to be an email hosted by same server, so make sure your email
(on last line of this file) is one hosted on same server.
————————— */

// read the variables form the string, (this is not needed with some servers).
$subject = $_REQUEST["subject"];
$message = $_REQUEST["message"];
$sender = $_REQUEST["sender"];

// include sender IP in the message.
$full_message = $_SERVER['REMOTE_ADDR'] . “\n\n” . $message;
$message= $full_message;

// remove the backslashes that normally appears when entering ” or ‘
$message = stripslashes($message);
$subject = stripslashes($subject);
$sender = stripslashes($sender);

// add a prefix in the subject line so that you know the email was sent by online form
$subject = “Contact form test”. $subject;

// send the email, make sure you replace email@yourserver.com with your email address
if(isset($message) and isset($subject) and isset($sender)){
mail(“email@yourserver.com”, $subject, $message, “From: $sender”);
}?>
Contents of the FLA flash file (ActionScript)
stop();
send_btn.onRelease = function() {
my_vars = new LoadVars();
my_vars.sender = email_box.text;
my_vars.subject = subject_box.text;
my_vars.message = message_box.text;
if (my_vars.sender != “” and my_vars.subject != “” and my_vars.message != “”) {
my_vars.sendAndLoad(“mailer.php”, my_vars, “POST”);
gotoAndStop(2);
} else {
error_clip.gotoAndPlay(2);
}
my_vars.onLoad = function() {
gotoAndStop(3);
};
};
email_box.onSetFocus = subject_box.onSetFocus=message_box.onSetFocus=function () {
if (error_clip._currentframe != 1) {
error_clip.gotoAndPlay(6);
}
};


How to open Named Anchor links in flash actionscript

Writing 70-536 and 70-642 is not a big issue for a 642-642 professional, especially since they all have done 350-018 as well as 70-647 and 640-816 earlier in their careers.

About anchor links

In html you can link to a speciffic area of a html page by adding anchors, for example this link will point you to the “solution” area of this page; you link to an area of a page (to an anchor) by adding # after file name followed by the anchor name, e.g: products.php#product4 or just #product4 if destination is on same page.

The ‘namedanchor’ (destination) is written like this in the html code.


The flash issue

When you want a flash button to open a Named Anchor inside the html page normally you would think that the link can be open by something like this:

getURL(‘products.php#product4′);

but the above will not work because of some flash limitations
Solution

Write a really short javascript in the html page and set the getURL from flash to trigger that JavaScript.

Write this function in … area of html code:

Modify getURL actions from flash to call the above JavaScript:
getURL(“javascript:openNewWindow(‘anchor_test.html#title2′,’_parent’)”;

This solution was tested and worked in both Internet Explorer and Mozilla Firefox type browsers.


Simple Flash and XML sample Learning flash and xml

About this article

This article will show you basic connection between flash and XML, it will show you what to add in the flash file in order to be able to read tags from an XML file and then use that data inside flash.

Few details about the XML file

The XML that we will use will look like this, you can create a file called sample.xml and paste this in it:

<?xml version="1.0" encoding= "UTF-8" ?>
<products>
<product product_name="Flash Book" price="25.00"></product>
<product product_name="Flash CD" price="10.00"></product>
<product product_name="Dreamweaver CD" price="50.00"></product>
</products>

In the above XML file the “products” are called XML tags and “product_name” and “price” are called attributes.
“Products” is the first child of the XML file and the lines inside are child 0,1,2 of the first child.

To get the value “Flash Book” you have to write this in ActionScript:
my_xml.firstChild.childNodes[0].attributes.product_name
To get the value “Flash CD” use this code in ActionScript:
my_xml.firstChild.childNodes[1].attributes.product_name

The flash file preview

Contents of the flash file

In our samples we created 6 text fields where the data (product names and product prices) is written but is not important how you use the data, in this article we want to explain how to read the XML data.

Now the contents in the flash file…. open Macromedia Flash, create a blank file, click on first key frame, open Actions panel and paste this code:

// define an XML object called "my_xml"
my_xml = new XML();
// load data from an external XML file into "my_xml" object
my_xml.load("sample.xml");
// what to do when data is loaded ... Call a function ("my_function" in this case)
my_xml.onLoad = my_function;
// ignore "white spaces", text nodes that only contain white space are discarded
my_xml.ignoreWhite = 1;
// function contents
function my_function() {
// take the data from the XML lines (line 0,1,2) and place that data inside text fields
text_field_1.text = my_xml.firstChild.childNodes[0].attributes.product_name;
text_field_2.text = my_xml.firstChild.childNodes[1].attributes.product_name;
text_field_3.text = my_xml.firstChild.childNodes[2].attributes.product_name;
//
text_field_a.text = my_xml.firstChild.childNodes[0].attributes.price;
text_field_b.text = my_xml.firstChild.childNodes[1].attributes.price;
text_field_c.text = my_xml.firstChild.childNodes[2].attributes.price;
}

As you may see, the above code loads data from an external XML file called “sample.xml” and places the data from the XML tags to text fields inside the flash file.

For example: to access the product name on first line (“Flash Book”) the ActionScript line inside the flash file will be like this:

my_xml.firstChild.childNodes[0].attributes.product_name

“my_xml” is the name given to the new XML object at beginning of ActionScript code; the next code are the levels, it reads from first level (“firstChild”) this is “products” tag, from “products” tags it loads first child (“childNodes[0]“) and the attribute name is “product_name”.
So the above line will return the value “Flash Book”.
As you can see counting starts from zero when counting XML lines.

Product_name, price and XML tags are defined by user, in an XML file you can name the tags and the attributes as you wish, the tags are not predefined like in HTML language.


ffmpeg video When I submit a node, a thumbnail gets created, but a 0 byte FLV file is created that is unusable…

This is probably the most popular of all issues with with FlashVideo module in drupal. What causes this issue is when your FFMPEG installation does not have an MP3 codec installed with that module. If you are using a Linux server, you can easily verify if you FFMPEG is using an MP3 codec by simply typing the following command…

/usr/bin/ffmpeg --help

If it cannot find the FFMPEG binary, then you will need to change the path. Otherwise, you should see some information about your FFMPEG installation. In this information, look for where it says –enable-mp3, or maybe –enable-libmp3lame, or something that has to do with enabling an mp3 codec. If you do not see anything in your configuration that hints that your FFMPEG has an MP3 codec, then this is your problem…
So, here is how to fix it. What you need to do is install the mp3 codec for your ffmpeg binary. There are several articles out there that I would recommend on following to solve this issue. They are as follows.

  • http://blog.gwikzone.org/articles/2006/09/25/flv-encoding-with-ffmpeg
  • http://www.travistidwell.com/node/263
      Now, lets suppose that you DO see an MP3 codec installed in your FFMPEG binary, but still no luck. This is usually caused because in your FFMPEG Command within the FlashVideo Settings, you do not have the right name for the codec. By default, in the FFMPEG Settings within the FlashVideo Settings you will see that the FFMPEG command is set for…

      -i @input -f flv -acodec mp3 -ar 22050 -ab 64k -ac 1 @output

      What you will be most concerned with is the little part in this command that says -acodec mp3. The mp3 is the name of the codec that will be performing the mp3 conversion. So, when you called the help for the FFMPEG, you should have seen something that says something like –enable-libmp3lame or –enable-mp3, or maybe even something else that has mp3 in the name. Well, all you have to do now is change the FFMPEG command to reflect the same codec name that is given. So, for example, if your FFMPEG has enabled the libmp3lame codec, your FFMPEG command will look like the following…

      -i @input -f flv -acodec libmp3lame -ar 22050 -ab 64k -ac 1 @output

Before using ffmpeg on linux system for video conversion we can check ffmpeg in following method.This will generate a thumbnail from one video file and will save in second given location this command can be run on linux command prompt after changing the source and destionations.

Example:-

/usr/include/ffmpeg -y -i “/home/dev/public_html/files/4533_4NEW_child.wmv” -vframes 1 -ss “00:00:02″ -an -vcodec mjpeg -f rawvideo -s “200×200″ “/home/dev/public_html/files/flashflv/4533_4NEW_child.jpg”

FLV encoding with ffmpeg

ffmeg is a command-line tool for video encoding which has the ability to encode videos in FLV format (Macromedia plugin for direct-streaming).

First, you need to install ffmpeg with liblame support.

You may grab it as package or compile from sources.

We will compile from sources in this article for more compatibility.

first step : Installing lame get sources at http://lame.sourceforge.net, untar the archive and chdir to unpacked sources directory.

$ ./configure && make && sudo make install

second step : Installing ffmpeg

Getting sources from svn :

 $ svn export svn://svn.mplayerhq.hu/ffmpeg/trunk ffmpeg

Change dir to ffmpeg and compile with liblame

$ ./configure --enable-mp3lame && make && sudo make install

Your now setup. You can continue with encoding your first video

$ /usr/local/bin/ffmpeg  -i input.mov -ar 22050 -ab 56 -aspect 4:3 \
 -b 200 -r 12 -f flv -s 320x240 -acodec mp3 -ac 1 output.flv

to view the result download a swf FLV player and create a html file :

<html>
<head>
<title>Flash FLV Player</title>
</head>
<body>
<h3>My First FLV video</h3>
<object type="application/x-shockwave-flash" width="320" height="260" wmode="transparent" data="flvplayer.swf?file=output.flv&amp;autoStart=false">
<param name="movie" value="flvplayer.swf?file=output.flv&amp;autoStart=false" />
<param name="wmode" value="transparent" />
</object>

</body>
</html>

Enjoy !


Installing FFmpeg On LInux in easy method

650-393 and 70-284 are both required by a 642-552 professional in order to qualify for higher exams like 646-588 as well as 70-293 and 70-294.

FFmpeg is an audio/video conversion tool. It includes libavcodec, the leading open source codec library. An experimental streaming server for live broadcasts is also included. The project was started by Fabrice Bellard (using the pseudonym “Gerard Lantau”), and is now maintained by Michael Niedermayer. Many FFmpeg developers are also part of the MPlayer project, and FFmpeg is hosted at the MPlayer project server.

FFmpeg is developed under Linux, but it can be compiled under most operating systems, including Apple Mac OS X, Microsoft Windows and AmigaOS. There are no releases. Instead, FFmpeg developers recommend using the latest Subversion snapshot as development attempts to maintain a stable trunk.[3] Released under the GNU Lesser General Public License or GNU General Public License (depending on which sub-libraries one would include), FFmpeg is free software.

FFmpeg is a computer program that can record, convert and stream digital audio and video in numerous formats.[1] FFmpeg is a command line tool that is composed of a collection of free software / open source libraries. It includes libavcodec, an audio/video codec library used by several other projects, and libavformat, an audio/video container mux and demux library. The name of the project comes from the MPEG video standards group, together with “FF” for “fast forward”.[2]

Installing FFMpeg

yum install ffmpeg ffmpeg-devel

If you get package not found, then you will need to add few
lines in the yum repository for dag packages installation. Create a file named
dag.repo in /etc/yum.repos.d with the following
contents on it

[dag]
name=Dag RPM Repository for Red Hat Enterprise Linux

baseurl=http://apt.sw.be/redhat/el$releasever/en/$basearch/dag
gpgcheck=1
enabled=1

then

yum install ffmpeg ffmpeg-devel

If everything is fine, then the installation should proceed smoothly. If not
you will get something like warning GPG public key missing .

Common Errors

To fix rpmforge GPG key warning:

rpm -Uhv http://apt.sw.be/redhat/el5/en/i386/rpmforge/RPMS/rpmforge-release-0.3.6-1.el5.rf.i386.rpm

For more information refer to this
faq
depending on Centos version

Missing Dependency Error:

If you get missing dependency error like shown below, in the middle of ffmpeg
installation

Error: Missing Dependency: libc.so.6(GLIBC_2.4) is needed
by package ffmpeg
Error: Missing Dependency: libtheora.so.0(libtheora.so.1.0) is needed by package
ffmpeg

Error: Missing Dependency: rtld(GNU_HASH) is needed by package ffmpeg
Error: Missing Dependency: libc.so.6(GLIBC_2.4) is needed by package imlib2
Error: Missing Dependency: rtld(GNU_HASH) is needed by package a52dec
Error: Missing Dependency: rtld(GNU_HASH) is needed by package imlib2
Error: Missing Dependency: rtld(GNU_HASH) is needed by package gsm
Error: Missing Dependency: libc.so.6(GLIBC_2.4) is needed by package x264

Error: Missing Dependency: rtld(GNU_HASH) is needed by package xvidcore
Error: Missing Dependency: libc.so.6(GLIBC_2.4) is needed by package lame
Error: Missing Dependency: libc.so.6(GLIBC_2.4) is needed by package a52dec
Error: Missing Dependency: rtld(GNU_HASH) is needed by package faad2
Error: Missing Dependency: rtld(GNU_HASH) is needed by package x264
Error: Missing Dependency: rtld(GNU_HASH) is needed by package lame

Error: Missing Dependency: libc.so.6(GLIBC_2.4) is needed by package xvidcore
Error: Missing Dependency: libc.so.6(GLIBC_2.4) is needed by package faac
Error: Missing Dependency: libc.so.6(GLIBC_2.4) is needed by package faad2
Error: Missing Dependency: libgif.so.4 is needed by package imlib2
Error: Missing Dependency: rtld(GNU_HASH) is needed by package faac
Error: Missing Dependency: libc.so.6(GLIBC_2.4) is needed by package gsm

Error: Missing Dependency: libpng12.so.0(PNG12_0) is needed by package imlib2
Error: Missing Dependency: rtld(GNU_HASH) is needed by package libmp4v2
Error: Missing Dependency: libc.so.6(GLIBC_2.4) is needed by package libmp4v2

then most commonly you have GLIB 2.3 installed instead of GLIB 2.4 version.
To check the current GLIB version installed on your server. just use

yum list glib*

and it should list the latest GLIB package version.

The reason i was getting this error was my rpmforge packages was pointed to
centos 5 versions instead of centos 4.6.

To fix dependency error:

To fix this error, you might need to check your rpmforge packages compatible
to the release of your existing CentOS version.
Check the file /etc/yum.repos.d/rpmforge.repo and it should
look like for Centos 4.6(Final). If you have lines like http://apt.sw.be/redhat/el5/en/mirrors-rpmforge
you might need to make changes to the rpmforge.repos
like shown below

Note: Backup the original rpmforge.repo file
before you edit its content.

[rpmforge]
name = Red Hat Enterprise $releasever – RPMforge.net – dag
#baseurl = http://apt.sw.be/redhat/el4/en/$basearch/dag

mirrorlist = http://apt.sw.be/redhat/el4/en/mirrors-rpmforge
#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge
enabled = 1
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag

gpgcheck = 1

To know what linux type and version you are running

cat /etc/redhat-release

Once this is done, do again yum install ffmpeg.

This trick resolved the problem in my linux box running Centos 4.6 and this
is the only way i found to install ffmpeg using yum.

To check the FFmpeg working:

Finally, check the ffmpeg whether it is working or not.

> ffmpeg
> ffmpeg -formats
> ffmpeg –help
// This lists path of mpeg, its modules and other path information

ffmpeg -i Input.file Output.file

To check what audi/video formats are supported

ffmpeg -formats > ffmpeg-format.txt

Open the ffmpeg-formats.txt to see the ooutput

D means decode
E means encode

V means video
A means audio
T = Truncated

Install FFMPEG-PHP Extension

FFmpeg-php
is a very good extension and wrapper for PHP which can pull useful information
about video through API interface. Inorder to install it you will need to download
the source file and then compile and install extension in your server. You can
download the source tarball : http://ffmpeg-php.sourceforge.net/

wget /path/to/this/file/ffmpeg-php-0.5.2.1.tbz2

tar -xjf ffmpeg-0.5.2.1.tbz2

phpize

./configure
make
make install

Common Errors

1. If you get command not found error for
phpize, then you will need to do yum install php-devel

2. If you get error like “ffmpeg headers not
found”
while configuring the source.

configure: error: ffmpeg headers not found. Make sure ffmpeg is
compiled as shared libraries using the –enable-shared option

then it means you have not installed ffmpeg-devel packages.

To Fix: Just install ffmpeg-devel using

yum install ffmpeg-devel

3. If you get an error like shared libraries not found problem
and the program halts in the middle, then you must specify the ffmpeg installed
path explicitly to the ./configure.

configure: error: ffmpeg shared libraries not found. Make sure
ffmpeg is compiled as shared libraries using the –enable-shared option

To Fix:

1. First find out the ffmpeg path with ffmpeg –help command.
The prefix default path should be like /usr/local/cpffmpeg
2. Configure the FFmpeg-php with –with-ffmpeg option

./configure –with-ffmpeg=/usr/local/cpffmpeg

That should resolve the problem!

Editing PHP.INI

Once you have done that without any problems then you will see the php extension
file /usr/local/lib/php/extensions/no-debug-non-zts-20060613/ffmpeg.so
and you will need mention that extension in php.ini file

nano /usr/local/lib/php.ini

Put the below two lines at the end of the php.ini file

[ffmpeg]
extension=ffmpeg.so

Then restart the server service httpd restart

To check whether ffmpeg enabled with php, point your browser
to test.php file. It should show the confirmation of installed
ffmpeg php extension

// #test.php

<?php

phpinfo()

?>

If any case the ffmpeg does not show in the phpinfo() test make sure that php.ini
path to ffmpeg.so is correct. Still the problem occurs, the reason could be
you might be using older versions of ffmpeg-php which is buggy. Just download
the latest version of ffmpeg-php source then compile it.


Getting Started with DNN-Creating first DotnetNuke module(DNN custom module)

What do you need to do to create a Simple first DotNetNuke (DNN) module?(contact form)

  1. Set up your development environment
  2. Under DesktopModules create a folder called contactme
  3. Create three files under contactme folder
    • contactme.dnn
    • Viewcontactme.ascx
    • Viewcontactme.ascx.cs
  4. Code for Contactme.dnn:-
    <dotnetnuke version=”3.0″ type=”Module”>
    <folders>
    <folder>
    <name>Phinest.contactme</name>
    <friendlyname>contactme</friendlyname>
    <foldername>Phinest.contactme</foldername>
    <modulename>Phinest.contactme</modulename>
    <description>A contactme module</description>
    <version>01.00.00</version>
    <businesscontrollerclass>Phinest.Modules.contactme.contactmeController</businesscontrollerclass>
    <modules>
    <module>
    <friendlyname>contactme</friendlyname>
    <cachetime>60</cachetime>
    <controls>
    <control>
    <src>DesktopModules/contactme/Viewcontactme.ascx</src>
    <type>View</type>
    <helpurl></helpurl>
    </control>
    </controls>
    </module>
    </modules>
    <files>
    <file>
    <name>Viewcontactme.ascx</name>
    </file>
    <file>
    <name>Viewcontactme.ascx.cs</name>
    </file>
    </files>
    </folder>
    </folders>
    </dotnetnuke>
  5. Code for contactme.aspx<%@ Control language=”C#” Inherits=”Phinest.Modules.contactme.Viewcontactme” CodeFile=”Viewcontactme.ascx.cs” AutoEventWireup=”true” Explicit=”True”%>

    Form here

  6. Code for contactme.aspx.csusing System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Reflection;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    namespace Phinest.Modules.contactme
    {
    partial class Viewcontactme : PortalModuleBase, IActionable
    {
    private string strTemplate;
    protected void Page_Load(System.Object sender, System.EventArgs e)
    {
    try
    {
    if (!Page.IsPostBack)
    {
    }
    }
    catch (Exception exc) //Module failed to load
    {
    Exceptions.ProcessModuleLoadException(this, exc);
    }

    }
    }
    }


The SqlCommand Object database operations C# dot net

The SqlCommand Object

This lesson describes the SqlCommand object and how you use it to interact with a data base. Here are the objectives of this lesson:

  • Know what a command object is.
  • Learn how to use the ExecuteReader method to query data.
  • Learn how to use the ExecuteNonQuery method to insert and delete data.
  • Learn how to use the ExecuteScalar method to return a single value.

Introduction

A SqlCommand object allows you to specify what type of interaction you want to perform with a data base. For example, you can do select, insert, modify, and delete commands on rows of data in a data base table. The SqlCommand object can be used to support disconnected data management scenarios, but in this lesson we will only use the SqlCommand object alone. A later lesson on the SqlDataAdapter will explain how to implement an application that uses disconnected data. This lesson will also show you how to retrieve a single value from a data base, such as the number of records in a table.

Creating a SqlCommand Object

Similar to other C# objects, you instantiate a SqlCommand object via the new instance declaration, as follows:

SqlCommand cmd = new SqlCommand(“select CategoryName from Categories”, conn);

The line above is typical for instantiating a SqlCommand object. It takes a string parameter that holds the command you want to execute and a reference to a SqlConnection object. SqlCommand has a few overloads, which you will see in the examples of this tutorial.

Querying Data

When using a SQL select command, you retrieve a data set for viewing. To accomplish this with a SqlCommand object, you would use the ExecuteReader method, which returns a SqlDataReader object. We’ll discuss the SqlDataReader in a future lesson. The example below shows how to use the SqlCommand object to obtain a SqlDataReader object:

// 1. Instantiate a new command with a query and connection
SqlCommand cmd =
new SqlCommand(“select CategoryName from Categories”, conn);

// 2. Call Execute reader to get query results
SqlDataReader rdr = cmd.ExecuteReader();

In the example above, we instantiate a SqlCommand object, passing the command string and connection object to the constructor. Then we obtain a SqlDataReader object by calling the ExecuteReader method of the SqlCommand object, cmd.

This code is part of the ReadData method of Listing 1 in the Putting it All Together section later in this lesson.

Inserting Data

To insert data into a data base, use the ExecuteNonQuery method of the SqlCommand object. The following code shows how to insert data into a data base table:

// prepare command string
string insertString = @”
insert into Categories
(CategoryName, Description)
values (‘Miscellaneous’, ‘Whatever doesn”t fit elsewhere’)”;

// 1. Instantiate a new command with a query and connection
SqlCommand cmd = new SqlCommand(insertString, conn);

// 2. Call ExecuteNonQuery to send command
cmd.ExecuteNonQuery();

The SqlCommand instantiation is just a little different from what you’ve seen before, but it is basically the same. Instead of a literal string as the first parameter of the SqlCommand constructor, we are using a variable, insertString. The insertString variable is declared just above the SqlCommand declaration.

Notice the two apostrophes (”) in the insertString text for the word “doesn”t”. This is how you escape the apostrophe to get the string to populate column properly.

Another observation to make about the insert command is that we explicitly specified the columns CategoryName and Description. The Categories table has a primary key field named CategoryID. We left this out of the list because SQL Server will add this field itself. trying to add a value to a primary key field, such as CategoryID, will generate an exception.

To execute this command, we simply call the ExecuteNonQuery method on the SqlCommand instance, cmd.

This code is part of the Insertdata method of Listing 1 in the Putting it All Together section later in this lesson.

Updating Data

The ExecuteNonQuery method is also used for updating data. The following code shows how to update data:

// prepare command string
string updateString = @”
update Categories
set CategoryName = ‘Other’
where CategoryName = ‘Miscellaneous’”;

// 1. Instantiate a new command with command text only
SqlCommand cmd = new SqlCommand(updateString);

// 2. Set the Connection property
cmd.Connection = conn;

// 3. Call ExecuteNonQuery to send command
cmd.ExecuteNonQuery();

Again, we put the SQL command into a string variable, but this time we used a different SqlCommand constructor that takes only the command. In step 2, we assign the SqlConnection object, conn, to the Connection property of the SqlCommand object, cmd.

This could have been done with the same constructor used for the insert command, with two parameters. It demonstrates that you can change the connection object assigned to a command at any time.

The ExecuteNonQuery method performs the update command.

This code is part of the UpdateData method of Listing 1 in the Putting it All Together section later in this lesson.

Deleting Data

You can also delete data using the ExecuteNonQuery method. The following example shows how to delete a record from a data base with the ExecuteNonQuery method:

// prepare command string
string deleteString = @”
delete from Categories
where CategoryName = ‘Other’”;

// 1. Instantiate a new command
SqlCommand cmd = new SqlCommand();

// 2. Set the CommandText property
cmd.CommandText = deleteString;

// 3. Set the Connection property
cmd.Connection = conn;

// 4. Call ExecuteNonQuery to send command
cmd.ExecuteNonQuery();

This example uses the SqlCommand constructor with no parameters. Instead, it explicity sets the CommandText and Connection properties of the SqlCommand object, cmd.

We could have also used either of the two previous SqlCommand constructor overloads, used for the insert or update command, with the same result. This demonstrates that you can change both the command text and the connection object at any time.

The ExecuteNonQuery method call sends the command to the data base.

This code is part of the DeleteData method of Listing 1 in the Putting it All Together section later in this lesson.

Getting Single values

Sometimes all you need from a data base is a single value, which could be a count, sum, average, or other aggregated value from a data set. Performing an ExecuteReader and calculating the result in your code is not the most efficient way to do this. The best choice is to let the data base perform the work and return just the single value you need. The following example shows how to do this with the ExecuteScalar method:

// 1. Instantiate a new command
SqlCommand cmd = new SqlCommand(“select count(*) from Categories”, conn);

// 2. Call ExecuteNonQuery to send command
int count = (int)cmd.ExecuteScalar();

The query in the SqlCommand constructor obtains the count of all records from the Categories table. This query will only return a single value. The ExecuteScalar method in step 2 returns this value. Since the return type of ExecuteScalar is type object, we use a cast operator to convert the value to int.

This code is part of the GetNumberOfRecords method of Listing 1 in the Putting it All Together section later in this lesson.

Putting it All Together

For simplicity, we showed snippets of code in previous sections to demonstrate the applicable techniques . It is also useful to have an entire code listing to see how this code is used in a working program. Listing 1 shows all of the code used in this example, along with a driver in the Main method to produce formatted output.

Listing 1. SqlConnection Demo

using System;
using System.Data;
using System.Data.SqlClient;

/// <summary>
///
Demonstrates how to work with SqlCommand objects
/// </summary>
class SqlCommandDemo
{
SqlConnection conn;

public SqlCommandDemo()
{
// Instantiate the connection
conn = new SqlConnection(
“Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI”);
}

// call methods that demo SqlCommand capabilities
static void Main()
{
SqlCommandDemo scd = new SqlCommandDemo();

Console.WriteLine();
Console.WriteLine(“Categories Before Insert”);
Console.WriteLine(“————————”);

// use ExecuteReader method
scd.ReadData();

// use ExecuteNonQuery method for Insert
scd.Insertdata();
Console.WriteLine();
Console.WriteLine(“Categories After Insert”);
Console.WriteLine(“——————————”);

scd.ReadData();

// use ExecuteNonQuery method for Update
scd.UpdateData();

Console.WriteLine();
Console.WriteLine(“Categories After Update”);
Console.WriteLine(“——————————”);

scd.ReadData();

// use ExecuteNonQuery method for Delete
scd.DeleteData();

Console.WriteLine();
Console.WriteLine(“Categories After Delete”);
Console.WriteLine(“——————————”);

scd.ReadData();

// use ExecuteScalar method
int numberOfRecords = scd.GetNumberOfRecords();

Console.WriteLine();
Console.WriteLine(“Number of Records: {0}”, numberOfRecords);
}

/// <summary>
/// use ExecuteReader method
/// </summary>
public void ReadData()
{
SqlDataReader rdr = null;

try
{
// Open the connection
conn.Open();

// 1. Instantiate a new command with a query and connection
SqlCommand cmd = new SqlCommand(“select CategoryName from Categories”, conn);

// 2. Call Execute reader to get query results
rdr = cmd.ExecuteReader();

// print the CategoryName of each record
while (rdr.Read())
{
Console.WriteLine(rdr[0]);
}
}
finally
{
// close the reader
if (rdr != null)
{
rdr.Close();
}

// Close the connection
if (conn != null)
{
conn.Close();
}
}
}

/// <summary>
/// use ExecuteNonQuery method for Insert
/// </summary>
public void Insertdata()
{
try
{
// Open the connection
conn.Open();

// prepare command string
string insertString = @”
insert into Categories
(CategoryName, Description)
values (‘Miscellaneous’, ‘Whatever doesn”t fit elsewhere’)”;

// 1. Instantiate a new command with a query and connection
SqlCommand cmd = new SqlCommand(insertString, conn);

// 2. Call ExecuteNonQuery to send command
cmd.ExecuteNonQuery();
}
finally
{
// Close the connection
if (conn != null)
{
conn.Close();
}
}
}

/// <summary>
/// use ExecuteNonQuery method for Update
/// </summary>
public void UpdateData()
{
try
{
// Open the connection
conn.Open();

// prepare command string
string updateString = @”
update Categories
set CategoryName = ‘Other’
where CategoryName = ‘Miscellaneous’”;

// 1. Instantiate a new command with command text only
SqlCommand cmd = new SqlCommand(updateString);

// 2. Set the Connection property
cmd.Connection = conn;

// 3. Call ExecuteNonQuery to send command
cmd.ExecuteNonQuery();
}
finally
{
// Close the connection
if (conn != null)
{
conn.Close();
}
}
}

/// <summary>
/// use ExecuteNonQuery method for Delete
/// </summary>
public void DeleteData()
{
try
{
// Open the connection
conn.Open();

// prepare command string
string deleteString = @”
delete from Categories
where CategoryName = ‘Other’”;

// 1. Instantiate a new command
SqlCommand cmd = new SqlCommand();

// 2. Set the CommandText property
cmd.CommandText = deleteString;

// 3. Set the Connection property
cmd.Connection = conn;

// 4. Call ExecuteNonQuery to send command
cmd.ExecuteNonQuery();
}
finally
{
// Close the connection
if (conn != null)
{
conn.Close();
}
}
}

/// <summary>
/// use ExecuteScalar method
/// </summary>
/// <returns>number of records</returns>
public int GetNumberOfRecords()
{
int count = -1;

try
{
// Open the connection
conn.Open();

// 1. Instantiate a new command
SqlCommand cmd = new SqlCommand(“select count(*) from Categories”, conn);

// 2. Call ExecuteNonQuery to send command
count = (int)cmd.ExecuteScalar();
}
finally
{
// Close the connection
if (conn != null)
{
conn.Close();
}
}
return count;
}
}

In Listing 1, the SqlConnection object is instantiated in the SqlCommandDemo structure. This is okay because the object itself will be cleaned up when the CLR garbage collector executes. What is important is that we close the connection when we are done using it. This program opens the connection in a try block and closes it in a finally block in each method.

The ReadData method displays the contents of the CategoryName column of the Categories table. We use it several times in the Main method to show the current status of the Categories table, which changes after each of the insert, update, and delete commands. Because of this, it is convenient to reuse to show you the effects after each method call.


Getting Post, Redirect, Get data Dot Net Forms getting started

Asp Dot Net Web Forms

A normal ASP.NET Web Form Lifecycle has the following pattern

  1. HTTP GET of “Create.aspx”
  2. HTTP POST of “Create.aspx”
  3. Validation Fails, “Create.aspx” is Re-Rendered
  4. HTTP POST of “Create.aspx”
  5. Item is created, “Create.aspx” is Re-Rendered with confirmation message

The major problems with this Postback pattern, is that hitting the Refresh button of your browser in steps 3 or 5 will re-post your submitted data. Step 5 is more of a problem as it could possibly re-submit that created information. Granted, there are steps that you can take to approach this problem, but this is how default ASP.NET Web Forms are treated.

Taking this same approach within ASP.NET MVC, can be achieved in the same manner by rendering a your “Create” view from your POST action. For example:

  1. HTTP GET of “/products/create”, “Create” view is rendered
  2. HTTP POST to “/products/submit”
  3. Validation Fails, “Create” view is rendered
  4. HTTP POST to “/products/submit”
  5. Item is created, “Confirm” view is rendered

As you’ll notice, the same problems we had with ASP.NET Web Forms exists with ASP.NET MVC. The really nice option, is that ASP.NET MVC gives you a lot more “freedom” of how the workflow is processed. If we strictly follow the PRG pattern within ASP.NET MVC, it would look something like

  1. HTTP GET of “/products/create”, “Create” view is rendered
  2. HTTP POST to “/products/submit”
  3. Validation Fails, redirect to “/products/create”, “Create” view is rendered
  4. HTTP POST to “/products/submit”
  5. Item is created, redirect to “/products/confirm”, “Confirm” view is rendered

As you’ll notice, where we previously could have had issues in step 3 or 5 before, we no longer have issues. If a user presses the Refresh button in either of those steps, they’ll not get the lovely “Would you like to resubmit the form data” confirmation as featured below – instead, the page just reloads.

image

To implement this, you’ll need 1 controller, 3 action methods, and 2 views. Follow the steps below to achieve this pattern:

   1:  using System.Web.Mvc;
   2:  
   3:  public class ProductsController : Controller
   4:  {
   5:     public ActionResult Create() { ... }
   6:     public ActionResult Submit() { ... }
   7:     public ActionResult Confirm() { ... }
   8:  }

When you implement your Create action, you have to keep in mind that validation may fail and you may need to re-display the form. TempData is best suited for this scenario, and is implemented as such.

   1:  public ActionResult Create()
   2:  {
   3:     if (TempData["ErrorMessage"] != null)
   4:     {
   5:        ViewData["ErrorMessage"] = TempData["ErrorMessage"];
   6:        ViewData["Name"] = TempData["Name"];
   7:        ViewData["Price"] = TempData["Price"];
   8:        ViewData["Quantity"] = TempData["Quantity"];
   9:     }
  10:     return RenderView();
  11:  }

Next you’ll implement your Submit action. This will perform some validation of the user input data, and if successful will save the info and redirect to the Confirm action. If it is not successful, we’ll store the form data into the TempData and redirect to the action Create. This way we mimic maintaining the view’s state even if it fails.

   1:  public ActionResult Submit()
   2:  {
   3:      string error = null;
   4:      string name = Request.Form["Name"];
   5:      if (string.IsNullOrEmpty(name))
   6:      {
   7:          error = "Name is empty. ";
   8:      }
   9:      decimal price;
  10:      if (!decimal.TryParse(Request.Form["Price"], out price))
  11:      {
  12:          error += "Price is invalid. ";
  13:      }
  14:      int quantity;
  15:      if (!int.TryParse(Request.Form["Quantity"], out quantity))
  16:      {
  17:          error += "Quantity is invalid.";
  18:      }
  19:  
  20:      if (!string.IsNullOrEmpty(error))
  21:      {
  22:          TempData["ErrorMessage"] = error;
  23:          TempData["Name"] = Request.Form["Name"];
  24:          TempData["Price"] = Request.Form["Price"];
  25:          TempData["Quantity"] = Request.Form["Quantity"];
  26:          return RedirectToAction("Create");
  27:      }
  28:      else
  29:      {
  30:          return RedirectToAction("Confirm");
  31:      }
  32:  }

Something very interesting to note in the above example, is that even though I’ve pulled all values out of the form into local variables, should either Price or Quantity fail in parsing and I set the TempData to the local variables…I would have lost the user input. So, it’s always a smart idea to retrieve the data from the form directly into the TempData. Finally, the Confirm action needs to be implemented.

   1:  public ActionResult Confirm()
   2:  {
   3:      return RenderView();
   4:  }

Now, it’s time to create our views:

~/Views/Products/Create.aspx

   1:  <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Create.aspx.cs" Inherits="Views_Products_Create" %>
   2:  <html xmlns="http://www.w3.org/1999/xhtml">
   3:  <head runat="server">
   4:      <title>Create Product</title>
   5:  </head>
   6:  <body>
   7:      <% using (Html.Form<ProductsController>(c => c.Submit())) { %>
   8:      <% if (!string.IsNullOrEmpty((string) ViewData["ErrorMessage"])) { %>
   9:          <div style="color:Red;">
  10:              <%= ViewData["ErrorMessage"] %>
  11:          </div>
  12:      <% } %>
  13:      Name: <%= Html.TextBox("Name", ViewData["Name"]) %><br />
  14:      Price: <%= Html.TextBox("Price", ViewData["Price"]) %><br />
  15:      Quantity: <%= Html.TextBox("Quantity", ViewData["Quantity"]) %><br />
  16:      <%= Html.SubmitButton("submitButton", "Save") %>
  17:      <% } %>
  18:  </body>
  19:  </html>

~/Views/Products/Confirm.aspx

   1:  <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Confirm.aspx.cs" Inherits="Views_Products_Confirm" %>
   2:  <html xmlns="http://www.w3.org/1999/xhtml">
   3:  <head id="Head1" runat="server">
   4:      <title>Confirm Create Product</title>
   5:  </head>
   6:  <body>
   7:      Thanks for creating your product.
   8:      <%= Html.ActionLink<ProductsController>(c => c.Create(), "Click here") %> to create a new one.
   9:  </body>
  10:  </html>

Easy payments using Paypal IPN,Using Paypal in PHP

There are several PHP scripts and classes to process PayPal payments using their native IPN (Internet payment notification) feature. Because the whole process is based on the data you need to send via a web form to the PayPal payment processor these script look very similar.

Inside the form there are several required values to process a payment. PayPal gives the advice to post them all to get everything working. The following variables get some special attention:

business = your PayPal email address
cmd = single payments or subscription service (_xclick or _xclick-subscriptions)
return = the URL where the buyer get back after the payment is processed
cancel_return = the URL where the buyer get back if he has cancelled the payment
notify_url = the location where your IPN script is located
rm = how you need the data submitted from PayPal to your IPN script (1=get, 2=post)
currency_code = the currency you accept for your payment
lc = the country version of PayPal where your buyer is send to

<?php
$url
= ‘https://www.paypal.com/cgi-bin/webscr’;
$postdata = ;
foreach(
$_POST as $i =&gt; $v) {
$postdata .= $i.‘=’.urlencode($v).‘&amp;’;
}
$postdata .= ‘cmd=_notify-validate’; $web = parse_url($url);
if (
$web[’scheme’] == ‘https’) {
$web[‘port’] = 443;
$ssl = ’ssl://’;
} else {
$web[‘port’] = 80;
$ssl = ;
}
$fp = @fsockopen($ssl.$web[‘host’], $web[‘port’], $errnum, $errstr, 30);if (!

$fp) {
echo
$errnum.‘: ’.$errstr;
} else {
fputs($fp, “POST ”.$web[‘path’].“ HTTP/1.1rn”);
fputs($fp, “Host: ”.$web[‘host’].“rn”);
fputs($fp, “Content-type: application/x-www-form-urlencodedrn”);
fputs($fp, “Content-length: ”.strlen($postdata).“rn”);
fputs($fp, “Connection: closernrn”);
fputs($fp, $postdata . “rnrn”);while(!

feof($fp)) {
$info[] = @fgets($fp, 1024);
}
fclose($fp);
$info = implode(‘,’, $info);
if (
eregi(‘VERIFIED’, $info)) {
// yes valid, f.e. change payment status
} else {
// invalid, log error or something
}
}

?>