Thursday, December 27, 2012

Create Folders in a Sharepoint Library through Code

Hi
 
In this post I'll explain how to create folders in a sharepoint library using C# Code.

This will be useful when you have to create custom folder structures in a sharepoint library.

First you'll need a shapoint Document Library which you are going to add folders to.

Here I'm using the library named 'My Documents' and creating a folder named 'New Folder'

using(SPSite mySite=new SPSite("http://mysite"))
{
 using(SPWeb myWeb=mySite.OpenWeb())
 {
  //Get the Folder Library
  SPList MyFiles = myWeb.Lists["My Documents"];

  //Create the URL for the Folder Library
  //You can have a string variable for url on top and use it here as well
  string folderURL = myWeb.Url + "/" + MyFiles.Title;

  //Set the name for the folder
  string folderName="New Folder";

  //Create the folder inside the library
  SPListItem OpportunityFolder = MyFiles.Items.Add(url, SPFileSystemObjectType.Folder, folderName);
  OpportunityFolder.Update();
 }
}
 
Now we'll see how to delete the folder we created.

using(SPSite mySite=new SPSite("http://mysite"))
{
 using(SPWeb myWeb=mySite.OpenWeb())
 {
  //Get the document folder library
  SPList MyFiles = myWeb.Lists["My Documents"];
  //Get the folder url
  string url = myWeb.Url + "/" + MyFiles.Title;
  //Get the folder name
  string folderName = "New Folder";
  //Delete the created folder
  properties.Web.Folders["My Documents"].SubFolders.Delete(folderName);
 }
}
 
Hope this is useful
Please leave a comment

Saturday, December 8, 2012

Connect Android and Mysql via PHP Webservice Part 2

Hi readers
This is the part two of the Android PHP connection
You can find Part 1 HERE

 First we'll see the structure of the project

As you can see we have class representations for the Employee and the Loginresult they are to be used by GSON to generate the objects for us.

The Constants class contains the constants such as the URL of the Web service and the user id of the currently logged in user.

The server access class handles the interaction between the server and the Application The classes PHPClientActivity and the EmployeeListActivity are for the activities.

 In the layouts section we have 3 layouts one for the Login activity , one for the Employee list activity and the third one is for the employee list item which is shown in the list.

Now we'll see the server access class the explanation is given as inline comment

public class ServerAccess {

 //Convert an inputstream to a string
 public static String convertStreamToString(InputStream is)
    {
     BufferedReader reader = new BufferedReader(new InputStreamReader(is));
     StringBuilder sb = new StringBuilder();

     String line = null;
     try {
      while ((line = reader.readLine()) != null) {
       sb.append(line + "\n");
      }
     }
     catch (IOException e) {
      Log.e("PHP Client","Error : "+e.getMessage());
     }
     finally {
      try {
       is.close();
      } catch (IOException e1) {
       Log.e("PHP Client","Error : "+e1.getMessage());
      }
     }
     return sb.toString();
    }

 //Get the response form the server as an object
 public Object getResponseObject(ArrayList Parameters,Class c)
 {
  try{
   //Create a HTTP Client
   HttpClient httpclient = new DefaultHttpClient();

   //Create and object to Post values to the server
   //The url is specified in the Constants class to increase modifiability
   HttpPost httppost = new HttpPost(Constants.SERVICE_URL);

   //Set the attributes to be posted as Parameters
   httppost.setEntity(new UrlEncodedFormEntity(Parameters));

   //Execute the post and get the response
   HttpResponse response = httpclient.execute(httppost);

   //Get the response as ans entity
   HttpEntity entity = response.getEntity();

   //Get the content of the response as a stream
   InputStream stream=entity.getContent();

   //Convert the stream to a GSON object
         String result= convertStreamToString(stream);

         //Create a GSON object
         Gson gson=new Gson();

         //Convert the respose string to a object of the given type
         //Here Object class is used so that we can use the same method to get any
         //class's object as response
   Object responseObject=gson.fromJson(result, c);
   //Return the object
         return responseObject;
  }catch(Exception e){
   Log.e("PHP Client", "Error in http connection"+e.toString());
   return null;
  }
 }

