follow me

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...

Creating a Captcha image

This time I will talk about a simple captcha image. This will prevent some automated scripts that will spam your registration area in you website, or if you have some comments area in the page.

An overview of the output will be, you will see an image in some part of the page and you will type the text you see in the image in order for you too complete what you are doing.

You need to use the Drawing Assemblies.


using System.Drawing;
using System.Drawing.Text; //for styling fonts
using System.Drawing.Imaging; // for rendering the background


The drawing assemblies are very important because we will draw some random images programmatically.

Now you will need to have a separate page or save it to an image file for the captcha. We will talk about this later.

On the page load event handler of the page, you will have to define the captcha image. The safest way I know is to have a Web user control and place the code inside the page load of the user control and place the user control in any part of the main page. The user control that you place your code shall not have any other controls to prevent disfiguration of the main page.

Ok, on the Page_Load event handler on your user control, you have to initialize the Bitmap.

 
protected void Page_Load(object sender, EventArgs e)
{
// define the Bitmap image with its size.
Bitmap b = new Bitmap(60, 20);
// create a graphics from the initialized bitmap.
Graphics g = Graphics.FromImage(b);
//creates a background color of the image.
g.Clear(Color.Blue);
g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;

// ~following codes will be here.
}


You already have initiallize your image. Next is to generate a random alphanumeric characters on the image you just created.



Font f = new Font("Verdana", 8, FontStyle.Bold); // creates an instance of font you will be using.
string randomStr = "";

// initialize all the alphanumeric characters that can be generated on the fly.
string[] str = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q",
"R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h",
"i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y",
"z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" };

//generate 5 random alphanumeric characters or depends on how many character you want
Random ar = new Random();

for(int i=0;i$lt;5;i++)
{
string rn = str[ar.Next(0, 62)];
// (0, 62) this means that it will get a random character from str from first character
// to the last and there are 62 characters in all

randomStr += rn; // stack up to randomStr the random characters choosen.
}

g.DrawString(randomStr, f, Brushes.White, 3, 3); // Draw the text to the image.
Response.ContentType = "image/GIF"; // set the image type to GIF.

// save the image into your server path with the filename.
b.Save(Server.MapPath("captcha.gif"), ImageFormat.Gif);



This time you have your alphanumeric characters generated and drawn into the image for later comparison. How can I compare an imge from a text?

Here's how. Remember we stack up the generated random characters into the variable randomStr right? You'll just need to add that string to a session or a cookie. I use session for this example.


// add the randomStr value to a session named "randomStr".
Session.Add("randomStr", randomStr);


Now we're done.

In order to compare the captcha image versus the text the user enters is you have to get the Session value of randomStr.


if(Session["randomStr"].ToString() == txtCaptcha.Text)
{
// your code goes here
}


And here's the complete code.



using System.Drawing;
using System.Drawing.Text; // you need this so you can style your fonts
using System.Drawing.Imaging; // you need this so you can do rendering the background

...

protected void Page_Load(object sender, EventArgs e)
{
Bitmap b = new Bitmap(60, 20); // define the Bitmap image with its size.
Graphics g = Graphics.FromImage(b); // create a graphics from the initialized bitmap.
g.Clear(Color.Blue); // creates a background color of the image.
g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;

Font f = new Font("Verdana", 8, FontStyle.Bold); // creates an instance of font you will be using.
string randomStr = "";

// initialize all the alphanumeric characters that can be generated on the fly.
string[] str = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q",
"R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h",
"i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y",
"z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" };

// generate 5 random alphanumeric characters
Random ar = new Random();
for(int i=0;i$lt;5;i++)
{
string rn = str[ar.Next(0, 62)];
// (0, 62) this means that it will get a random character from str from first character
// to the last and there are 62 characters in all

randomStr += rn; // stack up to randomStr the random characters choosen.
}

g.DrawString(randomStr, f, Brushes.White, 3, 3); // Draw the text to the image.
Response.ContentType = "image/GIF"; // set the image type to GIF.
b.Save(Server.MapPath("captcha.gif"), ImageFormat.Gif); // save the image into your server path with the filename.
Session.Add("randomStr", randomStr); // add the randomStr value to a session named "randomStr".

// destroys the objects created
f.Dispose();
g.Dispose();
b.Dispose();
}





ciao

Read More...

Export SQL Data Into .DBF (foxpro)

This will show you how to export your SQL data into a .DBF file which is a Foxpro application.
The mean purpose on having this is to get all your data from the SQL database and generate a report that can be restore in the Foxpro database.
This is an accounting sample program using VB6.0.


Dim rsql As New ADODB.Recordset 'sql recordset
Dim sqlz As String 'sql statement
Dim ddate As String 'date
Dim pathz As String 'path

On Error GoTo Error_Handle

'SQL connection
Set rsql = New ADODB.Recordset

'Create a connection to SQL.
sqlz = "SELECT * FROM SALES WHERE TRANDATE BETWEEN '" & datef & "' AND '" & datet & "'"

rsql.Open sqlz, cConn, adOpenForwardOnly, adLockReadOnly

Do While rsql.EOF = False
Set myTDef = New TableDef 'set an object for table definition
Set myRS = New Recordset ' recordset

'create a file name date Formated
ddate = Format(Month(rsql!TRANDATE), "00") & Format(Day(rsql!TRANDATE), "00")
'create a file path
pathz = App.Path & "\Report\"

'create and set a table for foxpro database
Set mydb = OpenDatabase(pathz, False, 0, "DBase 5.0;")
Set myTDef = mydb.CreateTableDef(ddate & ".dbf")
'create fields name and its datatype and size

With myTDef
'dont be confuse on the data field name i had
'fieldname, datatype, digit no.
.Fields.Append .CreateField("TRANDATE", dbDate, 8)
.Fields.Append .CreateField("OLDGT", dbCurrency, 6)
.Fields.Append .CreateField("NEWGT", dbCurrency, 6)
.Fields.Append .CreateField("DLYSALE", dbCurrency, 6)
.Fields.Append .CreateField("TOTDISC", dbCurrency, 6)
.Fields.Append .CreateField("TOTREF", dbCurrency, 6)
.Fields.Append .CreateField("TOTCAN", dbCurrency, 6)
.Fields.Append .CreateField("VAT", dbCurrency, 6)
.Fields.Append .CreateField("TENTNAME", dbText, 10)
.Fields.Append .CreateField("BEGINV", dbText, 6)
.Fields.Append .CreateField("ENDINV", dbText, 6)
.Fields.Append .CreateField("BEGOR", dbText, 6)
.Fields.Append .CreateField("ENDOR", dbText, 6)
.Fields.Append .CreateField("TRANCNT", dbInteger, 9)
.Fields.Append .CreateField("LOCALTX", dbCurrency, 6)
.Fields.Append .CreateField("SERVCHARGE", dbCurrency, 6)
.Fields.Append .CreateField("NOTAXSALE", dbCurrency, 6)
.Fields.Append .CreateField("RAWGROSS", dbCurrency, 6)
.Fields.Append .CreateField("DLYLOCTAX", dbCurrency, 6)
.Fields.Append .CreateField("OTHERS", dbCurrency, 6)
.Fields.Append .CreateField("TERMNUM", dbText, 3)
End With
' append it to the table
mydb.TableDefs.Append myTDef

' open the foxpro table
Set sql = mydb.CreateQueryDef("")
sql.sql = "select * from " & ddate & ".dbf;"
Set myRS = sql.OpenRecordset()

' assigning the value you have in the SQL.
With myRS
.AddNew
!TRANDATE = rsql!TRANDATE
!OLDGT = rsql!OLD_GT
!NEWGT = rsql!NEW_GT
!DLYSALE = rsql!DLYSALE
!TOTDISC = rsql!TOTDISC
!TOTREF = rsql!TOTREF
!TOTCAN = rsql!TOTCAN
!VAT = rsql!VAT
!TENTNAME = rsql!TENTNAME
!BEGINV = rsql!BEGINV
!ENDINV = rsql!ENDINV
!BEGOR = rsql!BEGOR
!ENDOR = rsql!ENDOR
!TRANCNT = rsql!TRANCNT
!LOCALTX = rsql!LOCALTX
!SERVCHARGE = rsql!SERVCHARGE
!NOTAXSALE = rsql!NONTAXSALE
!RAWGROSS = rsql!RAWGROSS
!DLYLOCTAX = rsql!DLYLOCTAX
!OTHERS = rsql!OTHERS
!TERMNUM = rsql!TERMNUM
.Update
End With
' Cleanup all objects (resume next on errors)
Set mydb = Nothing
Set myTDef = Nothing
Set myRS = Nothing
Set sql = Nothing
rsql.MoveNext
If rsql.EOF = True Then
MsgBox " Data(s) finish loaded! ", vbInformation, "Report Form"
Set rsql = Nothing
Exit Function
End If
Loop
Error_Handlr:
MsgBox Err.Description, vbCritical, "Error: " & Err.Number



But the simplest way you can do is to go to your SQL Enterprise Manager and do the exporting, but it does not create any report.

You can post a comment if you have questions and for further explanation.

- Read More...

Export SQL data into Text File

Notepad is one good example of a text file. This method will show you how to export your data from your SQL database into your text file using VB6.0.

The RunTextFileReport function is an accounting application that will pass a date "datef " of transaction, and generate a report that will be stored in notepad.



Function RunTextFileReport(string datef)
Dim rs2 As New ADODB.Recordset
Dim sql1, pathz, s As String
Dim filename As String
Dim sDBPath As String
Dim temp As Double
Dim fso As New FileSystemObject
Dim thefile As TextStream
Dim des As String

On Error GoTo Err_Handler

'connecting to your database
Set rs2 = New ADODB.Recordset
sql1 = "SELECT * FROM SALES WHERE TSL_DTE = '" & datef & "'"

