27 September 2013

Chat using WCF

Hi Friends,

Let see how can we create Chat app using WCF.  This is the basic app we can modify a lot in this sample project.  Its just a sample. You can download the sample from here.

1.  First create the WCF Services Library project in Visual Studio and give a name (FirstWCF).


2. Delete the pre-created files IServices1.cs and Services.cs
3. Add a class into project and named it (Message) and paste the following code. I will use it as a message object to communicate and transfer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

namespace FirstWCF
{
  [DataContract]
  public class Message
  {
     [DataMember]
     public string toUser;
     [DataMember]
     public string fromUser;
     [DataMember]
      public string msg;
  }
}
4. Add another class into project and named it (ISendMsg) and make it interface by paste the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace FirstWCF
{
  [ServiceContract]
  public interface ISendMsg
  {
     [OperationContract]
     string SendMsg(Message msg);
     [OperationContract]
     List getAllMsg(string toUser);
     [OperationContract]
     List getSentItem(string fromUser);
     [OperationContract]
     string DeleteMsgFrom(string fromUser, string toUser);
  }
}
5. Add another class into project and named it(MsgCollection), it implement the interface defined in previous step.  I implement the method define in interface. Paste the following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace FirstWCF
{
  [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
  class MsgCollection:ISendMsg
  {
  List<Message> AllMsgs = new List<Message>();
  public string SendMsg(Message msg)
  {
      try
      {
        AllMsgs.Add(msg);
        return "Message Send Successfully..!!";
      }
      catch (Exception e)
      {
        return "Message Failed..!!";
      }
    }

    public List<Message>  getAllMsg(string toUser)
    {
      List<Message> filterMsgs = new List<Message>();
      foreach (Message msg in AllMsgs)
      {
        if(msg.toUser.Equals(toUser))
        {
          filterMsgs.Add(msg);
        }
      }
      return filterMsgs;
    }

    public List<Message> getSentItem(string fromUser)
    {
      List<Message> filterMsgs = new List<Message>();
      foreach (Message msg in AllMsgs)
      {
        if (msg.fromUser.Equals(fromUser))
        {
          filterMsgs.Add(msg);
        }
      }
      return filterMsgs;
    }

    public String DeleteMsgFrom(string fromUser, string toUser)
    {
      try
      {
        AllMsgs.RemoveAll(e => (e.fromUser.Equals(fromUser) && e.toUser.Equals(toUser)));
        return "Message deleted successfully..!!!";
      }
      catch (Exception e)
      {
        return "Deleting message failed..!!!";
      }
    }    
  }
}
6.  Now you can run it, but it will open a client provided by Microsoft to test the WCF apps. But I would say to design you own client and use that to test this chatting application.
7. Right click the project solution file in project explorer in Visual Studio and Add -> Project->Console Application give name (ClientForFirstWCF) to project and click OK.
8. Now you need to add the reference of WCF you created, for that you must know the metadata exchange URL. You can get it from the App.config file under the FirstWCF project you created.
..
..
<host>
  <baseAddresses>
    <add baseAddress="http://localhost:8732/Design_Time_Addresses/FirstWCF/Service1/" />
  </baseAddresses>
</host>
..
..
get this baseAddress and add "mex" at all this would be your metadata exchange URL
http://localhost:8732/Design_Time_Addresses/FirstWCF/Service1/mex
9. Now we need to add reference of this WCF to the client project we created in Step 7.
   Right click ClientForFirstWCF project and say 'Add Service Reference' and provide the URL of metadata exchange we found in previous step. Select the Service found on that URL and click Ok.
10. Open Program.cs file of client project and overwrite with following content.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClientForFirstWCF.MsgCollectionServices;

namespace ClientForFirstWCF
{
  class Program
  {
    static string loginName = "";
    static SendMsgClient client = new SendMsgClient("WSHttpBinding_ISendMsg");
    static void Main(string[] args)
    {
      try
      {
        client.Open();      
        int choice=0;
        bool flag = true;
        do
        {
          Console.Clear();
          Console.WriteLine("--------- WCF messaging --------");
          Console.WriteLine("");
          Console.Write("Enter Your name : ");
          loginName = Console.ReadLine();
        } while (loginName.Length == 0);
      
        while (flag)
        {
          Console.Clear();
          Console.WriteLine("--------- WCF messaging --------");
          Console.WriteLine("Hello " + loginName);
          Console.WriteLine("");
          Console.WriteLine("Enter You Choice..");
          Console.WriteLine("1. Compose");
          Console.WriteLine("2. Inbox");
          Console.WriteLine("3. Sent Item");
          Console.WriteLine("4. Delete Messages");
          Console.WriteLine("5. Exit");
          Console.Write("Your Choice : ");
          try
          {
            choice = int.Parse(Console.ReadLine());

            switch (choice)
            {
              case 1:
                SendMsg();
                break;
              case 2:
                ReadMsg();
                break;
              case 3:
                SentItem();
                break;
              case 4:
                DeleteMsg();
                break;
              default:
                flag = false;
                break;
            }
          }
          catch (Exception e)
          {
          }          
        }

        client.Close();
      }
      catch (Exception e)
      {
        Console.WriteLine("Sorry.!!WCF is down. Please set it up and running.");
        Console.ReadKey();
      }      
    }

    static void SendMsg()
    {
      Message msg = new Message();
      msg.fromUser = loginName;
      msg.toUser="";
      msg.msg = "";
      do
      {
        Console.Clear();
        Console.Write("To : ");
        msg.toUser = Console.ReadLine();
      } while (msg.toUser.Length == 0);
      
      do
      {
        Console.Write("Content : ");
        msg.msg = Console.ReadLine();
      } while (msg.msg.Length == 0);

      //sending message 
      Console.WriteLine(client.SendMsg(msg));
      Console.ReadLine();
    }


    static void ReadMsg()
    {
      Console.Clear();
      Message []all = client.getAllMsg(loginName);
      foreach (Message msg in all)
      {
        Console.WriteLine("From :"+msg.fromUser);
        Console.WriteLine("Content :"+msg.msg);
        Console.WriteLine();
      }
      Console.ReadLine();
    }

    static void SentItem()
    {
      Console.Clear();
      Message[] all = client.getSentItem(loginName);
      foreach (Message msg in all)
      {
        Console.WriteLine("To :" + msg.toUser);
        Console.WriteLine("Content :" + msg.msg);
        Console.WriteLine();
      }
      Console.ReadLine();
    }

    static void DeleteMsg()
    {
      string fromUser="";
      do
      {
        Console.Clear();
        Console.WriteLine("Delete the message came from User");
        Console.Write("Enter the User Name : ");
        fromUser = Console.ReadLine();
      } while (fromUser.Length == 0);
      
      Console.WriteLine(client.DeleteMsgFrom(fromUser, loginName));
      Console.ReadLine();
    }
  }
}
11. Now if you try to run the WCF project it will again open the default Microsoft client, so you have to assign your own client. Select your WCF project -> right click -> Properties -> Debug and change the command line argument
/client:"../../../ClientForFirstWCF/bin/debug/ClientForFirstWCF.exe"

12. Congratulation you have created the chat app using WCF. Its basic chat you can still modify it.

You can download the sample from here.
Output - 
When I start two client (deepak and gaurav)to communicate to each other (send/receive message)

When first client(deepak) send the message to second client(gaurav)


When second client(gaurav) check his Inbox

Happy Coding.. :)


24 September 2013

Programmatically get Java (JRE) version

Hi Friends,

Lets see how to get the installed jre programmtically.

See consider if we have installed more than 1 jre then get to know which
JRE my program referring.  Or you want to set up a conditional statement which checks for installed jre and execute accordingly.

public class JreVersion
{
     public static void main(String[] args)
     {  
         // return the jre version e.g. 1.7
         String version = System.getProperty("java.version");

         if(Float.parseFloat(version.substring(0,3)) > 1.6f)
         {
             MyDialog md = new MyDialog();
             /* do your code here.. */ 
         }
         else
         {
             String msg = "Please installed the JRE 1.7 or higher";
             JOptionPane.showMessageDialog(null, msg);
         }  
     }
}
some time we need this statement because our code is only supported in JRE higher then X.X so we need to get the version of JRE installed at client machine at run time..

Happy knowledge sharing.. :)


23 September 2013

Download - Uploading in JSP - Servlet with MySql DB

Hello Friends,

Lets see how can we code to upload and download file in JSP and Servlet.  Here I am using the database MySql.  I'm saving the file in database directly, I used the Medium Blob to store the file in database. Remember as I'm using medium blob(Max. size=16 MB) so I am considering we will upload a file with maximum size 15 MB.

By default MySql packet size is 1 MB so to support the uploading for 15 MB file, we need to change a attribute in my.ini file.

