Download data over HTTP or FTP

Problem: You need a quick, simple way to download data from the internet using HTTP or FTP.

Solution: You can use the methods of the System.Net.WebClient class. 

Code: It’s very easy!!. The .NET Framework provides several mechanisms for transferring data over the Internet. One of the easier approaches is to use the System.Net.WebClass class. WebClient provides many high-level methods that simplify the transfer of data by specifying the source as a uniform resourse identifier (URI). The URI can specify that a file(file://), FTP (ftp://), or HTTP (http:// or https://) scheme be used to download the resource.

Technorati のタグ:

using System;
using System.IO;
using System.Net;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace DataDownload
{
    class Program
    {
        private static void Main()
        {
            string uri = "http://www.microsoft.com/japan/";

            // make a client
            WebClient client = new WebClient();

            // get the contents of the file
            Console.WriteLine("Downloading {0} " + uri);
            // download the page and store the bytes
            byte[] bytes;
            try
            {
                bytes = client.DownloadData(uri);
            }
            catch (WebException we)
            {
                Console.WriteLine(we.ToString());
                return;
            }
            // Write the HTML out
            string page = Encoding.ASCII.GetString(bytes);
            Console.WriteLine(page);

            // go get the file
            Console.WriteLine("Retrieving file from {0}…\r\n", uri);
            // get file and put it in a temp file
            string tempFile = Path.GetTempFileName();
            try
            {
                client.DownloadFile(uri, tempFile);
            }
            catch (WebException we)
            {
                Console.WriteLine(we.ToString());
                return;
            }
            Console.WriteLine("Downloaded {0} to {1}", uri, tempFile);

            uri = "ftp://ftp.microsoft.com/ResKit/win2000/whoami.zip";
            WebClient client2 = new WebClient();

            Console.WriteLine("Downloading {0} " + uri);
            try
            {
                client2.DownloadFile(uri, "whoami.zip");
            }
            catch (WebException we)
            {
                Console.WriteLine(we.ToString());
                return;
            }
        }
    }
}

Advertisements

Hash Code for a Data Type sample

public static void CreateHashCodeDataType()
{
    SimpleClass simpleClass = new SimpleClass();

    Hashtable hashTable = new Hashtable();
    hashTable.Add(simpleClass, 100);
}

public class SimpleClass
{
    private int x = 0;
    private int y = 0;

    public override int GetHashCode()
    {
        return(SimpleHash(x, y));
    }

    public int SimpleHash(params int[] values)
    {
        int hashCode = 0;
        if (values != null)
        {
            foreach (int val in values)
            {
                hashCode ^= val;
            }
        }

        return (hashCode);
    }
}

public int SimpleHash(params int[] values)
{
    int hashCode = 0;
    if (values != null)
    {
        foreach (int val in values)
        {
            hashCode ^= val;
        }
    }

    return (hashCode);
}

public int FoldingHash(params long[] values)
{
    int hashCode = 0;
    if (values != null)
    {
        int tempLowerVal = 0;
        int tempUpperVal = 0;
        foreach (long val in values)
        {
            tempLowerVal = (int)(val & 0x000000007FFFFFFF);
            tempUpperVal = (int)((val >> 32) & 0xFFFFFFFF);
            hashCode^= tempLowerVal ^ tempUpperVal;
        }
    }

    return (hashCode);
}

public int ContainedObjHash(params object[] values)
{
    int hashCode = 0;
    if (values != null)
    {
        foreach (int val in values)
        {
            hashCode ^= val.GetHashCode();
        }
    }

    return (hashCode);
}

public int CryptoHash(string strValue)
{
    int hashCode = 0;
    if (strValue != null)
    {
        byte[] encodedUnHashedString =
            Encoding.Unicode.GetBytes(strValue);

        // Replace the following Key with your own
        // key value
        byte[] Key = new byte[16] {1,122,3,11,65,7,9,45,42,98,
                                      77,34,99,45,167,211};

        MACTripleDES hashingObj = new MACTripleDES(Key);
        byte[] code =
            hashingObj.ComputeHash(encodedUnHashedString);

        // use the BitConverter class to take the
        // first 4 bytes and use them as an int for
        // the hash code
        hashCode = BitConverter.ToInt32(code,0);   
    }

    return (hashCode);
}

public int CryptoHash(long intValue)
{
    int hashCode = 0;
    byte[] encodedUnHashedString =
        Encoding.Unicode.GetBytes(intValue.ToString());

    SHA256Managed hashingObj = new SHA256Managed();
    byte[] code = hashingObj.ComputeHash(encodedUnHashedString);

    // use the BitConverter class to take the
    // first 4 bytes and use them as an int for
    // the hash code
    hashCode = BitConverter.ToInt32(code,0);   

    return (hashCode);
}

public int ShiftAndAddHash (string strValue)
{
    int hashCode = 0;
    long workHashCode = 0;

    if (strValue != null)
    {
        for (int counter=0; counter<strValue.Length; counter++)
        {
            workHashCode = (workHashCode << (counter % 4)) +
                (int)strValue[counter];
        }
        workHashCode = workHashCode % (127);
    }
    hashCode = (int)workHashCode;

    return (hashCode);
}

public int CalcHash(short someShort, int someInt, long someLong,
    float someFloat, object someObject)
{
    int hashCode = 7;
    hashCode = hashCode * 31 + (int)someShort;
    hashCode = hashCode * 31 + someInt;
    hashCode = hashCode * 31 +
        (int)(someLong ^ (someLong >> 32));
    long someFloatToLong = (long)someFloat;
    hashCode = hashCode * 31 +
        (int)(someFloatToLong ^ (someFloatToLong >> 32));

    if (someObject != null)
    {
        hashCode = hashCode * 31 +
            someObject.GetHashCode();
    }

    return (hashCode);
}

public int ConcatStringGetHashCode(int[] someIntArray)
{
    int hashCode = 0;
    StringBuilder hashString = new StringBuilder();

    if (someIntArray != null)
    {
        foreach (int i in someIntArray)
        {
            hashString.Append(i.ToString() + "^");
        }
    }
    hashCode = hashString.GetHashCode();

    return (hashCode);
}

Binary tree sample

public static void TestBinaryTree()
        {
            BinaryTree tree = new BinaryTree("d");
            tree.AddNode("a");
            tree.AddNode("b");
            tree.AddNode("f");
            tree.AddNode("e");
            tree.AddNode("c");
            tree.AddNode("g");
            tree.Print();
            tree.Print();

            Console.WriteLine("tree.TreeSize: " + tree.TreeSize);           
            Console.WriteLine("tree.GetRoot().DepthFirstSearch(a).NumOfChildren: " +
                tree.GetRoot().DepthFirstSearch("b").NumOfChildren);           
            Console.WriteLine("tree.GetRoot().DepthFirstSearch(a).NumOfChildren: " +
                tree.GetRoot().DepthFirstSearch("a").NumOfChildren);           
            Console.WriteLine("tree.GetRoot().DepthFirstSearch(g).NumOfChildren: " +
                tree.GetRoot().DepthFirstSearch("g").NumOfChildren);           

            Console.WriteLine("tree.SearchDepthFirst(a): " +
                tree.SearchDepthFirst("a").Value.ToString());
            Console.WriteLine("tree.SearchDepthFirst(b): " +
                tree.SearchDepthFirst("b").Value.ToString());
            Console.WriteLine("tree.SearchDepthFirst(c): " +
                tree.SearchDepthFirst("c").Value.ToString());
            Console.WriteLine("tree.SearchDepthFirst(d): " +
                tree.SearchDepthFirst("d").Value.ToString());
            Console.WriteLine("tree.SearchDepthFirst(e): " +
                tree.SearchDepthFirst("e").Value.ToString());
            Console.WriteLine("tree.SearchDepthFirst(f): " +
                tree.SearchDepthFirst("f").Value.ToString());

            tree.GetRoot().RemoveLeftNode();
            tree.Print();

            tree.GetRoot().RemoveRightNode();
            tree.Print();
        }

        public class BinaryTree
        {
            public BinaryTree() {}

            public BinaryTree(IComparable value, int index)
            {
                BinaryTreeNode node = new BinaryTreeNode(value, index);
                root = node;
                counter = 1;
            }

            // Use this .ctor when you need to flatten this tree (see recipe 9.15)
            public BinaryTree(IComparable value)
            {
                BinaryTreeNode node = new BinaryTreeNode(value);
                root = node;
                counter = 1;
            }

            protected int counter = 0;             // Number of nodes in tree
            protected BinaryTreeNode root = null;  // Pointer to root node in this tree

            public  void AddNode(IComparable value, int index)
            {
                BinaryTreeNode node = new BinaryTreeNode(value, index);
                ++counter;

                if (root == null)
                {
                    root = node;
                }
                else
                {
                    root.AddNode(node);
                }
            }

            // Use this method to add a node
            //    when you need to flatten this tree (see recipe 9.15)
            public int AddNode(IComparable value)
            {
                BinaryTreeNode node = new BinaryTreeNode(value);
                ++counter;

                if (root == null)
                {
                    root = node;
                }
                else
                {
                    root.AddNode(node);
                }

                return (counter – 1);
            }

            public BinaryTreeNode SearchDepthFirst(IComparable value)
            {
                return (root.DepthFirstSearch(value));
            }

            public void Print()
            {
                root.PrintDepthFirst();
            }

            public BinaryTreeNode GetRoot()
            {
                return (root);
            }

            public int TreeSize
            {
                get {return (counter);}
            }       
        }

        public class BinaryTreeNode
        {
            public BinaryTreeNode() {}

            public BinaryTreeNode(IComparable value)
            {
                nodeValue = value;
            }

            // These 2 ctors Added to allow tree to be flattened
            public BinaryTreeNode(int index)
            {
                nodeIndex = index;
            }

            public BinaryTreeNode(IComparable value, int index)
            {
                nodeValue = value;
                nodeIndex = index;
            }

            protected int nodeIndex = 0;         // Added to allow tree to be flattened
            protected IComparable nodeValue = null;
            protected BinaryTreeNode leftNode = null;     //  leftNode.Value < Value
            protected BinaryTreeNode rightNode = null;    //  rightNode.Value >= Value

            public int NumOfChildren
            {
                get {return (CountChildren());}
            }

            public int CountChildren()
            {
                int currCount = 0;

                if (leftNode != null)
                {
                    ++currCount;
                    currCount += leftNode.CountChildren();
                }

                if (rightNode != null)
                {
                    ++currCount;
                    currCount += rightNode.CountChildren();
                }

                return (currCount);
            }

            public int Index
            {
                get {return (nodeIndex);}
            }

            public BinaryTreeNode Left
            {
                get {return (leftNode);}
            }

            public BinaryTreeNode Right
            {
                get {return (rightNode);}
            }

            public IComparable Value
            {
                get {return (nodeValue);}
            }

            public void AddNode(BinaryTreeNode node)
            {
                if (node.nodeValue.CompareTo(nodeValue) < 0)
                {
                    if (leftNode == null)
                    {
                        leftNode = node;
                    }
                    else
                    {
                        leftNode.AddNode(node);
                    }
                }
                else if (node.nodeValue.CompareTo(nodeValue) >= 0)
                {
                    if (rightNode == null)
                    {
                        rightNode = node;
                    }
                    else
                    {
                        rightNode.AddNode(node);
                    }
                }
            }

            public bool AddUniqueNode(BinaryTreeNode node)
            {
                bool isUnique = true;

                if (node.nodeValue.CompareTo(nodeValue) < 0)
                {
                    if (leftNode == null)
                    {
                        leftNode = node;
                    }
                    else
                    {
                        leftNode.AddNode(node);
                    }
                }
                else if (node.nodeValue.CompareTo(nodeValue) > 0)
                {
                    if (rightNode == null)
                    {
                        rightNode = node;
                    }
                    else
                    {
                        rightNode.AddNode(node);
                    }
                }
                else   //node.nodeValue.CompareTo(nodeValue) = 0
                {
                    isUnique = false;
                    // Could throw exception here as well…
                }

                return (isUnique);
            }

            public BinaryTreeNode DepthFirstSearch(IComparable targetObj)
            {
                // NOTE: foo.CompareTo(bar) == -1   –>   (foo < bar)
                BinaryTreeNode retObj = null;
                int comparisonResult = targetObj.CompareTo(nodeValue);

                if (comparisonResult  == 0)
                {
                    retObj = this;
                }
                else if (comparisonResult > 0)
                {
                    if (rightNode != null)
                    {
                        retObj = rightNode.DepthFirstSearch(targetObj);
                    }
                }
                else if (comparisonResult < 0)
                {
                    if (leftNode != null)
                    {
                        retObj = leftNode.DepthFirstSearch(targetObj);
                    }
                }

                return (retObj);
            }

            public void PrintDepthFirst()
            {
                if (leftNode != null)
                {
                    leftNode.PrintDepthFirst();
                }

                Console.WriteLine(this.nodeValue.ToString());

                try
                {
                    Console.WriteLine("\tContains Left: " +
                        leftNode.nodeValue.ToString());
                }
                catch
                {
                    Console.WriteLine("\tContains Left:  NULL");
                }
                try
                {
                    Console.WriteLine("\tContains Right: " +
                        rightNode.nodeValue.ToString());
                }
                catch
                {
                    Console.WriteLine("\tContains Right: NULL");
                }

                if (rightNode != null)
                {
                    rightNode.PrintDepthFirst();
                }
            }

            public void RemoveLeftNode()
            {
                leftNode = null;
            }

            public void RemoveRightNode()
            {
                rightNode = null;
            }
        }

What is stress testing?

Q: What is stress testing?
A: Stress testing is testing that investigates the behavior of software (and hardware) under extraordinary operating conditions.
For example, when a web server is stress tested, testing aims to find out how many users can be on-line, at the same time, without crashing the server. Stress testing tests the stability of a given system or entity.
Stress testing tests something beyond its normal operational capacity, in order to observe any negative results. For example, a web server is stress tested, using scripts, bots, and various denial of service tools.

Q: What is load testing?
A: Load testing simulates the expected usage of a software program, by simulating multiple users that access the program’s services concurrently. Load testing is most useful and most relevant for multi-user systems, client/server models, including web servers.
For example, the load placed on the system is increased above normal usage patterns, in order to test the system’s response at peak loads.

Q: What is the difference between stress testing and load testing?
A: Load testing generally stops short of stress testing.
During stress testing, the load is so great that the expected results are errors, though there is gray area in between stress testing and load testing.
Load testing is a blanket term that is used in many different ways across the professional software testing community.
The term, load testing, is often used synonymously with stress testing, performance testing, reliability testing, and volume testing.


Q: What is the difference between performance testing and load testing?
A: Load testing is a blanket term that is used in many different ways across the professional software testing community. The term, load testing, is often used synonymously with stress testing, performance testing, reliability testing, and volume testing. Load testing generally stops short of stress testing. During stress testing, the load is so great that errors are the expected results, though there is gray area in between stress testing and load testing.

Q: What is the difference between reliability testing and load testing?
A: Load testing is a blanket term that is used in many different ways across the professional software testing community. The term, load testing, is often used synonymously with stress testing, performance testing, reliability testing, and volume testing. Load testing generally stops short of stress testing. During stress testing, the load is so great that errors are the expected results, though there is gray area in between stress testing and load testing.

Q: What is usability?
A: Usability means ease of use; the ease with which a user can learn to operate, prepare inputs for, and interpret outputs of a software product.

Q: What is automated testing?
A: Automated testing is a formally specified and controlled method of formal testing approach.

Q: What is alpha testing?
A: Alpha testing is final testing before the software is released to the general public. First, (and this is called the first phase of alpha testing), the software is tested by in-house developers. They use either debugger software, or hardware-assisted debuggers. The goal is to catch bugs quickly.
Then, (and this is called second stage of alpha testing), the software is handed over to software QA staff for additional testing in an environment that is similar to the intended use.

Q: What is beta testing?
A: Following alpha testing, "beta versions" of the software are released to a group of people, and limited public tests are performed, so that further testing can ensure the product has few bugs.
Other times, beta versions are made available to the general public, in order to receive as much feedback as possible. The goal is to benefit the maximum number of future users.

Q: What is the difference between alpha and beta testing?
A: Alpha testing is performed by in-house developers and software QA personnel. Beta testing is performed by the public, a few select prospective customers, or the general public.


Q: What is clear box testing?
A: Clear box testing is the same as white box testing. It is a testing approach that examines the application’s program structure, and derives test cases from the application’s program logic.

Q: What is black box testing?
A: Black box testing a type of testing that considers only externally visible behavior. Black box testing considers neither the code itself, nor the "inner workings" of the software.

A: Black box testing is functional testing, not based on any knowledge of internal software design or code. Black box testing are based on requirements and functionality.

Q: What is black box testing?
A: Black box testing is functional testing, not based on any knowledge of internal software design or code. Black box testing are based on requirements and functionality.

Q: What is white box testing?
A: White box testing is based on knowledge of the internal logic of an application’s code. Tests are based on coverage of code statements, branches, paths and conditions.

Q: What is closed box testing?
A: Closed box testing is the same as black box testing. Black box testing a type of testing that considers only externally visible behavior. Black box testing considers neither the code itself, nor the "inner workings" of the software.

Q: What types of white box testing can you tell me about?
A: White box testing is a testing approach that examines the application’s program structure, and derives test cases from the application’s program logic.
Clear box testing is a white box type of testing. Glass box testing is also a white box type of testing. Open box testing is also a white box type of testing.

Q: What black box testing types can you tell me about?
A: Black box testing is functional testing, not based on any knowledge of internal software design or code.
Black box testing is based on requirements and functionality. Functional testing is also a black-box type of testing geared to functional requirements of an application.
System testing is also a black box type of testing. Acceptance testing is also a black box type of testing. Functional testing is also a black box type of testing. Closed box testing is also a black box type of testing. Integration testing is also a black box type of testing.

Q: What is unit testing?
A: Unit testing is the first level of dynamic testing and is first the responsibility of developers and then that of the test engineers.
Unit testing is performed after the expected test results are met or differences are explainable/acceptable.

Q: What is bottom-up testing?
A: Bottom-up testing is a technique for integration testing. A test engineer creates and uses test drivers for components that have not yet been developed, because, with bottom-up testing, low-level components are tested first. The objective of bottom-up testing is to call low-level components, for testing purposes.

Q: What is software quality?
A: The quality of the software does vary widely from system to system. Some common quality attributes are stability, usability, reliability, portability, and maintainability. See quality standard ISO 9126 for more information on this subject.

Q: What is functional testing?
A: Functional testing is the same as black box testing. Black box testing a type of testing that considers only externally visible behavior. Black box testing considers neither the code itself, nor the "inner workings" of the software.

Q: What is the difference between a software fault and software failure?
A: A software failure occurs when the software does not do what the user expects to see. Software faults, on the other hand, are hidden programming errors. Software faults become software failures only when the exact computation conditions are met, and the faulty portion of the code is executed on the CPU. This can occur during normal usage. Other times it occurs when the software is ported to a different hardware platform, or, when the software is ported to a different complier, or, when the software gets extended.

Q: What is reliability testing?
A: Reliability testing is designing reliability test cases, using accelerated reliability techniques (e.g. step-stress, test/analyze/fix, and continuously increasing stress testing techniques), AND testing units or systems to failure, in order to obtain raw failure time data for product life analysis.
The purpose of reliability testing is to determine product reliability, and to determine whether the software meets the customer’s reliability requirements.
In the system test phase, or after the software is fully developed, one reliability testing technique we use is a test/analyze/fix technique, where we couple reliability testing with the removal of faults.

When we identify a failure, we send the software back to the developers, for repair. The developers build a new version of the software, and then we do another test iteration. We track failure intensity (e.g. failures per transaction, or failures per hour) in order to guide our test process, and to determine the feasibility of the software release, and to determine whether the software meets the customer’s reliability requirements.

What is your view of software QA/testing?

Q: What is your view of software QA/testing?
A: Software QA/testing is easy, if requirements are solid, clear, complete, detailed, cohesive, attainable and testable, and if schedules are realistic, and if there is good communication.
Software QA/testing is a piece of cake, if project schedules are realistic, if adequate time is allowed for planning, design, testing, bug fixing, re-testing, changes, and documentation.

Software QA/testing is relatively easy, if testing is started early on, and if fixes or changes are re-tested, and if sufficient time is planned for both testing and bug fixing.

Software QA/testing is easy, if new features are avoided, and if one sticks to initial requirements as much as possible.

Q: How can I be a good tester?
A: We, good testers, take the customers’ point of view. We are tactful and diplomatic. We have a "test to break" attitude, a strong desire for quality, an attention to detail, and good communication skills, both oral and written.
Previous software development experience is also helpful as it provides a deeper understanding of the software development process.

Q: What is software testing?
A: Software testing is a process that identifies the correctness, completeness, and quality of software. Actually, testing cannot establish the correctness of software. It can find defects, but cannot prove there are no defects.

Q: What is a test engineer?
A: We, test engineers, are engineers who specialize in testing. We create test cases, procedures, scripts and generate data. We execute test procedures and scripts, analyze standards of measurements, and evaluate results of system/integration/regression testing.

Q: What is a QA engineer?
A: QA engineers are test engineer, but they do more than just testing. Good QA engineers understand the entire software development process and how it fits into the business approach and the goals of the organization.
Communication skills and the ability to understand various sides of issues are important. A QA engineer is successful if people listen to him, if people use his tests, if people think that he’s useful, and if he’s happy doing his work.
I would love to see QA departments staffed with experienced software developers who coach development teams to write better code. But I’ve never seen it. Instead of coaching, QA engineers tend to be process people.


Q: How do you write test cases?
A: When I write test cases, I concentrate on one requirement at a time. Then, based on that one requirement, I come up with several real life scenarios that are likely to occur in the use of the application by end users. When I write test cases, I describe the inputs, action, or event, and their expected results, in order to determine if a feature of an application is working correctly.
To make the test case complete, I also add particulars e.g. test case identifiers, test case names, objectives, test conditions (or setups), input data requirements (or steps), and expected results.

If I have a choice, I prefer writing test cases as early as possible in the development life cycle. Why? Because, as a side benefit of writing test cases, many times I am able to find problems in the requirements or design of an application. And, because the process of developing test cases makes me completely think through the operation of the application.

You can learn to write test cases! If there is a will, there is a way! You CAN do it, if you put your mind to it! You CAN learn to write test cases, with little or no outside help. Click on a link!

Q: What is the role of the test engineer?
A: We, test engineers, speed up the work of the development staff, and reduce the risk of your company’s legal liability.
We also give your company the evidence that the software is correct and operate properly.
We, test engineers, improve problem tracking and reporting, maximize the value of the software, and the value of the devices that use it.
We, test engineers, assure the successful launch of the product by discovering bugs and design flaws, before users get discouraged, before shareholders loose their cool and before employees get bogged down.
We, test engineers, help the work of the software development staff, so the development team can devote its time to build up the product.
We, test engineers, promote continual improvement.

Q: What testing approaches can you tell me about?
A: Each of the followings represents a different testing approach: black box testing, white box testing, unit testing, incremental testing, integration testing, functional testing, system testing, end-to-end testing, sanity testing, regression testing, acceptance testing, load testing, performance testing, usability testing, install/uninstall testing, recovery testing, security testing, compatibility testing, exploratory testing, ad-hoc testing, user acceptance testing, comparison testing, alpha testing, beta testing, and mutation testing.

Q: What are the QA engineer’s responsibilities?
A: Let’s say, an engineer is hired for a small software company’s QA role, and there is no QA team. Should he take responsibility to set up a QA infrastructure/process, testing and quality of the entire product? No, because taking this responsibility is a classic trap that QA people get caught in. Why? Because we QA engineers cannot assure quality. And because QA departments cannot create quality.
What we CAN do is to detect lack of quality, and prevent low-quality products from going out the door. What is the solution? We need to drop the QA label, and tell the developers that they are responsible for the quality of their own work. The problem is, sometimes, as soon as the developers learn that there is a test department, they will slack off on their testing. We need to offer to help with quality assessment, only.

Q: What metrics can be used in for software development?
A: Metrics refer to statistical process control. The idea of statistical process control is a great one, but it has only a limited use in software development.
On the negative side, statistical process control works only with processes that are sufficiently well defined AND unvaried, so that they can be analyzed in terms of statistics. The problem is, most software development projects are NOT sufficiently well defined and NOT sufficiently unvaried.
On the positive side, one CAN use statistics. Statistics are excellent tools that project managers can use. Statistics can be used, for example, to determine when to stop testing, i.e. test cases completed with certain percentage passed, or when bug rate falls below a certain level. But, if these are project management tools, why should we label them quality assurance tools?

TCP Server with SSL

Problem:

I made the TCP Server program with SSL and the TCP client program to investigate the product issue.

Solution:

I published the code of the TCP Server with SSL.

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Diagnostics;
using System.Threading;
using System.IO;

using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Security.Authentication;

namespace ConsoleTCPServer_SSL
{
    class TCPServer_SSL
    {
        private TcpListener _listener = null;
        private IPAddress _address = IPAddress.Parse("127.0.0.1");
        private int _port = 55555;

        #region CTORs
        public TCPServer_SSL()
        {
        }

        public TCPServer_SSL(string address, string port)
        {
            _port = Convert.ToInt32(port);
            _address = IPAddress.Parse(address);
        }
        #endregion // CTORs

        #region Properties
        public IPAddress Address
        {
            get { return _address; }
            set { _address = value; }
        }

        public int Port
        {
            get { return _port; }
            set { _port = value; }
        }
        #endregion

        public void Listen()
        {
            try
            {
                _listener = new TcpListener(_address, _port);

                // fire up the server
                _listener.Start();

                // Enter the listening loop.
                while (true)
                {
                    Console.Write("Looking for someone to talk to… ");

                    // Wait for connection
                    TcpClient newClient = _listener.AcceptTcpClient();
                    Console.WriteLine("Connected to new client");

                    // spin a thread to take care of the client
                    ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessClient), newClient);
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
            finally
            {
                // shut it down
                _listener.Stop();
            }

            Console.WriteLine("\nHit any key (where is ANYKEY?) to continue…");
            Console.Read();
        }

        private void ProcessClient(object client)
        {
            TcpClient newClient = (TcpClient)client;

            // Buffer for reading data
            byte[] bytes = new byte[1024];
            string clientData = null;

            SslStream sslStream = new SslStream(newClient.GetStream());
            sslStream.AuthenticateAsServer(GetServerCert("MyTestCert2"), false, SslProtocols.Default, true);

            // get the stream to talk to the client over
            //NetworkStream ns = newClient.GetStream();
            // Loop to receive all the data sent by the client.
            int bytesRead = 0;
            while ((bytesRead = sslStream.Read(bytes, 0, bytes.Length)) != 0)
            {
                // Translate data bytes to an ASCII string.
                clientData = Encoding.ASCII.GetString(bytes, 0, bytesRead);
                Console.WriteLine("Client says: {0}", clientData);

                // Thank them for their input
                bytes = Encoding.ASCII.GetBytes("Thanks call again!");

                // Send back a response.
                sslStream.Write(bytes, 0, bytes.Length);
            }

            // stop talking to client
            sslStream.Close();
            newClient.Close();
        }

        private static X509Certificate GetServerCert(string subjectName)
        {
            X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);
            X509CertificateCollection certificate = store.Certificates.Find(X509FindType.FindBySubjectName, subjectName, true);
            if (certificate.Count > 0)
                return (certificate[0]);
            else
                return (null);
        }
    }
}

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace ConsoleTCPServer_SSL
{
    class Program
    {
        static void Main(string[] args)
        {
            TCPServer_SSL server = new TCPServer_SSL();
            server.Listen();
        }
    }
}

TCP Client with SSL

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Diagnostics;
using System.Threading;

using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Security.Authentication;

namespace ConsoleTCPClient_SSL
{
    class TCPClient_SSL
    {
        private TcpClient _client = null;
        private IPAddress _address = IPAddress.Parse("127.0.0.1");
        private int _port = 5;
        private IPEndPoint _endPoint = null;

        public TCPClient_SSL(string address, string port)
        {
            _address = IPAddress.Parse(address);
            _port = Convert.ToInt32(port);
            _endPoint = new IPEndPoint(_address, _port);
        }

        public void ConnectToServer(string msg)
        {
            try
            {
                _client = new TcpClient();
                _client.Connect(_endPoint);

                SslStream sslStream = new SslStream(_client.GetStream(), false, new RemoteCertificateValidationCallback(CertificateValidationCallback));
                sslStream.AuthenticateAsClient("MyTestCert2");
                DisplaySSLInformation("MyTestCert2", sslStream, true);

                // Get the bytes to send for the message
                byte[] bytes = Encoding.ASCII.GetBytes(msg);
                // get the stream to talk to the server on
                //NetworkStream ns = _client.GetStream();
                // send message
                Console.WriteLine("Sending message to server: " + msg);
                sslStream.Write(bytes, 0, bytes.Length);

                // Get the response
                // Buffer to store the response bytes.
                bytes = new byte[1024];

                // Display the response
                int bytesRead = sslStream.Read(bytes, 0, bytes.Length);
                string serverResponse = Encoding.ASCII.GetString(bytes, 0, bytesRead);
                Console.WriteLine("Server said: " + serverResponse);

                // Close everything.
                sslStream.Close();
                _client.Close();
            }
            catch (SocketException e)
            {
                Console.WriteLine("There was an error talking to the server: {0}",
                    e.ToString());
            }
        }

        private bool CertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return true;
            }
            else
            {
                if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors)
                {
                    Console.WriteLine("The X509Chain.ChainStatus returned an array of " +
                        "X509ChainStatus objects containing error information.");
                }
                else if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNameMismatch)
                {
                    Console.WriteLine("There was a mismatch of the name on a certificate.");
                }
                else if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNotAvailable)
                {
                    Console.WriteLine("No certificate was available.");
                }
                else
                {
                    Console.WriteLine("SSL Certificate Validation Error!");
                }

                Console.WriteLine(Environment.NewLine + "SSL Certificate Validation Error!");
                Console.WriteLine(sslPolicyErrors.ToString());

                return false;
            }
        }

        private static void DisplaySSLInformation(string serverName, SslStream sslStream, bool verbose)
        {
            DisplayCertInformation(sslStream.RemoteCertificate, verbose);

            Console.WriteLine("\n\nSSL Connect Report for : {0}\n", serverName);
            Console.WriteLine("Is Authenticated:            {0}", sslStream.IsAuthenticated);
            Console.WriteLine("Is Encrypted:                {0}", sslStream.IsEncrypted);
            Console.WriteLine("Is Signed:                   {0}", sslStream.IsSigned);
            Console.WriteLine("Is Mutually Authenticated:   {0}\n", sslStream.IsMutuallyAuthenticated);

            Console.WriteLine("Hash Algorithm:              {0}", sslStream.HashAlgorithm);
            Console.WriteLine("Hash Strength:               {0}", sslStream.HashStrength);
            Console.WriteLine("Cipher Algorithm:            {0}", sslStream.CipherAlgorithm);
            Console.WriteLine("Cipher Strength:             {0}\n", sslStream.CipherStrength);

            Console.WriteLine("Key Exchange Algorithm:      {0}", sslStream.KeyExchangeAlgorithm);
            Console.WriteLine("Key Exchange Strength:       {0}\n", sslStream.KeyExchangeStrength);
            Console.WriteLine("SSL Protocol:                {0}", sslStream.SslProtocol);

        }

        private static void DisplayCertInformation(X509Certificate remoteCertificate, bool verbose)
        {
            Console.WriteLine("Certficate Information for:\n{0}\n", remoteCertificate.Subject);
            Console.WriteLine("Valid From:      \n{0}", remoteCertificate.GetEffectiveDateString());
            Console.WriteLine("Valid To:        \n{0}", remoteCertificate.GetExpirationDateString());
            Console.WriteLine("Certificate Format:     \n{0}\n", remoteCertificate.GetFormat());

            Console.WriteLine("Issuer Name:     \n{0}", remoteCertificate.Issuer);

            if (verbose)
            {
                Console.WriteLine("Serial Number:   \n{0}", remoteCertificate.GetSerialNumberString());
                Console.WriteLine("Hash:            \n{0}", remoteCertificate.GetCertHashString());
                Console.WriteLine("Key Algorithm:   \n{0}", remoteCertificate.GetKeyAlgorithm());
                Console.WriteLine("Key Algorithm Parameters:     \n{0}", remoteCertificate.GetKeyAlgorithmParametersString());
                Console.WriteLine("Public Key:     \n{0}", remoteCertificate.GetPublicKeyString());
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Diagnostics;
using System.Threading;

namespace ConsoleTCPClient_SSL
{
    class Program
    {
        static void Main(string[] args)
        {

            MakeClientCallToServer("Just wanted to say hi");
            MakeClientCallToServer("Just wanted to say hi again");
            MakeClientCallToServer("Are you ignoring me?");

            // now really beat on it…

            // make sure we use a bigger number than the number of thread pool threads
            string msg;
            for (int i = 0; i < 100; i++)
            {
                msg = string.Format("I’ll not be ignored! (round {0})", i);
                ThreadPool.QueueUserWorkItem(new WaitCallback(MakeClientCallToServer), msg);
            }

            Console.WriteLine("\n Press any key to continue… (if you can find it…)");
            Console.Read();
        }

        static void MakeClientCallToServer(object objMsg)
        {
            string msg = (string)objMsg;
            TCPClient_SSL client = new TCPClient_SSL("127.0.0.1", "55555");
            client.ConnectToServer(string.Format(msg,
                Process.GetCurrentProcess().Id, Thread.CurrentThread.ManagedThreadId));
        }
    }

}

Swapping Two Elements in an Array

Problem:

You want an efficient method to swap two elements that exist within a single array.

Solution:

public static void SwapElementsInArray<T>(T[] theArray, int index1, int index2)
{
    if (theArray.Length > 0)
    {
        if (index1 >= theArray.Length || index2 >= theArray.Length || index1 < 0 || index2 < 0)
        {
            Console.WriteLine("index passed in to this method is out of bounds.");
        }
        else
        {
            T tempHolder = theArray[index1];
            theArray[index1] = theArray[index2];
            theArray[index2] = tempHolder;
        }
    }
    else
    {
        Console.WriteLine("Nothing to reverse");
    }
}

There is no specific method in the .NET Framework that allows you to swap only two specific elements within an array. The SwapElementsInArray mehtod presented in this recipe allows for only two specified elements on an array.

Finding the location of all occurrences of a string within another string

Problem:

This content is for a beginner programmer.

You need to search a string for ever occurrence of a specific string. In addition, the case sensitivity, or in sensitivity, of the search needs to be contorlled.

Solution:

Using IndxOf of IndexOfArry in a loop, you can determine how many occurences of a charactor or string exist as well as their locations within the string. To find each occurrence of a string in another string using a case-sensitive search, use the following code:

public static int[] FindAll(string matchStr, string searchedStr, int startPos)
{
    int foundPos = -1;   // -1 represents not found
    int count = 0;
    List<int> foundItems = new List<int>();

    do
    {
        foundPos = searchedStr.IndexOf(matchStr, startPos);
        if (foundPos > -1)
        {
            startPos = foundPos + 1;
            count++;
            foundItems.Add(foundPos);

            Console.WriteLine("Found item at position: " + foundPos.ToString());
        }
    }while (foundPos > -1 && startPos < searchedStr.Length);

    return ((int[])foundItems.ToArray());
}

If the FindAll mehtod is called with the following parameters:

  int[] allOccurrences = FindAll("Red", "BlueTealRedredGreenRedYellow", 0);

the string "Red" is found at locations 8 and 19 in the string searchedStr. This code uses the IndexOf method inside a loop to iterate through each found matchStr string in the searchStr string.

When and Where to use Generic?

Problem: 

You want to use generic types in a new project or convert nongeneric types in an existing project to their generic equivalent. However, you do not really know why you would want to do this, and you do not know which nongeneric types should be converted to be generic.
 

Solution:

You need to consider several things:
  1. Will you type contain or be operating on various on unspecified data types? If so, creating a generic tyep will offer several benefits over creating a nongeneric type. If your type will operate on only a single specific type, then you may not need to create a generic type.
  2. If your type will be operating on value types, so that boxing and unboxing operations will occur, you should consider using generics to prevent the boxing and unboxing operations.
  3. The stronger type checking associated with generic will aid in finding erros sooner, thus shortening your bug-fixing cycle.
  4. Is your conde suffering from "code bloat" with you writing multiple classess to handle diffrent data types on which they operate? It is easier to write the code once and have it just work for each of the data type it operates on.
  5. Generics allow for greater clarity of code. By eliminating code bloat and forcing stronger type checking on your types, your code will be easier to read and understantd.

See Also: See the "Generics Overviews" and "Benefits of Generics" topics in the MSDN documentation.