Monday, August 8, 2011

Tuesday, August 2, 2011

jquery guid

  function Hexa4() {
                return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
            }
            function GenerateGuid() {
                return (Hexa4() + Hexa4() + "-" + Hexa4() + "-" + Hexa4() + "-" + Hexa4() + "-" + Hexa4() + Hexa4() + Hexa4()).toUpperCase();
            }

            // USE
            var guid = GenerateGuid();
            //alert(guid);

Thursday, July 28, 2011

Reading contact from gmail to gridview

http://www.dotnetfunda.com/articles/article884-import-gmail-contacts-into-aspnet-gridview-.aspx

Reading contacts from gmail

http://code.google.com/p/google-gdata/downloads/detail?name=Google_Data_API_Setup_1.8.0.0.msi&can=2&q=                  (api link)


http://isharpnote.com/isharpnote/post/2011/03/01/google_contact_import_aspnet.aspx


using Google.Contacts;
using Google.GData.Client;
using Google.GData.Contacts;
using Google.GData.Extensions;


<form id="form1" runat="server">
   <div><b>Email Address :</b> <br />
        <asp:TextBox ID="txtEmail" runat="server"> </asp:TextBox><br /><br /><b>Password :</b> <br />
        <asp:TextBox ID="txtPassword" runat="server" TabIndex="1" TextMode="Password"></asp:TextBox><br /> <br />
        <asp:Button ID="btnContacts" runat="server" onclick="btnContacts_Click"


                    TabIndex="2" Text="Import Contacts" Width="125px" /><br /> <br /> <br />
        <b>Contacts:<br /> </b>
        <asp:ListBox ID="lstContacts" runat="server" Height="176px" Width="229px"></asp:ListBox><br /> <br />
   </div>
</form>


protected void btnContacts_Click(object sender, EventArgs e)
{
       //Provide Login Information
       RequestSettingsrsLoginInfo = new RequestSettings(" ", txtEmail.Text, txtPassword.Text);
       rsLoginInfo.AutoPaging = true;
        // Fetch contacts and dislay them in ListBox
       ContactsRequestcRequest = new ContactsRequest(rsLoginInfo);
       Feed <contact>feedContacts = cRequest.GetContacts();
      foreach (Contact gmailAddresses in feedContacts.Entries)
      {
           Console.WriteLine("\t" + gmailAddresses.Title);
           lstContacts.Items.Add(gmailAddresses.Title);
            foreach (EMailemailId in gmailAddresses.Emails)
            {
                 Console.WriteLine("\t" + emailId.Address);
                 lstContacts.Items.Add(" " + emailId.Address);
            }
      }
}

Thursday, July 21, 2011

get the other columns data using command argument in grideview

 if (e.CommandName == "setfinactive")
        {
          
            //GridViewRow row = GridView2.Rows[index];

           GridViewRow gvr = (GridViewRow)((Control)e.CommandSource).NamingContainer;

           LinkButton pEdit = (LinkButton)gvr.FindControl("lblcourseid");

            userid = e.CommandArgument.ToString();
            courseid = Convert.ToInt32(pEdit.Text);
           
            //con.Open();
            //cmd = new SqlCommand("update usercourse set FInactive1 = 4 where userid =   ");
            //con.Close();


        }

Friday, July 15, 2011

confirmation box using gridview control when delete button click

under.aspx
-----------

  <asp:GridView DataKeyNames="sno" ID="GridView1"
       runat="server" AutoGenerateColumns="False"
       OnRowCommand="GridView1_RowCommand"
       OnRowDataBound="GridView1_RowDataBound"
       OnRowDeleted="GridView1_RowDeleted" OnRowDeleting="GridView1_RowDeleting">
  <Columns>
   <asp:BoundField DataField="sno" HeaderText="sno" />
   <asp:BoundField DataField="name" HeaderText="name" />
   <asp:TemplateField HeaderText="Select">
     <ItemTemplate>
       <asp:LinkButton ID="LinkButton1"
         CommandArgument='<%# Eval("sno") %>'
         CommandName="Delete" runat="server">
         Delete</asp:LinkButton>
     </ItemTemplate>
   </asp:TemplateField>
  </Columns>
</asp:GridView>



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class dummy : System.Web.UI.Page
{

    SqlConnection con = null;
    SqlCommand cmd = null;
    SqlDataReader dr = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
        con.Open();
        cmd = new SqlCommand("select sno,name from dummy",con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
        con.Close();

    }
 
  

    protected void GridView1_RowDataBound(object sender,
                          GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton l = (LinkButton)e.Row.FindControl("LinkButton1");
            l.Attributes.Add("onclick", "javascript:return " +
            "confirm('Are you sure you want to delete this record " +
            DataBinder.Eval(e.Row.DataItem, "sno") + "')");
        }
    }


    protected void GridView1_RowCommand(object sender,
                         GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Delete")
        {
            // get the categoryID of the clicked row

            int sno = Convert.ToInt32(e.CommandArgument);
            // Delete the record

           // DeleteRecordByID(categoryID);
            con.Open();
            cmd = new SqlCommand("delete from dummy where sno=@sno", con);
            cmd.Parameters.Add(new SqlParameter("@sno", sno));
            cmd.ExecuteNonQuery();
            con.Close();


            // Implement this on your own :)

        }
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int sno = (int)GridView1.DataKeys[e.RowIndex].Value;
       // DeleteRecordByID(categoryID);
        con.Open();
        cmd = new SqlCommand("delete from dummy where sno=@sno",con);
        cmd.Parameters.Add(new SqlParameter("@sno",sno));
        cmd.ExecuteNonQuery();
        con.Close();
    }


    protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e)
    {

    }
}

display alert by by using serverside code(works fine)

<asp:Button ID="ApproveButton" runat="server" CausesValidation="False" Text="ravi"
   
        OnClientClick="return confirm('Are you certain you want to approve this record?');"
        onclick="ApproveButton_Click" />

If the user clicks OK your normal click code will run but if they cancel the function returns false so the click won't be processed.

display alert by using serverside code

 string str = "Are you sure, you want to Approve this Record?";
        this.ClientScript.RegisterStartupScript(typeof(Page), "Popup", "ConfirmApproval('" + str + "');", true);

Wednesday, July 13, 2011

repeater control code

http://www.netrostar.com/Tutorials-91-ASP.NET%20Tutorial.%20How%20to%20use%20Repeater

Monday, July 11, 2011

mailattachment code

 protected void LinkButton1_Click(object sender, EventArgs e)
    {
         MailMessage message = new MailMessage();
       


            message.To.Add(new MailAddress("ravivarma_07d@yahoo.com"));
           // message.From = new MailAddress("ravivarma_07d@yahoo.com");


            message.Subject = "Testing";
            message.Body = "we are sending test mail";
            message.BodyEncoding = System.Text.Encoding.UTF8;
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            Attachment attach = new Attachment(FileUpload1.PostedFile.InputStream,FileUpload1.FileName);
            message.Attachments.Add(attach);

          
            message.Priority = MailPriority.Normal;

                string err = "";

                SmtpClient smtpClient1 = new System.Net.Mail.SmtpClient();

                try
                {
                    smtpClient1.Send(message);
                }

                catch (SmtpFailedRecipientException ex)
                {

                    err = ex.Message;
                }
                catch (SmtpException ex)
                {

                    err = ex.Message;
                }
       

    }

Saturday, July 9, 2011

pdf certificate

http://www.mikesdotnetting.com/Article/80/Create-PDFs-in-ASP.NET-getting-started-with-iTextSharp

Sunday, July 3, 2011

reading url form web.config (wcf service)

In Web.config:

 <appSettings>
    <add key="wsUrl" value="http://192.168.1.7:650/CafeService.svc"/>
  </appSettings>

in the .aspx page declare a globle variable

var wsurl;

in document.ready

 wsurl = '<%=ConfigurationManager.AppSettings["WsUrl"].ToString() %>';

Saturday, July 2, 2011

date formats

Declare @d datetime
select @d = getdate()

select @d as OriginalDate,
convert(varchar,@d,100) as ConvertedDate,
100 as FormatValue,
'mon dd yyyy hh:miAM (or PM)' as OutputFormat
union all
select @d,convert(varchar,@d,101),101,'mm/dd/yy'
union all
select @d,convert(varchar,@d,102),102,'yy.mm.dd'
union all
select @d,convert(varchar,@d,103),103,'dd/mm/yy'
union all
select @d,convert(varchar,@d,104),104,'dd.mm.yy'
union all
select @d,convert(varchar,@d,105),105,'dd-mm-yy'
union all
select @d,convert(varchar,@d,106),106,'dd mon yy'
union all
select @d,convert(varchar,@d,107),107,'Mon dd, yy'
union all
select @d,convert(varchar,@d,108),108,'hh:mm:ss'
union all
select @d,convert(varchar,@d,109),109,'mon dd yyyy hh:mi:ss:mmmAM (or PM)'
union all
select @d,convert(varchar,@d,110),110,'mm-dd-yy'
union all
select @d,convert(varchar,@d,111),111,'yy/mm/dd'
union all
select @d,convert(varchar,@d,112),112,'yymmdd'
union all
select @d,convert(varchar,@d,113),113,'dd mon yyyy hh:mm:ss:mmm(24h)'
union all
select @d,convert(varchar,@d,114),114,'hh:mi:ss:mmm(24h)'
union all
select @d,convert(varchar,@d,120),120,'yyyy-mm-dd hh:mi:ss(24h)'
union all
select @d,convert(varchar,@d,121),121,'yyyy-mm-dd hh:mi:ss.mmm(24h)'
union all
select @d,convert(varchar,@d,126),126,'yyyy-mm-dd Thh:mm:ss:mmm(no spaces)'

Thursday, June 30, 2011

Wednesday, June 29, 2011

download excel sheet/video/any thing from folder in the solution


// just writ this code under button click:

 protected void Button1_Click(object sender, EventArgs e)
    {
        string filename = "qtn.txt";//file name which used to download
        string filepath = "README.txt";//where you want to download the file
        Response.Clear();
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename);
        Response.ContentType = "application//octet-stream";
        Response.TransmitFile(Server.MapPath(filepath));
        Response.End();
    }

Friday, June 24, 2011

Bloc Ui code

