Thursday, February 28, 2013

Jquery Method to hide all the buttons and submit buttons from a HTML FORM on the page whenever the form is submitted.

JQuery is widely used these days for all type of page html tag manipulations and is frequently used to hide, show, navigate the form elements.

Some times when a form is submitted we need to hide / disable all the submit buttons from the page so that we can avoid the double form submissions and avoid any errors related to double request.

To achieve the same to some extent and avoid such errors, following code can be used to hide all the submit buttons from the page within the form which is being submitted.
$(document).ready( function() {
   $("form").each(function() {
      $(this).submit(function(){
          $(document).find("input[type=button],input[type=submit]").each(function(){
             var display=$(this).css("display");
             if(display!='none'){
                $(this).hide();
                $(this).parent().append("");
             }
          });
      });
   });
});

How it works: It finds all the form elements in the document loaded and on submit of the form it finds all the HTML INPUT tags of type BUTTON and SUBMIT.

And on each it check and finds the CSS attribute "DISPLAY" and if its NOT 'none' then it will hide the INPUT BUTTON/SUBMIT and will append an image (loading.gif) to its parent tag, so that it appears at the same positions as the button.

Hope it will help you solve some issues related to Form Submission. Feel free to comment if any issues.


Tuesday, February 19, 2013

JavaScript function to remove all spaces in a String using regular expression

Many a time it is needed to trim all the spaces from a text field like First Name, Last Name, Amount etc where Spaces " " are not allowed and which should be removed then its very useful to replace all the spaces in the text field or text area.

The following function can be used to replace all the spaces through the use of regular expression:

function trimString(field)
{
 return field.replace(/\s/g,"");
}

Example :

trimString (" Code - Zila  :  The -  Code - District  ");

returns : "Code-Zila:The-Code-District" 


How it works:

The function internally used javaScript replace function to find spaces " " using regular expression "\s" for space character and then replaces it with "".

The function call be called through the events : onClick() or onBlur()

Hope you would find it helpful. 

Thursday, June 7, 2012

Java Standalone method to create a File from an InputStream

This method can be used to save any type of file (image, pdf...) for which you have the InputStream:

 public void createLocalCopy(String localFileName,InputStream iStream) throws IOException{
  OutputStream outStream = new FileOutputStream("C:\\Users\\MYFILE\\"+localFileName);
        try{
        System.out.println("making a local copy="+localFileName);
        byte[] buffer = new byte[1024];
        int len;
        while((len = iStream.read(buffer)) >= 0)
         outStream.write(buffer, 0, len);
        outStream.flush();
        outStream.close();
        iStream.close();
        }catch(Exception e)
        {
         outStream.flush();
         outStream.close();
         iStream.close();
        System.out.println("ERROR IN MAKING LOCAL COPY "+localFileName+", ERROR MSG = "+e.getMessage());
        }
        System.out.println("iStream====="+iStream);
 }

Java Class code to test whether springframework's SimpleJdbcCall is Thread Safe or not


import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.jdbc.datasource.AbstractDriverBasedDataSource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import com.sushant.verma.common.dto.UserDto;

public class MyThread implements Runnable{
 private static Logger log=LogManager.getLogger(MyThread.class);
 /**
  * creating Instance Variables
  */
 private UserDto userDto;
 private static SimpleJdbcCall procReaduserDto;
 /**
  * name and password VALUE set at instance level to be used
  */
 private String name="code";
 private String pwd="zila";


 public static void setDataSource(DataSource dataSource) {
  log.debug("Inside setDataSource ");
  /**
   * procReaduserDto Object to be created by the main thread in start to be used by multiple threads
   * as in the case of Spring IOC
   */
  procReaduserDto =new SimpleJdbcCall(dataSource);  
 } 

 public static void main(String [] args) throws Throwable  
 {
  /**
   * calling setDataSource with new dataSource object
   * in the start before starting thread as in Spring IOC
   */
  DataSource dataSource = new DriverManagerDataSource();
  ((DriverManagerDataSource) dataSource).setDriverClassName( "com.mysql.jdbc.Driver");
  ((AbstractDriverBasedDataSource) dataSource).setUrl( "jdbc:mysql://localhost:3306/test");
  ((AbstractDriverBasedDataSource) dataSource).setUsername( "root");
  ((AbstractDriverBasedDataSource) dataSource).setPassword( "admin"); 
  setDataSource(dataSource);

  log.debug("========Creating & Starting Threads===========");
  MyThread obj1 = new MyThread();
  MyThread obj2 = new MyThread();
  new Thread(obj1).start();
  new Thread(obj2).start();
  // main thread is ending here,
  // Thread-0 and Thread-1 continue to run.
 }