rs2.Open sql1, cConn, adOpenForwardOnly, adLockReadOnly

'create a textfile filename using date format
filename = Format(datef, "mmddyy")
'create a textfile filepath
pathz = App.Path & "\Report\" & filename & ".txt"

'create a textfile.
'pathz is the filepath and true(means you can overwrite the existing file)
Set thefile = fso.CreateTextFile(pathz, True)

' dont be confuse about the format , you can get raid of it.
' this program is required to have a 258 character in the textfile .
Do While rs2.EOF = False
thefile.Write (rs2!BR_CODE & " " & rs2!N_CHECK & " " & _
Format(rs2!CLAS_C, "00") & " " & Format(rs2!CLAS_TRD_C, "000") & " " & _
Format(rs2!STOR_NO, "00") & " " & Format(rs2!tsl_NEW_A, "000000000.00") & " " & _
Format(rs2!TSL_OLD_A, "000000000.00") & " " & Format(rs2!TSL_DAY_A, "000000000.00") & " " & _
Format(rs2!TSL_DIS_A, "00000.00") & " " & _
Format(rs2!TSL_TAX_A, "00000.00") & " " & _
Format(rs2!TSL_ADJ_A, "0000000.00") & " " & _
Format(rs2!TSL_NET_A, "000000000.00") & " " & _
Format(rs2!TSL_VOID, "000000000.00") & " " & _
Format(rs2!TSL_RFND, "000000000.00") & " " & _
Format(rs2!TSL_TX_SAL, "000000000.00") & " " & _
Format(rs2!TSL_NX_SAL, "000000000.00") & " " & _
Format(rs2!TSL_CHG, "000000000.00") & " " & _
Format(rs2!TSL_CSH, "000000000.00") & " " & _
Format(rs2!TSL_ZCNT, "0000") & " " & Format(rs2!TSL_DTE, "mm/dd/yy"))
rs2.MoveNext
If rs2.EOF = True Then
Set rs2 = Nothing
' this will create a backup file to the other path which i think is very important for an application like this
des = "C:\backup\" & filename & ".txt"
fso.CopyFile pathz, des, True
s = "Notepad" & " " & pathz
'Shell is a predefine function that will automatically open your textfile after exec
Call Shell(s, vbMaximizedFocus)
Exit Function
End If
Loop
Err_Handler:
MsgBox Err.Description, vbCritical, "Error: " & Err.Number
End Function



You can do Open (filepath) and Input (fields) for retrieving the data inside the text file. Read More...

Export SQL data into Excel Spreadsheet

The simplest way in exporting your SQL database to excel is using the Enterprise Manager SQL 2000

This is a simple accounting application. This will show you how to export your application to Excel using VB6.0

Let us assume that you are now connected to your SQL database. and all you need to do is to get your data information from your SQL and put it in Excel app.



And be sure you already added a reference in your VB6 program to access the Excel App. (refer the pic. above).




On Error GoTo Err_Handler
Dim rs2 As New ADODB.Recordset
Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim oRng As Excel.Range
Dim nrow As Integer

' Start Excel and get Application object.
Set oXL = CreateObject("Excel.Application")
oXL.Visible = True

' Get a new workbook.
Set oWB = oXL.Workbooks.Add
Set oSheet = oWB.ActiveSheet

' Add table headers going cell by cell.
With oSheet
.Cells(1, 1).Value = "BR_CODE"
.Cells(1, 2).Value = "N_CHECK"
.Cells(1, 3).Value = "CLAS_C"
.Cells(1, 4).Value = "CLAS_TRD_C"
.Cells(1, 5).Value = "STOR_NO"
.Cells(1, 6).Value = "TSL_NEW_A"
End With

' Format A1:D1 as bold, vertical alignment = center.
With oSheet.Range("A1", "AA1")
.Font.Bold = True
.VerticalAlignment = xlVAlignCenter
End With


Here's some of the format that you can apply in your fields since it wont automatically change the data type you have in your SQL. Don't be confuse about the cell row since my existing program has many fields..you can have your way. But more or less it looks like these.


' Fill date apply format.
Set oRng = oSheet.Range(oSheet.Cells(3, 27), oSheet.Cells(nrow, 27))
oRng.NumberFormat = "mm/dd/yy"
' Numeric apply format.
oSheet.Range(oSheet.Cells(3, 9), oSheet.Cells(nrow, 10)).NumberFormat = "00000.00"
oSheet.Range(oSheet.Cells(3, 6), oSheet.Cells(nrow, 8)).NumberFormat = "0000"



and have this at end of the code


oXL.Visible = True
oXL.UserControl = True

' Cleanup all objects (resume next on errors)
Set rs2 = Nothing
Set oRng = Nothing
Set oSheet = Nothing
Set oWB = Nothing
Set oXL = Nothing

Exit Function
Err_Handler:
MsgBox Err.Description, vbCritical, "Error: " & Err.Number


Excel is indeed a great product and will be very useful to our users for the indefinite future.
User can easily manage excel application for reporting purposes.

Read More...