MySql installed directory > bin > "my.ini" file
search for "max_allowed_packet" you will find a line with value "1M" change to "15M"
max_allowed_packet =  1M 

max_allowed_packet = 15M
Now your MySql server is capable to transfer a big data packet to server size upto 15MB.

Create the table to store the document in MySql server
CREATE TABLE IF NOT EXISTS 'documents' (
  'Doc_id' int(11) NOT NULL AUTO_INCREMENT,
  'FileName' varchar(100) NOT NULL,
  'type' varchar(20) NOT NULL,
  'upload_time' timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  'content' mediumblob NOT NULL,
  'upload_by' varchar(50) NOT NULL,
  PRIMARY KEY ('Doc_id')
)


Lets code for first index page which is used to select the file to upload..
Index.html
<form enctype="multipart/form-data" action="uploadfile.jsp" method="post" onsubmit="return verify()">      
<table border='1'>
<tr>
   <td>   
      Remember you can upload only MS-word, MS-Excel, txt and PDF files.max size = 15mb       
   </td>
</tr>
<tr>
   <td>
      <input type="file" name="filename" id="filename"
      accept=".txt,
           application/pdf,
           application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,
           application/vnd.ms-excel,
           application/vnd.openxmlformats-officedocument.wordprocessingml.document,
           application/msword"/>                                                            
   </td>
</tr>
<tr>
   <td>
      <input type="submit" value="Save File" />
   </td>
</tr>
</table>
</form>
Code for uploadfile.jsp file which is used to get the select file and upload it to server.
uploadfile.jsp
<%
String rtempfile = File.createTempFile("temp","1").getParent(); 

// get the file from the previous page form           
// save the file in temporary directory of server
// specify the max size = 15MB
MultipartRequest multi = new MultipartRequest(request,rtempfile, 15*1024*1024);

Enumeration files = multi.getFileNames();

String st="insert into documents(filename, type,content, upload_by) values (?,?,?,?)";

// get the connection object from another class MyConnection's method getConnection();
// and create the prepareStatement
PreparedStatement psmt=MyConnection.getConnection().prepareStatement(st);

         
String name="";
String fileExtesion="";
File ff =null;
FileInputStream fin =null;

while (files.hasMoreElements())
{
   name=(String)files.nextElement();                                        
   ff = multi.getFile(name);
   fileExtesion = ff.getName().substring(ff.getName().lastIndexOf("."));
   
   // check user has select the correct file or not
   boolean fileAllowed = fileExtesion.equalsIgnoreCase(".txt")||
                         fileExtesion.equalsIgnoreCase(".pdf")||
                         fileExtesion.equalsIgnoreCase(".doc")||
                         fileExtesion.equalsIgnoreCase(".docx")||
                         fileExtesion.equalsIgnoreCase(".xls")||
                         fileExtesion.equalsIgnoreCase(".xlsx");
   
   if((ff!=null)&&fileAllowed)
   {
     
     try
     {
       fin=new FileInputStream(ff);
       psmt.setString(1, ff.getName());
       psmt.setString(2, fileExtesion);
       psmt.setBinaryStream(3,(InputStream)fin, (int)(ff.length()));
       psmt.setString(4, "Logged User name or ID");        // pass the user name or id 
       boolean sss = psmt.execute();
       
       out.print("uploaded successfully..");
       out.print("<br/> Go to <a href='downloadfile.jsp'>Download</a> page");
     }
     
     catch(Exception e)
     {
       out.print("Failed due to " + e);
     }
     
     finally
     {
      // next statement is must otherwise file will not be deleted from the temp as fin using f.
      // its necessary to put outside otherwise at the time of exception file will not be closed.
           fin.close();
           ff.delete();
     }
   }
   else
   {
         out.print("Please select the correct file...");
   }// end of if and else
}// end of while

MyConnection.CloseConnection();     // close the connection
%>

get the list of the uploaded file and link to download the file.
downloadfile.jsp
<table border="1">
  <tr>
    <th>File Name</th>
    <th>Uploaded By</th>
    <th>File Type</th>
    <th>Upload Time</th>
    <th>Action</th>
  </tr>
<%
  String query = "select doc_id,filename,type, upload_time, upload_by from documents";
  ResultSet rs = MyConnection.getResultFromSqlQuery(query);
  int count =0;
  while(rs.next())
  {
    out.println("<tr>"
        + "<td>"+rs.getString(2)+"</td>"
        + "<td>"+rs.getString(5)+"</td>"
        + "<td>"+rs.getString(3)+"</td>"
        + "<td>"+rs.getString(4)+"</td>"
        + "<td>"
        +   "<a href='download.jsp?Doc_id="+rs.getInt(1) +"'> Download </a>"
        + "</td>"
        + "</tr>");
    count++;
  }
  rs.close();
  MyConnection.CloseConnection();
  if(count==0)
  {
    out.println("<tr><td colspan='4'> No File Found..!! </td></tr>");
  }
%>            
</table>
This page will give you the list of the file uploaded by any user with few details and a link to download the file from server.  As file is saved in database in blob so we have to create the file from blob and have to send it to client.

Lets see the code which extract the information from database and send the file to client.
download.jsp
<%
  String doc_id = request.getParameter("Doc_id");     
  String query = "select filename, type, content from Documents where doc_id = " + doc_id;
  ResultSet rs = MyConnection.getResultFromSqlQuery(query);
  rs.next();
  
  // clear the response header information.
  response.reset();                        
  // check the file type and set the header contentType accordingly..   
  if(rs.getString(2)==".txt")
  {
      response.setContentType("application/octet-stream");
  }
  else if(rs.getString(2)==".pdf")
  {
      response.setContentType("application/pdf");
  }
  else if((rs.getString(2)==".doc")||rs.getString(2)==".docx")
  {
      response.setContentType("application/msword");
  }
  else if((rs.getString(2)==".xls")||(rs.getString(2)==".xlsx"))
  {
      response.setContentType("application/vnd.ms-excel");
  }
  // add header information to response object
  response.addHeader("Content-Disposition","attachment; filename="+rs.getString(1));
  // create the byte array from Blob
  Blob blb = rs.getBlob(3);
  byte[] bdata = blb.getBytes(1, (int) blb.length());
  
  // get the response Output stream object to write the content of the file into header
  OutputStream output =  response.getOutputStream();
  output.write(bdata);
  output.close();
  // close the obejct of ResultSet
  rs.close();
  
  // close the connection object.. 
  MyConnection.CloseConnection(); 
%>

Remember you have to create the table document as specified at top.

You need to change the MyConnection class.  Provide you database credentials.
MyConnection.java
public class MyConnection
{    
  static Connection con;
  public static Connection getConnection()
  {
    try
    {            
      if(con==null)
      {
        Class.forName("com.mysql.jdbc.Driver");  
        String url = "jdbc:mysql://localhost:3306/Your_DB_Name?"+
                     "user=db_user&password=user_password";
        con= DriverManager.getConnection(url);
      }
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }        
    return con;
  }
  