 public void run()
 {
  try {
   /**
    * Iterating for 3 times
    */
   for (int i=0; i<3; i++) {
    log.info("************************loop "+i+" begins************************");
    if(Thread.currentThread().getName().equals("Thread-1")){
     /**
      * changing Instance Variable name/pwd value for thread-1 
      */
     setName("wrong_userName");
     setPwd("wrong_password");
    }

    /**
     * calling the readUser method for both the threads with different name/pwd values
     */
    setUserDto(readUser(name, pwd));
    /**
     * Thread-1 should return __isUserValid=false & __getUserExists=0
     * Thread-0 should return __isUserValid=true & __getUserExists=1
     */
    log.info("~~~~~~~~~loop "+i+" ends~~~~~~~~~");
   }
  } catch (Throwable t) { }
 }


 public UserDto readUser(String userEmail,String password) {
  /**
   * procReaduserDto object value should be same as created before the thread starts as to be the case with Spring IOC
   */
  log.debug(" @ readUser with procReaduserDto="+procReaduserDto);
  MyThread.procReaduserDto.withProcedureName("sp_authenticateUser");  

  Map args=new HashMap();  
  args.put("in_userName", userEmail);  
  args.put("in_password", password);  
  @SuppressWarnings("unused")
  Map out = procReaduserDto.execute(args);  

  UserDto userDto = new UserDto();  
  userDto.setUserExists((String) out.get("out_userexists"));  
  String userValid=(String) out.get("out_isuservalid");  
  if(userValid.equals("1"))  
   userDto.setUserValid(true);  
  else  
   userDto.setUserValid(false);  

  return userDto;  
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getPwd() {
  return pwd;
 }

 public void setPwd(String pwd) {
  this.pwd = pwd;
 }

 public void setUserDto(UserDto userDto) {
  this.userDto = userDto;
 }

 public UserDto getUserDto() {
  return userDto;
 }


}

Wednesday, April 25, 2012

How to generate a random alphanumeric word with special characters of variable length

Usually we need to create a random word of some 8+ character to use as a password or an encryption key.
I have recently created this one, though very simple but very effective.
I have tried to replicate the same sequence and run in a loop of 1000000 iteration but with length of 8 characters there were no repetition. Hope the readers would like it.

package in.codeZila.www.utility;

public class RandomWordGenerator {

 public static final String getRandomWord(int length) {
  String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*";
  String rw = "";
  for(int i = 0; i < length; i++) {
   int index = (int) Math.floor(Math.random() * 62);
   rw += chars.charAt(index);
  }

  return rw;
 }
 
 public static void main(String[] args) {
  for(int i=0;i<100;i++){
   String randomPwd=getRandomWord(8);
   System.out.println(randomPwd);
  }
 }
 
}


The Random words generated are :

Please feel free to ask any doubts or clarifications.

Saturday, April 14, 2012

How to get the XML String for a DTO (Data transfer object) using XStream

To get the XML for a DTO XStream (com.thoughtworks.xstream.XStream) is used, Download the "xstream-1.4.2.jar" jar : Click Here and add into your lib folder.

The Method which returns the XML for the passed DTO:
public static String getDTOasXML(Object dto){
 XStream xstream = new XStream();
        return xstream.toXML(dto);
}


The UserDto which needs to be converted to XML :

public class UserDto{

 
 private Long userId;

 private String userName;

 private String userEmail;

 public Long getUserId() {
  return userId;
 }

 public void setUserId(Long userId) {
  this.userId = userId;
 }

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }

 public String getUserEmail() {
  return userEmail;
 }

 public void setUserEmail(String userEmail) {
  this.userEmail = userEmail;
 } 
}

Note: Notice that the fields are private. XStream doesn't care about the visibility of the fields. No getters or setters are needed. Also, XStream does not limit you to having a default constructor.

The Test Class to implement the XStream.toXML() method :

package in.codeZila.test;

import in.codeZila.test.dto.UserDto;
import com.thoughtworks.xstream.XStream;


public class Test{
 
 /**
  * Using XStream method toXML():String to generate the XML for the passed DTO object
  * @param dto
  * @return dto XML as String
  */
 public static String getDTOasXML(Object dto){
  XStream xstream = new XStream();
  /**
   * Now, to make the XML outputted by XStream more concise, 
   * you can create aliases for your custom class names to XML 
   * element names. This is the only type of mapping required to 
   * use XStream and even this is optional.
   * 
   * Note: This is an optional step. Without it XStream would work fine, 
   * but the XML element names would contain the fully qualified name of 
   * each class (including package) which would bulk up the XML a bit.
   */
  xstream.alias("UserDto", UserDto.class);
  return xstream.toXML(dto);
 }
 
 public static void main(String[] args) {
  /**
   * Instantiate the UserDto and set its variables
   */
  UserDto userDto=new UserDto();
  userDto.setUserId(new Long(1));
  userDto.setUserName("CodeZila");
  userDto.setUserEmail("codezila@codezila.in");
  /**
   * Pass the userDto Object created above as getDTOasXML() argument
   */
  String dtoXml=Test.getDTOasXML(userDto);
  System.out.println(dtoXml);
 }
}



The Output XML :

Thats all, how simple XStream is!

Summary:

  • Create element name to class name aliases for any custom classes using xstream.alias(String elementName, Class cls); 
  • Convert an object to XML using xstream.toXML(Object obj); 
  • Convert XML back to an object using xstream.fromXML(String xml);


Your valuable inputs and suggestions are welcomed!

Monday, March 5, 2012

Java Method to copy a folder directory contents from source location to destination location


public void copyDirectory(java.io.File sourceLocation, java.io.File targetLocation) {
 System.out.println("Starting Copying");
 try {
  if (sourceLocation.isDirectory()) {
   if (!targetLocation.exists()) {
    targetLocation.mkdir();
   }

   String[] children = sourceLocation.list();
   for (int i = 0; i < children.length; i++) {
    copyDirectory(new java.io.File(sourceLocation, children[i]),
      new java.io.File(targetLocation, children[i]));
   }
  } 
  else {
   java.io.InputStream in = new java.io.FileInputStream(sourceLocation);
   java.io.OutputStream out = new java.io.FileOutputStream(targetLocation);
   byte[] buf = new byte[1024];
   int len;
   while ((len = in.read(buf)) > 0) {
    out.write(buf, 0, len);
   }
   in.close();
   out.close(); 
  }
 } catch (java.io.IOException e) {
  e.printStackTrace();
  throw new RuntimeException(e);
 }
 System.out.println("Completed Copying");
}

To test this method just create a directory at any location say: (c:/sourceLocation/) with some files in it. And you want to copy all the contents of this directory to a new location say : (d:/targetLocation) which may or may not exist. Then this function will create the target location and copy all the contents from the given source location to the target location. 

 The sample test class to test this method:
public class TestCopyDrectory {

 public static void main(String[] args) {
  copyDirectory(new java.io.File("C:/sourceLocation/"), new java.io.File("D:/targetLocation"));
 }

 public static void copyDirectory(java.io.File sourceLocation, java.io.File targetLocation) {
  System.out.println("Starting Copying");
  try {
   if (sourceLocation.isDirectory()) {
    if (!targetLocation.exists()) {
     targetLocation.mkdir();
    }

    String[] children = sourceLocation.list();
    for (int i = 0; i < children.length; i++) {
     copyDirectory(new java.io.File(sourceLocation, children[i]),
       new java.io.File(targetLocation, children[i]));
    }
   } 
   else {
    java.io.InputStream in = new java.io.FileInputStream(sourceLocation);
    java.io.OutputStream out = new java.io.FileOutputStream(targetLocation);
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
     out.write(buf, 0, len);
    }
    in.close();
    out.close(); 
   }
  } catch (java.io.IOException e) {
   e.printStackTrace();
   throw new RuntimeException(e);
  }
  System.out.println("Completed Copying");
 }

}

Wednesday, February 22, 2012

Steps to create a dataSource bean in applicationContext.xml in Spring Framework with its properties for jdbc connection string obtained from a properties file

In Spring Framework while creating a dataSource bean in applicationContext.xml, it is required to establish the jdbc connection with the connection properties like driverClassName, url, username, password being defined.

The same can be defined directly with all the property values there itself hard coded like :


But there is a better way, separate the jdbc connection dataSource bean in a seperate xml say dataSource.xml which you can import in the main applicationContext.xml

And it will be even further better if the properties  like driverClassName, url, username, password of jdbc connection string are fetched from a properties file which can be easily changed depending upon the environment without even touching the applicationContext.xml file thus the dependency is removed.

To separate the dataSource bean two files need to be created in src folder (in the same directory as applicationContext.xml):


1) dataSource.xml
2) jdbc.properties


Steps :

1) Inside src folder create a xml file dataSource.xml Paste the following in it :


Here i have used "org.springframework.jdbc.datasource.DriverManagerDataSource" as dataSource class which can be any other datasource class.


2) Inside src folder create a properties file jdbc.properties. Paste the following in it :


The Database connection string is created for mysql for database "TEST"

3) Import the created dataSource.xml in your applicationContext.xml:




That was all, you application is good to go. Got any doubts, feel free to ask/comment.

Thursday, December 15, 2011

ABC of WCF


ABC of WCF

WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the world.
All the WCF communications are take place through end point. End point consists of three components.

Address

Basically URL, specifies where this WCF service is hosted .Client will use this url to connect to the service. e.g
http://localhost:8090/MyService/SimpleCalculator.svc

Binding

Binding will describes how client will communicate with service. There are different protocols available for the WCF to communicate to the Client. You can mention the protocol type based on your requirements.
A binding has several characteristics, including the following:
  • Transport -Defines the base protocol to be used like HTTP, Named Pipes, TCP, and MSMQ are some type of protocols.
  • Encoding (Optional) - Three types of encoding are available-Text, Binary, or Message Transmission Optimization Mechanism (MTOM). MTOM is an interoperable message format that allows the effective transmission of attachments or large messages (greater than 64K).
  • Protocol(Optional) - Defines information to be used in the binding such as Security, transaction or reliable messaging capability
The following table gives some list of protocols supported by WCF binding.
Binding
Description
BasicHttpBinding
Basic Web service communication. No security by default
WSHttpBinding
Web services with WS-* support. Supports transactions
WSDualHttpBinding
Web services with duplex contract and transaction support
WSFederationHttpBinding
Web services with federated security. Supports transactions
MsmqIntegrationBinding
Communication directly with MSMQ applications. Supports transactions
NetMsmqBinding
Communication between WCF applications by using queuing. Supports transactions
NetNamedPipeBinding
Communication between WCF applications on same computer. Supports duplex contracts and transactions
NetPeerTcpBinding
Communication between computers across peer-to-peer services. Supports duplex contracts
NetTcpBinding
Communication between WCF applications across computers. Supports duplex contracts and transactions

Contract

Collection of operation that specifies what the endpoint will communicate with outside world. Usually name of the Interface

Wednesday, April 13, 2011

Performance optimization for XML query in SQL SERVER


As we all uses XML Query instead of row level query to insert/update bulk data into a database in order to achieve better performance. But when there is a large dataset having multilevel xml nodes, the performance degrade significantly.

While doing performance tuning in “AcceleRATE” I came across with “XML indexes” on an xml column.


Below is the step by step process to achieve this.

1. Create a temporary table with on identity column with primary key and one other column with xml datatype.

CREATE TABLE #OptimizedXML(id INT IDENTITY PRIMARY KEY, SurveyXML xml NOT NULL)



2. Create a primary XML index

CREATE PRIMARY XML INDEX PrimaryXMLIndex ON #OptimizedXML(SurveyXML)

3. Create a secondary XML index

CREATE XML INDEX

XMLDataStore_XmlCol_PATH ON #OptimizedXML(SurveyXML)

USING XML INDEX PrimaryXMLIndex FOR PATH

4. Now insert the values into a table
INSERT INTO #OptimizedXML VALUES(@SurveyXML)
5. Here we are ready to perform the same XML query with some tweak to achieve performance.

SELECT F.Manager.value('@fname','varchar(255)') as fname,

F.Manager.value('@lname', 'varchar(255)') as lname,

F.Manager.value('@title', 'varchar(255)') as title,

F.Manager.value('@email', 'varchar(255)') as email,

F.Manager.value('@domainid', 'int') as domainid,

F.Manager.value('@ID', 'int') as userid,

F.Manager.value('@encryptedmail', 'varchar(500)') as encryptedemail

FROM #OPtimizedXML X

cross apply X.SurveyXML.nodes('Surveys[1]/Survey/Manager') AS F(Manager)