 //Verify the login and return user id or 0
 public int getUserID(String Username,String Password)
 {
  //Create an arraylist to store the parameters and values as key value pairs
  ArrayList parameters=new ArrayList();

  //Please make sure the spellings of the keys are correct
  //Set the method name
  parameters.add(new BasicNameValuePair("method","verifyLogin"));
  //Set the username
  parameters.add(new BasicNameValuePair("username",Username));
  //Set the password
  parameters.add(new BasicNameValuePair("password",Password));
  //Get the result from the server using the getresponse method
  LoginResult o= (LoginResult)getResponseObject(parameters,LoginResult.class);
  return Integer.parseInt(o.result);
 }

 //Get the employees
 public Employee[] getEmployees(int id)
 {
  //Create the arraylist to set the parameters of the post
  ArrayList parameters=new ArrayList();
  //Set the method name
  parameters.add(new BasicNameValuePair("method","getEmployees"));
  parameters.add(new BasicNameValuePair("id",String.valueOf(id)));

  //Get the array of employee arrays as the result
  Employee[] o= (Employee[])getResponseObject(parameters,Employee[].class);
  return o;
 }
}
Now we'll see the Activity class Here i've provided the code only for the button click event
ServerAccess ss=new ServerAccess();
 Constants.USER_ID=ss.getUserID(txtUsername.getText().toString(), txtPassword.getText().toString());
 if(Constants.USER_ID==0)
 {
  Toast.makeText(getApplicationContext(), "Invalid Username or Password", Toast.LENGTH_LONG).show();
 }
 else
 {
  Intent employeeListActivity=new Intent(getApplicationContext(),EmployeesListActivity.class);
  startActivity(employeeListActivity);
 }
Now we'll see the code for the Listing part
public class EmployeesListActivity extends Activity {

 ListView listEmployeeDetails;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.employeeslist);

  listEmployeeDetails=(ListView)findViewById(R.id.listViewEmployees);
  //Get the employee array from the server access class
  ServerAccess ss=new ServerAccess();
  Employee[] employeesArray= ss.getEmployees(Constants.USER_ID);
  //Set the adapter with our custom view so that the Employee name and his/her address will be shown
  listEmployeeDetails.setAdapter(new EmployeeAdapter(this, R.layout.employeeitem, employeesArray));

 }

 private class EmployeeAdapter extends ArrayAdapter
 {
  //Array to have the objects
  private Employee[] array;

  public EmployeeAdapter(Context context, int textViewResourceId,
    Employee[] objects) {
   super(context, textViewResourceId, objects);
   array=objects;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
   //Set the view for each item in the list view
   View v = convertView;
            if (v == null) {
                LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.employeeitem, null);
            }
            //Get the Textviews from the row view and set the appropriate values for them
            TextView labelName=(TextView) v.findViewById(R.id.labelName);
            TextView labelAddress=(TextView)v.findViewById(R.id.labelAddress);
            labelName.setText(array[position].name);
            labelAddress.setText(array[position].address);
   return v;
  }
 }
}

Make sure you give the Uses internet permission in the manifest file.

you can DOWNLOAD SAMPLE HERE 


App screenshots
Happy Coding
-Guruparan Giritharan-
 Please leave a comment

Tuesday, November 27, 2012

Connect Android and Mysql via PHP Webservice Part 1

Hi Readers

I'll explain how to connect an Android application to a mysql database via PHP web service.
First we'll need to create the database which we are going to access via the PHP service.

Here the application is simple we are going to make a simple employee system where the Manager logs in and see all the details of employees who are managed by him.

--Create the database
CREATE DATABASE EmployeeDB;

--Select the database
USE EmployeeDB;

--Create the table
CREATE Table Employees
(
 ID int PRIMARY KEY AUTO_INCREMENT,
 Username varchar(20) UNIQUE,
 Password varchar(8),
 Name varchar(40),
 Address varchar(50),
 Manager int references Employees(ID)
);
Now we'll insert some values
Insert into Employees(username,password,name,address)
 values ('guru','123','Guruparan','Colombo');

Insert into Employees (username,password,name,address,manager)
 values ('saman','123','saman','colombo',1);

Insert into Employees (username,password,name,address,manager)
 values ('john','123','john','New York',1);

Insert into Employees(username,password,name,address,manager)
 values ('sean','123','sean','Washington',1);

Now we'll make the PHP web service which generates the JSON response The explanation is given via inline comments