design
---------- 
div.blockOverlay {
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; 
    filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=50); 
    -moz-opacity:.70;
    opacity:.70;
    background-color: #FFFFFF;
}



 $.blockUI.defaults.overlayCSS = {};
        $.blockUI({
            message: "<img src='images/loading.gif' />",
            css: { border: '0px ',
                backgroundColor: 'Transparent',
                '-webkit-border-radius': '10px',
                '-moz-border-radius': '10px',
                opacity: .5,
                color: '#fff'
            }
        });


                $.unblockUI();


<script src="Scripts/jquery.blockUI.js" type="text/javascript"></script>

get alerts fron .cs file in asp.net

 put this class in app_code folder save with the name Alert.cs

using System.Web;
using System.Text;
using System.Web.UI;

/// <summary>
/// A JavaScript alert
/// </summary>
public static class Alert
{

  /// <summary>
  /// Shows a client-side JavaScript alert in the browser.
  /// </summary>
  /// <param name="message">The message to appear in the alert.</param>
  public static void Show(string message)
  {
    // Cleans the message to allow single quotation marks
    string cleanMessage = message.Replace("'", "\\'");
    string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";

    // Gets the executing web page
    Page page = HttpContext.Current.CurrentHandler as Page;

    // Checks if the handler is a Page and that the script isn't allready on the Page
    if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
    {
      page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
    }
  }
   
}

Tuesday, June 21, 2011

calling .cs method from javascript

http://decoding.wordpress.com/2008/11/14/aspnet-how-to-call-a-server-side-method-from-client-side-javascript/

calling javascript function from c#code

<script>
function hi(var someVar)
{
   document.write("hi " + someVar);
}
</script>

in .NET on a method you wish to call the javascript method from:
string whatever = "blahblah";
Page.RegisterStartupScript("myScript", "<script language=JavaScript>hi('" + whatever + "');</script>");

I hope that is what you are looking for and hope it helps!

Wednesday, June 8, 2011

validation sourse code





make sure write onclick function <form tag in method attr> instead on button submit onclick



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="validations_Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <title>JQuery Validation Engine</title>
        <link rel="stylesheet" href="../css/validationEngine.jquery.css" type="text/css"/>
        <link rel="stylesheet" href="../css/template.css" type="text/css"/>
        <script src="../js/jquery-1.6.min.js" type="text/javascript">
        </script>
        <script src="../js/languages/jquery.validationEngine-en.js" type="text/javascript" charset="utf-8">
        </script>

        <script src="../js/jquery.validationEngine.js" type="text/javascript" charset="utf-8">
        </script>
        <script>
            jQuery(document).ready(function() {
                // binds form submission and fields to the validation engine
                jQuery("#formID").validationEngine();
            });

            function hello() {

                alert('hiiii');
            }
        </script>
    </head>
    <body>
   
        <div calss="viv">
        <form id="formID" class="formular" method="post" action="javascript:hello()">
       
       
          <fieldset>
                <legend>
                    Text field
                </legend>
                <label>
                    URL begin with http:// https:// or ftp://
                    <br/>
                    <span>Enter a URL : </span>
                    <input value="http://" class="validate[required,custom[url]] text-input" type="text" name="url" id="url" />

                </label>
            </fieldset>
           
           <table>
           <tr>
           <td>
           name
           </td>
           <td><input type="text" id="tdtxt" class="validate[required]"  /></td>
           </tr>
          
           <tr>
           <td>
            <select name="sport" id="sport" class="validate[required]">
                        <option value="">Choose a sport</option>
                        <option value="option1">Tennis</option>
                        <option value="option2">Football</option>
                        <option value="option3">Golf</option>
                    </select>
           </td>
           </tr>
           </table>
       
       
       
       
       
            <input class="submit" type="submit" value="Validate & Send the form!"/>
            <hr/>
        </form>
</div>
    </body>
</html>

jQuery Plugins that enhance and beautify HTML form elements and validations

http://www.queness.com/post/204/25-jquery-plugins-that-enhance-and-beautify-html-form-elements


http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/

Monday, June 6, 2011

Saturday, May 28, 2011

wcf restfull securitt link

http://debugmode.net/2011/05/09/exposing-wcf-rest-service-over-https/

Friday, May 27, 2011

Monday, May 23, 2011

Thursday, May 19, 2011

servicehost (web.config)------crossdomainpolacy

?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <bindings>
      <webHttpBinding>
        <binding name="crossdomain" crossDomainScriptAccessEnabled="true" />
      </webHttpBinding>
    </bindings>
    <services>
      <service name="Tenderslibrary.Service1">
        <endpoint address="" binding="webHttpBinding" behaviorConfiguration="WEB"
          bindingConfiguration="crossdomain" contract="Tenderslibrary.IService1" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="WEB">
          <webHttp/>
         
        </behavior>
     
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
 
</configuration>

Wednesday, May 18, 2011

jquery datepicker source code and link as well

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <title>dynDateTime: jQuery calendar plugin based on Dynarch date time calendar </title>

        <script src="datepickerjs/jquery-1.2.6.min.js" type="text/javascript"></script>

        <script src="datepickerjs/jquery.dynDateTime.js" type="text/javascript"></script>

        <script src="datepickerjs/calendar-en.js" type="text/javascript"></script>

        <link href="datepickerjs/calendar-win2k-cold-1.css" rel="stylesheet" type="text/css" />
   


    </head>
    <body>
   
    <h1>dynDateTime</h1>
   
    <p>See project <a href="http://code.google.com/p/dyndatetime/">home page</a> for details.</p>

   
        <form action="/nothing/to/post.to">
            <div>
                <h3>Default with no options</h3>
                <script type="text/javascript">
                    jQuery(document).ready(function() {
                        jQuery("#dateDefault").dynDateTime(); //defaults
                    });
                </script>
                <input type="text" name="dateDef" id="dateDefault"/>
                <hr/>
   
                <h3>Bind to multiple inputs in one go</h3>

                <script type="text/javascript">
                    jQuery(document).ready(function() {
   
                        jQuery("#multi input").dynDateTime({               
                            button: ".next()" //next sibling
                        });
                       
                    });
                </script>
                <div id="multi">
                    <input type="text" name="dateA"/>
                    <button type="button">PICKER</button>
                    <br/>
                   
                    <input type="text" name="dateB"/>
                    <button type="button">PICKER</button>

                    <br/>
                   
                    <input type="text" name="dateC" value="2001/09/11"/>
                    <button type="button">PICKER</button>
                    <br/>
                </div>
                <hr/>
   
                <h3>Using time, custom format, display output, and different pop-up location</h3>
                <script type="text/javascript">
                    jQuery(document).ready(function() {
                        jQuery("#dateTimeCustom").dynDateTime({
                            showsTime: true,
                            ifFormat: "%Y/%m/%d-%H:%M",
                            daFormat: "%l;%M %p, %e %m,  %Y",
                            align: "TL",
                            electric: false,
                            singleClick: false,
                            displayArea: ".siblings('.dtcDisplayArea')",
                            button: ".next()" //next sibling
                        });
                    });
                </script>

                The selected date is <span class="dtcDisplayArea"></span> <br/>
                <input type="text" name="dateTimeCust" id="dateTimeCustom"/>
                <button type="button">PICKER</button>
                <hr/>
   
                <h3>Flat example</h3>
                <script type="text/javascript">
                    jQuery(document).ready(function() {
                        jQuery("#dateFlat").dynDateTime({
                                flat: ".next()",
                                debug: false
                            });
                    });
                </script>

                <input type="text" name="dateDef" id="dateFlat" value="2001/09/11"/>
                <div style="float: left;">&nbsp;</div>
                <hr style="clear: both;"/>
   
            </div>
        </form>

        <p>
            <a href="http://validator.w3.org/check?uri=referer">
                <img src="http://www.w3.org/Icons/valid-xhtml10-blue" alt="Valid XHTML 1.0 Strict" height="31" width="88" />

            </a>
        </p>
    </body>
</html>






http://www.mechanicalmarksy.com/hosted/toolman/dyndatetime/example.html

crossdomain global.cs

<%@ Application Language="C#" %>

<script runat="server">

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        System.Web.Routing.RouteTable.Routes.Add(new System.ServiceModel.Activation.ServiceRoute("",new System.ServiceModel.Activation.WebServiceHostFactory(), typeof(System.Web.Services.Description.Service)));

    }
   
    void Application_End(object sender, EventArgs e)
    {
        //  Code that runs on application shutdown

    }

    protected void Application_BeginRequest(object sender, EventArgs e)
    {

        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        HttpContext.Current.Response.Cache.SetNoStore();

        EnableCrossDmainAjaxCall();
    }

    private void EnableCrossDmainAjaxCall()
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin","*");

        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods",
                          "GET, POST");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
                          "Content-Type, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age",
                          "1728000");
            HttpContext.Current.Response.End();
        }
    }
       
    void Application_Error(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occurs

    }

    void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started

    }

    void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends.
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer
        // or SQLServer, the event is not raised.

    }
      
</script>
 using System.ServiceModel.Activation;
 [AspNetCompatibilityRequirements
(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
     public class Service1 : IService1

Tuesday, May 17, 2011

fancy box code

fancy box code


 <%-- fancybox--%>
    <script src="fancybox/jquery.mousewheel-3.0.4.pack.js" type="text/javascript"></script>
    <script src="fancybox/jquery.fancybox-1.3.4.pack.js" type="text/javascript"></script>
    <link href="fancybox/jquery.fancybox-1.3.4.css" rel="stylesheet" type="text/css" />
<!--fancy box-->



1) $(document).ready(function () {
      
        $("#siginid").fancybox({
            'transitionIn': 'elastic',
            'transitionOut': 'elastic',
            'speedIn': 600,
            'speedOut': 200,
            'overlayShow': false
        });

    });


2)<a id="siginid" href="#signinhref">Sign in</a>


3)<div id="fancy" style="display:none">
<div id="signinhref">
<table>
<tr><td>Userid</td><td><input id="txtuserid" type="text" /></td></tr>
<tr><td>Password</td><td><input id="Text1" type="password" /></td></tr>
<tr><td><input id="btnsignin" type="button" value="Sign in" /></td></tr>

</table>


</div>
</div>

Monday, May 16, 2011

Sunday, May 15, 2011

Sedning email through serivce(wcf)

Through smtp
==============   USING WCF SERVICE SENDING MAIL

            email.From = new MailAddress("crmprocorp1@gmail.com");
            email.CC.Add("crmprocorp1@gmail.com");
           email.To.Add(txtemail);

         
            float persentage = Convert.ToSingle(examscore) * 100 / 20;

          string str= "<table><tr><td>Congratulations on attaining the following score. Your counselling is scheduled for this Saturday. Please call your</td></tr>";
                   str+=  "<tr><td>Counsellor : Mr.David  at 07799400500 to get your appointment time. Please get a copy of the score card/CV for the counselling.<br/><br/></td></tr>";
                 
                    str+=  "<tr><td>Regards,</td></tr>";
                      str+="<tr><td><b>Anuj T</b></td></tr><br/><br/>";

                      str += "<tr><td><b>Email</b> :anuj@cliniindia.com |<b> Phone</b> :  040 6555 0643  | <b> Website</b> :<a href='www.cliniindia.com'>www.cliniindia.com/info@cliniindia.com</a></td></tr>";
                       str += "<tr><td><b>Address</b> : CLINI INDIA, Swathi Plaza , Raj Bhavan Road ( Near Yashoda Hospital ), Somajiguda , Hyderabad - 500 082</td></tr>";
                       str += "</table>";


            string gradstr = "";
            if (grade == "Grade A")
            {

               // gradstr = "You have scored " + persentage.ToString() + "% for Grade A and secured a schorlarship for RS.30,000 ";
                gradstr = str;
            }
            if (grade == "Grade B")
            {

               // gradstr = "You have scored " + persentage.ToString() + "% for Grade B and secured a schorlarship for RS.20,000 ";
                gradstr = str;
            }
            if (grade == "Grade C")
            {

              //  gradstr = "You have scored " + persentage.ToString() + "% for Grade C and secured a schorlarship for RS.10,000 ";
                gradstr = str;
            }
            if (grade == "sorry")
            {

             //   gradstr = "You have not attended the desired score for the scholarship,You may try again or call our counsellor at 040- 6555 0643.";
                gradstr = str;
                //grade=
            }

            StringBuilder sb1 = new StringBuilder();
            sb1.Append("<html><head><title></title></head><body><table>");
            sb1.Append(" Dear " + txtname + ", <br/><br/> " + gradstr + "<br/><br/>");
            sb1.Append("<tr><td><br/></td></tr><tr><td>");

            sb1.Append("<table>");
            sb1.Append("<tr><td style='background-color:Green' colspan='2'></td></tr>");
            sb1.Append("<tr><td  colspan='2'><h2><b>CliniIndia Exam score card</b></h2></td></tr>");
            sb1.Append("<tr><td><h4><b>Name</b></h4></td><td>" + txtname + "</td></tr>");
            sb1.Append("<tr><td><h4><b>Date of exam</b></h4></td><td>" + DateTime.Now + "</td></tr>");
            sb1.Append("<tr><td><h4><b>Score</b></h4></td><td>" + examscore + " out of 20</td></tr>");
            sb1.Append("<tr><td><h4><b>Percentage</b></h4></td><td>" + persentage + "%</td></tr>");
            //sb1.Append("<tr><td><h4><b>Grade</b></h4></td><td>" + grade + "</td></tr>");
            sb1.Append("<tr><td style='background-color:Green'  colspan='2'></td></tr>");
            sb1.Append("<tr></table>");

              sb1.Append("</td>");
            sb1.Append("</tr></table></body></html>");


            email.Body = sb1.ToString();


            email.Subject = "Scholarship";
            email.IsBodyHtml = true;
            email.Priority = MailPriority.Normal;

            string err = "";

            SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
         
            try
            {
                smtpClient.Send(email);
            }
         
            catch (SmtpFailedRecipientException ex)
            {

                err = ex.Message;
            }
            catch (SmtpException ex)
            {

                err = ex.Message;
            }
            return true;


IN APP.CONFIG
==============

 <!--<smtp from="bhaskar@crmprocorp.com" deliveryMethod="Network">
        <network defaultCredentials="false" enableSsl="false" host="mail.crmprocorp.com" port="25" password="password" userName="bhaskar@crmprocorp.com" />
     
      </smtp>-->
      <smtp from="crmprocorp1@gmail.com" deliveryMethod="Network">
        <network defaultCredentials="false" enableSsl="false" host="smtp.gmail.com" port="587" password="Pu99et@1" userName="crmprocorp1@gmail.com" />
      </smtp>
































Saturday, May 7, 2011

generate uniqid lilke gudi using jqery

 function generateGuid() {
            var result, i, j;
            result = '';
            for (j = 0; j < 32; j++) {
                if (j == 8 || j == 12 || j == 16 || j == 20)
                    result = result + '-';
                i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
                result = result + i;
            }
           alert(result);
        }

Wednesday, April 27, 2011

conveting html to pdf


http://www.devtoolshed.com/content/c-free-component-

generate-pdf-convert-html-pdf



under button click
=====================



     // set a path to where you want to write the PDF to.

string sPathToWritePdfTo = @"d:\new_pdf_name.pdf";



// build some HTML text to write as a PDF.  You could also

// read this HTML from a file or other means.

// NOTE: This component doesn't understand CSS or other

// newer style HTML so you will need to use depricated

// HTML formatting such as the <font> tag to make it look correct.

System.Text.StringBuilder sbHtml = new System.Text.StringBuilder();

sbHtml.Append("<html>");

sbHtml.Append("<body>");

sbHtml.Append("<font size='14'>My Document Title Line</font>");

sbHtml.Append("<br />");

sbHtml.Append("This is my document text");

sbHtml.Append("</body>");

sbHtml.Append("</html>");



// create file stream to PDF file to write to

using (System.IO.Stream stream = new System.IO.FileStream

(sPathToWritePdfTo, System.IO.FileMode.OpenOrCreate))

{

    // create new instance of Pdfizer

    Pdfizer.HtmlToPdfConverter htmlToPdf = new Pdfizer.HtmlToPdfConverter();

    // open stream to write Pdf to to

    htmlToPdf.Open(stream);

    // write the HTML to the component

    htmlToPdf.Run(sbHtml.ToString());

    // close the write operation and complete the PDF file

    htmlToPdf.Close();

}

//This component also supports PDF Chapters. You could add a single line of code right before the Run() method to make the HTML specified a single chapter like this:

// open stream to write Pdf to to

//htmlToPdf.Open(stream);



//// add a chapter for this HTML

//htmlToPdf.AddChapter("My Chapter Title 1");



//// write the HTML to the component

//htmlToPdf.Run(sbHtml.ToString());

Tuesday, April 26, 2011

good looking imgaes using jquey

http://www.templatezone.com/html-email-marketing-software/high-impact-email-free-trial-download


http://www.campaignmonitor.com/templates/

Saturday, April 16, 2011

Tuesday, April 12, 2011

emailcode using in handler

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Configuration;
using System.Net.Mail;
using System.Net.Configuration;

//using System.Web.Mail;



public class EmailHandler : IHttpHandler {

    string result = null;
    int id = 0;
    String strMethodName = String.Empty;

    string smtpHost;
    string smtpport;
    string smtpuser;
    string smtppwd;
    SmtpClient client = null;

   
    SqlConnection con = null;
    DataSet ds;
   StringBuilder sb = new StringBuilder();

   
    public void ProcessRequest (HttpContext context) {
       
         con = new SqlConnection("Data Source=CRM1-PC;Initial Catalog=LibraryApp;User ID=sa;Password=hyd@345");
        context.Response.ContentType = "text/plain";
        strMethodName = "sendemail";

        if (!String.IsNullOrEmpty(context.Request.QueryString["StrMethodName"]))
        {
          //  strMethodName = Convert.ToString(context.Request.QueryString["StrMethodName"]);
            strMethodName = "sendemail";
        }

       

        //if (!String.IsNullOrEmpty(context.Request.Form["CategoryId"]))
        //{
        //    categoryId = Convert.ToInt32(context.Request.Form["CategoryId"]);
        //}


        //if (!String.IsNullOrEmpty(context.Request.QueryString["StrMethodName"]))
        //{
        //    strMethodName = Convert.ToString(context.Request.QueryString["StrMethodName"]);
        //}

        if (strMethodName.Length > 0 && strMethodName.Equals("sendemail"))
        {

            bool Result = SendMail("giribhushan1988@gmail.com","hi","hello");
            context.Response.Write(Result);
          
        }
      
     
    }



   
    private static MailMessage message = null;


    public bool SendMail(string toMailAddress, string mailSubject, string mailMessage)
    {
        Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
        MailSettingsSectionGroup settings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");
         smtpHost = settings.Smtp.Network.Host;
         smtpport = settings.Smtp.Network.Port.ToString();
         smtpuser = settings.Smtp.Network.UserName;
         smtppwd = settings.Smtp.Network.Password;
       
     



        string MessageBody = string.Empty;
        try
        {

            message = new MailMessage();
            message.From = new MailAddress(smtpuser);
        
            message.To.Add(toMailAddress);
           
            message.BodyEncoding = System.Text.Encoding.UTF8;
           
            message.Subject = mailSubject;
            message.Body = mailMessage.ToString();



            message.IsBodyHtml = true;

            client = new SmtpClient();
            client.Host = smtpHost;
            //if (isSSLEnabled)
            //{
            //    client.EnableSsl = true;
            //}

            client.Port =  Convert.ToInt32(smtpport);
            client.EnableSsl = false;
            client.Credentials = new System.Net.NetworkCredential(smtpuser, smtppwd);
          
            client.Send(message);
        }
        catch (Exception ex)
        {
            string x = ex.Message;
        }
        return true;
    }
   

    public bool IsReusable {
        get {
            return false;
        }
    }

}

Handler code

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web.Mail;


public class EmailHandler : IHttpHandler {

    string result = null;
    int id = 0;
    SqlConnection con = null;
    DataSet ds;
   StringBuilder sb = new StringBuilder();
 
   
    public void ProcessRequest (HttpContext context) {
       
         con = new SqlConnection("Data Source=CRM1-PC;Initial Catalog=LibraryApp;User ID=sa;Password=hyd@345");
        context.Response.ContentType = "text/plain";


        string Mehtodname = "sendemail";//context.Request.QueryString["str"].ToString();
       

        //if (!String.IsNullOrEmpty(context.Request.Form["CategoryId"]))
        //{
        //    categoryId = Convert.ToInt32(context.Request.Form["CategoryId"]);
        //}


        //if (!String.IsNullOrEmpty(context.Request.QueryString["StrMethodName"]))
        //{
        //    strMethodName = Convert.ToString(context.Request.QueryString["StrMethodName"]);
        //}

        //if (strMethodName.Length > 0 && strMethodName.ToUpper().Equals("REGISTERUSER"))
        //{

        //    Result = RegisterUser();
        //    context.Response.Write(Result);
        //    //context.Response.Write("<div><p><strong>Name : </strong>" + strSalutation + " " + strFirstName + " " + strLastName + "</p><p><strong>Email: </strong>" + strEmailID + "</p><p><strong>Location: </strong> " + strCity + ", " + strContactNo + ", " + strReferalId + ", " + strCaptcha + "</p></div>");
        //}
      
        //context.Response.Write("Hello World");
    }



    //private int RegisterUser()
    //{
    //    objuser.Salutation = strSalutation;
    //    objuser.FirstName = strFirstName;
    //    objuser.LastName = strLastName;
    //    objuser.Email = strEmailID;
    //    objuser.Phone = strContactNo;
    //    objuser.ReferalId = strReferalId;
    //    // objuser.City = strCity;
    //    objuser.RoleId = 3;
    //    objuser.Captcha = strCaptcha;
    //    objuser.IsFirstLogin = false;
    //    objuser.Status = 0;

    //    return objuser.AddUser();

    //}
   

    public bool IsReusable {
        get {
            return false;
        }
    }

}

Monday, April 11, 2011

menus and sliders using jquery

http://wowslider.com/jquery-slider-noble-fade-demo.html

http://apycom.com/menus/9-deep-sky-blue.html

Extracting images from pdf file

http://kishor-naik-dotnet.blogspot.com/2011/01/cnet-extract-image-from-pdf-file.html



C#.net - Extract image from PDF file.

In this article i will show you how to extract image from PDF file.

Step 1
First you need to download "ITextSharp.dll" from the following link.
http://sourceforge.net/projects/itextsharp/

Step 2
Create a Console application and give the solution name as ConExtractImagefromPDF.

Step 3
Add two assembly reference to the project from solution explorer.

1.ITextSharp.dll
2.System.Drawing.dll
Step 4
Write a static method for extracting image from pdf file,it is look like this

