Uncategorized

Upload Photo From iPhone to Asp.Net Server PHP

This tutorial will go over the HTML post.

This will start off where Using a UIImagePickerController left off. So you can grab the code and start there if you want. So lets begin.

So first open up testPickerViewController.h and we want to add in one outlet and one action.

So here is the outlet we want to add

IBOutlet UIButton *upload;

Here is the action we want to add

IBOutlet UIButton *upload;

Now double click on testPickerViewController.xib and we need to connect the new outlet and action. We also need to create our new upload button. So drag around the current items and place the new button under the grab button. Then you want to make the button hidden by default. The option is as shown below. Do get to that selector you do Tools -> Attributes Inspector

You might also want to setup your UIImageView to aspect fit. If the image is larger then your box you created in IB it will shrink the image to fill it. Click on the UIImageView and in the Attributes Inspector select the following drop down for Mode.

Now you want to make your connections to the new outlet and action we created in code. So here is another screenshot of what they should look like

Now it is back to the code. So save this and you can quit IB.

So open up testPickerViewController.m and find the imagePickerController method and at the end add

upload.hidden = NO;

That will show our upload button once a image is set.

So now we need to create our uploadImage method that gets called then the button is pressed. So it is below and hopefully pretty well commented.

– (IBAction)uploadImage {
/*
turning the image into a NSData object
getting the image back out of the UIImageView
setting the quality to 90
*/
NSData *imageData = UIImageJPEGRepresentation(image.image, 90);
// setting up the URL to post to
NSString *urlString = @”http://iphone.zcentric.com/test-upload.php”;

// setting up the request object now
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@”POST”];

/*
add some header info now
we always need a boundary when we post a file
also we need to set the content type

You might want to generate a random boundary.. this is just the same
as my output from wireshark on a valid html post
*/
NSString *boundary = [NSString stringWithString:@”—————————14737809831466499882746641449″];
NSString *contentType = [NSString stringWithFormat:@”multipart/form-data; boundary=%@”,boundary];
[request addValue:contentType forHTTPHeaderField: @”Content-Type”];

/*
now lets create the body of the post
*/
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@”\r\n–%@\r\n”,boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@”Content-Disposition: form-data; name=\”userfile\”; filename=\”ipodfile.jpg\”\r\n”] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@”Content-Type: application/octet-stream\r\n\r\n”] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@”\r\n–%@–\r\n”,boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];

// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

NSLog(returnString);
}

So now if you build and go you will upload the image you selected to the following image URL

http://iphone.zcentric.com/uploads/ipodfile.jpg

Below is my PHP file I am using to handle uploads.

$uploaddir = ‘./uploads/’;
$file = basename($_FILES[‘userfile’][‘name’]);
$uploadfile = $uploaddir . $file;

if (move_uploaded_file($_FILES[‘userfile’][‘tmp_name’], $uploadfile)) {
echo “http://iphone.zcentric.com/uploads/{$file}”;
}

For .net code……………..

on page load event write below statement

Request.Files[0].SaveAs(DirectoryPath + “/” + Request.Files[0].FileName.ToString());

where “DirectoryPath” is a path of folder where image has to be save.

SQL split funtion

ex. 1. select top 10 * from dbo.split(‘Chennai,Bangalore,Mumbai’,’,’)

Link: http://blog.logiclabz.com/sql-server/split-function-in-sql-server-to-break-comma-separated-strings-into-table.aspx

JSON ASP.NET Web Services with jQuery

using System;

using System.Web;

using System.Web.Services;

using System.Web.Services.Protocols;

using System.Web.Script.Services;

using System.Collections.Generic;

using System.Linq;

public class Employee

{

public string firstname;

public string lastname;

public int age;

}

///

/// Summary description for Employeeservice

///

[WebService(Namespace = “http://tempuri.org/”)]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

[ScriptService]

public class Employeeservice : WebService

{

List Employees = new List{

new Employee{firstname=”Aamir”,lastname=”Hasan”,age=20},
new Employee{firstname=”awais”,lastname=”Hasan”,age=50},
new Employee{firstname=”Bill”,lastname=”Hasan”,age=70},
new Employee{firstname=”sobia”,lastname=”khan”,age=80},

};

[WebMethod]

public List GetAllEmployees()

{

return Employees;

}

[WebMethod]

public List GetEmployeesByDoors(int doors)

{

var query = from c in Employees

where c.Doors == doors

select c;

return query.ToList();

}

}

All that’s needed now is some Javascript for the getEmployees() method that has been assigned to the onclick event of the html button. This will go into the section of the page:

$(function() {

$(‘#Button1’).click(getEmployees);

});

function getEmployees() {

$.ajax({

type: “POST”,

url: “Employeeservice.asmx/GetAllEmployees”,

data: “{}”,

contentType: “application/json; charset=utf-8”,

dataType: “json”,

success: function(response) {

var Employees = (typeof response.d) == ‘string’ ? eval(‘(‘ + response.d + ‘)’) : response.d;

$(‘#output’).empty();

for (var i = 0; i < Employees.length; i++) {

$('#output').append('

‘ + Employees[i].lastname + ‘ ‘ +

Employees[i].firstname + ‘
Age: ‘ +

Employees[i].age + ‘
Doors: ‘ +

‘);

}

},

failure: function(msg) {

$(‘#output’).text(msg);

}

});

}

JSON ASP.NET Web Services with JavaScript

——————————————WebForm1.aspx——————————————

// This function calls the Web service method

// passing simple type parameters and the

// callback function

function CallWebMethod() {
// debugger;
var User_Name = document.getElementById(”).value;

checkDuplicateUserName.WebService1.CheckDuplicate(User_Name, OnSucceeded, OnError);

}

// This is the callback function invoked if the Web service

// succeeded

function OnSucceeded(result) {

var rsltElement = document.getElementById(“lblDuplicate”);
rsltElement.innerHTML = “”;
if (result.length>0)

for (var i = 0; i < result.length; i++)
{
rsltElement.innerHTML += result[i] + ‘
‘;
}
//rsltElement.innerHTML = “This User Name is exist”;

else

rsltElement.innerHTML = “”;
}

function OnError(error) {

// Display the error.

alert(“Service Error: ” + error.get_message());
}

——————————————WebService—————————————–

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

namespace checkDuplicateUserName
{
///
/// Summary description for WebService1
///
[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]

public class WebService1 : System.Web.Services.WebService
{

[WebMethod]
[ScriptMethod(ResponseFormat= ResponseFormat.Json)]
public List CheckDuplicate(string username)
{
List userdetail = new List();
PL.UserProperties objuser = DAL.clUsers.LoadByUserName(username);
if (objuser != null)
{
userdetail.Add(objuser.Id.ToString());
userdetail.Add(objuser.FullName.ToString());
userdetail.Add(objuser.Email.ToString());
}
return userdetail;
}
}
}

Preventing duplicate User Names with ASP.NET and jQuery

It’s a common problem: you have a registration form, but you want to prevent user names or other values from being used more than once. You need a user-friendly way to prevent duplicate values being submitted. This is where the simplicity of jQuery excels.

User names and passwords are normally stored within a database. Commonly, developers wait until the form has been submitted before they perform any duplicate checking. This means that the user has to wait for a postback to complete before being informed that the user name they chose is already in use, and that they need to choose another one. Ajax tidies this up by allowing asynchronous querying of databases, so that the checking can be done behind the scenes while the user is still completing the registration form. I choose jQuery for my AJAX instead of ASP.NET AJAX because it is so much simpler to use in my opinion.

This example shows a very simple registration form:

Register

User Name:

Password:

 

A web service will be used to house the method that checks the database for possible duplicates:

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;

///

/// Summary description for UserService

///

[WebService(Namespace = “http://tempuri.org/”)]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

[ScriptService]

public class UserService : WebService {

public UserService () {

}

[WebMethod]

public int CheckUser(string username)

{

string connect = @”Server=SERVER;Database=Database;Trusted_Connection=True;”;

string query = “SELECT COUNT(*) FROM Users WHERE UserName = @UserName”;

using(SqlConnection conn = new SqlConnection(connect))

{

using(SqlCommand cmd = new SqlCommand(query, conn))

{

cmd.Parameters.AddWithValue(“UserName”, username);

conn.Open();

return (int)cmd.ExecuteScalar();

}

}

}

}

There’s nothing clever about this code. It is trimmed down to just show the working parts, and ignores error checking, for example – although it makes use of parameters to prevent SQL Injection. IF you are wondering why I don’t close the connection after I’m done, that’s what the using statement does for me behind the scenes. Any disposable object (one that implements IDisposable) can be instantiated within a using block which then takes care of Close() and Dispose() at the end of the block. One (Web) method – CheckUser() – accepts a string as an argument and then returns the number of rows in the database where that name is found. The [ScriptService] attribute is uncommented, so that the service is available to AJAX calls (not just ASP.NET AJAX, incidentally).

Now we’ll look at the Javascript that uses jQuery to effect the call:

$(function() {

$(“#UserName”).change(checkUser);

});

function checkUser() {

$.ajax({

type: “POST”,

url: “UserService.asmx/CheckUser”,

data: “{username: ‘” + $(‘#UserName’).val() + “‘}”,

contentType: “application/json; charset=utf-8”,

dataType: “json”,

success: function(response) {

$(“#duplicate”).empty();

if (response.d != “0”) {

$(“#duplicate”).html(‘ That user name has already been taken’);

}

}

});

}

The first tag brings in the jQuery library from Google’s public code repository. Then an event handler is added to the element with the ID of UserName, which is the TextBox waiting for the user to put their chosen User Name in. The handler is wired up to the TextBox’s onchange event, and calls the checkUser() function. Then the checkUser() function is defined in code.

When the user has added some text to the TextBox and then moves their cursor away, the “change” event is fired, and an AJAX call is made to the web service. If the response is not 0, then the web method has found at least one row that matches the user name that the user is attempting to submit. The with the ID of “duplicate” is emptied of any messages resulting from previous attempts, and the message displayed to the user.

I’ve used ASP.NET controls for the inputs in the registration form, but jQuery is not an ASP.NET component (although it has been embraced by the ASP.NET team). So this approach will work with any server-side technology. One thing to note, though – if you place the registration form within a container, such as a ContentPlaceHolder in a Master Page, you will need to change the jQuery code that references its controls to counter the effects of INamingContainer (which is the bit that adds stuff to the ID of the control, such as ctl00_ContentPlaceHolder1_ControlID). The change needed is to use the control’s ClientID property, so the first 3 lines of jQuery code will look like this:

$(function() {

$(“#”).change(checkUser);

});

And of course, the ClientID will need to be used where controls are referenced in the the checkUser() function too.

—————————————————————————————————————-

— Second Method —

1-Create a new project , if you are using VS 2005 you have to create ASP.NET Ajax Enabled Web site.

2-Create your own Database which contain user table that have User_Name field. for Testing I’ve added SQL Server Database that come with Dot Net 2008:

SqlServerDataBase

Then I’ve created tblUsers:

definition

This table and this structure just for our example, you can use your own table to implement this approach.

3-Add new Item to your project or website, Choose Web Service file, lets say WebService.cs .In this Web Service file import System.Data.SqlClient Namespace, Then Add your web method that contain string parameter which received the Username parameter from the Script , Finally don’t forget to qualified the Web Service Class with the ScriptServiceAttribute attribute ([System.Web.Script.Services.ScriptService])

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Services;

using System.Data.SqlClient;

[WebService(Namespace = “http://tempuri.org/”)]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

[System.Web.Script.Services.ScriptService]

public class WebService : System.Web.Services.WebService {

[WebMethod]

public int CheckDuplicate(string User_Name)

{

string strConn = @”Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\TestDB.mdf;Integrated Security=True;User Instance=True”;

string strQuery = “SELECT COUNT(*) FROM tblUsers WHERE User_Name = @User_Name”;

SqlConnection con = new SqlConnection(strConn);

SqlCommand cmd = new SqlCommand(strQuery, con);

cmd.Parameters.Add(“User_Name”, User_Name);

con.Open();

int RetVal= (int)cmd.ExecuteScalar();

con.Close();

return RetVal;

}

}

Our Web Method here is CheckDuplicate Which accept User_Name String as a parameter and return number of the rows , if the name will found in the database this method will return 1 else it will return 0. I’ve applied [WebMethod] Attribute to our method CheckDuplicate, And applied the ScriptService attribute to a Web Service class named WebService.

4-Add this simple Registration form :

User Name

onblur event is added to the Textbox txtUserName, This event Fires when the Textbox loses the input focus, That mean after the user get focus out from the Textbox CallWebMethod function will be fired. CallWebMethod will be implemented in step 6.

5-Add ScriptManager Control to your aspx file then reference the Web service by adding an asp:ServiceReference child element to the ScriptManager control and setting its path attribute to point to the Web service, That generate a JavaScript proxy class for calling the specified Web service from client script.

6-Define the JavaScript code to call the Web Service :

// This function calls the Web service method

// passing simple type parameters and the

// callback function

function CallWebMethod() {

var User_Name = document.getElementById(”).value;

WebService.CheckDuplicate(User_Name, OnSucceeded, OnError);

}

// This is the callback function invoked if the Web service

// succeeded

function OnSucceeded(result) {

var rsltElement = document.getElementById(“lblDuplicate”);

if (result == 1)

rsltElement.innerHTML = “This User Name is exist”;

else

rsltElement.innerHTML = “”;

}

function OnError(error) {

// Display the error.

alert(“Service Error: ” + error.get_message());

}

This call references the WebService Class and CheckDuplicate Web Method defined in the service. It passes a User_Name value obtained from a textbox as well as a callback function named OnSucceeded that should be invoked when the asynchronous Web Service call returns.

If the Web Service in different Namespace you can refer it before the class name this Main formula may help you :

NameSpaceName.ClassName.WebMethdName(Parameters , Success callback function, Error callback function);

Parameters: you can pass one or many parameters.

Success callback function :handles returned data from the service .

Resize Your Windows Automatically for Different Resolutions MAC os x

tell application “Finder”
set desktopFrame to bounds of window of desktop
set screenHeight to item 4 of desktopFrame
end tell

tell application “System Events”
set activeApplication to name of the first process whose frontmost is true
end tell

tell application activeApplication
set appFrame to bounds of the first window
set xpos to item 1 of appFrame
set ypos to 0
set width to item 3 of appFrame
set height to screenHeight
set bounds of the first window to {xpos, ypos, width, height}
end tell

try
tell application “iTunes”
activate
set the bounds of the first window to {xpos, ypos, width, height}
end tell
end try

Cross Platform Socket Programming (Mac-Windows)

Overview: Sockets vs Streams

Socket represents a unique communication endpoint on the network. When your app needs to exchange data with another app, it creates a socket and uses it to connect to the other app’s socket. You can both send and receive data through the same socket. Each socket has an IP address and a port number (between 1 and 65535) associated with it. IP address uniquely identifies each computer on a given network and port number uniquely identifies a network socket on that computer.

Stream is a one-way channel through which data is transmitted serially. There are 2 types of streams: the ones into which you can write data, and the ones from which you can read. By itself, stream is just a buffer that temporarily holds data before or after its transmission. In order to actually deliver data somewhere meaningful, streams need to be tied to something (like a file, a memory location etc). In this tutorial, we’ll use streams that are paired up with sockets to allow our app to send data over network.

Overview: Bonjour

Bonjour is a protocol that allows devices or applications to find each other on the network. More precisely, it provides a way for an application to tell others what IP address and port they can connect to in order to communicate with it. In Bonjour terminology, such announcement is called publishing a service. Other apps can then look for services by browsing. Once an app finds a service that it would like to talk to, it resolves the service to find out what IP address and port number it needs to establish a socket connection to.

In the SDK, Bonjour can be used via NSNetServices and CFNetServices APIs.

Recursive in C#

public partial class _Default : System.Web.UI.Page
{
List lst = new List();
int mainnode = 0;
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
RadTreeView1.Nodes.Insert(0, new RadTreeNode(“Table of Content”));
}

protected void Button1_Click(object sender, EventArgs e)
{
updatemainnode();
lst.Add(“end”);

gv1.DataSource = lst;
gv1.DataBind();
}

public void updatemainnode()
{
for (int i = 0; i 0)
{
mainnode = i;
string str = i.ToString();
lst.Add(str);
updatesubnode(RadTreeView1.Nodes[i]);
ViewState[“BookIndex”] = null;
}
}
}

public void updatesubnode(RadTreeNode treenode)
{
if (ViewState[“BookIndex”] == null)
{
ViewState[“BookIndex”] = mainnode;
}

for (int i = 0; i 0)
{
ViewState[“BookIndex”] = strBookindex;
updatesubnode(treenode.Nodes[i]);
}
}
string strnew = ViewState[“BookIndex”].ToString();
if (strnew.Contains(“.”))
{
strnew = strnew.Remove(strnew.LastIndexOf(“.”));
ViewState[“BookIndex”] = strnew;
}
}
}

Mouse click event using Apple Script

set “Google” as Home page for test this application…

tell application “Safari”
activate
tell application “Safari”
run
tell application “System Events”
tell process “Safari”
click at {50, 100}
end tell
end tell
end tell
end tell

System tray menu in MAC OS x application

1. Open interface builder create NSMenu from Tools->Library. And create NSMenuItem “Active” and “Quit”.
2. “Active” select “Sent Action” -> “Window Server” and select “deminiature” action.
3. “Quit” select “Sent Action” -> “Application” and select “terminate” action.
4. “Menu” select “Outlet” ->ServerControll (applcation name control)
5. In “ServerController.h” file
IBOutlet NSMenu *menu;
NSStatusItem *statusItem;
NSImage *statusImage;
NSImage *statusHightlightImage;
6. In “ServerController.m” file
//Used to detect where our files are
NSBundle *bundle = [NSBundle mainBundle];
statusItem = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength] retain];
[statusItem setEnabled:YES];
[statusItem setMenu:menu];
[statusItem setHighlightMode:YES];
[statusItem setToolTip:@”KB Keys”];
statusImage = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@”appicon” ofType:@”png”]];
[statusItem setImage:statusImage];
statusHightlightImage = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@”hoverappicon” ofType:@”png”]];
[statusItem setHighlightMode:YES];
[statusItem setAlternateImage:statusHightlightImage];