Thursday, 30 March 2017

Writing Directories into File & Reading from File C#




sample.aspx
=====================================================

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>


<%

Context.Response.ContentType = "text/plain";

    DirectoryInfo[] cDirs = new DirectoryInfo(@"D:\").GetDirectories();

    StreamWriter sw = new StreamWriter("D:/CDriveDirs.txt", true);
 
        foreach (DirectoryInfo dir in cDirs)
        {
            sw.WriteLine(dir.Name);
            sw.WriteLine("\n");
            Response.Write(dir.Name);
            Response.Write("\n");
       
       }

        sw.Flush();
        sw.Close();
%>
=====================================================

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>


<%

Context.Response.ContentType = "text/plain";

    DirectoryInfo[] cDirs = new DirectoryInfo(@"D:\").GetDirectories();

   
       StreamReader sr = new StreamReader("D:/CDriveDirs.txt");
 
           String line;
               
           while((line=sr.ReadLine())!=null)
           {
         
               Response.Write(line+"\n");
         
           }  
 
        sr.Close();
%>

=====================================================

Friday, 24 March 2017

c#

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>

<%

Context.Response.ContentType = "text/plain";

String directory = "/usr/local/tomcat7/webapps/voices/";

String action = Request.QueryString["action"];
HttpRequest request;

String upload = "upload";
String save = "save";
String delete = "delete";

if (upload==action){
 
    Response.Write("uploading file");
    directory += "temp/";
   
   
   
   
}
 else if (save==action) {

     Response.Write("saving file");
   
     String fileName = Request.QueryString["filename"];
     String language = Request.QueryString["language"];
     String mediaLibrary = Request.QueryString["mediaLibrary"];
     String path= directory + language + "/" + mediaLibrary + "/";

     File.Create(path + fileName);

     FileStream fs = File.Create(path + fileName);
   
 }

 else if (delete==action) {

     Response.Write("deleting file");

     if (File.Exists("test.txt"))
     {
         File.Delete("test.txt");
         if (File.Exists("test.txt") == false)
             Response.Write("File deleted...");
     }
     else
         Response.Write("File test.txt does not yet exist!");
   
   
   
   
 }

 

%>
   
   

%>

Thursday, 23 March 2017

ASP.NET & C#

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%
 
    Context.Response.ContentType = "text/plain";

     String sree = "mobigesture";
     Response.Write(sree);
     
   
%>
----------------------------------------
http://10.10.1.153/voices/sample.aspx
------------------------------------------

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%

Context.Response.ContentType = "text/plain";

String sree = Request.QueryString["test"];
Response.Write(sree);
%>

--------------------------------------------------
http://10.10.1.153/voices/sample.aspx?test=HelloWorld
----------------------------------------------


=================================================================
var dataFile = Server.MapPath("~/Persons.txt");
Array userData = File.ReadAllLines(dataFile);

  foreach (string dataLine in userData)
  {
  foreach (string dataItem in dataLine.Split(','))
  Response.Write(dataItem);
 
  }
 
  =========================================
 
 
  <%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%

Context.Response.ContentType = "text/plain";

var dataFile = Server.MapPath("~/Persons.txt");
Array userData = File.ReadAllLines(dataFile);

  foreach (string dataLine in userData)
  {
  foreach (string dataItem in dataLine.Split(','))
  Response.Write(dataItem);
 
  }
%>

===================================================


<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%
 
    Context.Response.ContentType = "text/plain";


    var names = new List<string>() { "John", "Tom", "Peter" };
    foreach (string name in names)
    {
        Response.Write(name+" \n");
    }
%>

=========================================================

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%
 
    Context.Response.ContentType = "text/plain";


    string[] filePaths = Directory.GetFiles(@"D:\");

    for (int i = 0; i < filePaths.Length; i++)
    {
        Response.Write(filePaths[i]+"\n");
    }
 
%>

====================================================================
<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%
 
    Context.Response.ContentType = "text/plain";

    int caseSwitch = 1;
    switch (caseSwitch)
    {
        case 1:
            Response.Write("Case 1");
            break;
        case 2:
            Response.Write("Case 2");
            break;
        default:
            Response.Write("Default case");
            break;
    }
%>

=====================================================================

Monday, 20 March 2017

HttpClient

Concepts

The general process for using HttpClient consists of a number of steps:
  1. Create an instance of HttpClient.
  2. Create an instance of one of the methods (GetMethod in this case). The URL to connect to is passed in to the the method constructor.
  3. Tell HttpClient to execute the method.
  4. Read the response.
  5. Release the connection.
  6. Deal with the response.

---------------------------------------------

Instantiating HttpClient

The no argument constructor for HttpClient provides a good set of defaults for most situations so that is what we'll use.
HttpClient client = new HttpClient();

Creating a Method

The various methods defined by the HTTP specification correspond to the various classes in HttpClient which implement the HttpMethod interface. These classes are all found in the package org.apache.commons.httpclient.methods.
We will be using the Get method which is a simple method that simply takes a URL and gets the document the URL points to.
HttpMethod method = new GetMethod("http://www.apache.org/");


-------------------

Execute the Method

The actual execution of the method is performed by calling executeMethod on the client and passing in the method to execute. Since networks connections are unreliable, we also need to deal with any errors that occur.

There are two kinds of exceptions that could be thrown by executeMethod, 


HttpException and 


IOException.

HttpException

An HttpException represents a logical error and is thrown when the request cannot be sent or the response cannot be processed due to a fatal violation of the HTTP specification.

IOException

A plain IOException (which is not a subclass of HttpException) represents a transport error and is thrown when an error occurs that is likely to be a once-off I/O problem. 

------------------

Read the Response

It is vital that the response body is always read regardless of the status returned by the server. There are three ways to do this:
  • Call method.getResponseBody(). This will return a byte array containing the data in the response body.

  • Call method.getResponseBodyAsString(). This will return a String containing the response body. Be warned though that the conversion from bytes to a String is done using the default encoding so this method may not be portable across all platforms.

  • Call method.getResponseBodyAsStream() and read the entire contents of the stream then call stream.close(). This method is best if it is possible for a lot of data to be received as it can be buffered to a file or processed as it is read. 


byte[] responseBody = method.getResponseBody();


Release the Connection

This is a crucial step to keep things flowing. We must tell HttpClient that we are done with the connection and that it can now be reused. Without doing this HttpClient will wait indefinitely for a connection to free up so that it can be reused.
method.releaseConnection();

Deal with the Repsonse

We've now completed our interaction with HttpClient and can just concentrate on doing what we need to do with the data. In our case, we'll just print it out to the console.

System.out.println(new String(responseBody));

------------


Final Source Code

When we put all of that together plus a little bit of glue code we get the program below.
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.*;

public class HttpClientTutorial {
  
  private static String url = "http://www.apache.org/";

  public static void main(String[] args) {
    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(url);
    
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
      new DefaultHttpMethodRetryHandler(3, false));

    try {
      // Execute the method.
      int statusCode = client.executeMethod(method);

      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + method.getStatusLine());
      }

      // Read the response body.
      byte[] responseBody = method.getResponseBody();

      // Deal with the response.
      // Use caution: ensure correct character encoding and is not binary data
      System.out.println(new String(responseBody));

    } catch (HttpException e) {
      System.err.println("Fatal protocol violation: " + e.getMessage());
      e.printStackTrace();
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    } finally {
      // Release the connection.
      method.releaseConnection();
    }  
  }
}











