Thursday, 21 August 2014

Send Email With ASP.NET C# with Formated Text

Send Email With ASP.NET C# with Formated Text

Here i have implemented Email send program with the console application just you need to use your email address and password from where you want to send the email.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;
using System.Net.Mail;
using System.Data.SqlClient;
using System.Data;
namespace TaskRunner
{
    class Program
    {
        public static string connectionString="ServerName;Initial Catalog=DataBaseName;Persist Security Info=True;User";
   
   
        static void Main(string[] args)
        {
            Program p = new Program();
            p.SendMail();
        }
       
    protected void SendMail()
    {
 
        SqlConnection cn = new SqlConnection(@""+connectionString+"");
        DataSet ds = new DataSet();
        DateTime d = new DateTime();
        string yesterday = DateTime.Today.ToString("yyyy-MM-dd");
        string nextday = DateTime.Today.AddDays(1).ToString("yyyy-MM-dd");
   
        SqlDataAdapter da = new SqlDataAdapter("select * from Table where id=1", cn);
        da.Fill(ds);
        int i=0;
        for (i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            Console.WriteLine("Please wait ...");
            System.Net.Mail.MailMessage ms = new System.Net.Mail.MailMessage();
            var fromAddress = "from@gmail.com";      // Gmail Address from where you send the mail
            MailAddress to = new MailAddress("to@abc.com"); // Address to whome you send the mail
       
            string body = "Hi XYZ, <br>";
            body += "<h2>How are You?</h2><h3>Dear<br> Thank you, <br> From Jayesh Jakhaniya";
       
            ms.From = new MailAddress("from@gmail.com");
            ms.To.Add(to);
            ms.Subject = "Subject";
            ms.IsBodyHtml = true;
            ms.Body = body;
       
            var fromPassword = "password";
       
            var smtp = new System.Net.Mail.SmtpClient();
            {
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;
                smtp.EnableSsl = true;
                smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
                smtp.Timeout = 20000;
            }
       
            smtp.Send(ms);
        }
   
    }
    }


}



Wednesday, 20 November 2013

JSON With Web Service AJAX Call In c# Asp.NET

here i have created on service and called that service with use of ajax function from javascript.

the service is returning list as json

data to ajax function as a result.

(i have just explain you a basic example, you can return what ever you want to return)

 

WebService1.asmx.cs File

This file is having service method

 
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Web.Script.Services;
using System.Runtime.Serialization;
using Newtonsoft.Json;     ///Add the reference of JSON.NET Dll for the json converter used in program



namespace TestJavascriptServices
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public String HelloWorld()
        {


            Hashtable ht = new Hashtable();
            ht.Add("me", "jayesh");
            ht.Add("you", "CPU");
            ht.Add("My", "Mind");
            ht.Add("Your", "Processor");
            ht.Add("And", "Blast");

            List<String> ls = new List<string>();
            ls.Add("Jayesh");
            ls.Add("Jayesh1");
            ls.Add("Jayesh2");
            ls.Add("Jayesh3");
            ls.Add("Jayesh4");
            Test t = new Test();

            t.setData("me", "jayesh");
            
            //return "{\"me\":\"Hello this is jayesh\",\"u\":\"hsdh\",\"t\":\"dhdsfh\",\"s\":\"dsfhsdjh\"}";
            return JsonConvert.SerializeObject(t.getData());
            //return JsonConvert.SerializeObject(ls);
            //return JsonConvert.SerializeObject(ht);
            //return JsonConvert.SerializeObject(t);


        }
    }

    public class Test {
        public string Name;
        public string salary;

        public void setData(string n,string s)
        {
            this.Name = n;
            this.salary = s;
        }

        public Test getData() {
            return this; 
        }
      
    }

}


TestWebServiceHello.js

This file is having ajax functions which will call service 



var test;
function pageLoad() 
{
    test = new TestJavascriptServices.WebService1();
    test.set_defaultSucceededCallback(SucceededCallback);
    test.set_defaultFailedCallback(FailedCallback);
}


