Thursday, 26 July 2012

C# File copy application, Learning file manipulation [source code attached]

file copy icon File copy
This is a simple file copy application in which you will going know about file handling functions and also some threading concepts available in C#

Overview of application
  • Developed in visual studio 2008, language C#
  • It's a Windows forms application
  • Only one instance can run at a time (using SingleExecution.cs)
  • FileCopy.cs contain main logic for program
  • Defination.cs is a static class holding the labels used within program
  • Download : Source code, Application
Screen shots


Thursday, 12 July 2012

JSP: How JSP is working ?


A basic tip for JSP beginners !!
  1. Get the request for any page (for eg: login.jsp)
  2. Search respective JspServlet (loginServlet.java)
  3. Parse the JspServlet file after that it  generate the servlet source and then load it
  4. finally generate the response & then send it !!
JSP execution

Thursday, 31 May 2012

Understanding JPA entities

  • A JPA entity is a java class referring to one row of a table
  • Each entity has same number fields/properties as in table structure
  • It can be with or without relationship
  • that is One to one, One to many or many to many
  • Consider the following table structure for one to many relationship
  • For above table structure two entity will be created
  • Categories.java (manage Categories table)
  • Products.java (manage product table)



//////////////////////////////////////////////////////////////////////
// CATEGORIES

package entities;

import java.io.Serializable;
import javax.persistence.*;
import java.util.List;

/**
* The persistent class for the Categories database table.
*
*/
@Entity
@Table(name="Categories")
public class Categories implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@Column(name="CategoryId", unique=true, nullable=false)
private String categoryId;

@Column(name="CategoryName")
private String categoryName;

@Column(name="Description", length=50)
private String description;

//bi-directional many-to-one association to Products
@OneToMany(mappedBy="category", cascade={CascadeType.PERSIST, CascadeType.REMOVE})
private List products;

 public Categories() {
 }

public String getCategoryId() {
return this.categoryId;
}

public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}

public Object getCategoryName() {
return this.categoryName;
}

public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}

public String getDescription() {
return this.description;
}

public void setDescription(String description) {
this.description = description;
}

public List getProducts() {
return this.products;
}

public void setProducts(List products) {
this.products = products;
}

}
//////////////////////////////////////////////////////////////////////
// PRODUCTS
package entities;


import java.io.Serializable;
import javax.persistence.*;


/**
* The persistent class for the Products database table.
*
*/
@Entity
@Table(name="Products")
public class Products implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@Column(name="ProductId", unique=true, nullable=false)
private String productId;

@Column(name="ProductName", length=50)
private String productName;

@Column(name="Supplier", length=50)
private String supplier;

//bi-directional many-to-one association to Categories
 @ManyToOne
@JoinColumn(name="CategoryId")
private Categories category;

 public Products() {
 }

public String getProductId() {
return this.productId;
}

public void setProductId(String productId) {
this.productId = productId;
}

public String getProductName() {
return this.productName;
}

public void setProductName(String productName) {
this.productName = productName;
}

public String getSupplier() {
return this.supplier;
}

public void setSupplier(String supplier) {
this.supplier = supplier;
}

public Categories getCategory() {
return this.category;
}

public void setCategory(Categories category) {
this.category = category;
}

}
  • Above two class represent two tables Categories and products
  • You need to import javax.persistence.*
  • Using above classes & EntityManager we can fetch data from database
  • Consider the following code ....

