Saturday, April 11, 2009

Fetching Pages with the HTTP

Fetching Web Pages with HTTPby Joe Mayo, 3/10/02, 9/19/04
IntroductionHTTP is the primary transport mechanism for communicating with resources over the World-Wide-Web. A developer will often want to obtain web pages for different reasons to include: search engine page caching, obtaining info on a particular page, or even implementing browser-like capabilities. To help with this task, the .NET Framework includes classes that make this easy.
Getting an HTTP PageThe HTTP classes in the .NET framework are HTTPWebRequest and HTTPWebResponse. The steps involved require specifying a web page to get with a HTTPWebRequest object, performing the actual request, and using a HTTPWebResponse object to receive the page. Thereafter, you would use stream operations to extract page information. Listing 1 demonstrates how this process works.
Listing 1: Getting a Web Page: WebFetch.csusing System;using System.IO;using System.Net;using System.Text;
/// /// Fetches a Web Page/// class WebFetch{ static void Main(string[] args) { // used to build entire input StringBuilder sb = new StringBuilder();
// used on each read operation byte[] buf = new byte[8192];
// prepare the web page we will be asking for HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://www.mayosoftware.com");
// execute the request HttpWebResponse response = (HttpWebResponse) request.GetResponse();
// we will read data via the response stream Stream resStream = response.GetResponseStream();
string tempString = null; int count = 0;
do { // fill the buffer with data count = resStream.Read(buf, 0, buf.Length);
// make sure we read some data if (count != 0) { // translate from bytes to ASCII text tempString = Encoding.ASCII.GetString(buf, 0, count);
// continue building the string sb.Append(tempString); } } while (count > 0); // any more data to read?
// print out page source Console.WriteLine(sb.ToString()); }}The program in Listing 1 will request the main page of a web site and display the HTML on the console screen. Because the page data will be returned in bytes, we set up a byte array, named buf, to hold results. You'll see how this is used in a couple paragraphs.
The first step in getting a web page is to instantiate a HttpWebRequest object. This occurs when invoking the static Create() method of the WebRequest class. The parameter to the Create() method is a string representing the URL of the web page you want. A similar overload of the Create() method accepts a single Uri type instance. The Create() method returns a WebRequest type, so we need to cast it to an HttpWebRequest type before assigning it to the request variable. Here's the line creating the request object:
// prepare the web page we will be asking for HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://www.mayosoftware.com");Once you have the request object, use that to get a response object. The response object is created by using the GetResponse() method of the request object that was just created. The GetResponse() method does not accept parameters and returns a WebResponse object which must be cast to an HttpWebResponse type before we can assign it to the response object. The following line shows how to obtain the HttpWebResponse object.
// execute the request HttpWebResponse response = (HttpWebResponse) request.GetResponse();The response object is used to obtain a Stream object, which is a member of the System.IO namespace. The GetResponseStream() method of the response instance is invoked to obtain this stream as follows:
// we will read data via the response stream Stream resStream = response.GetResponseStream();Remember the byte array we instantiated at the beginning of the algorithm? Now we'll use it in the Read() method, of the stream we just got, to retrieve the web page data. The Read() method accepts three arguments: The first is the byte array to populate, second is the beginning position to begin populating the array, and the third is the maximum number of bytes to read. This method returns the actual number of bytes that were read. Here's how the web page data is read:
// fill the buffer with data count = resStream.Read(buf, 0, buf.Length);We now have an array of bytes with the web page data in it. However, it is a good idea to transform these bytes into a string. That way we can use all the built-in string manipulation methods available with .NET. I chose to use the static ASCII class of the Encoding class in the System.Text namespace for this task. The ASCII class has a GetString() method which accepts three arguments, similar to the Read() method we just discussed. The first parameter is the byte array to read bytes from, which we pass buf to. Second is the beginning position in buf to begin reading. Third is the number of bytes in buf to read. I passed count, which was the number of bytes returned from the Read() method, as the third parameter, which ensures that only the required number of bytes were read. Here's the code that translates bytes in buf to a string and appends the results to a StringBuilder object.
// translate from bytes to ASCII text tempString = Encoding.ASCII.GetString(buf, 0, count);
// continue building the string sb.Append(tempString);The buffer size is set at 8192, but that is only large enough to hold a small web page. To get around this, the code that reads the response stream must be wrapped in a loop that keeps reading until there isn't any more bytes to return. Listing 1 uses a do loop because we have to make at least one read. Recall that every read() returns a count of items that were actually read. The while condition of the do loop checks the count to make sure something was actually read. Also, notice the if statement that makes sure we don't try to translate bytes when nothing was read. Because we used a loop, we needed to collect the results of each iteration, which is why we append the result of each iteration to a StringBuilder.

Advance Steps to Solve Stego Problems (On Demand)

I have seen that lots of people are demanding algo to implement steganography I have specified in my earlier posts. I can give you steps to do stegano. Coding will be a paid solution for you.

1) Read Source file in Binary format so that you can write into another file till EOF of the first file. Remember that you have to make byte array for that. Which will only allow to use max integer values i.e. 65536.
2) Read File to be embeded in Binary format in the same way you have read earlier file.
Note that it does not matter what file type you are embeding but you have to take all these things into consideration when you retrieve a file from the source file.
3) Implement a keyword to find out that current file is hiding anything or not. You can use encryption for hiding things into it.

Thats all what you need to do steganography when you are speaking about theory algos. But you need an advance coding knowledge to do so in any language.

You can implement this code into any language like JAVA, VB, VB.NET, C# and even in VC++. Thing is you should know how to read data in binary format and how to write data in binary format.

It seems pretty easy for someone but in fact it is not. Everything is easy if you know it.

Complete code is a paid solution from me.

Note that this algorithm can be identified as a MSB Algorithm of the steganography. Because we are using space provided by the source file after the EOF of the source file. Theoritically its different as MSB is used in the Assembly but practically you should read the block till the end of file and each block will be considered as a byte array. So you can write anything in the binary format at the end of the file.

Just wonder what happen when you double click a file after embeding into it?

Thing is Windows is programmed in such a way that when it finds EOF of the file it stops reading it. So it wont read the message after the EOF.

Do remember that you should Encrypt all the things before you actually do steganography.

Retrieving data is the difficult part in any type of steganography. You have to file what is embeded and where it is embeded. We will discuss this algorithm later in another Blog Post.

Want to Contact me for More about this ?

Write your email at Comment section

Starting Processing From C#

IntroductionA C# program can launch another program using the Process class. The Process class is part of the System.Diagnostics namespace. You start another program by instantiating a Process object, setting members of it's StartInfo property, and invoking it's Start() method. Listing 1 shows how to start a process from C#.
Listing 1: Starting a Process: ProcessStart.csusing System;using System.Diagnostics;
namespace csharp_station.howto{ /// /// Demonstrates how to start another program from C# /// class ProcessStart { static void Main(string[] args) { Process notePad = new Process();
notePad.StartInfo.FileName = "notepad.exe"; notePad.StartInfo.Arguments = "ProcessStart.cs";
notePad.Start(); } }}
When the program in Listing 1 runs, it will open the Windows (TM) notepad application in editing mode on the ProcessStart.cs file. The first thing the program does is instantiate a Process object called notePad, an identifier that happens to have the same name as the program that will be executed, as follows:
Process notePad = new Process();
Next, we specify what program will be executed. This happens by assigning the program name to the FileName member of the notePad Process object's StartInfo property. Here's the line from the code:
notePad.StartInfo.FileName = "notepad.exe";
The StartInfo property also has a member called Arguments, which is used to specify command-line options that are passed to the program. In the following example, the string ProcessStart.cs is passed as an argument, so the notepad application will know what file to open when it is executed:
notePad.StartInfo.Arguments = "ProcessStart.cs";
The program is then executed by invoking the Start() method, as shown here:
notePad.Start();
The results of this program are the same as if the instructions below were typed on the command-line:
C:>notepad ProcessStart.cs
SummaryThis article showed how to start a new process from C#. This is handy when you want to launch another program from your application. The example shown, demonstrated how to open the ProcessStart.cs code file with the notepad application.

Reading and writing Text Files in C#