function SucceededCallback(result) {
    var RsltElem = document.getElementById("Results");

    var dd = $.parseJSON(result);
    alert(dd);
    RsltElem.innerHTML = dd.me;
}

function calll() {
alert("here");
    var greetings = test.HelloWorld();

}

function FailedCallback(error, userContext, methodName) {
    if (error !== null) {
        var RsltElem = document.getElementById("Results");

        RsltElem.innerHTML = "An error occurred: " +
            error.get_message();
    }
}

if (typeof (Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

Default.aspx

This file is having html inputs

 

 
<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="TestJavascriptServices._Default" %>




<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js" ></script>
<asp:ScriptManager runat="server" ID="scriptManager">
                <Services>
                    <asp:ServiceReference path="~/WebService1.asmx" />
                </Services>
                <Scripts>
                    <asp:ScriptReference Path="~/TestWebServiceHello.js" />
                </Scripts>
            </asp:ScriptManager>

    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit <a href="http://www.asp.net" title="ASP.NET Website">www.asp.net</a>.
    </p>
    <p>
        You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&amp;clcid=0x409"
            title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>.
    </p>
    <span id="Results"></span>

    <input type="button" id="btn" onclick="calll();return false;" value="Click me" />






Download   
Newtonsoft plugin from here and add the reference to the project file

http://james.newtonking.com/json


Tuesday, 22 October 2013

Like button of facebook using javascript SDK

Facebook Like Button implementation code 



<div id="fb-root"></div>
<script>
(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id))return;
  js = d.createElement(s);
  js.id = id;
  js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=your_API_id";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
//like button
<div class="fb-like" data-href="https://developers.facebook.com/docs/plugins/" data-width="16" data-height="16" data-colorscheme="light" data-layout="standard" data-action="like" data-show-faces="true" data-send="false">
</div>

Post on Facebook using javascript SDK


Post On facebook using javascript SDK

below id the code to create comment box on you page to post the comment on facebook page just you need to put your page facebook pageid/appid where you want to post the comment.

<script type=&quot;syntaxhighlighter&quot; class=&quot;brush: csharp&quot;>
<![CDATA[
function postOnFB()
{
      window.fbAsyncInit = function() {
   FB.init({
   // window.location.reload();console.log(response);    FB.getLoginStatus(function(response) {      appId: ' YOUR APP ID ',
   xfbml: true,
   status: true,
   cookie: true,
   oauth: true,
    channelUrl : 'CHANNEL URL / REDIRACT URL', // Channel File
});


FB.Event.subscribe("auth.authResponseChange", function(response) {
    });
      if (response && response.status == 'connected') {   

           FB.api('/me', function(response) {
      });
   
        } else if (response.status === 'not_authorized') {
      } else {
      }
     
     });
  
 };

 (function(d, s, id){
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/all.js";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));
              

      FB.login(
                function(response) {
                    if (response.authResponse) {
                    var access_token = FB.getAuthResponse()['accessToken'];
                    console.log("token:==>");
                    console.log(access_token);
                    FB.api(
                    'me/photos',
                    'post', {
                    name:"My Post",
                    message: 'here is yor post message',
                    status: 'success',
                    access_token: access_token,
                    url:$("#myimage").attr("src");    /// yourimage url is here
                    },
                    function(response) {
                        if (!response || response.error) {
                        console.log(response);
                        alert('Error occured:' + response);
                        } else {
                        // document.getElementById('imguploadheader').innerHTML="Status";
                        alert(Sucessfully posted);
                        }
                    });
                    } else {
                    errordisplay();
                    $("#appendtext").html(
                    "User cancelled login or did not fully authorize.");
                    $("#uploadingpregress")
                    .css("display","none");
                    successfullyupload();

                    }
                }, {
                scope: 'user_photos,photo_upload,publish_stream,offline_access'
          });
}
]]></script>