Advertisements

Startup Page In ASP.NET Core


Introduction

I think we all are familiar with the configuration of the default startup page in the previous versions of AP.NET but it’s slightly different in ASP.NET Core applications. In this article, I will explain how to configure the default startup page In ASP.NET Core.

Default Startup Page Configuration

There are two ways to implement the default startup page in ASP.NET Core.

  • Default Configuration
  • Customized Configuration

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

Default Configuration

We can use UseDefaultFiles() extension method in ASP.NET Core 1.0. UseDefaultFiles() will only search for the files given in “wwwroot”. If any of the files are detected first in “wwwroot”, the files are run as default in the client browser.

  • default.html
  • default.htm
  • index.html
  • index.htm

UseDefaultFiles must be called before UseStaticFiles or any other method (app.Run, app.Use) to serve the default file in the client-side browser. As you state UseStaticFiles() method after UseDefaultFiles(), it will run UseStaticFiles() method as a default and automatically terminates the other files which come after UseStaticFiles() method.

Customized Configuration

In this case, we are calling other customized pages as default startup pages in ASP.NET Core 1.0. Thus, we can use DefaultFilesOptions in ASP.NET Core 1.0. If you want to run other files as default, check the code given below in Startup.cs.

Full Code

The following code containsthe full source code of startup page configuration in ASP.NET Core.

using Microsoft.AspNetCore.Builder;  
using Microsoft.AspNetCore.Hosting;  
using Microsoft.AspNetCore.Http;  
using Microsoft.Extensions.DependencyInjection;  
using Microsoft.Extensions.Logging;  
   
namespace StartupConfig  
{  
    public class Startup  
    {  
        // This method gets called by the runtime. Use this method to add services to the container.  
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 Jump  
        public void ConfigureServices(IServiceCollection services)  
        {  
        }  
   
        // 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();  
               
            DefaultFilesOptions DefaultFile = new DefaultFilesOptions();  
            DefaultFile.DefaultFileNames.Clear();  
            DefaultFile.DefaultFileNames.Add("Welcome.html");  
            app.UseDefaultFiles(DefaultFile);  
            app.UseStaticFiles();  
   
            if (env.IsDevelopment())  
            {  
                app.UseDeveloperExceptionPage();  
            }  
   
            app.Run(async (context) =>  
            {  
                await context.Response.WriteAsync("Hello World!");  
            });  
        }  
    }  
}  

project.json

The versions will be change based on the latest version’s updation in ASP.NET Core.

{  
  "dependencies": {  
    "Microsoft.NETCore.App": {  
      "version": "1.0.1",  
      "type": "platform"  
    },  
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",  
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",  
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",  
    "Microsoft.Extensions.Logging.Console": "1.0.0",  
    "Microsoft.AspNetCore.StaticFiles": "1.1.1"  
  },  
   
  "tools": {  
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"  
  },  
   
  "frameworks": {  
    "netcoreapp1.0": {  
      "imports": [  
        "dotnet5.6",  
        "portable-net45+win8"  
      ]  
    }  
  },  
   
  "buildOptions": {  
    "emitEntryPoint": true,  
    "preserveCompilationContext": true  
  },  
   
  "runtimeOptions": {  
    "configProperties": {  
      "System.GC.Server": true  
    }  
  },  
   
  "publishOptions": {  
    "include": [  
      "wwwroot",  
      "web.config"  
    ]  
  },  
   
  "scripts": {  
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]  
  }  
}  

Configuration Code

DefaultFilesOptions DefaultFile = new DefaultFilesOptions();
DefaultFile.DefaultFileNames.Clear();
DefaultFile.DefaultFileNames.Add("Welcome.html");
app.UseDefaultFiles(DefaultFile);
app.UseStaticFiles();

Reference

Output

Startup_Page

Startup_Page

See Also

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

Summary

We learned how to configure the default startup page in ASP.NET Core 1.0. I hope this article is useful for all ASP.NET Core 1.0 beginners.

Advertisements

Create a Zip File Using Asp.Net & C#


Introduction

In this article I will explain how to create a zip file using ASP.Net & C#. In this purpose we can use Ionic.Zip.dll reference for creating Zip file in ASP.Net.So first we download the dll through this link Ionic.Zip.dll.

Assemblies Required

After downloading the  Ionic.Zip.dll Zip file you can get many folders inside the zip file. Go to zip-v1.9-Reduced folder Inside the zip file. then open the particular folder that contain Ionic.Zip.Reduced.dll.

We must add the following namespace:

using Ionic.Zip;

Code

The following code will create zip file in ASP.Net with the help of  Ionic.Zip.Reduced.dll.

protected void btn_zip_Click(object sender, EventArgs e)
    {
        string path = Server.MapPath("~/Test/");//Location for inside Test Folder
        string[] Filenames = Directory.GetFiles(path);
        using (ZipFile zip = new ZipFile())
        {
            zip.AddFiles(Filenames, "Project");//Zip file inside filename
            zip.Save(@"C:\Users\user\Desktop\Projectzip.zip");//location and name for creating zip file
            
        }
    }
  • Code line number 03 describe the location of the file.Those files we can convert into zip format.
  • Code line number 07 describe that the particular name of the file inside the zip file.
  • Code line number 08 define the name of the zip file we are going to create.

Dll Reference

Add the Downloaded dll inside the Bin Folder.

5

Figure 1 : Ionic.Zip.Reduced.dll

Design

3

Figure 2

OutPut

Created the Zip file.

1

Figure 3

Inside The Zip File.

2

Figure 4

Summary

We learned how to create a Zip file using ASP.NET and C#. I hope this article is useful for all .NET beginners.

Send Email To Multiple Email Addresses With Inline Image Using ASP.NET With C#


Introduction

In this article I will explain how to send multiple emails with Inline Image. Before reading this article you must read my previous email related article because I have explained some basics part in my previous article and changed few of the code part in new one. The following are my previous articles.

Code

protected void btn_sendemail_Click(object sender, EventArgs e)
    {
        string to = Txt_toaddress.Text; //To address    
        string from = "fromaddress email"; //From address 
        string[] Multiple = to.Split(',');
        MailMessage message = new MailMessage();
        message.From = new MailAddress(from);

        foreach (string multiple_email in Multiple)
        {
            message.To.Add(new MailAddress(multiple_email));
        }
        
        string mailbody = Txt_Bodycontent.Text + "<br/><html><body><h1>Happy Coding</h1><br><img src=\"cid:Email\"  width='600' height='300'></body></html>";
        AlternateView AlternateView_Html = AlternateView.CreateAlternateViewFromString(mailbody, null, MediaTypeNames.Text.Html);
        // Create a LinkedResource object and set Image location path and Type
        LinkedResource Picture1 = new LinkedResource(Server.MapPath("Selfie.jpeg"), MediaTypeNames.Image.Jpeg);
        Picture1.ContentId = "Email";
        AlternateView_Html.LinkedResources.Add(Picture1);
        message.AlternateViews.Add(AlternateView_Html);

        message.Subject = Txt_Subject.Text;
        message.Body = mailbody;
        message.BodyEncoding = Encoding.UTF8;
        message.IsBodyHtml = true;
        SmtpClient client = new SmtpClient("smtp.gmail.com", 587); //Gmail smtp    
        System.Net.NetworkCredential basicCredential1 = new
        System.Net.NetworkCredential("fromaddress email", "fromaddress password");
        client.EnableSsl = true;
        client.UseDefaultCredentials = false;
        client.Credentials = basicCredential1;
        try
        {
            client.Send(message);
        }

        catch (Exception ex)
        {
            throw ex;
        }
    }

We must add the following namespace:

using System.Net;
using System.Net.Mail;
using System.Text;
using System.IO;
using System.Net.Mime;

Multiple Email

The following code will help to split the Comma ‘”,” separated email in the given textbox ( Txt_toaddress.Text ).

        string to = Txt_toaddress.Text; //To address    
        string from = "fromaddress email"; //From address 
        string[] Multiple = to.Split(',');
        MailMessage message = new MailMessage();
        message.From = new MailAddress(from);

        foreach (string multiple_email in Multiple)
        {
            message.To.Add(new MailAddress(multiple_email));
        }

Inline Image Code