<?php

 //Get the name of the Method
 //The method name has to be passed as Method via post

 $Request_Method=$_REQUEST['method'] or die('Method name not found');

 //Connect to the database
 $Connection = mysql_connect("localhost","root","") or die('Cannot connect to Database');

 //Select the database
 mysql_select_db("EmployeeDB") or die('Cannot select Database');

 //Method to verify the users login
 if($Request_Method=="verifyLogin")
 {
  //username and password are password are passed via querystrings
  $username=$_REQUEST['username'];
 $password=$_REQUEST['password'];

 //Generate the sql query based on username and password
 $query="select id from Employees where username='$username' and password='$password'";

 //Execute the query
 $result = mysql_query($query);

 //Get the rowcount
 $rowcount= mysql_num_rows($result);

 //if the count is 0 then no matching rows are found
 if($rowcount==0)
 {
  echo json_encode(array('result'=>0));
 }
 //Else there is an employee with the given credentials
 else {
  $row = mysql_fetch_assoc($result);
  //Get and return his employee id
  echo json_encode(array('result'=>$row['id']));
 }
 }

 //Get all th employees that are managed the by the given emplyee
 if($Request_Method=="getEmployees")
 {
  $id=$_REQUEST['id'];
 $query="select name,address from Employees where manager=$id";

 $result = mysql_query($query);

 while($row = mysql_fetch_assoc($result))
 {
  $resultArray[] = $row;
 }

 echo json_encode($resultArray);
 }

 //Close Connection
 mysql_close($Connection);
?>

The Android application will be discussed in Part 2

Friday, September 28, 2012

Mixing Client Side with Server side ASP.Net

Hi readers

Have you ever had the need to call a server side method from client side or a client side method from server side?

Well i've had this need so many times, so i've searched so many sites and read so many blogs about this. So i also wanted to write a post about this.

 First we'll see how to call a client side method from server side. Its pretty simple. you just have to register the method to the client side.

ClientScript.RegisterStartupScript(typeof(Page), "click", "alert('Hi');",true); ClientScript.RegisterStartupScript(typeof(Page), "click", "initialize()",true);

The first one will show an alert with text Hi and the second one will call the method initialize which is declared in the page.

Well lets see the calling of server side methods from client For this we'll need a script manager and the script manager's 'EnablePageMethods' attribute must be 'true'. And in the codebehind file you'll need to have a public static method

[System.Web.Services.WebMethod]
public static string sayHello(string name)
{
    return "Hello "+name;
}

And this method can be called from javascript
 
function sayHello(name) {
	PageMethods.sayHello(id, sayHellotSuccess, sayHellotFailure);
}
function sayHelloSuccess(result, userContext, methodName) {
	alert(result);
}
function sayHellotFailure(error, userContext, methodName) {
	alert(error.get_message());
}      

Now calling the method sayHello(name) will alert the output from server. And if you throw an exception in the server the 'sayHellotFailure' method will be executed.

 Leave a Comment if you like this post

Friday, August 24, 2012

Sharepoint : Get User's Permission for Lists

Hi this is a small program that print the permission for a given user in a sharepoint site
this helps the admins to know whether a user has access to a particular list and what access.