public static void main()
{
 // Creating entity manager to create Db query
 EntityManagerFactory factory = Persistence.createEntityManagerFactory("WebWithJPA");
 javax.persistence.EntityManager em = factory.createEntityManager();
 
 try 
 {
  // Creating Query using JPQL
  Query objQuery = em.createQuery("select c from Categories c");
 
  // Getting result set in List
  List objC = (List) objQuery.getResultList();
  
  // Listing all categories and its related products
  for (Categories c : objC) 
  {
   System.out.println("Category Name: " + c.getCategoryName());
   for (Products p : c.getProducts()) 
   {
    System.out.println("* " + p.getProductName());
   }
  }
}

Wednesday, 21 December 2011

Java EE Class [com.microsoft.sqlserver.jdbc.SQLServerDriver] not found.

Error description:
- unable to load SQL server drivers
- need to add it in project

How to add it ?? (Ref to Eclipse 3.7.1 indigo)
- download sqljdbc4.jar & sqljdbc.jar
- Add library into Eclipse project
- Right click on project menu -> properties -> Java build path -> Libraries
-> Add External jar
- Add same sqljdbc4.jar file in Deployment Assembly
Right click on project menu -> properties -> Deployment Assembly -> Add

I hope it can be solved !!

Monday, 31 October 2011

Java: File Read / Write

//******** File reading using scanner
     /**
     * Read given file line by line
     * @param m_strFileName File name
     * @throws Exception File not exist
     * @auther Amit 31/10/2011 
     */
    void printFile(String m_strFileName) throws Exception {

        // Create an instance of File for data file.
        File objFile = new File(m_strFileName);
        if(objFile.exists() == false)
        {
            throw new Exception(m_strFileName + "File does not exist");
        }

        // Reading and displaying file line by line
        Scanner objScanner = new Scanner(objFile);
        while(objScanner.hasNextLine() == true)
        {
            System.out.println(objScanner.nextLine());
        }
        objScanner.close();
    }

//********** Using FileInputStream

  // Get the object of DataInputStream, passing FileInputStream
  DataInputStream in = new DataInputStream(new FileInputStream("anyfile.txt"));
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  String strLine;

  //Read File Line By Line
  while ((strLine = br.readLine()) != null)   
  {
    // Print the line on the console
    System.out.println (strLine);
  }
  in.close();

Friday, 7 October 2011

c#: XML serialization and deserialization, that is from class to xml and xml to class

Consider following as xml structure



Amit
+91-9033334254
1986-01-01
Male
Single

ASI
IND
2000-01-10




  1. First you need to create class in which you can store xml data- For nested xml tag new class is created
  2. if you don't know how to create class for serialization then just search xsd.exe
    in you c:\ drive, or download from internet.
  3. Follow following command using xsd.exe in cmd
  • C:\xsd.exe Employee.xml
    Microsoft (R) Xml Schemas/DataTypes support utility
    [Microsoft (R) .NET Framework, Version 2.0.50727.42]
    Copyright (C) Microsoft Corporation. All rights reserved.
    Writing file 'C:\Employee.xsd'.
  • Above Command give u xml schema, later this schema will create class
  • C:\xsd.exe Employee.xsd /classes
    Microsoft (R) Xml Schemas/DataTypes support utility
    [Microsoft (R) .NET Framework, Version 2.0.50727.42]
    Copyright (C) Microsoft Corporation. All rights reserved.
    Writing file 'C:\Employee.cs'.
The Above code will generate required classes automatically,
it may contain three class, Employee, Employee_info, Branch etc
but really we don't need to care about these classes.
let's come to the actual coding


// Creating Object of XML Serializer for Getting Data into Emplyee Object
XmlSerializer objXmlSerializer = new XmlSerializer(typeof(Employees));
TextReader objTextReader;
Stream objStream = null;
FileStream objFileStream = null;

// Generated class from xsd.exe
Employees objEmployees = null;

objFileStream = new FileStream("Employee.xml", FileMode.OpenOrCreate);
objTextReader = new StreamReader(objFileStream);

// Get the xml data into the objEmployees obj
objEmployees = (Employees)objXmlSerializer.Deserialize(objTextReader);
objFileStream.Close();

///
/// Display Employees Records on Console
///

public void DisplayEmployeeInfo(Employees Employee)
{
if (Employee == null )
{
Console.WriteLine(Defination.NoRecordFound);
return;
}

for (int nIndex = 0; nIndex < Employee.Length; nIndex++)
{
// Calculating emp age
TimeSpan objTimeSpan = DateTime.Now - DateTime.Parse(Employee[nIndex].BirthDate);

Console.Write("{0}\t{1}\t{2} {3} ", Employee[nIndex].Name, Employee[nIndex].Telephone, ((int)objTimeSpan.TotalDays / 365), Employee[nIndex].RelationshipStatus);

Console.Write("\t{0}\t{1}\t{2}", Employee[nIndex].Branch[0].Name, Employee[nIndex].Branch[0].CountryCode, Employee[nIndex].Branch[0].EstablishmentDate);
Console.WriteLine();
}
}

// for insert / update just take new emplyees obj and serialize it
Employees objNewEmployees = new Employees();

// fill the required info like u get it in Display() method
...
...
XmlSerializer serializer = new XmlSerializer(typeof(Employees));
TextWriter textWriter = new StreamWriter("New file.xml");
serializer.Serialize(textWriter, objNewEmployees);
textWriter.Close();

Thursday, 6 October 2011

Create Thumbnail for image using c#


// Setting Thumbnail size
int height = 600;
int width = 400;

// Getting desired image
Bitmap objImage = new Bitmap("--file path --");

// Showing image in picturebox, here pictureBox1 is pictureBox control
pictureBox1.Image = objImage.GetThumbnailImage(width, height,null, IntPtr.Zero);