Tuesday, December 14, 2021

What is C# ("See Sharp") | Introduction of C#

 C# (pronounced "See Sharp") is a modern, object-oriented, and type-safe programming language. C# is a simple programming language developed by Microsoft within its .NET Framework, C# enables developers to build many types of secure and robust applications that run in . NET. C# has its roots in the C family of languages and will be immediately familiar to C, C++, Java, and JavaScript programmers. 

C# programming is very much based on C and C++ programming languages, so if you have a basic understanding of C or C++ programming, then it will be fun to learn C#.


Overview

C# is a modern, object-oriented programming language developed by Microsoft. C# was developed by Anders Hejlsberg during the development of the .Net Framework.

C# is designed for Common Language Infrastructure (CLI), which consists of the executable code and runtime environment that allows the use of various high-level languages on different computer platforms and architectures.

The below-given reasons make C# a widely used programing language:−

It is a modern, general-purpose programming language
It can be compiled on a variety of computer platforms.
It is a part of the .Net Framework.
It is object-oriented.
It is component-oriented.
It produces efficient programs.
It is easy to learn.
It is a structured language.
It is a very simple programing language.



Thursday, March 25, 2021

Function to Get EmailAddress of Linkedin user using Linkedin Auth token

 //Generate & Validate Linkedin token and then get EmailAddress Data


public LinkedinEmailAddressResponse ValidateLinkedinTokenAndGetEmailAddressDetails(string tokenCode)

{

try

{

LinkedinTokenDTO LinkedinToken = GenerateLinkedinToken(tokenCode);

var request = new RestRequest(Method.GET);

LinkedinEmailAddressResponse emailaddressData = new LinkedinEmailAddressResponse();

if (LinkedinToken != null && !string.IsNullOrWhiteSpace(LinkedinToken.access_token))

{

var client = new RestClient("https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))");

client.Timeout = -1;

request.AddHeader("Host", "api.linkedin.com");

request.AddHeader("Connection", "Keep-Alive");

request.AddHeader("Authorization", "Bearer " + LinkedinToken.access_token);

IRestResponse response = client.Execute(request);

emailaddressData = JsonConvert.DeserializeObject<LinkedinEmailAddressResponse>(response.Content);

}

return emailaddressData;

}

catch (Exception ex)

{

}

return null;

}

Function to Get Linkedin User Profile Data (like first name , last name , photo etc) using Linkedin Auth Token

//Function to get LinkedIn user profile data using LinkedIn auth token


public LinkedinProfileDetailsDTO ValidateLinkedinTokenAndGetProfileDetails(string tokenCode)

{

try

{

LinkedinTokenDTO LinkedinToken = GenerateLinkedinToken(tokenCode);

var request = new RestRequest(Method.GET);

LinkedinProfileDetailsDTO profiledata = new LinkedinProfileDetailsDTO();

if (LinkedinToken != null && !string.IsNullOrWhiteSpace(LinkedinToken.access_token))

{

                    var client = new RestClient("https://api.linkedin.com/v2/me");

                    client.Timeout = -1;

                    request.AddHeader("Host", "api.linkedin.com");

                    request.AddHeader("Connection", "Keep-Alive");

                    request.AddHeader("Authorization", "Bearer " + LinkedinToken.access_token);

                    IRestResponse response = client.Execute(request);

                    profiledata = JsonConvert.DeserializeObject<LinkedinProfileDetailsDTO>(response.Content);

                }

return profiledata;

}

catch (Exception ex)

{

}

return null;

}





///-----------------------Response Model Class's to receive and parse response----------------------


public class LinkedinProfileDetailsDTO
    {
        public string localizedLastName { get; set; }
        public FirstName firstName { get; set; }
        public LastName lastName { get; set; }
        public string id { get; set; }
        public string localizedFirstName { get; set; }
        public string emailAddress { get; set; }
    }
    public class Localized
    {
        public string en_US { get; set; }
    }

    public class PreferredLocale
    {
        public string country { get; set; }
        public string language { get; set; }
    }

    public class FirstName
    {
        public Localized localized { get; set; }
        public PreferredLocale preferredLocale { get; set; }
    }

    public class LastName
    {
        public Localized localized { get; set; }
        public PreferredLocale preferredLocale { get; set; }
    }
    public class LinkedinTokenDTO
    {
        public string access_token { get; set; }
        public int expires_in { get; set; }
    }