This simply helps to know what a user can do in each list.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace PermissionViewer
{
    class Program
    {
        static void Main(string[] args)
        {
            //Get the site url
            Console.Write("Enter Site Url  : ");
            string siteURL = Console.ReadLine();

            //Get the user name of user
            Console.Write("Enter User Name : ");
            string UserName = Console.ReadLine();

            try
            {
                //Get the sharepoint site
                using (SPSite sharepointSite = new SPSite(siteURL))
                {
                    //open the site
                    using (SPWeb sharepointweb = sharepointSite.OpenWeb())
                    {
                        //Get each and every list in sharepoint site
                        foreach (SPList sharepointList in sharepointweb.Lists)
                        {
                            //Get roles assigned for each list
                            foreach (SPRoleAssignment assignedRoles in sharepointList.RoleAssignments)
                            {
                                //Check whether the role if for a user
                                if (assignedRoles.Member is SPUser)
                                {
                                    //get the user from the role
                                    SPUser user = (SPUser)assignedRoles.Member;
                                    //Check whether its the same user that is entered
                                    if (user.Name.Equals(UserName, StringComparison.OrdinalIgnoreCase))
                                    {
                                        //removes user
                                        //item.RoleAssignments.Remove(item1);

                                        //Get users permissions - Add Remove Etc
                                        foreach (SPRoleDefinition item in assignedRoles.RoleDefinitionBindings)
                                        {
                                            Console.WriteLine("List : " + sharepointList.Title + "\nAccess : " + item.Name + "\n");
                                        }
                                    }
                                }

                                //Check whether the role is for a security group
                                if (assignedRoles.Member is SPGroup)
                                {
                                    //Get the security group
                                    SPGroup grp = (SPGroup)assignedRoles.Member;

                                    //Iterate members of the group
                                    foreach (SPUser groupMember in grp.Users)
                                    {
                                        //Check whether the user is the entered user
                                        if (groupMember.Name.Equals(UserName, StringComparison.OrdinalIgnoreCase))
                                        {
                                            //Get users permissions - Add Remove Etc
                                            foreach (SPRoleDefinition item in assignedRoles.RoleDefinitionBindings)
                                            {
                                                Console.WriteLine("List : " + sharepointList.Title + "\nGroup : " + grp.Name + "\nAccess : " + item.Name + "\n");
                                            }
                                            //uncomment if you want to remove a person from group
                                            //grp.RemoveUser(user1);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

            }
            catch (Exception Ex)
            {
                //Print if any exceptions occur
                Console.WriteLine("Error : "+Ex.Message);
            }
            //used make sure that the prompt is not closed
            Console.WriteLine("insert some value to exit");
            Console.ReadLine();
        }
    }
}

Monday, July 16, 2012

Linq to XML

Hi readers

This post is about using Linq to XML to create a small Employee Management System.
This post will explain how to add delete update and query an XML document which contains information of employees.
The post will contain the basic coding needed and you can download the complete sample HERE First we'll see the structure of the XML we are going to use.

<?xml version="1.0" encoding="utf-8"?>
<Employees>
  <Employee ID="1">
    <Name>Saman</Name>
    <Department>Delivery</Department>
  </Employee>
  <Employee ID="2">
    <Name>Nimal</Name>
    <Department>Delivery</Department>
  </Employee>
</Employees>
 
For this I'm using a class called Employee. You can do this with or without a class but using a class is a standard and easy way. This class is used to transfer data between the UI and the EmployeeManager class. The interaction between the XML file and the program are done using Linq.

This the class diagram for the Employee and the Employee Manager Class

Well lets got to the coding part The Employee class is very simple just three attributes

public class Employee
{
//attribute ID
public int ID { get; set; }

//Element Name
public string Name { get; set; }

//Element Department
public string Department { get; set; }
}

Now the Employee Manager Class

public class EmployeeManager
{
    /// <summary>
    /// The path of the XML file 
    /// </summary>
    private string XMLFile;

    /// <summary>
    /// Employee Manager is used to handle the interaction between the XML file
    /// and the application
    /// </summary>
    /// <param name="file">The Location of the XML File</param>
    public EmployeeManager(string file)
    {
        XMLFile = file;

        //create the XML file if it doest exist
        if (!File.Exists(XMLFile))
        {
            //As the file is not there a new XML Document is created
            //Blank space is used to create an empty tag
            XDocument document = new  XDocument(
                                        new XElement("Employees","")
                                      );
            document.Save(XMLFile);
        }
    }

    /// <summary>
    /// Add an Employee to the XML file
    /// </summary>
    /// <param name="newEmployee">The Employee to be added</param>
    /// <returns>True if Success false otherwise</returns>
    public bool addEmployee(Employee newEmployee)
    {
        try
        {
            //load the xml file 
            XDocument document = XDocument.Load(XMLFile);
            //Get create a new Employee Element
            XElement employee = new XElement("Employee");
            //Set the value for the attribute
            employee.SetAttributeValue("ID",newEmployee.ID);
            //set the value for the child elements
            employee.Add(new XElement("Name", newEmployee.Name));
            employee.Add(new XElement("Department", newEmployee.Department));
            //add the created Employee element to the root element Employee
            document.Element("Employees").Add(employee);
            //Save the XML file so that the new Employee will be added
            document.Save(XMLFile);
            //Return to if success
            return true;
        }
        catch (Exception)
        {
            //return false if any exception occur
            return false;
        }

    }

    /// <summary>
    /// Delete an Employee from the XML file
    /// </summary>
    /// <param name="EmployeeID">ID of the Employee to be Deleted</param>
    /// <returns>True if Success false otherwise</returns>
    public bool deleteEmployee(int EmployeeID)
    {
        try
        {
            //Load the XML document
            XDocument document = XDocument.Load(XMLFile);
            //Get the Root tag Employees and get the Employee element to be deleted
            document.Element("Employees").Elements("Employee").FirstOrDefault
                (
                    //in here we are getting the first or default so if no element
                    //is there we'll get an exception
                    //We are comparing the attribute here
                    X => X.Attribute("ID").Value.Trim() == EmployeeID.ToString()
                    //the remove method deletes the employee
                ).Remove();
            //saving the changes to the XML file
            document.Save(XMLFile);
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

    /// <summary>
    /// Update the attributes of an Employee
    /// </summary>
    /// <param name="updatedEmployee">Employee Object with Updated Values</param>
    /// <returns>True if Success false otherwise</returns>
    public bool updateEmployee(Employee updatedEmployee)
    {
        try
        {
            //Load the file
            XDocument document = XDocument.Load(XMLFile);
            //Update the child element values for the selected employee
            //you can use setAttribute method if you want to set an attributes value 
            document.Element("Employees").Elements("Employee").FirstOrDefault
                (
                    X => X.Attribute("ID").Value.Trim() == updatedEmployee.ID.ToString()
                ).SetElementValue("Name", updatedEmployee.Name);

            document.Element("Employees").Elements("Employee").FirstOrDefault
                (
                    X => X.Attribute("ID").Value.Trim() == updatedEmployee.ID.ToString()
                ).SetElementValue("Department", updatedEmployee.Department);
            //save changes to the xml file
            document.Save(XMLFile);
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

    /// <summary>
    /// Get a list of All The employees in the 
    /// </summary>
    /// <returns>List of all Employees</returns>
    public List<Employee> getAllEmployees()
    {
        //Create an empty List to store the employee object
        List<Employee> empList = new List<Employee>();

        XDocument document = XDocument.Load(XMLFile);
        //here we are reading all the Employee values and create objects
        //and add it to the list
        foreach (XElement employee in document.Element("Employees").Elements("Employee"))
        {
            Employee emp = new Employee();
            emp.ID = Convert.ToInt32(employee.Attribute("ID").Value.Trim());
            emp.Name = employee.Element("Name").Value.Trim();
            emp.Department = employee.Element("Department").Value.Trim();
            empList.Add(emp);
        }
        //return the list
        return empList;
    }

    /// <summary>
    /// Get a selectes employee from the XML file
    /// </summary>
    /// <param name="ID">ID of the Employee</param>
    /// <returns>Employee object for the given ID</returns>
    public Employee getEmployee(int ID)
    {
        try
        {
            XDocument document = XDocument.Load(XMLFile);
            //Here we are selecting a single employee element and retrive its element values and
            //create a Employee object from it
            XElement employee = document.Element("Employees").Elements("Employee").FirstOrDefault(
                X => X.Attribute("ID").Value.Trim() == ID.ToString()
                );

            Employee selectedEmployee = new Employee() { 
                ID = Convert.ToInt32(employee.Attribute("ID").Value.Trim()),
                Name=employee.Element("Name").Value.Trim(),
                Department=employee.Element("Department").Value.Trim() 
            };
            //return the employe object
            return selectedEmployee;
        }
        catch (Exception)
        {
            //return null if no employee found with given ID
            return null;
        }

    }
}
This is the coding part.
Now you can create a UI like this and access the Employee Manager class and get things done.

Sample UI
 

You can download the complete sample HERE
Please leave a comment if you like the post 
Happy Coding :)
Guruparan Giritharan.

Saturday, June 2, 2012

Google maps - locations live update from SQL Server


Hi Readers This post is about showing the locations (Longitude and Latitude) values stored in a SQL server database in a google map. this will automatically update the location lively. For this I'm using a ASP .Net website . Languages used will be C# Linq and javascript. First we'll create the database
--Create Database
CREATE DATABASE MapSample
USE MapSample

--Create Table
CREATE TABLE Locations
(
 ID INT PRIMARY KEY IDENTITY(1,1),
 Longitude FLOAT,
 Latitude FLOAT,
 Bounce INT,
 [Description] VARCHAR(50)
);

Here the bounce column is to make a marker bounce and the description column is to show the message when the marker is clicked.
Now lets see the javascript explanation
        //The array to hold the markers this will be used to clear the markers for every refresh
        var markersArray = [];

        //The map object
        var map;
        //Longitude of the center point
        var longt = 80.727539;
        //Latitude of the center point
        var lat = 7.373362;

        //Make the update method run once in every 10 seconds
        self.setInterval("updateMap()", 10000);

        //initialize the google map
        function initialize() {
            //Options for the map object
            var myOptions = {
                zoom: 8,
                center: new google.maps.LatLng(lat, longt),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            //create the map object
            map = new google.maps.Map(document.getElementById('map_canvas'),myOptions);
        }

        //method to clear the markers in the map
        function clearOverlays() {
            if (markersArray) {
                for (var i = 0; i < markersArray.length; i++) {
                    //remove the marker from the map
                    markersArray[i].setMap(null);
                }
                //set the marker array as null
                markersArray = [];
            }
        }

        //show the map in the web page
        google.maps.event.addDomListener(window,  load , initialize);

        //The update method that is used to insert markers to the map
        function updateMap() {

            //clear the markers that are currently in the map so that new once can be added
            clearOverlays();

            //loop to set the markers
            for (var i = 0; i < lonarray.length; i++) {

                //get the longtitude from the longtitude array this array is set from the C# code 
                longt = lonarray[i];
                //get the latitude from the latitude array this array is set from the C# code
                lat = latarray[i];
                //set a title
                var title =  test ;

                //create the location object
                var location = new google.maps.LatLng(lat, longt);
                //create the marker
                var marker1 = new google.maps.Marker({ position: location, title: title });
                //set whether the marker should bounce or not
                if (bounce[i] == 1) {
                    marker1.setAnimation(google.maps.Animation.BOUNCE);
                }

                //set the information of the overlay which will be displayed when marker is clicked
                var infoContent = infoarray[i];
                setContent(marker1, infoContent);

                //add the marker to the marker array so that it can be cleared
                markersArray.push(marker1);

                //add the marker to the map
                marker1.setMap(map);

            }
            //clear the array contents so that new locations can be loaded
            infoarray = [];
            latarray = [];
            lonarray = [];
            emergencies = [];
        }

        //the method used to set the onclick method and info window
        function setContent(marker,message) {

            var infowindow = new google.maps.InfoWindow({
                content: message
            });

            google.maps.event.addListener(marker,  click , function() {
                infowindow.open(map, marker);
            });
        }
Now we'll go to the C# code that will be used to set the array contents
Here i'm using an update panel and timer control which refreshes it every 10 seconds (Please download and see the HTML part to see the code)
This will be the code behind file
 protected void UpdatePanel1_Load(object sender, EventArgs e)
        {
            //Linq is used to load the table to the code
            DataClassesDataContext data = new DataClassesDataContext();

            //Select all from the table
            List lst = (from u in data.Locations select u).ToList();

            //add the table contents to the javascript array so that new locations will be loaded
            foreach (Location item in lst)
            {
                ScriptManager.RegisterArrayDeclaration(UpdatePanel1, "infoarray", "'"+item.Description.ToString()+"'");
                ScriptManager.RegisterArrayDeclaration(UpdatePanel1, "lonarray", item.Longitude.ToString());
                ScriptManager.RegisterArrayDeclaration(UpdatePanel1, "latarray", item.Latitude.ToString());
                ScriptManager.RegisterArrayDeclaration(UpdatePanel1, "bounce", item.Bounce.ToString()); 
            }
        }

        protected void Timer1_Tick(object sender, EventArgs e)
        {
            //update the update panel every 10 seconds
            UpdatePanel1.Update();
        }

You can download the source files HERE
Hope this is useful
Happy Coding.

Monday, May 14, 2012

iPhone SQLite for Absolute Beginners

Hi this post is about creating a sqlite database in iPhone and manipulating it.
This is a tutorial for absolute beginners
As this is contains a lot of coding the code is not put in the blog but its fully commented and available for download.

The Code Demonstrates the following
  • Create a Sqlite Database
  • Add values to the database
  • Search for values in the database
  • Delete values from the database
  • Show all the values in a Picker
  • show all the values in a Table

Here are the UI's of the project



You Can download the source code

HERE


Please leave a comment.

Thursday, March 29, 2012

C# age function

Hi readers this is a function developed to get the age on a given date.
feel free to use it.
Inputs are Date of Birth and the date to compare
if you want to get the Age as of Today set the second argument as DateTime.Today.

public static int calculateAge(DateTime DateOfBirth,DateTime DateAsOF)
{
   int years = DateAsOF.Year - DateOfBirth.Year-1;
            
   if (DateAsOF.Month > DateOfBirth.Month)
   {
      years++;
   }
   else if (DateAsOF.Month == DateOfBirth.Month)
   {
      if (DateAsOF.Day>=DateOfBirth.Day)
      {
          years++;
      }

   }
   return years;
}