Check if strings are anagrams using LINQ–C#

 

The approach in this article shows the use of LINQ to group by array elements and comparing two strings. The underlying algorithm is the traditional approach of sorting the characters in the strings and then comparing the strings. However the more efficient implementation of anagram checking could be done by using hash tables or dictionaries.

   1:  

   2: using System;

   3: using System.Collections.Generic;

   4: using System.Linq;

   5: using System.Text;

   6:  

   7: namespace AnagramCheck

   8: {

   9:     public class AnagramChecker

  10:     {

  11:         public bool IsAnagram(string[] anagrams)

  12:         {

  13:             var orderGroups = anagrams.GroupBy(w => w.Trim(), new AnagramEqualityComparer());

  14:  

  15:             foreach (var group in orderGroups)

  16:             {

  17:                 if (group.Count() == anagrams.Length)

  18:                 {

  19:                     return true;

  20:                 }

  21:             }

  22:             return false;

  23:         }

  24:     }

  25:  

  26:     public class AnagramEqualityComparer : IEqualityComparer<string>

  27:     {

  28:         public bool Equals(string x, string y)

  29:         {

  30:             return getCanonicalString(x) == getCanonicalString(y);

  31:         }

  32:  

  33:         public int GetHashCode(string obj)

  34:         {

  35:             return getCanonicalString(obj).GetHashCode();

  36:         }

  37:  

  38:         private string getCanonicalString(string word)

  39:         {

  40:             char[] wordChars = word.ToCharArray();

  41:             Array.Sort<char>(wordChars);

  42:             return new string(wordChars);

  43:         }

  44:     }

  45: }

Advertisements

Testing a Web Method Using Sockets

Problem
You want to test a Web method in a Web service by calling the method using sockets.
Design
First, construct a SOAP message to send to the Web method. Second, instantiate a Socket object and connect to the remote server that hosts the Web service. Third, construct a header that contains HTTP information. Fourth, send the header plus SOAP message using the Socket.Send() method. Fifth, receive the SOAP response using Socket.Receive() in a while loop. Sixth, analyze the SOAP response for an expected value(s).

            Console.WriteLine("Calling Web Method GetTitles() using sockets");
            string input = "testing";
            string soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
            soapMessage += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchemainstance\"";
            soapMessage += " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"";
            soapMessage += " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
            soapMessage += "<soap:Body>";
            soapMessage += "<GetTitles xmlns=\"http://tempuri.org/\">";
            soapMessage += "<filter>" + input + "</filter>";
            soapMessage += "</GetTitles>";
            soapMessage += "</soap:Body>";
            soapMessage += "</soap:Envelope>";
            Console.WriteLine("SOAP message is: \n");
            Console.WriteLine(soapMessage);
            string host = "localhost";
            string webService = "/TestAuto/Ch8/TheWebService/BookSearch.asmx";
            string webMethod = "GetTitles";
            IPHostEntry iphe = Dns.Resolve(host);
            IPAddress[] addList = iphe.AddressList; // addList[0] == 127.0.0.1
            EndPoint ep = new IPEndPoint(addList[0], 80); // ep = 127.0.0.1:80
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(ep);
            if (socket.Connected)
                Console.WriteLine("\nConnected to " + ep.ToString());
            else
                Console.WriteLine("\nError: socket not connected");
            string header = "POST " + webService + " HTTP/1.1\r\n";
            header += "Host: " + host + "\r\n";
            header += "Content-Type: text/xml; charset=utf-8\r\n";
            header += "Content-Length: " + soapMessage.Length.ToString() + "\r\n";
            header += "Connection: close\r\n";
            header += "SOAPAction: \"http://tempuri.org/" + webMethod + "\"\r\n\r\n";
            Console.Write("Header is: \n" + header);
            string sendAsString = header + soapMessage;
            byte[] sendAsBytes = Encoding.ASCII.GetBytes(sendAsString);
            int numBytesSent = socket.Send(sendAsBytes, sendAsBytes.Length,   SocketFlags.None);
            Console.WriteLine("Sending = " + numBytesSent + " bytes\n");
            byte[] receiveBufferAsBytes = new byte[512];
            string receiveAsString = "";
            string entireReceive = "";
            int numBytesReceived = 0;
            while ((numBytesReceived = socket.Receive(receiveBufferAsBytes, 512,
            SocketFlags.None)) > 0)
            {
                receiveAsString = Encoding.ASCII.GetString(receiveBufferAsBytes, 0,
                numBytesReceived);
                entireReceive += receiveAsString;
            }
            Console.WriteLine("\nThe SOAP response is " + entireReceive);
            Console.WriteLine("\nDetermining pass/fail");
            if (entireReceive.IndexOf("002") >= 0 &&
            entireReceive.IndexOf("004") >= 0 &&
            entireReceive.IndexOf("005") >= 0)
                Console.WriteLine("\nPass");
            else
                Console.WriteLine("\nFail");

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }