Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, August 6, 2025

Send mail using SendGrid

 Hi, Today I'm writing a brief post on how to send mail through SendGrid using C#.

Here I'm using the free mail service offered by SendGrid, which will expire in a month's time.

1) Go to SendGrid and sign up for a free account https://sendgrid.com/

2) Provide the details

Fill in:

  • Name, email, password
  • Company name (can be anything)

Verify your email address

Add a phone number (sometimes required for verification)

3) Once you are in, go to Settings > API Keys to generate your API Key. Save your api key in a secure place, as it will not be viewable afterwards.

4) Next, you have to create a Sender Authentication. Go to Settings > Sender Authentication and select from the two sender authentication types available.

  1. Domain Authentication [learn more from SendGrid How-to-set-up-domain-authentication ]
  2. Single Sender Verification [learn more from SendGrid Docs sender-verification ]


Below is my C# code for a very basic POC console application

        public static void SendEmail()

        {

            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            MailMessage mail = new MailMessage("from@mail.com", "to@mail.com");

            mail.Subject = "3rd mail TEST Personal Email";

            mail.Body = "3rd mail TEST Personal Sent using manual SMTP ";

            using (SmtpClient smtp = new SmtpClient("smtp.sendgrid.net", 587))

            {

                smtp.Credentials = new NetworkCredential("apikey", "SG.h2******.*******-***");

                smtp.EnableSsl = true;

                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

                smtp.Send(mail);

            }

        }

Note: SG.h2******.*******-*** is the API Key I received from SendGrid

Execute the code and get your mails delivered. You can also view the mail delivery status from SendGrid Activity Feed.




Thursday, January 30, 2020

Extension Methods

Extension methods allow you to inject additional methods without modifying, deriving or recompiling the original class, struct or interface.

An extension method is actually a special kind of static method defined in a static class. To define an extension method, define a static class.

The first parameter of the extension method specifies the type on which the extension method is applicable. So the first parameter must be preceded with the this modifier.

Extension methods can be recognized in Visual Studio Intellisense as shown below



Example :  In the below example I am performing multiplication on a integer by calling the Multiply() extension method. then I do a division. Here before dividing the two numbers I check if the divisor is positive by using the isPositive() extension method, then do the division by using the Division() extension method

1) static class containing Extension Methods

    public static class Extensions
    {
        public static int Multiply(this int number, int multiplier)
        {
            return number * multiplier;
        }

        public static bool isPositive(this int number)
        {
            return number > 0;
        }

        public static double Division(this int dividend, int divisor)
        {
            return dividend / divisor;
        }
    }

2) class to test the extension methods

    class ExtensionMethodsTest
    {
        /// <summary>
        ///  Usage one - Multiplication
        /// </summary>
        public void GetMultiplier()
        {
            int i = 5;
            int result = i.Multiply(10);
            Console.WriteLine(result);         
        }

    /// <summary>
    /// usage two - Division
    /// </summary>
    public void GetDivisor()
        {
            int dividend = 256;
            int divisor = -1;
            double? quotient = null;

            if (divisor.isPositive())
            {
                quotient = dividend.Division(divisor);
            }
            else
            {
                Console.WriteLine("Divisor should be a positive number");
            }
            Console.ReadLine();
        }
    }

3) calling the ExtensionMethodsTest class

            ExtensionMethodsTest test = new ExtensionMethodsTest();
            test.GetMultiplier();
            test.GetDivisor();

Result:

Monday, August 6, 2018

Create Azure Storage and store images as blobs

1. Create a Storage Account

Connect to Azure portal.
In the left pane you can see the "Storage accounts". Click on the link.

On the top left hand side you can click on "Add" and add new storage account. Specify the storage name and etc.. You can either create a new resource group or use an existing group for your storage's resource group.

once created you get the below page, listing your storage accounts. click on the newly created storage account.

Note that you get a list of storage options which you can modify and add. You can  also get the connection string to the storage account under the "Access keys" section.

The next step is to create a container inside the storage to hold the blobs, in my care its going to be the images.


2. Create the container to store the blobs
Click on containers. create a new container. I have named it as "Images"


3. Now is the fun part. Coding to upload the images to Azure Blob Storage

        public string UploadImageUsingByteArray(byte[] byteArray, string fileNamewithGuid)
        {
            string blobUrl = string.Empty;
            try
            {
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString); //here the storageConnectionString you can obtain from the storage properties under Access keys

                //Create a blob client
                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer container = blobClient.GetContainerReference(imageContainerName); //my container name is image
                container.CreateIfNotExists();

                if (container.Exists())
                {
                    CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileNamewithGuid);
                    blockBlob.Properties.ContentType = "image/jpeg";
                    blockBlob.UploadFromByteArray(byteArray, 0, byteArray.Length);


                    blobUrl = blockBlob.Uri.AbsoluteUri; //returns the blob's URL. How awesome is that
                }
            }
            catch (Exception)
            {
                throw;
            }
            return blobUrl;
        }

Here I have used the option to upload a byte array using the method UploadFromByteArray(). You can also use the method UploadFromStream() if your input is a stream. It works for a file stream as well.

Refresh the container when your code has run, and you get your images in Azure blob

Tuesday, July 31, 2018

Use of Linq when mapping between objects

The class which data is loaded from the database. Notice data is loaded through Entity Framework

    public class UserType : EntityBase
    {
        [DisplayName("User Type")]
        [Required]
        [Remote("IsUserTypeExist", "Validation", ErrorMessage = "user type already exist! ")]
        public string UserTypeName { get; set; }

        public virtual List<User> users { get; set; }
    }

The Data Transfer Object which is used in the system

    public class UserTypeDTO
    {
        public int Id { get; set; }
        public string UserTypeName { get; set; }
        public bool Archived { get; set; }
    }

Mapping inside the method

        public List<UserTypeDTO> GetUserTypes(AppContext db)
        {
            return db.UserTypes.Select(u => new UserTypeDTO()
            {
                Id = u.Id,
                UserTypeName = u.UserTypeName,
                Archived = u.Archived
            }
            ).ToList();
        }


Saturday, February 21, 2015

Playing around with the TreeView

Playing around with the ASP.Net TreeView.

Initially a TreeNode is created and child nodes are added under the node.

        TreeNode tree = new TreeNode();
        
        tree.Value = "Social Media";
        tree.ImageUrl = "/images/home.png";
        tree.ChildNodes.Add(new TreeNode("Facebook", "Facebook","/images/fb.png"));
        tree.ChildNodes.Add(new TreeNode("G+","GPlus","/images/google.png"));
        tree.ChildNodes.Add(new TreeNode("Printrest", "Printrest", "/images/pintrest.png"));
        tree.ChildNodes.Add(new TreeNode("Twitter", "Twitter", "/images/twitter.jpg"));

Now lets add some child nodes under the created nodes. In this example the below would be the leaf nodes.

            foreach (TreeNode node in tree.ChildNodes)
            {
                node.ChildNodes.Add(new TreeNode("Sri Lanka", string.Concat(node.Value,"-","SL"), "/images/countries/SL-flag.jpg"));
                node.ChildNodes.Add(new TreeNode("Malaysia", string.Concat(node.Value,"-","ML"), "/images/countries/malaysia-flag.png"));
                node.ChildNodes.Add(new TreeNode("USA", string.Concat(node.Value,"-","USA"), "/images/countries/US-Flag.png"));
                node.ChildNodes.Add(new TreeNode("Britain", string.Concat(node.Value,"-","BRIT"), "/images/countries/Britain-flag.png"));
                node.ChildNodes.Add(new TreeNode("Australia", string.Concat(node.Value,"-","AUS"), "/images/countries/Australia-Flag.png"));
                node.ChildNodes.Add(new TreeNode("Netherlands", string.Concat(node.Value,"-","NL"), "/images/countries/netherlands-flag.png"));
                node.ChildNodes.Add(new TreeNode("Egypt", string.Concat(node.Value,"-","EG"), "/images/countries/Egypt-Flag.png"));
                node.ChildNodes.Add(new TreeNode("Greece", string.Concat(node.Value,"-","GR"), "/images/countries/greece_flag.png"));
                node.ChildNodes.Add(new TreeNode("Germany", string.Concat(node.Value,"-","GE"), "/images/countries/germany-flag.png"));
                node.ChildNodes.Add(new TreeNode("Canada", string.Concat(node.Value,"-","CA"), "/images/countries/canada_flag.png"));
                node.ChildNodes.Add(new TreeNode("Brazil", string.Concat(node.Value,"-","BR"), "/images/countries/brazil-flag.png"));
            }

 The TreeNode is then set to a TreeView to be displayed in the Form.

        TreeView view = new TreeView();
        view.ShowCheckBoxes = TreeNodeTypes.All;
        view.Nodes.Add(tree);
        view.TreeNodeCheckChanged += view_TreeNodeCheckChanged;
        view.Attributes.Add("onclick", "postBackByObject()");

        form1.Controls.Add(view);

