Category Archives: C#

Fizz Buzz game C#

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

//FizzBuzz Game
for (int i = 1; i <= 100; i++)
{
    if (i % 3 == 0 && i % 5 == 0)
    {
        Console.WriteLine("FizzBuzz");
    }
    else if (i % 3 == 0)
    {
        Console.WriteLine("Fizz");
    }
    else if (i % 5 == 0)
    {
        Console.WriteLine("Buzz");
    }
    else
    {
        Console.WriteLine(i);
    }
}
Console.ReadKey();

Update List from another list C#.

To update a list from another list, Here is the Syntax.
Syntax

foreach (var item in List2)
{
   List1.Where(m=>m.UniqueField == item.UniqueField).FirstOrDefault().Property = item.Property;
}


Example
1. Create Student model

class Student
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public double Marks { get; set; }

    public Student(int ID, string Name, int Age)
    {
        this.ID = ID;
        this.Name = Name;
        this.Age = Age;

    }
    public Student(int ID, double Marks)
    {
        this.ID = ID;
        this.Marks = Marks;
    }
}


2. Create Student List as listStudents

List<Student> listStudents = new List<Student>() 
{ 
    new Student(1, "Sam", 12),
    new Student(2, "Patrick", 15),
    new Student(3, "Adam", 10),
    new Student(4, "Raj", 9),
    new Student(5, "Seema", 14)
};


3. Create Student Marks as listMarks

List<Student> listMarks = new List<Student>() 
{ 
    new Student(1,89.5),
    new Student(2,97.5),
    new Student(3,96.0),
    new Student(4,78.0),
    new Student(5,84.7)            
};


4. Now Update listStudents from listMarks

Console.WriteLine("ID Name Marks");
foreach (var StudentMarks in listMarks)
{
    var selectedStudent = listStudents.Where(S => S.ID == StudentMarks.ID).FirstOrDefault();
    selectedStudent.Marks = StudentMarks.Marks;
    Console.WriteLine("{0} {1} {2} ", selectedStudent.ID, selectedStudent.Name, selectedStudent.Marks);
}
Console.ReadKey();

Convert a list of string to comma separated string C#.

Convert a list of string to Comma Separated String. String.join method is used to concatenate a list of string, Using a specified separator between each string.
Syntax : String.Join(string Separator, String[] Values);
Example :

static void Main(string[] args)
{           
    List<string> listStrings = new List<string>() { "C#", "Asp.Net", "SQL Server", "PHP", "Angular" };
    string CommaSeparateString = GenerateCommaSeparateStringFromList(listStrings);
    Console.Write(CommaSeparateString);
    Console.ReadKey();
}

private static string GenerateCommaSeparateStringFromList(List<string> listStrings)
{
    return String.Join(",", listStrings);            
}


Comma Separate String

Comma Separate String

Get address from latitude and longitude using Bing map api

We can find address components Country, AddressLine, Postal code etc. from latitude and longitude using Bing map api.
For this Microsoft provide a Bing map rest api service. Call this service using HttpClient and get response in json format. To use Bing map rest api service BingMapKey required. Create Bing map key from the portal https://www.bingmapsportal.com/. To parse json we use JsonConvert class. Install Newtonsoft.Json reference from the Nuget packages.

using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
public void GetAddressFromLatLon(decimal Latitude, decimal Longitude)
{
    var apiURL = "http://dev.virtualearth.net/Rest/v1/Locations/";
    var searchRequest = Latitude + "," + Longitude + "?&key=BingMapKey";
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri(apiURL);
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    HttpResponseMessage response = client.GetAsync(searchRequest).Result;
    string Country = string.Empty;
    string Address = string.Empty;
    if (response.IsSuccessStatusCode)
    {
        var json = response.Content.ReadAsStringAsync().Result;
        var jsonObject = JsonConvert.DeserializeObject<RootObject>(json);
        if (jsonObject.resourceSets.Count > 0)
        {
            if (jsonObject.resourceSets[0].resources.Count > 0)
            {
                Country = jsonObject.resourceSets[0].resources[0].address.countryRegion;
                Address = jsonObject.resourceSets[0].resources[0].address.addressLine;
            }
        }
    }

}


Call the service by passing Latitude and Longitude.

Decimal Latitude = Convert.ToDecimal(50.95846878);
Decimal Longitude = Convert.ToDecimal(6.97181002);
GetAddressFromLatLon(Latitude, Longitude);

How to fetch html from a URL in c#.

Fetching a html from an URL is easy. Class System.Net.HttpWebRequest provides an HTTP – specific implementation of the System.Net.WebRequest class.

using System.IO;
using System.Net;
public void FetchHtml()
{
    string result = string.Empty;
    string url = "http://codesolution.org";
    var request = HttpWebRequest.Create(url);
    using (var response = request.GetResponse())
    {
        result = new StreamReader(response.GetResponseStream()).ReadToEnd();
    }
    div1.InnerHtml = result;
}

Send email using smtp server.

We can send email using smtp server to any email address. We are using gmail smtp server to send email. For this we required Google username and password for authentication. If you want to send html text in body message than set IsBodyHtml property of MailMessage to true else false.

using System.Net.Mail;
public bool SendEmail()
{
    bool status = false;
    SmtpClient smtp = null;
    string sFrom = "From Email ID";
    string sTo = "To Email ID";
    string sBody = "Email body text";
    string sSubject = "Email subject";
    string sUser = "From Email ID";
    string sPwd = "From Email password";
    try
    {
        MailMessage mailmessage = new MailMessage();
        mailmessage.From = new MailAddress(sFrom);
        mailmessage.To.Add(sTo);
        mailmessage.Subject = sSubject;
        mailmessage.Body = sBody;
        mailmessage.IsBodyHtml = true; //false if body text is not in html format.
        smtp = new SmtpClient("Smtp.gmail.com");//send email using gmail smtp server.
        smtp.EnableSsl = true;
        smtp.Port = 587;
        smtp.Credentials = new System.Net.NetworkCredential(sUser, sPwd);//Google username and password for authentication.
        smtp.Send(mailmessage);
        status = true;
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        smtp.Dispose();
    }
    return status;
}

Enqueue and Dequeue operations on Queue in C#.

Enqueue Operations : Enqueue Operations are used to insert elements into Queue.

Queue<int> queue = new Queue<int>();
queue.Enqueue(1);
queue.Enqueue(2);
queue.Enqueue(3);
//Display queue elements after Enqueue
foreach (int i in queue )
  {
     Console.WriteLine(i);
  }

Dequeue Operations : Dequeue Operations are used to remove elements from the Queue.

queue.Dequeue();
//Display queue elements after Dequeue
foreach (int i in queue)
  {
     Console.WriteLine(i);
  }


Peek Operation : Peek Operation is used to get the beginning element from the Queue.

int begin = queue.Peek();
//Display Peek element from the Queue
Console.WriteLine(begin);

Push and Pop operations on Stack in C#.

Push Operations : Push Operations are used to insert elements into stack.

Stack<int> stack = new Stack<int>();
stack.Push(1);
stack.Push(2);
stack.Push(3);
//Display stack elements after Push
foreach (int i in stack)
  {
     Console.WriteLine(i);
  }


Pop Operations : Pop Operations are used to remove elements from the stack.

stack.Pop();
//Display stack elements after Pop
foreach (int i in stack)
  {
     Console.WriteLine(i);
  }


Peek Operation : Peek Operation is used to get the top element from the stack.

int top = stack.Peek();
//Display Peek element from the Stack
Console.WriteLine(top);

Difference between debug and trace in C#.

Debug

  • It is used to debug your code in development environment only.
  • Debugging is the process of finding and fixing errors in your code.
  • It works when solution configuration mode is Debug. In Release mode it does not write anything on the output window.
  • In debugging there is no such facility to differentiate between message types (Information, Error, Warning).
  • Example

    Debug.WriteLine("Debug Start");
    Debug.Indent();            
    Debug.WriteLine("Main Start");          
    Debug.WriteLine("Main End");
    Debug.Unindent();
    Debug.WriteLine("Debug End");
    Debug.Flush();
    Debug.Close();
    

Trace

  • It is used to trace the execution of your code in development as well as production environment.
  • Tracing is the process of collecting information about the program’s execution.
  • It works in both solution configuration modes Debug and Release.
  • In tracing we can easily differentiate between message types (Information, Error, Warning) using  Trace.TraceInformationTrace.TraceError and Trace.TraceWarning.
  • Example

    Trace.WriteLine("Trace Start");         
    Trace.Indent();
    Trace.TraceInformation("Information");
    Trace.TraceError("Error");
    Trace.TraceWarning("Warning");
    Trace.WriteLine("Main Start");
    Trace.WriteLine("Main End");
    Trace.Unindent();
    Trace.WriteLine("Trace End");
    Trace.Flush();
    Trace.Close();
    

How to destroy an object in C# ?

Destroying an object manually in C# is simple but it’s not a good practice. Assign null value to the object and call the garbage collector’s Collect() method.

public class BaseClass
{
    public BaseClass()
    {
        Console.WriteLine("base class constructor");
    }  

    ~BaseClass()
    {
        Console.WriteLine("base class destructor");
    }

    public virtual void Print()
    {
        Console.WriteLine("I am Software Developer !!");
    }
}
class Program
{
    static void Main(string[] args)
    {
        BaseClass objBase = new BaseClass();
        objBase.Print();
        objBase = null;
        GC.Collect();          
        Console.ReadKey();
    }
}