Generate Linkedin Auth Token using Token Code

 public LinkedinTokenDTO GenerateLinkedinToken(string tokenCode)

{

try

{

var ClientId = Startup.StaticConfig["Authentication:Linkedin:ClientId"];//Your client ID

var ClientSecret = Startup.StaticConfig["Authentication:Linkedin:ClientSecret"];//Your Client Secret

var RedirectURL = Startup.StaticConfig["Authentication:Linkedin:RedirectURL"];//Your application redirect URL

var client = new RestClient("https://www.linkedin.com/oauth/v2/accessToken?grant_type=authorization_code&code=" + tokenCode + "&redirect_uri=" + RedirectURL + "&client_id=" + ClientId + "&client_secret=" + ClientSecret);

var request = new RestRequest(Method.POST);

request.AddHeader("cache-control", "no-cache");

IRestResponse response = client.Execute(request);

LinkedinTokenDTO linkedinToken = new LinkedinTokenDTO();

linkedinToken = JsonConvert.DeserializeObject<LinkedinTokenDTO>(response.Content);

return linkedinToken;

}

catch (Exception ex)

{

}

return null;

}

Monday, March 1, 2021

How to create html table using code behind in asp.net / C#/ MVC

   StringBuilder sb = new StringBuilder();
            sb.Append("Dear Team <br/> Please find the " + FormName + " Request Details below. ");
            //Table start.
            sb.Append("<table cellpadding='5' cellspacing='0' style='border: 1px solid #ccc;font-size: 9pt;font-family:Arial'>");
            //Adding HeaderRow.
            sb.Append("<tr>");
            sb.Append("<th style='background-color: #B8DBFD;border: 1px solid #ccc'>" + "Name" + "</th><th style='background-color: #B8DBFD;border: 1px solid #ccc'>" + "Mobile no" + "</th>");
            sb.Append("<th style='background-color: #B8DBFD;border: 1px solid #ccc'>" + "Email" + "</th><th style='background-color: #B8DBFD;border: 1px solid #ccc'>" + "Nationality" + "</th>");
            sb.Append("<th style='background-color: #B8DBFD;border: 1px solid #ccc'>" + "City" + "</th><th style='background-color: #B8DBFD;border: 1px solid #ccc'>" + "Company" + "</th>");
            sb.Append("<th style='background-color: #B8DBFD;border: 1px solid #ccc'>" + "Occupation" + "</th><th style='background-color: #B8DBFD;border: 1px solid #ccc'>" + lblOccupation + "</th>");
            sb.Append("<th style='background-color: #B8DBFD;border: 1px solid #ccc'>" + lblTotalExp + "</th><th style='background-color: #B8DBFD;border: 1px solid #ccc'>" + "Remarks" + "</th>");
            sb.Append("</tr>");
            //Adding DataRow.
            sb.Append("<tr>");
            sb.Append("<td style='width:100px;border: 1px solid #ccc'>" + objRequest.Name + "</td> <td style='width:100px;border: 1px solid #ccc'>" + objRequest.Phone + "</td>");
            sb.Append("<td style='width:100px;border: 1px solid #ccc'>" + objRequest.Email + "</td> <td style='width:100px;border: 1px solid #ccc'>" + objRequest.Nationality + "</td>");
            sb.Append("<td style='width:100px;border: 1px solid #ccc'>" + objRequest.City + "</td> <td style='width:100px;border: 1px solid #ccc'>" + objRequest.Company + "</td>");
            sb.Append("<td style='width:100px;border: 1px solid #ccc'>" + objRequest.EmploymentStatus + "</td> <td style='width:100px;border: 1px solid #ccc'>" + OccupationName + "</td>");
            sb.Append("<td style='width:100px;border: 1px solid #ccc'>" + OccupationExperience + "</td> <td style='width:100px;border: 1px solid #ccc'>" + objRequest.Remarks + "</td>");
            sb.Append("</tr>");
            //Table end.
            sb.Append("</table>");

Send Email Using Gmail SMTP / Send Mails from asp.net Application / How to send Emails form Code Behind file in asp.net

C# Class to send mail
=======================

 
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Configuration;
using System.Net.Mail;
using System.Web;
using System.Web.UI.WebControls;
namespace VSGCapital.EMailer
{
    public class Mailer
    {
        public int  SendEmail(eMail request)
        {
            int isMailSent = 0;
            try
            {
                SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
                string receiverEmailAddress = ConfigurationSettings.AppSettings["ReceiverEmailAddress"];
                string smtpAddress = smtpSection.Network.Host;
                int portNumber = smtpSection.Network.Port;
                bool enableSSL = smtpSection.Network.EnableSsl;
                string emailFromAddress = smtpSection.From; //Sender Email Address  
                string password = smtpSection.Network.Password; //Sender Password  
                string emailToAddress = receiverEmailAddress; //Receiver Email Address  
                string subject = request.Subject;//mail subject line
                string body = request.Body;//mail body
                using (MailMessage mail = new MailMessage())
                {
                    mail.From = new MailAddress(emailFromAddress);
                    mail.To.Add(emailToAddress);
                    mail.Subject = subject;
                    mail.Body = body;
                    mail.IsBodyHtml = true;
                    mail.IsBodyHtml = true;
                    //mail.Attachments.Add(new Attachment("D:\\TestFile.txt"));//--Uncomment this to send any attachment  
                    using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
                    {
                        smtp.Credentials = new NetworkCredential(emailFromAddress, password);
                        smtp.EnableSsl = enableSSL;
                        smtp.Send(mail);
                        isMailSent = 1;
                    }
                }
            }
            catch (Exception ex)
            {
                isMailSent= 0;
            }
            return isMailSent;
        }
    }

   public class eMail
    {
        public string SenderEmailAddress { get; set; }

        public string ReceiverEmailAddress { get; set; }

        public string Body { get; set; }

        public string Subject { get; set; }
    }

}




Note- Add Below Given settings into Web.Config File.
=====================================

<appSettings>
    <add key="ReceiverEmailAddress" value="receiverEmailAccount@gmail.com" />
  </appSettings>

 <system.net>
    <mailSettings>
      <smtp deliveryMethod="Network" from="senderEmailAccount@gmail.com">
        <network
            host="smtp.gmail.com"
            port="587"
            enableSsl="false"
            userName="senderEmailAccount@gmail.com"
            password="abdc@123"
            defaultCredentials="true"/>
      </smtp>
    </mailSettings>
  </system.net>

Wednesday, February 17, 2021

Get Base64 Encoded String of Image from Image URL in .net core API ( convert image into base64 encoded string from URL in c#/asp.net )

NOTE-Please Include Below given Namespaces into you .net core api Controller.

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Extensions;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;             





  [HttpGet("get-base64string-from-ImageURL")]
  public async Task<string> GetImageBase64StringFromImageURL(string imageUrl)
       {
                      string response =string.Empty;
                      try
                      {
                             System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(imageUrl);
                             webRequest.AllowWriteStreamBuffering = true;
                             webRequest.Timeout = 30000;
                             System.Net.WebResponse webResponse = webRequest.GetResponse();
                             Stream ImageStream = webResponse.GetResponseStream();
                             using (System.Drawing.Image image = System.Drawing.Image.FromStream(ImageStream))
                             {
                                    using (MemoryStream m = new MemoryStream())
                                    {
                                           image.Save(m, image.RawFormat);
                                           byte[] imageBytes = m.ToArray();
                                           response = Convert.ToBase64String(imageBytes);
                                    }
                             }
                      }
                      catch (Exception e)
                      {
                             response = "";
                      }
                      return response;
      } 




What is C# ("See Sharp") | Introduction of C#

  C# (pronounced " See Sharp ") is a modern, object-oriented, and type-safe programming language.  C# is a simple programming lan...