By doing the above tweak, the query which was earlier taking more than 2 minutes to execute, now takes just 10-15 seconds.

Additionally, there are few points, which we need to keep in mind while using this approach.

We must have one primary key (clustered index) on a table; it is required to create a XML index.
There must be one primary xml index followed by one or more secondary xml indexes on xml column(s).
While querying the table, we have to use a cross apply on the node where in we want to fetch data.

Tuesday, January 25, 2011

JAVA Mock exam test paper with 25 most important and frequently asked questions with answers and explanation

 QUESTIONS

Q1public class Test1{

public static void main(String[] args)
{int arr[] = new int[3]; 
for(int i = 0;i < arr.length;i++){

System.out.println(arr[i]); 
}
 } }

What will be the output?
A1 0 0 0
A2 ArrayIndexoutOfBoundsException
A3 NullPointerException
A4 null null null


Q2 Which of the following are valid array declarations?
A1 int arr[] = new int[];
A2 float arr[10] = new fl
A3 double []arr = new double[10];
A4 None Of the Above.

Q3 public class Test3{
public void method(){
 System.out.println("Called");
}
public static void main(String[] args){
method();
}
}

What will be the output?
A1 "Called"
A2 Compiler
A3 Runtime
A4 Nothing

Q4 public class Test4{


public static void method(){
System.out.println("Called");

}


public static void main(String[] args)
{ Test4 t4 = null;
t4.method();
} }


What will be the output?

A1 "Called"

A2 Compiler

A3 Runtime Exception

A4 Nothing is printed in screen

Q5 public class Test5{
public void Test5()
{

System.out.println("Constructor1");
}
public Test5(){}
System.out.println("Constructor2");
public static void main(String[] args)
{
Test5 t5 = new Test5(); } }


What will be the output?
A1 "Constructor1"
A2 "Constructor2"
A3 "Constructor1""Constructor2"
A4 Compiler Errror

Q6 public class Test6{
public Test6()
{
this(4);
}
public Test6(byte var)
{


}
System.out.println(var);
public static void main(String[] args)
{
Test6 t6 = new Test6();
} }


What will be the output?
A1 4
A2 4 4
A3 Compiler Error
A4 Compiles and Runs without error

Q7 public class Test7{
public Test7(){}
public Test7(Test7 ref){
this (ref,"Hai");
}
public Test7(Test7 ref,String str)
{
 ref.Test7(str);
 System.out.println("Hi");
}
public void Test7(String str)
{ System.out.println(str); }
public static void main(String[] args){
Test7 t = new Test7();
Test7 t7 = new Test7(t);
 }
}

What will be the output?
A1 HI
A2 hai
A3 Hai Hi
A4 Hi Hai

Q8 Which of the following are valid Constructors?
A1 public Test8(){}
A2 private void Test8(){}
A3 protected Test8(int k){}
A4 Test8(){}

Q9 Which of the following are valid method declarations?

Tuesday, December 14, 2010

Embed Image in email to avoid enabling downlod/display image in outlook, Gmail and other

There are scenarios when we need to send automated mail through our code with an image. Most of the time user has to click on the "display image" or "download image" to view the image in an email.

So, the better way to add the image into an email is to embed it in the email body. Beolw is the steps by which we can achieve this.

1. Following two namespace is to be used.
using System.Net.Mime;
using System.Net.Mail;


We will use "LinkedResource" class available in System.Net.Mail for representing embedded external resource.
To create the object of LinkedResource we need the content of the embedded resource as stream or need the path of that resource and then it is added to the HTML part of AlternateView's LinkedResources collection.

To create an embedded image we will need to first create an HTML view of the email using AlternateView class. Within that alternate view we need to create a tag that points to the ContentId (cid) of the LinkedResource of the image view as shown below:

//creating LinkedResource object with passing the path to the image to its constructor.
LinkedResource lrImage = new LinkedResource(Server.MapPath("images") + "\\" + "newsletter.gif");

//Set the content ID for the LinkedResouce object
        lrImage.ContentId = "newsletter";       

        string strmail = "";
        strmail = strmail + "";
        strmail = strmail + "";       
        strmail = strmail + "";
        strmail = strmail + "";
        strmail = strmail + "
";

 //add the image at the desired place using contentId(cid). BY default linkedResource ContentId is used    as cid:contentId. In our case the content id is "newsletter" so the image source would be the way as written below:
        strmail = strmail + "";
        strmail = strmail + "
