Friday, 30 June 2017

Send Attachment in Email using Gmail in ASP.NET C#

Introduction:

In this topic, I will explain code to send attachment in email using Gmail in ASP.NET C#.

Description:

Usually, it is necessary to send email to user from ASP.NET application. We should use SMTP (Simple Mail Transfer Protocol) server to send email. If we don't have any SMTP server at that time we can use Gmail SMTP server to send email.

Following is source code to send email in ASP.NET :
  • Import following namespaces :
      using System.Net;   
      using System.Net.Mail;   
  • Add following button click event with function to send mail :
      public bool SendMail(string subject, string body, string to, string attachments)  
      {  
           bool result = false;  
           try  
           {  
                string emailSender = "Sender Gmail Email Address";  
                string passwordSender = "Sender Gmail Password";  
                using (SmtpClient smtpClient = new SmtpClient())  
                {  
                     smtpClient.Host = "smtp.gmail.com";  
                     smtpClient.Port = 587;  
                     smtpClient.Credentials = new NetworkCredential(emailSender, passwordSender);  
                     smtpClient.EnableSsl = true;  
                     using (MailMessage message = new MailMessage())  
                     {  
                          message.From = new MailAddress(emailSender);  
                          message.Subject = subject;  
                          message.Body = body;
                          if (!string.IsNullOrEmpty(attachments))
                          {
                       foreach (string attachment in attachments.Split(",".ToCharArray()))
                       message.Attachments.Add(new Attachment(attachment));
                          }  
                          message.To.Add(to);  
                          smtpClient.Send(message);  
                     }  
                }  
                result = true;  
           }  
           catch (Exception)  
           {  
                result = false;  
           }  
           return result;  
      }  

Friday, 26 May 2017

Send Email using Gmail in ASP.NET C#

Introduction:

In this topic, I will explain code to send email using Gmail in ASP.NET C#.

Description:

Usually, it is necessary to send email to user from ASP.NET application. We should use SMTP (Simple Mail Transfer Protocol) server to send email. If we don't have any SMTP server at that time we can use Gmail SMTP server to send email.

Following is source code to send email in ASP.NET :

In aspx page,
  • Add following code,
      <div>   
           <asp:TextBox ID="txtTo" runat="server" placeholder="To"></asp:TextBox>   
      </div>   
      <br />   
      <div>   
           <asp:TextBox ID="txtSubject" runat="server" placeholder="Subject"></asp:TextBox>   
      </div>   
      <br />   
      <div>   
           <asp:TextBox ID="txtMessage" runat="server" TextMode="MultiLine" Rows="3" Columns="20" placeholder="Message"></asp:TextBox>   
      </div>   
      <br />   
      <div>   
           <asp:LinkButton ID="lnkbtnSendMail" runat="server" OnClick="lnkbtnSendMail_Click"> Send </asp:LinkButton>   
      </div>   
Here,
         txtTo - It will contain Email address of User to which we need to send Email
  txtSubject - It will contain Subject of Email
  txtMessage - It will contain content of Body of Email
  lnkbtnSendMail - It is button to send Email

In code behind,
  • Import following namespaces :
      using System.Net;   
      using System.Net.Mail;   
  • Add following button click event with function to send mail :
      protected void lnkbtnSendMail_Click(object sender, EventArgs e)  
      {  
           bool isMailSent = SendMail(txtSubject.Text,txtMessage.Text,txtTo.Text);  
      }  
      public bool SendMail(string subject, string body, string to)  
      {  
           bool result = false;  
           try  
           {  
                string emailSender = "Sender Gmail Email Address";  
                string passwordSender = "Sender Gmail Password";  
                using (SmtpClient smtpClient = new SmtpClient())  
                {  
                     smtpClient.Host = "smtp.gmail.com";  
                     smtpClient.Port = 587;  
                     smtpClient.Credentials = new NetworkCredential(emailSender, passwordSender);  
                     smtpClient.EnableSsl = true;  
                     using (MailMessage message = new MailMessage())  
                     {  
                          message.From = new MailAddress(emailSender);  
                          message.Subject = subject;  
                          message.Body = body;  
                          message.To.Add(to);  
                          smtpClient.Send(message);  
                     }  
                }  
                result = true;  
           }  
           catch (Exception)  
           {  
                result = false;  
           }  
           return result;  
      }  

Tuesday, 16 May 2017

Allow Access of SQL Server Database to Other Computer (When Windows Firewall is OFF)

Introduction:

In this topic, I will explain steps to allow access of SQL server Database to other Computer when Windows Firewall is OFF.

Description:

In previous article, I explained about Restrict Database Access of User in SQL Server. (Please read this article to restrict access of user in shared database)

When you work with your team in single project then it becomes necessary to share SQL server database in many computer. By sharing database, all team members can work on same database which will increase productivity.

SQL server provides database sharing functionality in very easy to configure manner. You just need to follow some steps and you can allow access of any SQL server database to other computer.

Let's jump directly on steps to allow access of your SQL Server database :

1. From Start menu, open SQL Server Configuration Manager.

2. Expand SQL Server Network Configuration from left pane and select protocol for which you like to allow access. It will open Protocol name and current Status of protocol in right pane.



3. In Right pane, from listed protocol select TCP/IP protocol and make it Enabled. You can use either of following ways to make protocol Enabled :

    - Right click on TCP/IP protocol name and select Enable option.

    - Double click on TCP/IP protocol name, it will open TCP/IP properties window. From opened window, select Protocol tab and set Enabled property to Yes and click Ok.



4. After completing above steps, you need to restart SQL Server Browser and SQL Server services. To restart services, go to Run and open services.msc. It will open Services window which includes all services currently available in computer.



5. From opened Services window, right click on SQL Server Browser and SQL Server services and select restart option which will restart both services automatically.

After restarting both services, any user can access SQL Server database.
     

Thursday, 11 May 2017

Remove Brackets from Site Name after Opening Site in Visual Studio

Introduction:

Here, I will explain steps to remove brackets from Site name after opening site in Visual Studio IDE.

Description:

If you check site directory in Windows explorer then it will not contain any brackets in name. But, sometimes it happens that when you open site in Visual Studio then site name contains brackets with some number. For example, testing(1), studenterp(2), etc...

To remove unnecessary Brackets from Site name you can use following steps :

1. Go to, C:\Users\Administrator\Documents\IISExpress\config 

    - Here, C:\ is drive in which your operating system is installed.

    Note : If you have User created in your computer, then you need to select folder with Username instead of Administrator.

2. Open applicationhost.config file and go to, <sites> node and remove all <site> nodes containing same name as your site name in name attribute. Please ignore brackets in name attribute while checking name.

    For example,
         Site name : testing
         Remove all <site> node like, <site name="testing"></site>, <site name="testing(1)"></site>, etc...

3. Close your site and re open site in Visual Studio. Now, you will have proper site name.






Thursday, 4 May 2017

Prevent Bootstrap modal from Closing by ESC key and Outside clicking

Introduction:

Here, I will explain prevention of Bootstrap modal's closing by pressing ESC key of keyboard and by clicking outside area of modal.

Description:

By default configuration of Bootstrap modal is, it will close or disappear by clicking outside area of modal or by pressing ESC key of keyboard (if modal have focus).

Sometimes it is mandatory to override this functionality and prevent default closing of modal. For example, if your site contains multi-step registration form in Bootstrap modal and user have filled details of entire form and by mistake press ESC key of keyboard or click outside of modal area then Bootstrap modal will close.

To prevent this, you need to change default value of  backdrop and keyboard configuration using HTML or jQuery.

- In HTML, you need to set data-backdrop="static" and data-keyboard="false". For example,

<a href="javascript:void(0);" data-target="#modalid" data-toggle="modal" data-backdrop="static" data-keyboard="false">Click to open popup</a>

OR

- In jQuery, you need to set backdrop: 'static' and keyboard: false attributes. For example,

$('#modalid').modal({
        backdrop: 'static',
        keyboard: false
});

Complete code is as follow: 

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Prevent Bootstrap modal from Closing by ESC key and Outside clicking</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />  

    <script type="text/javascript">
        jQuery(document).ready(function () {
            $('#lnkOpenPopup').click(function () {
                $('#modalid').modal({
                    backdrop: 'static',
                    keyboard: false
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
<div class="row">
            <div class="col-sm-2">
                <div class="form-group">
                    <a href="javascript:void(0);" class="btn btn-primary" data-target="#modalid" data-toggle="modal" data-backdrop="static" data-keyboard="false">Show Demo Using HTML</a>
                </div>
            </div>
            <div class="col-sm-2">
                <div class="form-group">
                    <a id="lnkOpenPopup" href="javascript:void(0);" class="btn btn-primary">Show Demo Using jQuery</a>
                </div>
            </div>
        </div>      

        <!-- Modal HTML -->
        <div id="modalid" class="modal fade" tabindex="1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    </div>
                    <div class="modal-body">
                        Prevent Bootstrap modal from Closing by ESC key and Outside clicking
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    </form>
</body>

</html>



Friday, 21 April 2017

Insert data from CSV file into SQL Server table

Introduction:

Here, I will explain how to insert data from CSV file into SQL Server table.

Description:

Recently, I did one task with requirement to insert bulk data from CSV file into SQL Server table. As you know, this is very simple task if we have same number of columns with same sequence in CSV file as table.

But to accomplish this task, I had CSV file containing same number of columns with same sequence as table EXCEPT ID column of table which was Identity Column with auto increment value. I had tried with various scripts but 1 column was missing in CSV file from table so NO scripts were allowing me to insert data into table.

To resolve error, I simply added dummy ID column into CSV file and data inserted properly into table.

Student table in SQL Server :


Original CSV file (Student.CSV) :


Updated CSV file :


You can use following script to process CSV file and insert data into table :

BULK
INSERT Student -- table name
FROM 'E:\Student.csv' -- Path of CSV file
WITH
(
          FIRSTROW = 2, -- This is used to start reading process from Row 2 of CSV file.
          FIELDTERMINATOR = ',',
          ROWTERMINATOR = '\n'
)

Data in Student table after running script :


Thursday, 20 April 2017

Restrict Database Access of User in SQL Server

Introduction: 

Here, I will explain steps to allow only single database access to user in SQL server.

Description:

While publishing SQL server database on hosting, I have found that I can do operation (Insert, Update, Delete, Select) in my published databases only. Here, interesting thing was that even I cannot open new Query windows for other User's database. We can also do same thing in SQL Server. To do this, please follow below steps :

Connect in SQL Server.


Go to Object Explorer.


From Object Explorer, open Security tab / Logins tab. Right click on Logins tab and click on New Login... option which will open window as shown below :


In General tab, set Login name, select SQL Server authentication and set password and uncheck Enforce password policy option.


In User Mapping tab, select database (You can select any number of databases) for which you like to restrict access for User from "Users mapped to this login" section and select all roles EXCEPT "db_denydatareader" and "db_denydatawriter" from "Database role membership for : Selected Database name" section (You can select any number of roles from list).



After selecting database and roles, click OK.

Featured post

Send Attachment in Email using Gmail in ASP.NET C#

Introduction : In this topic, I will explain code to send attachment in email using Gmail in ASP.NET C#. Description : Usually, it is ...