IntroductionText files provide a common denominator format where both people and programs can read and understand. The .NET Framework includes convenience classes that make reading and writing text files very easy. The following sequence outlines the basic steps necessary to work with text files:
Open the file Read/Write to the file Close the file It's that simple. Listing 1 shows how to write text data to a file.
Writing to a Text FileListing 1: Writing Text Data to a File: TextFileWriter.csusing System;using System.IO;
namespace csharp_station.howto{ class TextFileWriter { static void Main(string[] args) { // create a writer and open the file TextWriter tw = new StreamWriter("date.txt");
// write a line of text to the file tw.WriteLine(DateTime.Now);
// close the stream tw.Close(); } }}
This program creates a text file when it runs. In the directory where the executable program is located, you'll find a file named date.txt. If you view the contents of this file, you'll see the following textual representation of the date and time when the program last ran:
2/15/2002 8:54:51 PMThe first task in Listing 1 is to open the file. This happens by instantiating a StreamWriter class, which returns an object of type TextWriter. The result could have also been assigned to a StreamWriter instance. The StreamWriter was called with a single parameter, indicating the name of the file to open. If this file doesn't exist, the StreamWriter will create it. The StreamWriter also has 6 other constructor overloads that permit you to specify the file in different ways, buffer info, and text encoding. Here's the line that opens the date.txt file:
TextWriter tw = new StreamWriter("date.txt");
Using the TextWriter instance, tw, you can write text info to the file. The example writes the text for the current date and time, using the static Now property of the DateTime class. Here's the line from the code:
tw.WriteLine(DateTime.Now);
When you're done writing to the file, be sure to close it as follows:
tw.Close();
Reading From a Text FileListing 2 shows how to read from a text file:
Listing 2: Reading Text Data from a File: TextFileReader.csusing System;using System.IO;
namespace csharp_station.howto{ class TextFileReader { static void Main(string[] args) { // create reader & open file Textreader tr = new StreamReader("date.txt");
// read a line of text Console.WriteLine(tr.ReadLine());
// close the stream tr.Close(); } }}
In Listing 2, the text file is opened in a manner similar to the method used in Listing 1, except it uses a StreamReader class constructor to create an instance of a Textreader. The StreamReader class includes additional overloads that allow you to specify the file in different ways, text format encoding, and buffer info. This program opens the date.txt file, which should be in the same directory as the executable file:
Textreader tr = new StreamReader("date.txt");
Within a Console.WriteLine statement, the program reads a line of text from the file, using the ReadLine() method of the Textreader instance. The Textreader class also includes methods that allow you to invoke the Read() method to read one or more character or use the Peek() method to see what the next character is without pulling it from the stream. Here's the code that reads an entire line from the text file:
Console.WriteLine(tr.ReadLine());
When done reading, you should close the file as follows:
tr.Close();
SummaryThis article showed how to write text to a file and read it back out. For more details on additional methods, consult the .NET Frameworks reference on the StreamWriter, StreamReader, TextWriter, and Textreader classes.

Merge Files (Steganography)

Note : This is simple merge file techniques. You need Advance Level coding for Converting it to steganography.

Introduction:I have used FileStream class for merging two files. First file will be opened for appending. Second file will be opened and read into a byte array. Then this byte array is written onto the first file stream and then both file steams will be closed. Now you have successfully appended the first file with the second file.Uses:If are left with two parts of video or audio file you have no option to play it because the player may not be able to read partial files. This is useful for joining files of same format splitted due to some size restrictions.
private void cmdMerge_Click(object sender, EventArgs e)
{
string sFile1 = txtFile1.Text;
string sFile2 = txtFile2.Text;
FileStream fs1=null;
FileStream fs2=null;
try
{
fs1 = File.Open(sFile1, FileMode.Append);
fs2 = File.Open(sFile2, FileMode.Open);
byte[] fs2Content = new byte[fs2.Length];
fs2.Read(fs2Content, 0, (int)fs2.Length);
fs1.Write(fs2Content, 0, (int)fs2.Length);
MessageBox.Show("Done!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + " : " + ex.StackTrace);
}
finally
{
fs1.Close();
fs2.Close();
}
}
This is simple file merging , You can convert it to your need

Morphing Algorithm

How do I morph two images ?
Framework that allows me to do that or anyfree sample code on the web?
If you are having this questions then You can do morphing in .net.
This is a paid tutorial and not a free one.

Grayscale Algorithm

In this tutorial, we will create a grayscale image from a colored one. To run this application, you will need to have .NET Framework 1.1 installed. Also, to be able to follow this tutorial, you will need Visual Studio .NET installed on your machine.

Creating the Program for GrayScale Image:
The first thing we will need, before starting designing and coding our application will be a colored image. In the attached project, I've included an image on whitch I will work. It's not necessary to use the same image, you are welcomed to use any image you like, as long as it's colored. Now that we have an image, let's start programming.

We need to create a C# application. To do that, go to File -> New -> Project -> Visual C# Project -> Windows Application. Name the project GrayscaleImage(any other name will be fine). Drag and drop from the Toolbox(View -> Toolbox or Ctrl + Alt + X ) two PictureBox controls and a Button. Set the first PictureBox control's Name property to pb_color, SizeMode to StretchImage. Set the second PictureBox Name property to pb_grayscale and SizeMode to StretchImage. Now, set the button's Text property to Convert and it's Name to btn_convert.




Let's add two more buttons. For the first button we'll set the Text property to Load Image, and the Name to btn_load. The second button's Name to btn_save and its Text to Save Image

Now, before we get down to coding, I would like to explain a little about the images format, in general. An image has three channels: Red, Green and Blue. These channels represents different nuance of the above color. Put one over the other, they form all the known colors. For example, Red=0, Green=0, Blue=0 represents black and Red=255, Green=255, Blue=255 represents white.

The basic way to create a grayscale image is to set the Red, Green, and Blue to the same value. To convert a pixel from any color to a grayscale color, you need to apply the following formulas:

Grayscale color(R) = [Color(R)+Color(G)+Color(B)]/3
Grayscale color(G) = [Color(R)+Color(G)+Color(B)]/3
Grayscale color(B) = [Color(R)+Color(G)+Color(B)]/3

And this is how we convert the image.

Let's get to coding. In the Design view, double-click the form's surface. Visual Studio .NET will create a method called Form1_Load that will occur when our application is started. What we want to do here is disable all the buttons, except btn_load.

private void Form1_Load(object sender, System.EventArgs e)
{

btn_convert.Enabled=false;
btn_save.Enabled=false;
}

Go back to Design view and double-click btn_load. We'll have a method similar to this one:

private void btn_load_Click(object sender, System.EventArgs e)
{
}

In this method we will add the code to get the image from the user's drive. We must now add an OpenFileDialog, that will help the user to choose a file. Also, we have to set a filter, to allow only image files to be selected ( image files are files that have an extension of either jpg, jpeg, bmp, gif and other formats ).

OpenFileDialog open = new OpenFileDialog();
open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)*.jpg; *.jpeg; *.gif; *.bmp";

The next step is to show the OpenFileDialog window, to allow the user to select a file. Now, we'll also want to see what button the user clicked after selecting a file (OK or Cancel).

if (open.ShowDialog()==DialogResult.OK)
{
}


The ShowDialog method shows the control to the user. It also returns a DialogResult object to find out what button was pressed. To see if the user pressed the OK button, we compare the result to DialogResult.OK. If that happened, we should get the selected file and put it into the PictureBox. Also, we have to enable btn_convert to allow the conversion.

Now we must create the code to convert the image to grayscale. Go to Design view and double-click btn_convert. Here we will create the code to convert the image.

private void btn_convert_Click(object sender, System.EventArgs e)
{
}

The first thing we need to do is create a copy of the color image. To do that, we need to create a Bitmap object.

Bitmap grays = (Bitmap)pb_color.Image;

We have created a Bitmap object with the value of the original image. To convert it to grayscale, we must iterate through each pixel of the image and apply the algorithm described above. But first, we need to find out the size of the image. int width = grays.Size.Width;
int height = grays.Size.Height;

Now we found out the width and height of the image, so let's start converting.

for (int j=0; j
What we do is iterate through each pixel of our Bitmap, and set its color according to above algorithm. The last things we need to do is set the PictureBox's Image property to the new bitmap and enable the btn_save button.

pb_grayscale.Image = grays;
btn_save.Enabled=true;

Run the sample and see the code at work.
Note: You will see some images slightly distorted. This is because we've set a fixed size of the PictureBox object and “told” him to fit the image in it.

A last thing we want to add is the possibility for the user to save the grayscale image into his hard-drive. Go to Design view and double-click btn_save. In the newly created method, add the following code:

Bitmap b = (Bitmap)pb_grayscale.Image;
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)*.jpg; *.jpeg; *.gif; *.bmp";
if (save.ShowDialog()==DialogResult.OK)
{
b.Save(save.FileName);
}

First, we create a Bitmap from the pb_grayscale image. We then instantiate a SaveFileDialog object and add the same filter we added earlier. Then, we make the dialog visible, and check if the user presses OK button. If this happens, we save the image on the path and with the name chosen.