";
        strmail = strmail + "";

// Now we need to create a Alternate view for the strmail.

 AlternateView av = AlternateView.CreateAlternateViewFromString(strmail, null, MediaTypeNames.Text.Html);
//now add the lrImage LinkedResource object to Alternate view
av.LinkedResources.Add(lrImage);

Now our "strMail" is ready to be send as email body.



 

Thursday, February 4, 2010

ASP.NET Web PartsAS


ASP.NET Web Parts controls are an integrated set of controls for creating Web sites that enable end users to modify the content, appearance, and behavior of Web pages directly in a browser. The Web Parts control set consists of three main building blocks:  
  1. Personalization,
  2. User interface (UI) structural components, and
  3. Actual Web Parts UI controls.

  1. Personalization: Web Parts use a Personalization Provider.  This is so users that visit the site get a different perspective, depending on their personalization.  One user might want a red background while another might want blue.  This is their personalization, and it is stored in a database. By default, Web Parts are configured to use Sql server 2005 Express edition. For another version of Sql server 2005, there are few things which we must do to make it work smoothly.

First of all, we need to create a personalization database named aspnetdb. By default, Web Parts look for this database to keep the user personalization information. In order to do this, we must use the 'aspnet_regsql.exe' wizard.  Browse out to '%windir%\Microsoft.NET\Framework\' and run this command.  Once the wizard is up, choose to 'Configure SQL Server for application services'.  Select the correct server name (if using a named instance, be sure to include the server and named instance, such as 'fileserver\sql2k5instance').  If using SQL Server authentication, put in your username and password.  Select the database that will serve as your personalization database.  Now database is set up for membership and personalization.
   
  Now add a connection string to Web.config file with the key name ‘localSqlServer’. 
 <connectionStrings>
          <remove name="LocalSqlServer"/>
          <add name="LocalSqlServer" connectionString="Server=G01BR1P264; Database=aspnetdb; Integrated Security=SSPI; MultipleActiveResultSets=true;"providerName="System.Data.SqlClient"/>
    connectionStrings> 
   
  The name of the connection string is important, as Web Parts look by default for a connection string named 'LocalSqlServer'.  The data source is equally important and should reflect our database instance (be sure to include the name if using a named instance).  Since I have set up the 'aspnetdb' database as my personalization database, this will be what I use as the Initial Catalog.  Also, since only SQL Server 2005 Express Edition supports User Instances, I will set this property to 'false'. 
    Apart from these, either you have to user Window Authentication or Form Authentication. 
    Window Authentication: To use Window Authentication, Add the following to the Web.config. 
   <authentication mode="Windows">authentication> 
     Also, open the Inet Manger of your server, point to your website and open properties. Under the Directory security tab click on ‘Edit’ Anonymous access and Authenication control. 

Your browser may not support display of this image.


     Uncheck the Anonymous Access and check mark the integrated Windows authentication.  
Form Authentication: To use Form Authentication, Add the following in the web.config 
<authentication mode="Forms">
<forms name=".ASPXAUTH" loginUrl="Login.aspx" defaultUrl="Home.aspx" cookieless="UseUri" />
      authentication> 
Here loginUrl will be your login page name and defaultUrl will be your Home Page. Cookieless is the option property,  if false, a cookie will be saved to a user machine.
Now we have to user the FormAuthentication class and it’s static member to add the user as authenticated. 
For example: suppose we have another database where we keep the user list and their login credentials. 
Add the connection string information of this database also to web.config. During login process, check the user input against the duser credentials store in a database table. If it is true then redirect user to home page using  
FormsAuthentication.RedirectFromLoginPage(UserName, false); 
This is a static method of the FormAuthentication Class which add the user to authenticated list and redirect to default page mentioned in a web.config.
Now we can whether user has been authenticated or not by 
HttpContext.Current.User.Identity.IsAuthenticated Which return true in case of authenticated user. 
There is one another method which is used to make user log out. 
FormsAuthentication.SignOut(); 
  1. User interface (UI) structural components: 

Deploying Reports on the server programmatically

 SSRS provides 3 ways to deploy the reports on the server. 
  • Using the BI Development studio.
  • Using the SQL Server Management Studio
  • Programmatically ( using RS.EXE utility)
The first two options provide a very simple and easy way of deployment. But there are some cases where these options won’t work. For example if you want to deploy the report on the server that’s not directly accessed from your network/domain.
The only option to deploy the report in this scenario is deploying reports programmatically.
RS.EXE is a Command-line utility which is used to perform deployment and other administrative task programmatically. This RS.EXE utility expects a file with the extension .RSS which is usually written in VB.NET. The RS file will contain script to create Report folder on the server, to create Report Data Source and to publish the reports as well. 
Steps:
  1. Copy all the RDL file and RS file to server where you want to deploy the reports. Please note that all the RDL files and RS file (script file) needs to placed in the same folder.
  2. Open the command prompt and type the following command to execute the script:
    For example if you have all the files on a location “D:\Reports”  

This command will read the script from the” FileName.rss” file and create a report folder for you, report data source and publish all the reports you have mentioned in the file.
Below is the code for your RSS file.
Dim ReportSource As String
Public Sub Main()
TRY
  ReportSource = "D:\Reports"    ‘Path of the folder where script and reports file are located 
     rs.Credentials = System.Net.CredentialCache.DefaultCredentials      
     
    If rs.GetItemType("/Reports") = Microsoft.SqlServer.ReportingServices2005.ItemTypeEnum.Folder Then   
          rs.DeleteItem("/Reports")      ‘Deleting the report folder if already exists
    End If
        
    rs.CreateFolder("Reports", "/", Nothing)    ‘Creating the Report folder            
    Console.WriteLine("Parent folder [Reports] created successfully.")
       
    CreateReportDataSource("Reports", "SQL", "Data Source=(local);Initial Catalog=DataBaseName")    ‘Creating the Report data source
    PublishReport("MyReport")    ‘publishing reports with the name MyReport.rdl’
   
‘Note: you can publish as many reports you want, just keep adding ‘PublishReport(ReportName) method here,
   
    Console.WriteLine("Tasks completed successfully.")
CATCH  ex As Exception
   THROW ex
END TRY
End Sub
Public Sub CreateReportDataSource(name As String, extension As String, connectionString As String)
    'Data source definition.
    Dim definition As New DataSourceDefinition()
    definition.CredentialRetrieval = CredentialRetrievalEnum.Integrated
    definition.ConnectString = connectionString
    definition.Enabled = True
    definition.Extension = extension
   
      TRY 
            rs.CreateDataSource(name, "/Reports", False, definition, Nothing)   
          Console.WriteLine("Data source: {0} created successfully.", name)
      CATCH e As Exception
            Console.WriteLine("ERROR creating data source: " + name)
            THROW e
      END TRY
   
End Sub 
Public Sub PublishReport(ByVal reportName As String) 
TRY
    Dim stream As FileStream = File.OpenRead(ReportSource + "\" + reportName + ".rdl")
    definition = New [Byte](stream.Length) {}
    stream.Read(definition, 0, CInt(stream.Length))
    stream.Close()

   
    rs.CreateReport(reportName, parentPath, False, definition, Nothing)  
    Console.WriteLine("Report: {0} published successfully.", reportName)        
CATCH e As Exception
      Console.WriteLine("ERROR while Publishing report: " + reportName)
      THROW e
END TRY
End Sub

Monday, November 16, 2009

How to add a Menu Navigation Bar with hyper links at the top in a blogger blog with new XML template?

A blog does have a blogger navigation bar at the top but lacks a MENU BAR with links to your own blog or any other link with your own choice links, as we see in many websites.  http://codezila.blogspot.com/


This helps in easy navigation across your blog/site. The reader will have a wide variety of choice and will stay on your site or blog for a longer time. This also helps in categorizing your blog posts according to their category or genre. http://codezila.blogspot.com/

Follow the following steps and its all done... very easy indeed.
 http://codezila.blogspot.com/


  1. Login to your blogger account and go to LAYOUT & then  PAGE ELEMENTS (default) 
  2. Now click on EDIT HTML  and  check " 
  3. Use Browser Text Search Feature using shortcut "Ctrl+F" and type in "Inner layout" to find "/* Inner layout */" inside ""
  4. Paste the following code after "/* Inner layout */" :
  5. /****** Top Navigation ******/
    #topnav {width: 100%; 
       height: 20px;
       text-align: right;
       font-size: 0.7em;
       color: #999999;
       float: right; }
       
    #topnav img {
       border: none; 
       padding: 5px; }
    
    
    /****** Navigation ******/
    #navigation {
       width: 100%;
       background: 
    url(http://1.bp.blogspot.com/_3SdVQe5mP8U/Sssg9YVGb_I/AAAAAAAALfE/7QSG50RJYnM/s320/menu_button.JPG) repeat-x;
       height: 35px;
    /*   border-top: ##58b2eb solid 1px; */
       margin-bottom: 2px;}
    #navbar_link {
       height: 34px;
       float: left; }
    #navigation #navbar_link ul {
       float: left;
       height:34px;
       width: 100%;
       list-style-type: none; }
    #navigation #navbar_link ul li {
       display: inline; }
    #navigation #navbar_link ul li a {
       padding: 0px 15px;
       color: #ffffff;
       text-decoration: none;
       line-height: 1.7em;
       float: left;
       border-right: 2px solid #0c5684;
       text-decoration: none;
       font-size: 1em;
       font-weight: bold;
      }
    
    #navigation #navbar_link a:hover { 
       text-decoration: none; 
       border-right: 1px solid #0c5684;
       color: #FFFFFF;
    background: #ddd 
    url(http://2.bp.blogspot.com/_3SdVQe5mP8U/Sssf0YtHOyI/AAAAAAAALe8/H9Gh5b9Dn90/s320/menu_button.JPG) repeat-x;
    }
       
    .1ST a {
    background:  url(http://2.bp.blogspot.com/_3SdVQe5mP8U/Sssel0xFZRI/AAAAAAAALe0/Mm9U_ETVHeQ/s320/menu_button.JPG) repeat-x; 
    }
    
    
  6. Now Uncheck " " at the top right.
  7. Use Browser Text Search Feature using shortcut "Ctrl+F" and type in "header-wrapper" to find
    div id="header-wrapper"
  8. Now before this header div ends , paste the following code after /b:section



    <!--navigation links-->
    <div id='navigation'>
          <div id='navbar_link'>
            <ul>
               <li class='1ST'><a expr:href='data:blog.homepageUrl'>Home</a></li>
               <li><a href='url1'>Link Title</a></li>
               <li><a href='url2'>Link title2</a></li>
               <li><a href='url3'>link title 3</a></li>
    
    <!-- add as many links as you want -->
    
            </ul>
          </div><!-- end of navbar_link -->
          </div><!-- end of navbar -->
    


  9. Replace the url1/url2/... with your own links and Link Title1/2/3.... with your link title.
  10. Save the Template. Its All Done. You can see the green navigation bar as shown above.
  11. Having problem with the code? feel free to ask through below comment area.
  12. enjoy a new look to your blog or site.

Friday, November 6, 2009

How to add adsense ads just after the post title and after Post Ends in blogs.

It is always beneficial to show the ads just after the post title before the real content starts. But by default the ads are shown either in the sidebar or after the comment link at the bottom of the post. So many a time your visitors did not even give a look to the ads which is not desirable.
So what to do to make the adsense ads come just after the post Title and at the post bottom before the Comments or reaction buttons or anything else.

Follow the following steps and its all done... very easy indeed.


  1. Login to your blogger account and go to LAYOUT >> PAGE ELEMENTS (default) 
  2. Click on EDIT in BLOG POSTS (a pop-up window "configure blog posts" will open)
  3. Check the radio button  "SHOW ADS BETWEEN POSTS" at the last of "Post Page Option" in the pop-up.
  4. Scroll down and click on Ok (you can edit the colour of the ad displayed, its better to match the ad colour to your blog colour especially ad background and border must be same as blog background colour)
  5. Save the template by clicking on the BLUE button at the top right.
  6. Now click on EDIT HTML >> check " 
  7. Use Browser Text Search Feature using shortcut "Ctrl+F" and type in "adcode" to find <adcode> just after the comment section.
  8. Then add "!" before adcode like <!--adcode--> (this makes the defalut adcode as a comment for the browser and it will ignore it while interpreting the codes)
  9. Then Find  "<data:post.body/>" using "Ctrl+F".
  10. After and Before "<data:post.body/>" paste this code:
  11. <b:if cond='data:post.includeAd'>
    <data:adEnd/>
    <data:adCode/>
    <data:adStart/>
    </b:if> 
    
  12. Save the Template. Its All Done. Now after every each post title your ad will be shown and at the bottom also. To edit the type of ad size and colour see point 4. But its better to use a square size ad format.
  13. Best of Luck. Happy earning.
NOTE: Always Save your template before editing your HTML codes.