  public static void CloseConnection()
  {
    try
    {
       con.close();
       con = null;
    }
    catch (SQLException e)
    {
       e.printStackTrace();
    } 
  }
  
  public static ResultSet getResultFromSqlQuery(String SqlQueryString)
  {
     Statement stmt;
     ResultSet rs = null;
     try
     {  
        getConnection();  
        stmt = con.createStatement();
        rs = stmt.executeQuery(SqlQueryString);
     }
     catch (SQLException e)
     {
        e.printStackTrace();
     }       
     return rs;
  }
}
To make it work you also required two jar files-
1. MySql Connector jar file download
2. Another jar file to handle the uploading download
you need to add the reference of these two files into your project.

You can download the netbeans sample project. Download


Happy Coding..

19 September 2013

Life time IDM (Internet Download Manager)

Hello Friends,
Lets crack the IDM.  IDM is the tool generally we all are aware with. Its Internet Download Manager used to download the file with higher speed from internet. You can download the trial version from its official site click here. To continue use the IDM you have to register or purchase its license from Internet download manager site. It will cost you around $30.00 bucks, but that is again not for life time its for limited period of time. IDM is really a nice tool for downlaod purchase. But purchasing IDM is against Rule and definitely you also don't want to purchase it if you can get it free of cost. :)



You need to download the IDM Life Time Tool and Internet Download Manager(IDM), if you downloaded or installed. You can download these two from below links. -

IDM version 6.17 from here
IDM Life Time tool from here   - you need to extract it as its rar file use the password "MyTacticks" I will suggest you to disable your Antivirus while applying patch, as few antivirus may detect it as infected file. Its because this tool extract the information of IDM to apply the patch.

Steps -
1- Download and install the IDM. (You can download from above link)
2- Download Life time tool from above link.
3- Disable you AV for a while till you are applying the patch.
4- Extract life time tool.  Use the password  MyTacTics to extraction.
5- Run the file "IDMCrackForLife.exe" it will extract the few information about the IDM from you system.


6. In your system, you will get "Trial" at the place of "Full".
7. Now you just need to run it by clicking the button "Start".
8. After few seconds you will get a message that registration successful.
9. Open you IDM and see its registered with the name "Deepak.Sharma" in my case.  Or the user name you loggedin in your system.  You can change the name by unchecking the "Auto" checkbox.


10- See the registration tab is disabled thats mean IDM is already registered.

Happy Cracking.. :)


12 September 2013

Sql Server 2005 and 2008/R2 Connection string in Java

Hi Friend,

Let see how to connect to SQL Server 2005 and 2008/R2 in Java.  To establish a connection you need a jar file and an authentication dll file.

You can download both file as zip format from here.


package mssql_connection; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class MsSql_Connection { public static void main(String[] args) { String url = "jdbc:sqlserver://localhost\\SQLEXPRESS;databaseName=testing;integratedSecurity=true;user=user_testing;password=user_password;"; try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection con = DriverManager.getConnection(url); Statement smt = con.createStatement(); ResultSet result = smt.executeQuery("select * from Table_1"); while(result.next()) { System.out.println(result.getInt(1)); System.out.println(result.getString(2)); } System.out.println("done"); } catch(Exception e) { e.printStackTrace(); } } }

Note --

You require two files -
   1. sqljdbcX.jar (X - version)
   2. sqljdbc_auth.dll

You can download from here.

See the image. These highlighted file and folder are required to create connection with Sql Server.

Required_jar is the folder contains a jar file. We need to add the reference of this jar file only to the project.

You can download a sample netbeans project from below given link.


Download NetBeans sample project from here.

Happy Knowledge sharing.. :)


11 September 2013

IIS7 : An error occurred on the server when processing the URL. Please contact the system administrator

Hello Friends,

If you have worked with Classic ASP with IIS5 or IIS6, that is easy to recognize the error occurred in code.  IIS send the error information to client which show the file name, line no. and other information to understand where and what error occurred.  But now a days if you use IIS7 and trying to publish your classic ASP web application in IIS7, you may see a message like -

An error occurred on the server when processing the URL. Please contact the system administrator

After investigating a bit here and there I find out because scriptErrorSentToBrowser by default is false in IIS7 so we are unable to get the proper error message.  We need to change the default value(false) to true for the scriptErrorSentToBrowser flag in IIS7. Here is how to change it -

Open your cmd prompt "As Administrator" and run the following command -

%windir%\system32\inetsrv\appcmd set config -section:asp -scriptErrorSentToBrowser:true

now you'll be able to see the proper error message. I would suggest you to set the flag to false after debugging because sometimes it shows very critical imp details to end user that can be harmful. You can use the same command just replace the 'true' by 'false'

%windir%\system32\inetsrv\appcmd set config -section:asp -scriptErrorSentToBrowser:false

Happy knowledge sharing.. :)


10 September 2013

MySql connection string to connect with MySql database in Java


Hi Friends,

Lets see how to use the mysql connector jar file to create the connection with MySql database in Java.
As MySql is freeware sometime we think about to use the MySql with our Java application but we get failed to create the connection with MySql db.

You need to add the reference of mysql connector jar file to your project to create the connection with MySql database. You can download this connector jar file from here.

You can also download the net-beans MySql connection sample project from here. Its a zip file just extract it and Net Beans project is ready.

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package mysqlconnection; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; /** * * @author DeepakSharma */ public class MySqlConnection { /** * @param args the command line arguments */ public static void main(String[] args) { try { Class.forName("com.mysql.jdbc.Driver"); /** * TODO you need to provide the db user to access db * and the password of that user */ Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/YOUR_DB?user=db_user_name&password=db_user_password"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from tableA"); while(rs.next()) { // TODO database login goes here System.out.println(rs.getInt(1) +"/"+ rs.getString(2)); } System.out.println("done"); } catch (Exception ex) { ex.printStackTrace(); } } }

Happy Coding.. :)

8 September 2013

Print Matrix in Spiral Form (Java)


Hi Friends,

Did you even think to print the matrix in spiral form?? Just try it yourself its interesting to create the algorithm for Spiral form.



Square Matrix
Spiral Matrix
1234
5678
9101112
13141516
  to  
1234
1213145
1116156
1098

Let me explain you an algo to accomplish this task.. (In Java)

class Spiral
{
 public static void main(String args[]) 
 { 
  int n = 4; // matrix size 
  
  int a[][] = new int[n][n];
  int c = 1;
  for (int i = n-1, j = 0; i > 0; i--, j++) 
  {
   for (int k = j; k < i; k++)
   {
    a[j][k]=c++;
   }
   for (int k = j; k < i; k++)
   {
    a[k][i]=c++;
   }
   for (int k = i; k > j; k--)
   {
    a[i][k]=c++;
   }
   for (int k = i; k > j; k--)
   {
    a[k][j]=c++;
   }
  } 
  
  //special case for middle element if value of 'n' is odd
  if (n % 2 == 1)
  {
   a[(n-1)/2][(n-1)/2] = c++;
  }
  
  for(int i = 0; i < n; i++)
  {
   for(int j = 0; j < n; j++)
   {
    System.out.print(a[i][j]+"\t");
   }
   System.out.println();
  } 
 }
}

Just copy paste the above code and save as 'Spiral.java' and compile and run it..

Happy Coding..  :)


1 September 2013

Upload large SQL file in PHPAdmin XAMPP


Hello Friends,

Whats about if we want to import the SQL file in XAMPP PHPAdmin?  By Default we can import the SQL file upto 2 MB only.  But if we want to upload the sql file having size 5MB?



There is a trick to do so.  You can upload a sql file upto 128 MB.  You need to modify a file call php.ini (at the same place where you can find the php.exe file).  You can locate this file at

Xampp_Installed_Directory/php/php.ini

open this file in any text editor and search for 'post_max_size' and 'upload_max_filesize' and change the allocated size to both make them 8MB.  Restart the Apache and try it again, now you will see PHPAdmin  saying you can upload the sql file upto 8MB. :)

post_max_size = 8MB
upload_max_filesize = 8MB


Happy Trick :)


Unable to start the Apache in XAMPP, throwing an error

Hi Friends.

Sometime we face the problem when we installed the XAMPP successfully but when we try to start he Apache using XAMPP control panel.  It throws an error

[Apache]    Error: Apache shutdown unexpectedly.
[Apache]    This may be due to a blocked port, missing dependencies, 
[Apache]    improper privileges, a crash, or a shutdown by another method.
[Apache]    Check the "/xampp/apache/logs/error.log" file
[Apache]    and the Windows Event Viewer for more clues

and if we try to start the Apache using the batch file we get the following error on cmd prompt.

(OS 10048) Only one usage of each socket address (protocol/network address/port)
is normally permitted.  : AH00072: make_sock: could not bind to address [::]:443

(OS 10048) Only one usage of each socket address (protocol/network address/port)
is normally permitted.  : AH00072: make_sock: could not bind to address 0.0.0.0:
443
AH00451: no listening sockets available, shutting down
AH00015: Unable to open logs

Apache konnte nicht gestartet werden
Apache could not be started
Press any key to continue . . .


Because Xampp starts the Apache at port:80 and for secure socket layer it reserve the port:443, if you are getting these error thats mean either port:80 or port:443 or both are used by some other application. Like if we are running IIS which by default use the port:80, if you are running VMWare that use the port:443 for secure connection.  To check it out which port is in used you can run the command

    netstat -aon

it will show you the result of the port used by other applications. see the output of above command in my system

Active Connections

  Proto  Local Address          Foreign Address        State           PID
  TCP    0.0.0.0:135            0.0.0.0:0              LISTENING       864
  TCP    0.0.0.0:443            0.0.0.0:0              LISTENING       2196   
  TCP    0.0.0.0:445            0.0.0.0:0              LISTENING       4
  TCP    0.0.0.0:902            0.0.0.0:0              LISTENING       1048
  TCP    0.0.0.0:912            0.0.0.0:0              LISTENING       1048
  TCP    0.0.0.0:1025           0.0.0.0:0              LISTENING       532
  TCP    0.0.0.0:1026           0.0.0.0:0              LISTENING       948
  TCP    0.0.0.0:1027           0.0.0.0:0              LISTENING       1036
  TCP    0.0.0.0:1028           0.0.0.0:0              LISTENING       652
  TCP    0.0.0.0:1029           0.0.0.0:0              LISTENING       592
  TCP    0.0.0.0:2861           0.0.0.0:0              LISTENING       4
  TCP    0.0.0.0:12025          0.0.0.0:0              LISTENING       1480
  TCP    0.0.0.0:12110          0.0.0.0:0              LISTENING       1480
  .........
  .........
  .........


see port:443 is in used by someother application, in my case as I'm running VMWare which is using this port. So when I try to start Apache it throws in error.

To run the apche you have to change the port in config file.

if port:80 in used

1.  Go to
    Xampp installed directory/Apache/conf
2.  open the file httpd.conf and search for the text "Listen 80", you
    will find the first occurrence around line no. (45-50) change this
    line port from 80 to 8080

   Listen 80 make it Listen 8080


save the file and now try to run Apache

if port:443 is used

1.  Go to
    Xampp installed directory/Apache/conf/extra
2.  open the file httpd-ssl.conf and search for the text "Listen 443",
    you will find the first occurrence around line no. (40-45) change
    this line port from 443 to 1443 (or any other not used port)

   Listen 443 make it Listen 1443

save the file and now try to run Apache

if both port in used, follow the above both file changes..

Remember now you have to open the url in browser would be 
 https://localhost:8080
as we have changed the port from '80' to '8080'

and now run the Apache .. 
Happy knowledge sharing.. :)