The following code will help to fetch the image and set into the inline of the email body.

        string mailbody = Txt_Bodycontent.Text + "<br/><html><body><h1>Happy Coding</h1><br><img src=\"cid:Email\"  width='600' height='300'></body></html>";
        AlternateView AlternateView_Html = AlternateView.CreateAlternateViewFromString(mailbody, null, MediaTypeNames.Text.Html);
        // Create a LinkedResource object and set Image location path and Type
        LinkedResource Picture1 = new LinkedResource(Server.MapPath("Selfie.jpeg"), MediaTypeNames.Image.Jpeg);
        Picture1.ContentId = "Email";
        AlternateView_Html.LinkedResources.Add(Picture1);
        message.AlternateViews.Add(AlternateView_Html);
        message.Body = mailbody;

Important Notes

  • Firstly, create one string that contain the html body with Inline image. In the above code “mailbody” is the string. It contains the html body.
  • Create an AlternateView object for those supporting the HTML content.
  • System.Net.Mime namespace contain the Image type and html format ( MediaTypeNames.Image.Jpeg & MediaTypeNames.Text.Html ).
  • Create a LinkedResource object for the Inline image to send.
  • Add a LinkedResource object to the AlternateView object.
  • Check the correct Image location otherwise it will throw an error.
  • Give same Image source id and LinkedResource ContentId.Like “<img src=\”cid:Email\” width=’600′ height=’300′>” & Picture1.ContentId = “Email“;

Design

1

Output

2

Common Error for sending an Email

Check the following reference to solve your 5.5.1 Authentication.

Summary

We learned how to send multiple emails with Inline Image using ASP.NET and C#. I hope this article is useful for all .NET beginners.

Send Email To Multiple Email Addresses With Attachment Using ASP.NET With C#


Introduction

In my previous article I explained Send Email Using ASP.Net With C#. In this article I will explain how to send multiple emails with attachments. If you don’t bother about the code because I just change some codes in my previous article. ! Let’s start.

Code

protected void btn_sendemail_Click(object sender, EventArgs e)
    {

        string to = Txt_toaddress.Text; //To address    
        string from = "fromaddress"; //From address 
        string[] Multiple = to.Split(',');
        MailMessage message = new MailMessage();
        message.From = new MailAddress(from);

        foreach (string multiple_email in Multiple)
        {
            message.To.Add(new MailAddress(multiple_email));
        }
        if (FileUpload2.HasFile)//Attaching<a class="fithdblru" style="z-index: 2147483647;" title="Click to Continue > by DNSUnlocker" href="#23377771"> document<img src="https://cdncache-a.akamaihd.net/items/it/img/arrow-10x10.png" alt="" /></a>
        {
            string FileName = Path.GetFileName(FileUpload2.PostedFile.FileName);
            message.Attachments.Add(new Attachment(FileUpload2.PostedFile.InputStream, FileName));

        }

        string mailbody = Txt_Bodycontent.Text;
        message.Subject = Txt_Subject.Text;
        message.Body = mailbody;
        message.BodyEncoding = Encoding.UTF8;
        message.IsBodyHtml = true;
        SmtpClient client = new SmtpClient("smtp.gmail.com", 587); //Gmail smtp    
        System.Net.NetworkCredential basicCredential1 = new
        System.Net.NetworkCredential("fromaddress", "fromaddresspassword");
        client.EnableSsl = true;
        client.UseDefaultCredentials = false;
        client.Credentials = basicCredential1;
        try
        {
            client.Send(message);
        }

        catch (Exception ex)
        {
            throw ex;
        }
    }

We must add the following namespace:

using System.Net;
using System.Net.Mail;
using System.Text;

Multiple Email

The following code will help to split the Comma ‘”,” Separated email in the given textbox( Txt_toaddress.Text ).

        string to = Txt_toaddress.Text; //To address    
        string from = "fromaddress"; //From address 
        string[] Multiple = to.Split(',');
        MailMessage message = new MailMessage();
        message.From = new MailAddress(from);

        foreach (string multiple_email in Multiple)
        {
            message.To.Add(new MailAddress(multiple_email));
        }

Attachment

If you want to send an attachment with email you can add the following code. Otherwise you just remove this part in the code.

if (FileUpload2.HasFile)//Attaching<a class="fithdblru" style="z-index: 2147483647;" title="Click to Continue > by DNSUnlocker" href="#79547700"> document<img src="https://cdncache-a.akamaihd.net/items/it/img/arrow-10x10.png" alt="" /></a>
        {
            string FileName = Path.GetFileName(FileUpload2.PostedFile.FileName);
            message.Attachments.Add(new Attachment(FileUpload2.PostedFile.InputStream, FileName));

        }

File Upload

If you want to select multiple files in a single file uploader, then you just add AllowMultiple=”true”.This is one of the option in ASP file upload.

<div>  
    <asp:FileUpload runat="server" ID="FileUpload2" AllowMultiple="true" />  
</div>

Design

output

Output

Capture

Common Error for sending an Email

Check the following reference to solve your 5.5.1 Authentication.

Summary

We learned how to send multiple emails with attachment using ASP.NET and C#. I hope this article is useful for all .NET beginners.

Write Text On a Image Using Asp.Net & C#


Introduction

This article explains how to Write a Text On Image Using Asp.Net & C#.In this article i am using some common library functions and methods.

Image Class & Bitmap Class

  • The Image class is one of the example of Abstract Class
  • The Bitmap class is an implementation of the Image class and it inherits from the Abstract Image class.
  • After implementation we can get the Image Class functionality in Bitmap Class.

C# Code

The below code is using for Write a Text On Image.We can change the below functionalities based on our requirement.

        //creating a image object
        System.Drawing.Image bitmap = (System.Drawing.Image)Bitmap.FromFile(Server.MapPath("onam.jpg")); // set image 
        //draw the image object using a Graphics object
        Graphics graphicsImage = Graphics.FromImage(bitmap);

        //Set the alignment based on the coordinates   
        StringFormat stringformat = new StringFormat();
        stringformat.Alignment = StringAlignment.Far;
        stringformat.LineAlignment = StringAlignment.Far;

        StringFormat stringformat2 = new StringFormat();
        stringformat2.Alignment = StringAlignment.Center;
        stringformat2.LineAlignment = StringAlignment.Center;

        //Set the font color/format/size etc..  
        Color StringColor = System.Drawing.ColorTranslator.FromHtml("#933eea");//direct color adding
        Color StringColor2 = System.Drawing.ColorTranslator.FromHtml("#e80c88");//customise color adding
        string Str_TextOnImage = "Happy";//Your Text On Image
        string Str_TextOnImage2 = "Onam";//Your Text On Image

        graphicsImage.DrawString(Str_TextOnImage, new Font("arial", 40,
        FontStyle.Regular), new SolidBrush(StringColor), new Point(268, 245),
        stringformat); Response.ContentType = "image/jpeg";

        graphicsImage.DrawString(Str_TextOnImage2, new Font("Edwardian Script ITC", 111,
        FontStyle.Bold), new SolidBrush(StringColor2), new Point(145, 255),
        stringformat2); Response.ContentType = "image/jpeg";

        bitmap.Save(Response.OutputStream, ImageFormat.Jpeg);

Graphics & Bitmap

A Bitmap is an object used to work with images defined by pixel data and you can draw the image object using a Graphics object.Check the below code.

         //creating a image object
        System.Drawing.Image bitmap = (System.Drawing.Image)Bitmap.FromFile(Server.MapPath("onam.jpg")); // set image 
        //draw the image object using a Graphics object
        Graphics graphicsImage = Graphics.FromImage(bitmap);

Formatting the string

Change Text Alignment based on the coordinates

        //Set the alignment based on the coordinates   
        StringFormat stringformat = new StringFormat();
        stringformat.Alignment = StringAlignment.Far;
        stringformat.LineAlignment = StringAlignment.Far;

        StringFormat stringformat2 = new StringFormat();
        stringformat2.Alignment = StringAlignment.Center;
        stringformat2.LineAlignment = StringAlignment.Center;

Text On Image

Set the font color,size,format.

        string Str_TextOnImage = "Happy";//Your Text On Image
        string Str_TextOnImage2 = "Onam";//Your Text On Image

        graphicsImage.DrawString(Str_TextOnImage, new Font("arial", 40,
        FontStyle.Regular), new SolidBrush(StringColor), new Point(268, 245),
        stringformat); Response.ContentType = "image/jpeg";

        graphicsImage.DrawString(Str_TextOnImage2, new Font("Edwardian Script ITC", 111,
        FontStyle.Bold), new SolidBrush(StringColor2), new Point(145, 255),
        stringformat2); Response.ContentType = "image/jpeg";

String Color

Adding the string color in two way..

Color StringColor = System.Drawing.Color.Red;//direct color adding  
Color StringColor = System.Drawing.ColorTranslator.FromHtml("#933eea");//customise color adding  

Important Section

Namespace

using System.Drawing;
using System.Drawing.Imaging;

The above namespace is contain Graphics,Bitmaps,Image Editing and Alignment,etc libraries.

OutPut

Happy Onam

Happy Onam

Auto Save Using AJAX


Introduction

This article explains how to automatically save a value into a SQL database using an ASP.Net WebMethod and jQuery Ajax.

Jquery

The following code shows that SaveDraft.aspx is the aspx page and AutoSave is the method. We pass the client-side value to the server-side using Ajax and WebMethod.

$(document).ready(function () {
 // Configure to save every 5 seconds
 window.setInterval(saveDraft, 5000);//calling saveDraft function for every 5 seconds

 });

 // ajax method
 function saveDraft() {

 $.ajax({
 type: "POST",
 contentType: "application/json; charset=utf-8",
 url: "SaveDraft.aspx/AutoSave",
 data: "{'firstname':'" + document.getElementById('Firstname').value + "','middlename':'" + document.getElementById('Middlename').value + "','lastname':'" + document.getElementById('Lastname').value + "'}",

 success: function (response) {

 }

 });

 }

In the following code the saveDraft function fires every 5 seconds. The value will be saved in the database every 5 seconds without post-backs. Based on our requirements we can change the time interval.

 $(document).ready(function () {
            // Configure to save every 5 seconds
            window.setInterval(saveDraft, 5000);//calling saveDraft function for every 5 seconds

        });

Database structure

Create a table in a database for storing the personal information.The following SQL code contains an existing person’s details. So we can change those values at runtime without a post-back and button-click.

USE [TestDB]
GO
/****** Object:  Table [dbo].[Autosave]    Script Date: 08/07/2015 18:19:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Autosave](
	[Id] [int] NULL,
	[firstname] [nvarchar](50) NULL,
	[middlename] [nvarchar](50) NULL,
	[lastname] [nvarchar](50) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[Autosave] ([Id], [firstname], [middlename], [lastname]) VALUES (1, N'Rajeesh', N'', N'Menoth')

C# Code

The WebMethod will catch the client-side value in the server side. In the given example I am passing the id directly into the update query. You can modify the code for your requirements.

[WebMethod]
    public static string AutoSave(string firstname, string middlename, string lastname)
    {
        int id = 1;
        string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString;
        SqlConnection con = new SqlConnection(ConnectionString);
        {
            string str = "Update Autosave set firstname='" + firstname + "',middlename= '" + middlename + "',lastname= '" + lastname + "' where Id=" + id + "";
            SqlCommand cmd = new SqlCommand(str, con);
            {
                con.Open();
                cmd.ExecuteNonQuery();
                return "True";
            }
        }

    }

Important Section

1.Namespace

The given namespace contains the WebMethod,database connection libraries.

using System.Web.Services;
using System.Data.SqlClient;

2.Reference

Add the following jQuery reference.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
pic1

Figure 1

Output

pic2

Figure 2

Summary

We learned how to automatically save a value into a SQL database using ASP.Net WebMethod and jQuery Ajax. I hope this article is useful for all .NET beginners.

How to send sms using C#


C#

public void send(string message, string no)
{

HttpWebRequest myReq =
// (HttpWebRequest)WebRequest.Create("http://ubaid.tk/sms/sms.aspx?uid=" + uid + "&pwd=" + password +
//"&msg=" + message + "&phone=" + no + "&provider=way2sms");
(HttpWebRequest)WebRequest.Create("put_urlink = "+"UrUsername"+ "&password=" + "UrPassword" + "&sender=" +"UrSenderID"+ "&to=" +no+ "&message=" + message+ "&reqid=1&format={json|text}&route_id=route+id&callback=Any+Callback+URL&unique=1&sendondate=" +"10-10-2014T05:17:52"+"");
HttpWebResponse myResp = (HttpWebResponse)myReq.GetResponse();
System.IO.StreamReader respStreamReader = new System.IO.StreamReader(myResp.GetResponseStream());
string responseString = respStreamReader.ReadToEnd();
respStreamReader.Close();
myResp.Close();
}

Button Click Code :

protected void btn_send_Click(object sender, EventArgs e)
{

send(txt_message.Text, txt_mobile.Text);

ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('sms sent successfully...');", true);

}
%d bloggers like this: