Thursday, January 30, 2014

how to set multiple items are selected in ListBox?

List<string> Authors = new List<string>(new string[] { "Jk Rowling""Morris Mano" });
 
foreach (ListItem item in ListBox1.Items)
{
    if (Authors.Contains(item.Text))
        item.Selected = true;
}

Subquery returning csv written values in a Main Query Column

select 
    categorie, 
    stuff((select ', ' + id
           from table2 t2 where t1.categorie = t2.categorie
           for xml path('')),
          1,2,'') [IDs]
from table1 t1

Wednesday, January 29, 2014

Crystal Reports Viewer won't go past page 2

The problem may stem from setting the Crystal Report Viewer control's ReportSource during the Page_Load event. This causes the paging information to be over-written with each page load, so the "current page" is re-set to 1 when it should be at 2. As an easy solution, you can move the code that sets ReportSource into Page_Init
        protected void Page_Init(object sender, EventArgs e)
        {
            if (IsPostBack && Session["rd"] != null)
            {
                crv.ReportSource = (ReportDocument)Session["rd"];
            }
        }

Monday, January 27, 2014

asp net Register a Control assembly on web.config

How to Register a Control assembly on web.config
<pages theme="Normal" clientIDMode="Static">
    <controls>
        <add assembly="CKEditor.NET" namespace="CKEditor.NET" tagPrefix="CKEditor"/>
    </controls>
</pages>

Thursday, January 23, 2014

How to log the user out using FormsAuthentication.SignOut()

FormsAuthentication.SignOut();
Session.Abandon();
 
// clear authentication cookie
HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
cookie1.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie1);
cookie1.Path = FormsAuthentication.FormsCookiePath;
cookie1.HttpOnly = true;
 
// clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId""");
cookie2.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie2);
 
FormsAuthentication.RedirectToLoginPage();

How to Disable RequiredFieldValidator with javascript

<script>
    ValidatorEnable(document.getElementById('RequiredFieldValidator1'), false);
</script>

Sunday, January 19, 2014

Remove transparency in images with C#

Remove Transparency from png's in c# or asp net c#
public void RemoveTransparency(string filename)
{
   using (System.Drawing.Bitmap src = new System.Drawing.Bitmap(filename))
   {
      using (System.Drawing.Bitmap target = new System.Drawing.Bitmap(src.Size.Width, src.Size.Height))
      {
          using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(target))
          {
             g.Clear(System.Drawing.Color.White);
             g.DrawImage(src, 0, 0);  
          }
          target.Save("Full path of file");
      }
   }
}

Saving Image To MemoryStream asp net c#

Use this function to convert image to byte array
public byte[] GetByte(System.Drawing.Image image)
{
    using (System.IO.MemoryStream m = new System.IO.MemoryStream())
    {
        image.Save(m, image.RawFormat);
        return m.ToArray();
    }
}

Saturday, January 11, 2014

Errror casting System.DBNulll to System.Byte[]

Consider this line of code
imgSign.ImageUrl = "data:image/png;base64," + Convert.ToBase64String((byte[])dr["Signature"]);  
now if dr["Signature"] returns a null value compiler will raise the error
Error casting System.DBNulll to System.Byte[]

to handler this error we can either use try catch or if statement to see if dr["Signature"] is not null

if (dr["Signature"] != DBNull.Value)
imgSign.ImageUrl = "data:image/png;base64," + Convert.ToBase64String((byte[])dr["Signature"]);

Sunday, January 5, 2014

Sql temp table with primary key and autoincrement field?

CREATE TABLE #TBL
(
ID INT IDENTITY(1, 1) primary key ,
SOMETHING VARCHAR(50)
);

How to set multiple data attributes using the jQuery.attr()

$('#img').attr({
     alt: 'Beijing Brush Seller',
     title: 'photo by Kelly Clark'
});

Saturday, January 4, 2014

Save jSign image to file using php

Setup jSign first
in head section of page
<!-- you load jquery somewhere above here ... -->
<!--[if lt IE 9]>
<script type="text/javascript" src="libs/flashcanvas.js"></script>
<![endif]-->
in body section
<form action="save-sign.php" method="post">
 Sign here
 <div id="signature"></div>
 <input type="hidden" name="hdnSignature" id="hdnSignature" />
 <input type="button" id="btn_submit" value="Submit Form" />
</form>
<script>
$(function () {
 'use strict';
 var $sigdiv = $("#signature");
 $sigdiv.jSignature();// inits the jSignature widget.
 
 //save data to hidden field before submiting the form
 $('#btn_submit').click(function () {
  var datapair = $sigdiv.jSignature("getData""image");
  $('#hdnSignature').val(datapair[1]);
 //now submit form 
document.forms[0].submit();
  });
 });
</script>
and save-sign.php file should be like this
<?php
$sign = '';
if(isset($_POST['hdnSignature']))
{
 $sign = $_POST['hdnSignature'];
 $path = "path to file.png";
 $sign = base64_decode($sign); //convert base64
 file_put_contents($path$sign); //save to file
 //all done
}
?>

Validating date using Compare Validator asp net

Use below given code snippet
<asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="Invalid Date"  
Operator="DataTypeCheck" Type="Date" ControlToValidate="{}" ControlToCompare="not required">
</asp:CompareValidator>

Export / Output asp net gridview output to excel file

If you want to export gridview output to an excel file you can use the following code.
In this example it is done by clicking a button
Requirements
  1. GridView with ID GridView1
  2. ASP NET Button With ID Button1
    protected void Button1_Click(object sender, EventArgs e)
    {
        string filename = "Bingo.xls";
        ExportToExcel(filename, GridView1);
    }
     
    private void ExportToExcel(string filename, GridView gv)
    {
        Response.ClearContent();
        Response.AppendHeader("content-disposition""attachment; filename=" + filename);
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.ms-excel";
        System.IO.StringWriter stringWriter = new System.IO.StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(stringWriter);
        gv.RenderControl(htw);
        Response.Write(stringWriter.ToString());
        Response.End();
    }
Half way there Don't forget to override VerifyRenderingInServerForm
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}
All done.