---------------------------

Apache HttpClient tutorial

The general process for using HttpClient consists of a number of steps:

  1. Create an instance of HttpClient.
  2. Create an instance of one of the methods (GetMethod in this case). The URL to connect to is passed in to the the method constructor.
  3. Tell HttpClient to execute the method.
  4. Read the response.
  5. Release the connection.
  6. Deal with the response.
---------------------------------------------------------------------------------------------------

In this article, we will show you two examples to make HTTP GET/POST request via following APIs
  1. Standard HttpURLConnection.
  2. Apache HttpClient library.

1. Java HttpURLConnection example

This example uses HttpURLConnection (http) and HttpsURLConnection (https) to
  1. Send an HTTP GET request to Google.com to get the search result.
  2. Send an HTTP POST request to Apple.com search form to check the product detail.
HttpURLConnectionExample.java
package com.mkyong;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class HttpURLConnectionExample {

 private final String USER_AGENT = "Mozilla/5.0";

 public static void main(String[] args) throws Exception {

  HttpURLConnectionExample http = new HttpURLConnectionExample();

  System.out.println("Testing 1 - Send Http GET request");
  http.sendGet();

  System.out.println("\nTesting 2 - Send Http POST request");
  http.sendPost();

 }

 // HTTP GET request
 private void sendGet() throws Exception {

  String url = "http://www.google.com/search?q=mkyong";

  URL obj = new URL(url);
  HttpURLConnection con = (HttpURLConnection) obj.openConnection();

  // optional default is GET
  con.setRequestMethod("GET");

  //add request header
  con.setRequestProperty("User-Agent", USER_AGENT);

  int responseCode = con.getResponseCode();
  System.out.println("\nSending 'GET' request to URL : " + url);
  System.out.println("Response Code : " + responseCode);

  BufferedReader in = new BufferedReader(
          new InputStreamReader(con.getInputStream()));
  String inputLine;
  StringBuffer response = new StringBuffer();

  while ((inputLine = in.readLine()) != null) {
   response.append(inputLine);
  }
  in.close();

  //print result
  System.out.println(response.toString());

 }

 // HTTP POST request
 private void sendPost() throws Exception {

  String url = "https://selfsolve.apple.com/wcResults.do";
  URL obj = new URL(url);
  HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

  //add reuqest header
  con.setRequestMethod("POST");
  con.setRequestProperty("User-Agent", USER_AGENT);
  con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

  String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

  // Send post request
  con.setDoOutput(true);
  DataOutputStream wr = new DataOutputStream(con.getOutputStream());
  wr.writeBytes(urlParameters);
  wr.flush();
  wr.close();

  int responseCode = con.getResponseCode();
  System.out.println("\nSending 'POST' request to URL : " + url);
  System.out.println("Post parameters : " + urlParameters);
  System.out.println("Response Code : " + responseCode);

  BufferedReader in = new BufferedReader(
          new InputStreamReader(con.getInputStream()));
  String inputLine;
  StringBuffer response = new StringBuffer();

  while ((inputLine = in.readLine()) != null) {
   response.append(inputLine);
  }
  in.close();

  //print result
  System.out.println(response.toString());

 }

}
Output
Sending 'GET' request to URL : http://www.google.com/search?q=mkyong
Response Code : 200
Google search result...

Testing 2 - Send Http POST request

Sending 'POST' request to URL : https://selfsolve.apple.com/wcResults.do
Post parameters : sn=C02G8416DRJM&cn=&locale=&caller=&num=12345
Response Code : 200
Apple product detail...

2. Apache HttpClient

This is the equivalent example, but using Apache HttpClient to make HTTP GET/POST request.
HttpClientExample.java
package com.mkyong;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class HttpClientExample {

 private final String USER_AGENT = "Mozilla/5.0";

 public static void main(String[] args) throws Exception {

  HttpClientExample http = new HttpClientExample();

  System.out.println("Testing 1 - Send Http GET request");
  http.sendGet();

  System.out.println("\nTesting 2 - Send Http POST request");
  http.sendPost();

 }

 // HTTP GET request
 private void sendGet() throws Exception {

  String url = "http://www.google.com/search?q=developer";

  HttpClient client = new DefaultHttpClient();
  HttpGet request = new HttpGet(url);

  // add request header
  request.addHeader("User-Agent", USER_AGENT);

  HttpResponse response = client.execute(request);

  System.out.println("\nSending 'GET' request to URL : " + url);
  System.out.println("Response Code : " +
                       response.getStatusLine().getStatusCode());

  BufferedReader rd = new BufferedReader(
                       new InputStreamReader(response.getEntity().getContent()));

  StringBuffer result = new StringBuffer();
  String line = "";
  while ((line = rd.readLine()) != null) {
   result.append(line);
  }

  System.out.println(result.toString());

 }

 // HTTP POST request
 private void sendPost() throws Exception {

  String url = "https://selfsolve.apple.com/wcResults.do";

  HttpClient client = new DefaultHttpClient();
  HttpPost post = new HttpPost(url);

  // add header
  post.setHeader("User-Agent", USER_AGENT);

  List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
  urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM"));
  urlParameters.add(new BasicNameValuePair("cn", ""));
  urlParameters.add(new BasicNameValuePair("locale", ""));
  urlParameters.add(new BasicNameValuePair("caller", ""));
  urlParameters.add(new BasicNameValuePair("num", "12345"));

  post.setEntity(new UrlEncodedFormEntity(urlParameters));

  HttpResponse response = client.execute(post);
  System.out.println("\nSending 'POST' request to URL : " + url);
  System.out.println("Post parameters : " + post.getEntity());
  System.out.println("Response Code : " +
                                    response.getStatusLine().getStatusCode());

  BufferedReader rd = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));

  StringBuffer result = new StringBuffer();
  String line = "";
  while ((line = rd.readLine()) != null) {
   result.append(line);
  }

  System.out.println(result.toString());

 }

}