Advertisements

Sending SMS using ASP.NET Core With Twilio SMS API


Introduction

In this article, we will explain how to Send SMS using ASP.NET Core With Twilio SMS API. Twilio provides third party SMS API for sending sms over the global network. So we can learn a little bit through this article.

Before reading this article, you must read the articles given below for ASP.NET Core knowledge.

Package Installation

  1. Install-Package Twilio -Version 5.9.1

This package will install all the sms,video,etc related classes,methods and API’s for twilio.

  1. Install-Package jQuery.Validation.Unobtrusive -Version 2.0.20710

This package will install all the bootstrap & validation related Jquery libraries in our project.

Important Notes

1. If you don’t have any twilio account then you should register a free account using the following link Click here & I choose language as “C#”.

2. Once registration is completed then we can access Dashboard and Console of our twilio account. We will get “Account SID & Auth Token Id” from Dashboard for sending sms.

Dashborad Console

Dashborad Console

3. We need a Twilio From number because that number has sent sms to the global network! So we need to enable Twilio SMS number ( This will send sms from ur “To” numbers ). Go to this link click here and Click on the “Get a number” button in the “Programmble SMS Menu” mentioned in the following screenshot.

Get a Number

Get a Number

4. You have to get $15 for sending sms In the twilio trial account. I can see in my account they are charging $1 + for each sms and after that you need to buy a paid plan.

Name Spaces

The following namespaces are providing “ASP.Net Core MVC” & “Twilio SMS API” Classes & Methods.

using System;
using Microsoft.AspNetCore.Mvc;
using RegistrationForm.ViewModels;
using Twilio;
using Twilio.Types;
using Twilio.Rest.Api.V2010.Account;

Configuring ASP.NET MVC in ASP.NET Core

We are going to add “UseMvc” Middleware and “AddMvc()” Configure Services in Startup.cs Class. The code given below clearly mentions that manually we need to add our controller name and an action name in “MapRoute”. We can change this controller name and action name, which is based on our requirement in the Applications.

 app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

Startup.cs

The class given below contains the complete middleware details in our Applications. I choose a default project in our Visual Studio 2015. So automatically it will generate the following classes & methods.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace SMSApp
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();

            if (env.IsDevelopment())
            {
                // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
                builder.AddApplicationInsightsSettings(developerMode: true);
            }
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);

            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseApplicationInsightsRequestTelemetry();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseApplicationInsightsExceptionTelemetry();

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Code
The following code help to send sms over the global network using ASP.Net Core With Twilio SMS API.

[HttpPost]
        public IActionResult Registration(RegistrationViewModel model)
        {
            ViewData["Message"] = "Your registration page!.";

            ViewBag.SuccessMessage = null;

            if (model.Email.Contains("menoth.com"))
            {
                ModelState.AddModelError("Email", "We don't support menoth Address !!");
            }

            if (ModelState.IsValid)
            {
                try
                {
                    // Find your Account Sid and Auth Token at twilio.com/user/account
                    const string accountSid = "AXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
                    const string authToken = "6XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
                    TwilioClient.Init(accountSid, authToken);

                    var to = new PhoneNumber("+91" + model.Mobile);
                    var message = MessageResource.Create(
                        to,
                        from: new PhoneNumber("+18XXXXXXXXXX"), //  From number, must be an SMS-enabled Twilio number ( This will send sms from ur "To" numbers ).
                        body:  $"Hello {model.Name} !! Welcome to Asp.Net Core With Twilio SMS API !!");

                    ModelState.Clear();
                    ViewBag.SuccessMessage = "Registered Successfully !!";
                }
                catch (Exception ex)
                {
                    Console.WriteLine($" Registration Failure : {ex.Message} ");
                }

            }

            return View();
        }

New Tag Helpers

We used latest ASP.NET Core Tag Helpers in Registration page to access controller and actions, validation etc.





<div asp-validation-summary="All" class="text-danger"></div>



<label asp-for="Name"></label>  
<input asp-for="Name" class="form-control" />  
<span asp-validation-for="Name" class="text-danger"></span>  
<a asp-controller="Home" asp-action="Home" class="btn btn-info">Cancel</a>

Inject Tag Helpers

In the way given below, we can inject the Tag Helpers in our Application. Now, create the default “_ViewImports.cshtml” file in View Folder and add the code given below in that file.

@addTagHelper "*,Microsoft.AspNetCore.Mvc.TagHelpers"

Client Side validations

The Client Side validation is done with the help of Bootstrap & jQuery etc.

Validation

Validation

Registration Page

The message will send to the respective mobile number that you have given in the mobile number column in registration page.

OutPut

We will get a sms from the Twilio account, once we have registered successfully.

Reference

Download

See Also

You can download other ASP.NET Core source codes from MSDN Code, using the link, mentioned below.

Summary

We learned how to Send SMS using ASP.NET Core With Twilio SMS API. I hope this article is useful for all ASP.NET Core beginners.

Advertisements

Find and Highlight Data in Excel Using C# & Spire.XLS


Introduction

Hi Everyone..!! Recently I got an opportunity from a China-Based company, E-iceblue, to review one of their products. So I selected Spire.Pdf from E-iceblue.The article was Convert pdf to other format using Spire.Pdf. Now I am going introduce Spire.XLS. The Spire.XLS for .NET is a professional Excel .NET component that can be used to any type of .NET 2.0, 3.5, 4.0 or 4.5 framework application, both ASP.NET web sites and Windows Forms applications. Spire.XLS for .NET offers object model Excel API for speeding up Excel programming in .NET platform – create new Excel documents from template, edit existing Excel documents, and convert Excel files.

Namespace :

The following code contain “Spire.Xls”. This library contains the functionality of highlight data in excel,Excel Version,Excel Location,etc.

using Spire.Xls;
using System.Drawing;

Code :

using Spire.Xls;
using System.Drawing;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //load an excel file from system
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(@"C:\Users\RAJEESH\Desktop\TestSpireXls.xlsx", ExcelVersion.Version2013);

            //find and highlight excel data
            Worksheet sheet = workbook.Worksheets[0];
            foreach (CellRange range in sheet.FindAllString("Palakkad",true,true))
            {
                range.Style.Color = Color.Green;
            }
            //save and launch the project
            workbook.SaveToFile("NewProduct.xlsx", ExcelVersion.Version2013);
            System.Diagnostics.Process.Start("NewProduct.xlsx");
        }
    }
}

Creating the instance of PdfDocument

Workbook workbook = new Workbook();

Load the file location & Selecting the version of Excel

Loading the location of excel file for “TestSpireXls.xlsx“. We need to specify the version of excel file on loading the process.

 
workbook.LoadFromFile(@"C:\Users\RAJEESH\Desktop\TestSpireXls.xlsx", ExcelVersion.Version2013);

The following excel versions are contain in Spire.Xls.

  • ODS
  • Version2007
  • Version2010
  • Version2013
  • Version97to2003
  • Xlsb2007
  • Xlsb2010

Find and Highlight Excel Data

The following code is finding string as “Palakkad” in  excel sheet. So we can change this based on our requirement. Other finding options and Color options are specified in Pic 1 & Pic 2 respectively.

            Worksheet sheet = workbook.Worksheets[0];
            foreach (CellRange range in sheet.FindAllString("Palakkad",true,true))
            {
                range.Style.Color = Color.Green;
            }

Pic 1:

SpireXls

SpireXls

Pic 2 :

Test2

SpireXls

Save and Launch The Project

Highlighted data saved into the new excel sheet “NewProduct.xlsx“.

workbook.SaveToFile("NewProduct.xlsx", ExcelVersion.Version2013);
System.Diagnostics.Process.Start("NewProduct.xlsx");

Before Highlighting Data In Excel :

Test5

OutPut :

Test4

Pros :

  • Very fast conversion
  • Easy to handle code
  • Less code with quality output

Reference : Spire.Xls

Summary

We learned how to highlight data in Excel Using C# & Spire.Xls. I hope this article is useful for all beginners.

 

Convert Pdf to Other format Using Spire.Pdf


Introduction :

Spire.PDF from E-iceblue is a .NET component that lets you manipulate PDF documents programmatically. Spire.PDF for .NET is a professional .NET library specially designed for developers to create, read, write, convert and print PDF document files from any .NET platform with fast and high-quality performance.

Background :

I got an opportunity from a China-based company E-iceblue, to review one of their products. I selected Spire.Pdf from E-iceblue, which is a .Net component that lets you manipulate PDF documents programmatically.

Namespace:

using Spire.Pdf;
using Spire.Doc.Documents;

Add Reference :

  • Add the following reference.
  • Add the Spire.Pdf,Spire.Doc,Spire.License Dll files to the bin folder.
  • Spire.Pdf contains the PDF conversion libraries.
  • Spire.Doc contains the doc conversion libraries.
Reference

Figure 1: Add Reference

Code :

Code

Creating the instance of PdfDocument

PdfDocument document_doc = new PdfDocument();

Load the file location, in this code “spire.pdf” is a pdf file as in the following:

document_doc.LoadFromFile(@"E:\MVC APP\SpireDoc\SpireDoc\spire.pdf");

Convert the PDF file into Document format using “FileFormat.Doc”

document_doc.SaveToFile("Spire.doc", FileFormat.DOC);

Launch the conversion process as in the following:

System.Diagnostics.Process.Start("Spire.doc");

Examples :

The following converts a PDF to Xps:


//Creating instance of PdfDocument

PdfDocument document = new PdfDocument();

//Loading the File path of pdf file

document.LoadFromFile(@"E:\MVC APP\SpireDoc\SpireDoc\SpireXps.pdf");

//Save Spire.Pdf.PdfDocument object as XPS format.

document.SaveToFile("SpireXps.xps", FileFormat.XPS);

//Launch XPS

System.Diagnostics.Process.Start("SpireXps.xps");

OutPut :

Convert Pdf to Xps

OutPut 1

The following converts a PDF to Doc:


//Creating instance of PdfDocument

PdfDocument document_doc = new PdfDocument();

//Loading the File path of pdf file

document_doc.LoadFromFile(@"E:\MVC APP\SpireDoc\SpireDoc\spire.pdf");

//Save Spire.Pdf.PdfDocument object as DOC format.

document_doc.SaveToFile("Spire.doc", FileFormat.DOC);

//Launch Document

System.Diagnostics.Process.Start("Spire.doc");

OutPut :

Convert Pdf to Doc

Figure 3: Output 2

Important Points :

  • Merge/split PDF documents.
  • Set PDF position, title display, resize, page mode and print scaling, and so on.
  • Protect PDF documents by setting passwords and digital signature.
  • Overlay documents.
  • Decrypt PDF Document.
  • Fast Conversion Process.

Reference : http://www.e-iceblue.com/Tutorials.html

Published : http://www.c-sharpcorner.com/UploadFile/2a6dc5/convert-pdf-to-other-format-using-spire-pdf/

 

%d bloggers like this: