Thursday, 27 April 2017

Send mail using webconfig mailSettings SMTP details

Web config
====================
 <system.net>
    <mailSettings>
      <smtp deliveryMethod="Network">
         <network host="mail.seologistics.com" enableSsl="false" port="587"             userName="test_flexsin@seologistics.com" password="Ybv0B'mJKLIU*%$" />      
      </smtp>
    </mailSettings>
  </system.net>

-----------

 <add key="FromEmailId" value="test_flexsin@seologistics.com" />
    <add key="DisplayName" value="Wafroo" />
==============================================


Code
============

 public string SendMail(string FromEmail, string ToEmail, string subjectsend, string messagesend)
        {
            string Result = string.Empty;
            try
            {
                var fromAddress = new MailAddress(FromEmail);
                var toAddress = new MailAddress(ToEmail);
                string subject = subjectsend;
                string body = messagesend;

                var smtp = new SmtpClient();
                using (var message = new MailMessage(fromAddress, toAddress)
                {
                    Subject = subject,
                    Body = body,

                })
                {
                    message.IsBodyHtml = true;
                    smtp.Send(message);    
                }
           
                Result = "1";
            }
            catch (Exception ex)
            {
                Result = ex.Message;
            }
            return Result;
        }

Send Email and Attachment or uni code support in email

 static string displayName = System.Configuration.ConfigurationManager.AppSettings["DisplayName"];

        #region send mail without attchment
        /// <summary> send mail without attchment
        /// <para>EmailMessageID</para> pass to emailMessage id
        /// <para>MailSubject</para> pass mail subject name
        /// <para>MailBody</para> pass Mail decription
        /// <para>cc</para> pass cc mail id
        /// <para>bc</para> pass bc mail id
        /// <para>FromMail</para> pass Network Credential from emailMessage id (user name)
        /// <para>password</para> pass Network Credential Password (user password)
        /// <para>host</para> pass Network Credential host for send mailMessage
        /// <para>port</para> pass Network Credential port for send mailMessage
        /// <DevelopedBy>Neelkamal bansal</DevelopedBy>
        /// </summary>
        public static void SendMail(string emailMessageId, string mailMessageSubject, string mailMessageBody, string cC, string bC, string fromMail, string password, string host, int port)
        {
            try
            {
                string username = Convert.ToString(ConfigurationManager.AppSettings["Username"]);
                MailMessage mailMessage = new MailMessage();
                mailMessage.To.Add(emailMessageId);

                if (!string.IsNullOrEmpty(cC))
                {
                    mailMessage.CC.Add(cC);
                }

                if (!string.IsNullOrEmpty(bC))
                {
                    mailMessage.Bcc.Add(bC);
                }

                mailMessage.From = new MailAddress(fromMail, displayName);
                mailMessage.IsBodyHtml = true;
                mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
                mailMessage.Subject = mailMessageSubject;                          
                mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
                mailMessage.Body = mailMessageBody;
         

                SmtpClient smtpClient = new SmtpClient();
                smtpClient.Port = port;
                smtpClient.Host = host;
                smtpClient.EnableSsl = false;
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials = new NetworkCredential(username, password);
                smtpClient.Send(mailMessage);
                smtpClient.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static void ForgotPassSendMail(string emailMessageId, string mailMessageSubject, string mailMessageBody, string cC, string bC, string fromMail, string password, string host, int port)
        {
            try
            {
                string username = Convert.ToString(ConfigurationManager.AppSettings["FUsername"]);
                MailMessage mailMessage = new MailMessage();
                mailMessage.To.Add(emailMessageId);

                if (!string.IsNullOrEmpty(cC))
                {
                    mailMessage.CC.Add(cC);
                }

                if (!string.IsNullOrEmpty(bC))
                {
                    mailMessage.Bcc.Add(bC);
                }

                mailMessage.From = new MailAddress(fromMail, displayName);
                mailMessage.Subject = mailMessageSubject;
                mailMessage.IsBodyHtml = true;
                mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
                mailMessage.Body = mailMessageBody;
                mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;

                SmtpClient smtpClient = new SmtpClient();
                smtpClient.Port = port;
                smtpClient.Host = host;
                smtpClient.EnableSsl = false;
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials = new NetworkCredential(username, password);
                smtpClient.Send(mailMessage);
                smtpClient.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region send mail with single attchment
        /// <summary> send mailMessage with single attchment
        /// <para>EmailMessageID</para> pass to emailMessage id
        /// <para>MailSubject</para> pass mailMessage subject name
        /// <para>MailBody</para> pass Mail decription
        /// <para>cc</para> pass cc mailMessage id
        /// <para>bc</para> pass bc mailMessage id
        /// <para>FromMail</para> pass Network Credential from emailMessage id (user name)
        /// <para>password</para> pass Network Credential Password (user password)
        /// <para>host</para> pass Network Credential host for send mailMessage
        /// <para>port</para> pass Network Credential port for send mailMessage
        /// <para>attachmentfile</para> pass attchment (ex- doc, image, pdf and any other)
        /// <DevelopedBy>Neelkamal bansal</DevelopedBy>
        /// </summary>
        public static void SendMail(string emailMessageId, string mailMessageSubject, string mailMessageBody, string cC, string bC, string fromMail, string password, string host, int port, byte[] attachmentFile, string filename)
        {
            try
            {
                MailMessage mailMessage = new MailMessage();
                string username = Convert.ToString(ConfigurationManager.AppSettings["Username"]);
                mailMessage.To.Add(emailMessageId);

                if (!string.IsNullOrEmpty(cC))
                {
                    mailMessage.CC.Add(cC);
                }

                if (!string.IsNullOrEmpty(bC))
                {
                    mailMessage.Bcc.Add(bC);
                }

                mailMessage.From = new MailAddress(fromMail, displayName);
                mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
                mailMessage.Subject = mailMessageSubject;
                mailMessage.IsBodyHtml = true;
                mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
                mailMessage.Body = mailMessageBody;

                // Attachment attachment = new Attachment(attachmentFile, MediaTypeNames.Application.Octet);
                Attachment attachment = new Attachment(new MemoryStream(attachmentFile), filename);
                mailMessage.Attachments.Add(attachment);
                SmtpClient smtpClient = new SmtpClient();
                smtpClient.Port = port;
                smtpClient.Host = host;
                smtpClient.EnableSsl = false;
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtpClient.UseDefaultCredentials = false;
              //  smtpClient.ServicePoint.MaxIdleTime = 1;
                smtpClient.Credentials = new NetworkCredential(username, password);
                smtpClient.Send(mailMessage);
                smtpClient.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region send mail with multiple attchment
        /// <summary> send mailMessage with multiple attchment
        /// <para>EmailMessageID</para> pass to emailMessage id
        /// <para>MailSubject</para> pass mailMessage subject name
        /// <para>MailBody</para> pass Mail decription
        /// <para>cc</para> pass cc mailMessage id
        /// <para>bc</para> pass bc mailMessage id
        /// <para>FromMail</para> pass Network Credential from emailMessage id (user name)
        /// <para>password</para> pass Network Credential Password (user password)
        /// <para>host</para> pass Network Credential host for send mailMessage
        /// <para>port</para> pass Network Credential port for send mailMessage
        /// <para>attachmentfile</para> pass multiple attchment in array (ex- doc, image, pdf and any other)
        /// <DevelopedBy>Neelkamal bansal</DevelopedBy>
        /// </summary>
        public static void SendMail(string emailMessageIDd, string mailMessageSubject, string mailMessageBody, string cC, string bC, string fromMail, string password, string host, int port, string[] attachmentFile)
        {
            try
            {
                MailMessage mailMessage = new MailMessage();
                mailMessage.To.Add(emailMessageIDd);

                if (!string.IsNullOrEmpty(cC))
                {
                    mailMessage.CC.Add(cC);
                }

                if (!string.IsNullOrEmpty(bC))
                {
                    mailMessage.Bcc.Add(bC);
                }

                mailMessage.From = new MailAddress(fromMail, displayName);
                mailMessage.Subject = mailMessageSubject;
                mailMessage.IsBodyHtml = true;
                mailMessage.Body = mailMessageBody;

                if (attachmentFile.Length > 0)
                {
                    for (int i = 0; i < attachmentFile.Length; i++)
                    {
                        Attachment attachment = new Attachment(attachmentFile[i], MediaTypeNames.Application.Octet);
                        ContentDisposition disposition = attachment.ContentDisposition;
                        disposition.CreationDate = File.GetCreationTime(attachmentFile[i]);
                        disposition.ModificationDate = File.GetLastWriteTime(attachmentFile[i]);
                        disposition.ReadDate = File.GetLastAccessTime(attachmentFile[i]);
                        disposition.FileName = Path.GetFileName(attachmentFile[i]);
                        disposition.Size = new FileInfo(attachmentFile[i]).Length;
                        disposition.DispositionType = DispositionTypeNames.Attachment;
                        mailMessage.Attachments.Add(attachment);
                    }
                }

                SmtpClient smtpClient = new SmtpClient();
                smtpClient.Port = port;
                smtpClient.Host = host;
                smtpClient.EnableSsl = false;
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials = new NetworkCredential(fromMail, password);
                smtpClient.Send(mailMessage);
                smtpClient.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion





  <appSettings>
    <add key="DisplayName" value="تحدي القراءة العربي"/>
    <add key="EmailUname" value="test_flexsin@seologistics.com"/>
    <add key="Username" value="test_flexsin@seologistics.com"/>
    <add key="EmailPassword" value="Ybv0B'mJKLIU*%$"/>
    <add key="Host" value="mail.seologistics.com"/>
    <add key="Port" value="25"/>
    <add key="CC" value=""/>
    <add key="BC" value="neelkamal_bansal@seologistics.com"/>
    <add key="FDisplayName" value="Arab Reading Challenge"/>
    <add key="FEmailUname" value="test_flexsin@seologistics.com"/>
    <add key="FUsername" value="test_flexsin@seologistics.com"/>
    <add key="FEmailPassword" value="Ybv0B'mJKLIU*%$"/>
    <add key="FHost" value="mail.seologistics.com"/>
    <add key="FPort" value="25"/>
    <add key="FCC" value=""/>
    <add key="FBC" value="avdhesh_kumar12@seologistics.com"/>
    <add key="UserNameLength" value="8"/>
    <add key="pagingsize" value="25"/>
    <add key="PasswordLength" value="6"/>
    <add key="PageUrl" value="http://localhost:49787/index.aspx"/>
    <add key="BackupFolder" value="C:/ARC/"/>
    <add key="IndexredirectUrl" value="http://localhost:49787/index.aspx"/>
  </appSettings>

Get Current Latitude and longitude in jquery


 <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyD4IuRFVcMjWo1qWvBrS3v4uvDXcCiq_c4&sensor=false"></script>
<script type="text/javascript">
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (p) {
                alert('Latitude:' + p.coords.latitude + "<br />Longitude: " + p.coords.longitude);

            });
        }
        else {
            alert('Geo Location feature is not supported in this browser.');
        }
</script>

List data in to Json data and json date convert in to jquesry

Html google Chart
================

 <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
    google.charts.load("current", { packages: ["corechart"] });
    google.charts.setOnLoadCallback(drawChart);
    function drawChart() {

        debugger;      
        $.ajax({
            type: "post",
            url: "/DealsStatistics/selectcontryreport",
            success: function (response) {
                debugger;
                var reportdata = [];

  /*Age Chart*/
                var data = google.visualization.arrayToDataTable([
                ['Task', ''],
                ['Age 15-25', response.objreportAge.Age15to25],
                ['Age 26-35', response.objreportAge.Age26to35],
                ['Age 36-45', response.objreportAge.Age36to45],
                ['Age 45-56', response.objreportAge.Age46to55],
                ['Age upto 56', response.objreportAge.Age56]]);
                var options = {
                    title: '',
                    is3D: true,
                    legend: 'top',
                    tooltip: { isHtml: true },
                    chartArea: {
                        top: 20,
                        width: 300,
                        height: 300
                    },

                    slices: { 0: { color: '#0078d7' }, 1: { color: '#80b2da' }, 2: { color: 'red' } }
                };

                var chart = new google.visualization.PieChart(document.getElementById('idAgechart'));
                chart.draw(data, options);
   /*Age Chart End*/

   /*Gender Chart*/
                var data = google.visualization.arrayToDataTable([
                ['Task', ''],
                ['Male', response.objreportgender.male],
                ['Female', response.objreportgender.female]
                ]);

                var options = {
                    title: '',
                    is3D: true,
                    legend: 'top',
                    tooltip: { isHtml: true },
                    chartArea: {
                        top: 20,
                        width: 250,
                        height: 300
                    },

                    slices: { 0: { color: '#0078d7' }, 1: { color: '#80b2da' }, 2: { color: 'red' } }
                };

                var chart = new google.visualization.PieChart(document.getElementById('idgenderchart'));
                chart.draw(data, options);

  /*Gender Chart end*/

  /*Location Chart*/
                if (response.objreportcountrylist.length > 0) {
                    reportdata = [['Task', '']];
                    for (var i = 0; i < response.objreportcountrylist.length; i++) {
                        reportdata.push([response.objreportcountrylist[i].Country, response.objreportcountrylist[i].Countryper])
                    }
                    var data = google.visualization.arrayToDataTable(reportdata);
                    var options = {
                        title: '',
                        is3D: true,
                        legend: 'top',
                        tooltip: { isHtml: true },
                        chartArea: {
                            top: 20,
                            width: 250,
                            height: 300
                        },
                        slices: { 0: { color: '#0078d7' }, 1: { color: '#80b2da' }, 2: { color: 'red' } }
                    };
                    var chart = new google.visualization.PieChart(document.getElementById('idlocationchart'));
                    chart.draw(data, options);
                }
   /*Location end*/

                /*Bind Table*/
                if (response.objvenderreporttbllist.length > 0) {
                    reportdata = [['Task', '']];
                    var Html = '';
                    var item = 0;
                    for (var i = 0; i < response.objvenderreporttbllist.length; i++) {
                        var newdate = new Date(response.objvenderreporttbllist[i].date.match(/\d+/)[0] * 1);
                        Html = Html + "<tr><td>" + item++ + "</td><td>" + newdate + "</td><td>" + response.objvenderreporttbllist[i].male + "</td><td>" + response.objvenderreporttbllist[i].female + "</td><td>" + response.objvenderreporttbllist[i].total + "</td><td>" + response.objvenderreporttbllist[i].location + "</td></tr>"
                                          }
                    $("#tbldata").html(Html);
                }
                /*End Table*/
            }          
        });  
    }


========
C#
==========

   public ActionResult selectcontryreport()
        {
            int vendorid = 1;
            dealstaticsrepot obj = new dealstaticsrepot();          
            obj = (new vendorReport()).getvendorreport(vendorid);    
            return Json(obj);
        }


Wednesday, 26 April 2017

open Xml in sql or comma sepreted value in sql

==================
for open Xml
==================

(select  STUFF((SELECT ', ' + cast( CustomerID as nvarchar(20)) FROM UsedDealDetail WHERE cast(CouponUsedDate as date) =cast(ud.CouponUsedDate as date) FOR XML PATH('') ), 1, 2, '')) as userid


=================
for variable
=================
  declare @tmp varchar(2500),@customerid varchar(2500)
      SET @tmp = ''
      select @tmp = @tmp + Cast(CustomerID as nvarchar(10)) + ', ' from  UsedDealDetail where VendorID=@vendoeId group by CustomerID

set @customerid=SUBSTRING(@tmp, 0, LEN(@tmp))

Tuesday, 25 April 2017

convert list into jquery JsonConvert SerializeObject or jquery eval funcation

==============================
Jquery
=============================

            $(function () {

                $("#selectcountryid").change(function () {
                    debugger;
                        var selectedcountry = $(this).find("option:selected").text();
                        $.ajax({
                            type: "post",
                            url: "/Administrator/SelectState",
                            data: {'country': selectedcountry },
                            success: function (response) {
                                var item = eval("(" + response + ")");
                                if (item.length > 0) {
                                    var listitem = '<option  value="select">--Select state--</option>';
                                    for (var i = 0; i < item.length; i++) {
                                        listitem = listitem + '<option  value="' + item[i].stateid + '">' + item[i].stateName + '</option>'
                                    }                                  
                                    $('#idstate').html(listitem)
                                }
                            }
                        });
                });
 });

======================================
C# controller view
======================================
     public string SelectState(string country = null)
        {
            string listofsatate = "0";
            var objstatelist = (new pushnotification()).SelectState(country);
            if (objstatelist.Count > 0)
            {
                listofsatate = JsonConvert.SerializeObject(objstatelist);
            }
            return listofsatate;
        }
========================================

Thursday, 13 April 2017

Create a multi language Controller in mvc

HTML
=================
@{int Lid = Convert.ToInt32(Request.Cookies["LID"].Value);}
 <a class="@(Lid == 1 ? "comnBtn activelid" : "comnBtn")" id="enbtn" href="/Language/ChangeLanguage?Lang=en">English</a>
            <a class="@(Lid == 2 ? "comnBtn activelid" : "comnBtn")" id="arbtn" href="/Language/ChangeLanguage?Lang=ar">Arabic</a>


controller:
====================

        public ActionResult ChangeLanguage(string Lang)
        {
            if (Lang != null)
            {
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(Lang);
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(Lang);
                var cookie = new HttpCookie("Language");
                var cookieLID = new HttpCookie("LID");
                if (Lang == "en")                
                    cookieLID.Value = "1"; 
                else              
                    cookieLID.Value = "2";  

                cookie.Value = Lang;                
                Response.Cookies.Add(cookie);
                Response.Cookies.Add(cookieLID);

            }
            return Redirect(Request.UrlReferrer.ToString());
        }


Use of Cookies
======================

 [HttpGet]
        public ActionResult faq()
        {
            _FAQ obj = new _FAQ();
            int Lid = Convert.ToInt32(Request.Cookies["LID"].Value);
            obj = (new CMSdata()).faqByLID("GetbyLid", Lid);
            return View(obj);
        }