C#: Extension method to append specific character at start of each matching word in string

Standard
using System.Text.RegularExpressions;

public static string ReplaceKeywordsWithHashtags(this string data, params string[] filterTerms)
        {
            foreach (string term in filterTerms)
            {
                var item = term.Trim();
                if (!string.IsNullOrEmpty(item))
                {
                    if (data.ToLower().Contains(item))
                        data = Regex.Replace(data, item, '#' + item, RegexOptions.IgnoreCase);
                }
            }
            return data;
        }

Usage:

string temp = "Hello World! Hello World! Hello World! Hello World!";
string[] filter = {"abc", "xyz", "hello"};
string result = temp.ReplaceKeywordsWithHashtags(filter);
Advertisements

C#: Extension method to compare string against multiple other specific words

Standard
public static class Utilities
{
     public static bool ContainsAny(this string data, params string[] filter)
     {
            foreach (string term in filter)
            {
                var item = term.Trim();
                if (!string.IsNullOrEmpty(item))
                {
                    if (data.ToLower().Contains(term))
                        return true;
                }
            }
            return false;
     }
}

Usage:

string temp = "Hello World! Hello World! Hello World! Hello World!";
string[] filter = {"abc", "xyz", "hello"};
bool result = temp.ContainsAny(filter);

C#: Extension method to Limit character in string using linq

Standard
public static class Utilities
    {
        public static string LimitTo(this string data, int length)
        {
            return (data == null || data.Length < length)
              ? data
              : data.Substring(0, length);
        }
    }

Usage:

string temp = "Hello World! Hello World! Hello World! Hello World!";
var result = str.LimitTo(150)

C#: Error – ‘System.Net.Http.HttpContent’ does not contain a definition for ‘ReadAsAsync’ and no extension method

Standard

I was working with HttpClient class to connect to external REST API’s from C# code and was implementing solution with asynchronous programming(Async / Await). Since class library project already have reference of System.Net.Http but I was having issue with extension method ReadAsAsync<T>()

'HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method 
'ReadAsAsync' accepting a first argument of type 'HttpContent' could be found 
(are you missing a using directive or an assembly reference?)

screenshot_2

Solution:

ReadAsAsync is declared in the class HttpContentExtensions, which is in the namespace System.Net.Http in the library System.Net.Http.Formatting.

Right click on project and click Add a reference option, then go to Extensions from 
Assemblies tab and choose System.Net.Http.Formatting. If its not there then add 
manually this assembly, which is also available in the folder:
C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies 

screenshot_3

 

Alternate Solution:

Execute below command in NUGET console, make sure command is executed only relevant to that project

Install-Package Microsoft.AspNet.WebApi.Client

 

C#: Parsing HTML Table and Loading HTML Webpage using Html Agility Pack

Standard

Include HTML Agility Pack in your application using nuget. To install it in your project, type the following command in the Package Manager Console.

> Install-Package HtmlAgilityPack

After adding the reference via Nuget, you need to include the reference in your page using the following.

> using HtmlAgilityPack;

Below function will convert webpage HTML table to C# readable code, just need to pass table class name and page URL.

public List<List<string>> ScrapHtmlTable(string className, string pageURL)
{
    HtmlWeb web = new HtmlWeb();
    HtmlDocument document = web.Load(pageURL);
    List<List<string>> parsedTbl = 
      document.DocumentNode.SelectSingleNode("//table[@class='" + className + "']")
      .Descendants("tr")
      .Skip(1) //To Skip Table Header Row
      .Where(tr => tr.Elements("td").Count() > 1)
      .Select(tr => tr.Elements("td").Select(td => td.InnerText.Trim()).ToList())
      .ToList();

    return parsedTbl;
}

Invoking function signature:

ScrapHtmlTable("className1 className2", "https://www.abc.xz");

ASP.NET: Store Email Template in .NET

Standard

Simple and Easy to edit way to store email templates in your .net project is string email body in html file.

Step 1: Create a HTML mail message

2016-10-04-16_04_18-_c__users_hassan-muhammad_desktop_new-14-html-notepad

Step 1(a): You can introduce as many as variable in HTML template by any character scheme (@PARAMETER@ or #PARAMETER# or $$PARAMETER$$). Replace all names/variables with things like #VaraibleName#
The confirmation number is: <b>#confirmNumber#</b>
Step 2: Right click on web project and select Properties from right click menu

2016-10-04-16_08_58-recruiting-microsoft-visual-studio-administrator

Step 3: Select Resources tab from left, choose Add Resource, select Add Existing File and choose appropriate html file

2016-10-04-16_24_57-recruiting-microsoft-visual-studio-administrator

Step 4: File will be visible in Resources display pan

2016-10-04-16_26_31-recruiting-microsoft-visual-studio-administrator

Step 5: For Server side C# code

You can refer to HTML email template from Properties.Resources.EmailTemplate. You can use it as a string. Replace the #PARAMETER# text with the actual values.

private void SendConfirmationEmail(string email, string confirmNumber)
{
    var emailBody = Properties.Resources.EmailTemplate.Replace("#confirmNumber#", confirmNumber);
    MailMessage message =
        new MailMessage
        {
            From =
            new MailAddress("Sender Email Address"),
            Subject = "Email Subject Content",
            Body = string.Format(emailBody),
            IsBodyHtml = true
        };
 
    message.To.Add(new MailAddress(email));
    SmtpClient client = new SmtpClient("11.111.111.11");
    client.Send(message);
}

C#: Sending SOAP request and receiving response without using the WSDL or proxy classes

Standard

In order to send and receive SOAP messages from server in c# environment without the help of WSDL or Proxy classes.

Below major steps are involved:

  1. Mention Web Service URL and Method
  2. Create Web Request
  3. Create SOAP Envelope
  4. Insert SOAP Envelope into Web Request
  5. Capture SOAP response

Snippet

       public String SOAPManual()
       {
            const string url = "URL";
            const string action = "METHOD_NAME";
 
            XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
            HttpWebRequest webRequest = CreateWebRequest(url, action);
 
            InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
 
            string result;
            using (WebResponse response = webRequest.GetResponse())
            {
                using (StreamReader rd = new StreamReader(response.GetResponseStream()))
                {
                    result = rd.ReadToEnd();
                }
            }
            return result;
        }
 
        private static HttpWebRequest CreateWebRequest(string url, string action)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Headers.Add("SOAPAction", action);
            webRequest.ContentType = "text/xml;charset=\"utf-8\"";
            webRequest.Accept = "text/xml";
            webRequest.Method = "POST";
            return webRequest;
        }
 
        private static XmlDocument CreateSoapEnvelope()
        {
            XmlDocument soapEnvelopeXml = new XmlDocument();
            soapEnvelopeXml.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?>
                    <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
                    <soap:Body>
                    <Method xmlns=""http://www.sample.com/path/"">
                    <Parameter1>param1</Parameter1>
                    <Parameter2>param2</Parameter2>
                    </Method>
                    </soap:Body>
                    </soap:Envelope>");
            return soapEnvelopeXml;
        }
 
        private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
        {
            using (Stream stream = webRequest.GetRequestStream())
            {
                soapEnvelopeXml.Save(stream);
            }
        }