Here, notice the JavaScript method postBackByObject() which does the job of auto postbacking on clicking on a Checkbox of a Node. For this purpose you need to add the following script in the ASPX page. Auto post backing comes in handy when you need to check or uncheck the set of child-nodes belonging to a selected node.


    <script type="text/javascript">
        function postBackByObject() {
            var o = window.event.srcElement;
            if (o.tagName == "INPUT" && o.type == "checkbox") {
                __doPostBack("", "");
            }
        }
    </script>

To programmatically check or uncheck child nodes of a node, use the TreeNodeCheckChanged event. A sample code would be:

    void view_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
    {
        if (e.Node.Checked)
        {
            CheckChildNodes(e.Node.ChildNodes);
        }
        else if (e.Node.Checked == false)
        {
            UncheckChildNodes(e.Node.ChildNodes);
        }
    }

    private void UncheckChildNodes(TreeNodeCollection children)
    {
        foreach (TreeNode child in children)
        {
            if (child.Checked)
                child.Checked = false;
            UncheckChildNodes(child.ChildNodes);
        }
    }

    private void CheckChildNodes(TreeNodeCollection children)
    {
        foreach (TreeNode child in children)
        {
            if (child.Checked == false)
                child.Checked = true;
            CheckChildNodes(child.ChildNodes);
        }
    }

Then you get the resulting tree as below. The data in this view is created merely for illustration purposes of the ASP.Net TreeView and has no actual meaning.




Saturday, January 3, 2015

Add a new Row to DataTable in DataSet and Push the update to Database


Example is as below:

            string connectionString = "Data Source=****;Initial Catalog=master;Persist Security Info=True;User ID=**;Password=****";

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand command = new SqlCommand("select top 10 * from Test", conn))
                {

                    conn.Open();
                    SqlDataAdapter adapter = new SqlDataAdapter(command);
                    DataSet ds = new DataSet();
                    adapter.Fill(ds);

                    DataRow row = ds.Tables[0].NewRow();
                    row["EID"] = "006";
                    row["Name"] = "Saman";
                    row["Tel"] = "01115342";
                    row["Residence"] = "Galle, Sri Lanka";

                    ds.Tables[0].Rows.Add(row);

                    //Update Database
                    SqlCommandBuilder cb = new SqlCommandBuilder(adapter);
                    cb.DataAdapter.Update(ds.Tables[0]);
                }
            }

Sunday, December 7, 2014

T SQL - Playing around with Image Type ( Create, Insert, Select )

This post briefly describes about creating tables containing image, storing and retrieving images in SQL Server

1) Create a table containing image type

CREATE TABLE dbo.MyImages
(ImageId    INT IDENTITY(1,1) NOT NULL,
 uid             BIGINT NULL, 
 picture       IMAGE NULL
 PRIMARY KEY(ImageId ))


2) Insert an image into the DataBase table. 

INSERT INTO MyImages(picture)
SELECT * FROM OPENROWSET(BULK N'C:\images\emp001.png', SINGLE_BLOB) AS myrow

OR you can go with the full row insert as:

INSERT INTO MyImages(uid, picture)
SELECT 2000, PicColumn FROM OPENROWSET(BULK N'C:\images\emp001.png', SINGLE_BLOB) AS myrow

Here, you need to specify the path to the image in the drive, for it to be captured by the insert.

3) Retrieving for display

It's best that you have a handler for retrieving images from DB. For an example could use a generic handler (.ashx file).

3.1
In the handler's (.ashx file's) ProcessRequest() method set

        context.Response.Clear();
        context.Response.ContentType = "image/jpeg";

3.2
In the ashx file create a method to retrieve image from DB. The query string would be straight forward.

Eg: "SELECT uid, picture FROM dbo.MyImages WHERE" + uid

Capture the resulting row may be in a DataTable.

3.3
get the image into a byte array

byte[] imageByteArray=null;
imageByteArray=(byte[])sampleDataTable.Rows[0][1];

3.4
Include the byte[] to  memory stream, and set it for output

MemoryStream memStream = new MemoryStream(imageByteArray, false);
System.Drawing.Image img = System.Drawing.Image.FromStream(memStream);
img .Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);

3.5
In the aspx page's calling the method ( Eg: inside an item data bound method ).
Set the image url by pointing to the handler

myImage.ImageUrl = "/pathtothe ashpage/sample.ashx?uid=" + uid;




Sunday, November 30, 2014

Storing integers in an enum

Example
  
enum DepartmentID
    {
        HumanResource = 1001,
        Marketing = 1002,
        Sales = 1003,
        Logistics = 1004,
        Operations = 1005,
        Finance = 2003,
        IT = 2002,
        Training = 2001,      
        SharedServices = 1006,
    }

On instances where you need the departmental id, you could easily retrieve the integer values of the enum by casting:

Eg:
(int)DepartmentID.Marketing


Hence, the code becomes easy to maintain.
On a side note: Comes in handy when building a query string for a sql select command.


Saturday, November 29, 2014

Formatting ListView Items

Formatting can be done either through the ASPX page or on the code behind. Below are two different instances where formatting is done.

1) Formatting the <ItemTemplate> in the Aspx page


<div class="EmployeeName">

<asp:Label ID="sampleLabel" Text='<%# String.IsNullOrEmpty(DataBinder.Eval(Container.DataItem, "employeeName").ToString()) ? "" :  DataBinder.Eval(Container.DataItem, "employeeName").ToString().PadRight(140).Substring(0,140).TrimEnd() %>'
Runat="server"/>

</div>
   
Here....I'm getting values from the database. I do, an "empty or null" check. In case the condition is true, display nothing, else display the values retrieved from the DB while restricting text  to 141 characters.                  

2) Also, you could do stuff in the code behind. Below, I limit text on item data bound.

2.1) First create a event handler

<asp:ListView ID="SearchResultsListView" runat="server" ... OnItemDataBound="employeeListView_ItemDataBound">

2.2) Then...
In the employeeListView_ItemDataBound method add the relevant code. I have added some formatting code. The FindControl() method is used to capture the label.

protected void employeeListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
            string trailer = "...";
            string tempString = string.Empty;
            Label sampleLabel;

            sampleLabel = (Label)e.Item.FindControl("sampleLabel");
            if (sampleLabel.Text.Length > 100)
            {
                tempString = sampleLabel.Text.Substring(0, 96).Trim();
                sampleLabel.Text = tempString + trailer;
            }
}


Sunday, November 16, 2014

ADO.Net - SqlDataReader

Below is a sample usage of the SqlDataReader class in ADO.Net.
reader.HasRows checks if any rows are returned.


string connectionString = "Data Source=DataBaseServerName;Initial Catalog=DataBaseName;Persist Security Info=True;User ID=UserName;Password=Password;";
string query = "select eid, name, email from dbo.Employee where status=1";

            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    SqlCommand command = new SqlCommand(query, connection);
                    connection.Open();

                    SqlDataReader reader = command.ExecuteReader();

                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            Console.WriteLine("Column1 : {0} | Column2 : {1} | Column3 : {2}", reader[0],                                          reader[1], reader[2]);
                        }
                    }
                    reader.Close();
                }
            }


Saturday, November 15, 2014

Download file from SharePoint site to the Server Drive for processing

There could be times where one might need to download a file for processing in the server before rendering. May be for a file type conversion prior to rendering or so...During such instances this can be used. The below code block needs to be run within elevated privileges.


web.AllowUnsafeUpdates = true;
SPFile file = web.GetFile(fileUrl);

using (FileStream outStream = new FileStream("Specify the file Download location in server drive"), FileMode.Create))
{
    byte[] obj = (byte[])file.OpenBinary();
    outStream.Write(obj, 0, obj.Length);
}
web.AllowUnsafeUpdates = false;


Side Note:
You can specify the download location in the web.config <AppSettings> section and retrieved via:
ConfigurationManager.AppSettings["AppSettingName"].ToString();


Sunday, April 6, 2014

Execute Server Process from Server Side Code

Sometimes when dealing with certain scenarios, there comes the question, whether a server side process execution could be initiated through server side code. This could be done. In fact this could be done in SharePoint. The code needs to be run withing elevated privileges.



Process proc = new Process();
proc.StartInfo.FileName = string.Concat(ConfigurationManager.AppSettings["Get The File Path"].ToString(), "MYExecutable.exe");
 proc.StartInfo.Arguments = "\"" + ConfigurationManager.AppSettings["argumentOne"].ToString() + file.Name + "\"" + " -o \"" + ConfigurationManager.AppSettings["argumentTwo"].ToString() + myFile + "\"";

proc.StartInfo.UseShellExecute = false;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.RedirectStandardOutput = true;

proc.Start();
proc.WaitForExit();