/// <summary>
        ///  Extract Image from PDF file and Store in Image Object
        /// </summary>
        /// <param name="PDFSourcePath">Specify PDF Source Path</param>
        /// <returns>List</returns>
        private static List<System.Drawing.Image> ExtractImages(String PDFSourcePath)
        {
            List<System.Drawing.Image> ImgList = new List<System.Drawing.Image>();

            iTextSharp.text.pdf.RandomAccessFileOrArray RAFObj = null;
            iTextSharp.text.pdf.PdfReader PDFReaderObj = null;
            iTextSharp.text.pdf.PdfObject PDFObj = null;
            iTextSharp.text.pdf.PdfStream PDFStremObj = null;

            try
            {
                RAFObj = new iTextSharp.text.pdf.RandomAccessFileOrArray(PDFSourcePath);
                PDFReaderObj = new iTextSharp.text.pdf.PdfReader(RAFObj, null);

                for (int i = 0; i <= PDFReaderObj.XrefSize - 1; i++)
                {
                    PDFObj = PDFReaderObj.GetPdfObject(i);

                    if ((PDFObj != null) && PDFObj.IsStream())
                    {
                        PDFStremObj = (iTextSharp.text.pdf.PdfStream)PDFObj;
                        iTextSharp.text.pdf.PdfObject subtype = PDFStremObj.Get(iTextSharp.text.pdf.PdfName.SUBTYPE);

                        if ((subtype != null) && subtype.ToString() == iTextSharp.text.pdf.PdfName.IMAGE.ToString())
                        {
                            byte[] bytes = iTextSharp.text.pdf.PdfReader.GetStreamBytesRaw((iTextSharp.text.pdf.PRStream)PDFStremObj);

                            if ((bytes != null))
                            {
                                try
                                {
                                    System.IO.MemoryStream MS = new System.IO.MemoryStream(bytes);

                                    MS.Position = 0;
                                    System.Drawing.Image ImgPDF = System.Drawing.Image.FromStream(MS);

                                    ImgList.Add(ImgPDF);

                                }
                                catch (Exception)
                                {
                                }
                            }
                        }
                    }
                }
                PDFReaderObj.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return ImgList;
        }


Step 5
Write a static method for store extracting image file in folder,it is look like this

/// <summary>
        ///  Write Image File
        /// </summary>
        private static void WriteImageFile()
        {
            try
            {
                System.Console.WriteLine("Wait for extracting image from PDF file....");

                // Get a List of Image
                List<System.Drawing.Image> ListImage = ExtractImages(@"C:\Users\Kishor\Desktop\TuterPDF\ASP.net\ASP.NET 3.5 Unleashed.pdf");

                for (int i = 0; i < ListImage.Count; i++)
                {
                    try
                    {
                        // Write Image File
                        ListImage[i].Save(AppDomain.CurrentDomain.BaseDirectory + "ImageStore\\Image" + i + ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
                        System.Console.WriteLine("Image" + i + ".jpeg write sucessfully"); 
                    }
                    catch (Exception)
                    { }
                }

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

Step 6
Call above function in main method,it is look like this

static void Main(string[] args)
        {
            try
            {
                WriteImageFile(); // write image file
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);  
            }
        }

Full Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConExtractImagefromPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                WriteImageFile(); // write image file
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);  
            }
        }

        #region Methods

        /// <summary>
        ///  Extract Image from PDF file and Store in Image Object
        /// </summary>
        /// <param name="PDFSourcePath">Specify PDF Source Path</param>
        /// <returns>List</returns>
        private static List<System.Drawing.Image> ExtractImages(String PDFSourcePath)
        {
            List<System.Drawing.Image> ImgList = new List<System.Drawing.Image>();

            iTextSharp.text.pdf.RandomAccessFileOrArray RAFObj = null;
            iTextSharp.text.pdf.PdfReader PDFReaderObj = null;
            iTextSharp.text.pdf.PdfObject PDFObj = null;
            iTextSharp.text.pdf.PdfStream PDFStremObj = null;

            try
            {
                RAFObj = new iTextSharp.text.pdf.RandomAccessFileOrArray(PDFSourcePath);
                PDFReaderObj = new iTextSharp.text.pdf.PdfReader(RAFObj, null);

                for (int i = 0; i <= PDFReaderObj.XrefSize - 1; i++)
                {
                    PDFObj = PDFReaderObj.GetPdfObject(i);

                    if ((PDFObj != null) && PDFObj.IsStream())
                    {
                        PDFStremObj = (iTextSharp.text.pdf.PdfStream)PDFObj;
                        iTextSharp.text.pdf.PdfObject subtype = PDFStremObj.Get(iTextSharp.text.pdf.PdfName.SUBTYPE);

                        if ((subtype != null) && subtype.ToString() == iTextSharp.text.pdf.PdfName.IMAGE.ToString())
                        {
                            byte[] bytes = iTextSharp.text.pdf.PdfReader.GetStreamBytesRaw((iTextSharp.text.pdf.PRStream)PDFStremObj);

                            if ((bytes != null))
                            {
                                try
                                {
                                    System.IO.MemoryStream MS = new System.IO.MemoryStream(bytes);

                                    MS.Position = 0;
                                    System.Drawing.Image ImgPDF = System.Drawing.Image.FromStream(MS);

                                    ImgList.Add(ImgPDF);

                                }
                                catch (Exception)
                                {
                                }
                            }
                        }
                    }
                }
                PDFReaderObj.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return ImgList;
        }


        /// <summary>
        ///  Write Image File
        /// </summary>
        private static void WriteImageFile()
        {
            try
            {
                System.Console.WriteLine("Wait for extracting image from PDF file....");

                // Get a List of Image
                List<System.Drawing.Image> ListImage = ExtractImages(@"C:\Users\Kishor\Desktop\TuterPDF\ASP.net\ASP.NET 3.5 Unleashed.pdf");

                for (int i = 0; i < ListImage.Count; i++)
                {
                    try
                    {
                        // Write Image File
                        ListImage[i].Save(AppDomain.CurrentDomain.BaseDirectory + "ImageStore\\Image" + i + ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
                        System.Console.WriteLine("Image" + i + ".jpeg write sucessfully"); 
                    }
                    catch (Exception)
                    { }
                }

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion
    }
}

Saturday, April 9, 2011

JQUERY VALIDATINS AND FORM LAYOUTS

http://www.position-relative.net/creation/formValidator/


http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/



http://www.easywayserver.com/blog/must-see-the-best-jquery-examples/


http://demos.usejquery.com/ketchup-plugin/

http://www.queness.com/post/2190/40-extremely-useful-jquery-form-plugins

http://www.lullabot.com/files/bt/bt-latest/DEMO/index.html

http://tympanus.net/codrops/2010/04/30/rocking-and-rolling-rounded-menu-with-jquery/


http://tympanus.net/codrops/2010/04/29/awesome-bubble-navigation-with-jquery/

Friday, April 8, 2011

adding items to dropdown and clear items using javascript

<script type="text/javascript">
    function AddItem(Text,Value)
    {
        // Create an Option object       

        var opt = document.createElement("option");

        // Add an Option object to Drop Down/List Box
        document.getElementById("DropDownList").options.add(opt);

        // Assign text and value to Option object
        opt.text = Text;
        opt.value = Value;

    }<script />

clear items in dropdown

  var theDropDown = document.getElementById("testddl") 
         var numberOfOptions = theDropDown.options.length
         for (i = 0; i < numberOfOptions; i++) {
           //Note: Always remove(0) and NOT remove(i)
             theDropDown.remove(0);
            }


http://chiragrdarji.wordpress.com/2007/06/06/add-items-in-drop-down-list-or-list-box-using-javascript/

dynamically building table using javascript by stack overflow

function start() {
    // get the reference for the body
    var body = document.getElementsByTagName("body")[0];

    // creates a <table> element and a <tbody> element
    var tbl     = document.createElement("table");
    var tblBody = document.createElement("tbody");

    // creating all cells
    for (var j = 0; j < 2; j++) {
        // creates a table row
        var row = document.createElement("tr");

        for (var i = 0; i < 2; i++) {
            // Create a <td> element and a text node, make the text
            // node the contents of the <td>, and put the <td> at
            // the end of the table row
            var cell = document.createElement("td");
            var cellText = document.createTextNode("cell is row "+j+", column "+i);
            cell.appendChild(cellText);
            row.appendChild(cell);
        }

        // add the row to the end of the table body
        tblBody.appendChild(row);
    }

    // put the <tbody> in the <table>
    tbl.appendChild(tblBody);
    // appends <table> into <body>
    body.appendChild(tbl);
    // sets the border attribute of tbl to 2;
    tbl.setAttribute("border", "2");