Monday, 26 March 2012

Caml query compare between date range from today in sharepoint 2010 (SP 2010) and

How to calculate date from the list items using caml  query and compare date range between from today in sharepoint 2010 (SP 2010):

For my scenario, My start should lbe less than today and expiry date should be greater than today date and list items should be displayed based on priority order column( ascending or descending order.). The date format should not be empty or null.

This caml query also check for boolean status whether it is active or not. (true or false)

We can use caml query builder to check this whether it is working or not.


Caml Query:

Using the SP2010 Client Object Model to update a list item

    <Where> 
      <And> 
        <And> 
           
            <Leq> 
              <FieldRef Name='StartDate' /> 
              <Value Type='DateTime' IncludeTimeValue='False'> 
                <Today /> 
              </Value> 
            </Leq> 
            <IsNotNull> 
              <FieldRef Name='StartDate' /> 
            </IsNotNull> 
          
           
            <Gt> 
              <FieldRef Name='EndDate' /> 
              <Value Type='DateTime' IncludeTimeValue='False'> 
                <Today /> 
              </Value> 
            </Gt> 
            <IsNotNull> 
              <FieldRef Name='EndDate' /> 
            </IsNotNull> 
          
        </And> 
        <Eq> 
          <FieldRef Name='Active' /> 
          <Value Type='Boolean'>1</Value> 
        </Eq> 
      </And> 
    </Where> 
    <OrderBy> 
      <FieldRef Name='EndDate' Ascending='True' /> 
    </OrderBy> 


Sys.InvalidOperationException occurs on Lists sharepoint 2010

Sys.InvalidOperationException occurs Error Type: SP.Permissionkind has already been registered in Sharepoint (SP 2010):


Error : Type SP.PermissionKind has already been registered.


The only reason for this error is that some script files included several times in page body.


This error occured while using the javascript client object model ( ecma script ) in applciation page. The solution for this error is that any references of the js files made twice would cause an exception like this.




Problem is in detail,

Had refrence to SP.js file and also using the ExecuteOrDelayUntilScriptLoaded(something, "sp.js"); in my applictaion page.

This caused the "not very explanatory" error.

What to do ?
 
So by removing this scriptlink would help to fix this error.

Saturday, 24 March 2012

add custom list from event receiver of feature activation using sp sharepoint 2010

How to add custom list from event receiver of feature activation dynamically and how to add spfieldtype.Text, spfieldtype.number, spfieldtype.number dropdown select  range limit in sharepoint sp 
2010:

The below sample code demonstrate how to add choice / dropdown value property for a particular column using event receiver of feature avtivation in sharepoint 2010.

This sample

ADD SPFieldType.Choice, SPFieldChoice with SPChoiceFormatType.RadioButtons

Code:

using Microsoft.SharePoint;
using System.Collections.Specialized;


public void OnActivated(SPFeatureReceiverProperties properties)

{
    SPWeb web = (SPWeb)properties.Feature.Parent;
   
    string url = new Uri(web.Url).AbsolutePath;
    SPDocumentLibrary docLib = (SPDocumentLibrary)web.GetListFromUrl("Shared Documents/Forms/AllItems.aspx");
  
    StringCollection categories = new StringCollection();
    categories.AddRange(new string [] {"Choice A", "Choice B", "Choice C"} );
    docLib.Fields.Add("MyNewField", SPFieldType.Choice, true, false, categories);
 
    SPFieldChoice fieldChoice = (SPFieldChoice)docLib.Fields["MyNewField"];
    fieldChoice.DefaultValue = "Choice A";
    fieldChoice.EditFormat = SPChoiceFormatType.RadioButtons;
    fieldChoice.Update();
    docLib.Update();
 

 

OR


SPListCollection lists = web.Lists;
SPList listitem = web.Lists.TryGetList("Listname");
if(listitem == null)
{
 lists.Add("Listname","Your comments here", SPListTemplateType.GenericList);
 SPList newitem = web.Lists["Listname"];
 newitem.Fields.Add("Name",SPFieldType.Text, true);  // for adding text,  true- indicateds this column is mandatory
 newitem.Fields.Add("Link",SPFieldType.URL, true);  // for adding URL,  true- indicateds this column is mandatory
newitem.Fields.Add("ItemCount",SPFieldType.Number, true);  // for adding number,  true- indicateds this column is mandatory

StringCollection categories = new StringCollection();  // for adding choice dropdown, true- indicateds this column is mandatory
    categories.AddRange(new string [] {"Choice A", "Choice B", "Choice C"} );
     newitem.Fields.Add("Range", SPFieldType.Choice, true, false, categories);
  newitem.OnQuickLaunch = true;
newitem.update();

// to display item on default load

SPView itemview = newFeatureList.DefaultView;
itemview.ViewFields.Add("Name");
itemview.ViewFields.Add("Link");
itemview.ViewFields.Add("ItemCount");
itemview.ViewFields.Add("Range");
itemview.update();
   
}

}

 




Tuesday, 20 March 2012

Parsing Reading PDF file and convert it into text format using asp.net C#

How to Parsing / Reading PDF file and convert it into text format using programatically asp.net C# ?

The following code will demonstrate how to reading/parsing the pdf file and convert the same into text / string formate using string builder and PDFBo.

Steps:
 
1. Download the following file and put those files it into bin folder.


  • FontBox-0.1.0-dev.dll
  • IKVM.GNU.Classpath.dll
  • IKVM.Runtime.dll
  • PDFBox-0.7.3.dll
 Add this assembly files as reference using addreferrence to the working web application director.

2. Add the following namespaces then

using org.pdfbox.pdmodel;
using org.pdfbox.util;
using System.IO;

3. Create the new plain empty text file with the filename of "textfilename" where the converted pdf file would be stored. Add your pdf & text file in your project itself.

Sample full code demo:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using org.pdfbox.pdmodel;
using org.pdfbox.util;
using System.IO;

namespace MyWebApps.pdf
{
    public partial class pdfread : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            parsePDF(Server.MapPath("pdffilename.pdf"), Server.MapPath("textfilename.txt"));
        }
        public void parsePDF(string pdf_in, string txt_out)
        {
            StreamWriter sw = new StreamWriter(txt_out, false);
            try
            {
                sw.WriteLine();
                sw.WriteLine(DateTime.Now.ToString());
                PDDocument doc = PDDocument.load(pdf_in);
                PDFTextStripper stripper = new PDFTextStripper();
                sw.Write(stripper.getText(doc));
            }
            catch (Exception ex) { Response.Write(ex.Message); }
            finally
            {
                sw.Close();
                sw.Dispose();
            }
        }
    }
}




Ajax ModalUpdateProgress loading image using asp.net c#

How to show/display image loading or processing status bar/icon using Ajax ModalUpdateProgress control in asp.net c#

In Css:

.load{background-color: black;filter:alpha(opacity=50);-moz-opacity:.55;opacity:.55; z-index:1; position:relative;}


In Master page:

Place this following code where you want to display loading bar or image. You could change the display position of display bar by changing html style which is displayed/shown above..

 
<cc1:ModalUpdateProgress ID="ModalUpdateProgress1" runat="server"  BackgroundCssClass="load">
    <ProgressTemplate>
        <table border="0"    cellpadding="0" cellspacing="0">
            <tr>
                <td style="color:#fff;font-weight:bold;">
                Loading..
                </td>
            </tr>
                <tr>
                <td>
                <img alt="" src="images/loading.gif" />
                </td>
            </tr>
        </table>
     </ProgressTemplate>
     </cc1:ModalUpdateProgress>

Custom validation to calculate difference between date of birth DOB for any format using asp.net c#


How to use Custom validation to calculate difference between two date of birth DOB of any format using asp.net c# ?

We could customize our DOB format of any formate.

The following code base checks / validates year difference between two dates.

Same aspx code demo:

<asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtDOB" onservervalidate="cusCustom_ServerValidate" errormessage="Invalid D.O.B(Below 18 Yrs)" ValidationGroup="v" SetFocusOnError="true" Display="Dynamic" />

C# Code behind 


private int CalculateDifference(DateTime Date1, DateTime Date2)
        {
            TimeSpan span = Date2.Subtract(Date1);
            int years = (int)(span.Days / 365.25);
            return years;
        }

        protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
        {
            int i;
            DateTime FromDate = DateTime.ParseExact(e.Value.ToString(), "dd/MM/yyyy", null);
            DateTime ToDate = DateTime.ParseExact(DateTime.Now.ToString("dd/MM/yyyy"), "dd/MM/yyyy", null);
            i = CalculateDifference(FromDate, ToDate);
            if (i >= 18)
                e.IsValid = true;
            else
                e.IsValid = false;
        }

Validate string name,password,email,pan number, mobile number, mark digit, salary, file extension using asp.net expression validation control

How to Validate string name,password,email,pan number, mobile number, mark digit, salary, file extension, numeric numbers using asp.net expression validation control

We could use asp.net expression validation control to validate all kind of scenario. We might not need to go to use javascript or jquery for all types of validation.

I have listed some of validation tips of asp.net control such as required filed validator and regular expression validation.

Sample aspx code demo:

Validate Valid Name: 
<asp:RegularExpressionValidator ID="ValRUName" runat="server" ControlToValidate="txtEmployeename"
                                        Display="Dynamic" ErrorMessage="Please enter valid employee name" ValidationExpression="^[a-zA-Z'\s]{4,50}$"
                                        ValidationGroup="XXX" />
 <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ErrorMessage="Username should be 6min to 16max chars."
                                    ControlToValidate="txtUserName" ValidationGroup="XXX" ValidationExpression="[a-zA-Z]+(([a-zA-Z0-9])){5,15}"
                                    Display="Dynamic" />


Password Validation:


<asp:RegularExpressionValidator ID="revNewpass" runat="server" ControlToValidate="txtPwd"

                                            ErrorMessage="Password length should be Minimum 6 chars" ValidationExpression=".{6}.*"
                                            Display="Dynamic" ValidationGroup="XXX" />

<asp:CompareValidator ID="cmpvPassword" runat="server"

                                        ControlToValidate="txtCPasswd" ControlToCompare="txtPwd" ErrorMessage="Password does not match"
                                        ValidationGroup="XXX" Display="Dynamic" SetFocusOnError="true"></asp:CompareValidator>

Email Validation:


<asp:RegularExpressionValidator ID="regEmail" runat="server" ControlToValidate="txtEmail"

                                        SetFocusOnError="true" ValidationGroup="XXX" ErrorMessage="Field invalid" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>

PAN Validation:

 <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Please enter valid Pan No"
                                            ControlToValidate="txtPanNo" ValidationGroup="XXX" ValidationExpression="[a-zA-Z]+(([a-zA-Z0-9])){5,20}"
                                            Display="Dynamic" />

Mobile No Validation:

 <asp:RegularExpressionValidator ID="regMobile" runat="server" ControlToValidate="txtMobile"
                                            SetFocusOnError="true" ErrorMessage="Field invalid" ValidationGroup="XXX" ValidationExpression="(([0-9'--'//+' '])){10,15}"></asp:RegularExpressionValidator>                                     

Mark validation:


<asp:RangeValidator runat="server" id="rngDate" controltovalidate="txtCommunication" type="Double" minimumvalue="0" maximumvalue="10" errormessage="Mark should be less than or equal to 10" ValidationGroup="v" />

 <asp:CompareValidator ID="CompareValidator1" Display="Dynamic" runat="server" ErrorMessage="Max Score Should Not Be Less Than Score" ControlToValidate="txtMaxScore" ControlToCompare="txtScore" Type="Double" ValidationGroup="v" Operator="GreaterThanEqual"></asp:CompareValidator>

Salary Validation:

 <asp:RegularExpressionValidator ID="regsal" runat="server" ControlToValidate="txtSalary"
                                                 SetFocusOnError="true" ValidationGroup="v" ErrorMessage="Enter Valid Salary" ValidationExpression="^\d+(\.\d\d)?$"></asp:RegularExpressionValidator>

File Extension Validation:

 <asp:RegularExpressionValidator ValidationExpression="^.+\.((pdf)|(PDF)|(doc)|(DOC)|(docx)|(DOCX))$"
                                                                ID="regFileUpResume" runat="server" ErrorMessage="Please select a valid .doc file"
                                                                Display="Dynamic" ValidationGroup="v" ControlToValidate="fileupResume"></asp:RegularExpressionValidator>

Show alert message when window page redirected using asp.net c#

How to show alert message when window page redirected / navigated ( Response.Redirect() method ) using asp.net c#: 

This code using the javascript script and its created / called dynamically the  from code behind:

Sample code:
 
string scriptstring = "var res=confirm('Are you sure to redirect ?');if(res==true){window.location.href='pagemane.aspx?str=YES';}";
                    ClientScript.RegisterStartupScript(this.GetType(), "alertscript", scriptstring, true);

Close page window using java script asp.net c#

How to close window from code behind using c# asp.net:

This code using the javascript script and its created / called dynamically the  from code behind:

Sample code:

string scriptstring = "var res=confirm('Are you sure want to close?)');if(res==true){window.close();}";
                ClientScript.RegisterStartupScript(this.GetType(), "alertscript", scriptstring, true);

(OR
)
string str = "window.close();";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "alertscript", str, true);

Friday, 16 March 2012

Regular Expression Validator to allow only integer (numbers) not string in textbox asp.net c#

How to use regular expression validator to allow only integer (numbers) not string in textbox in asp.net c#

Javascript or Jquery not required to validate numeric  character not string. We can simply use regex validation control to achive this.

Sample code:

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="TextBox1" runat="server" ErrorMessage="Numbers Only allowed" ValidationExpression="\d+"></asp:RegularExpressionValidator>

To allow specific count of numbers, use the following regex expression

 ValidationExpression="^\d{7}$">  //Allows only 7 digit of char
 ValidationExpression="^\d{10}$">  //Allows only 10 digit of char



Thursday, 15 March 2012

set css all style for hyper link or image tags inside the div or panel or any other control id using jquery

How to set css style for all hyper link or image  tags inside the div or panel or any other control id using jquery:


Jquery Tips:

Unlike the javascript, we can easily style for all hyper link or image  tags inside the div or panel or any other control id using jquery:

By using, we can avoid use of looping / for each conditions.

This will be used to set css styles to the element dynamically.

Sample Code:


For all hyper link inside the DIV element.

$('#divid').find('a').css({visibility : "visible", display : "none"});

For all image inside the DIV element.


$('#divid').find('img').css({visibility : "visible", display : "none"});

How to get element attribute by css class name or id using jquery

How to get element attribute by css class name or id jquery:

Jquery Tips:

Unlike the javascript, we can easily get the elements attribute easily.
By using, we can avoid use of looping / for each conditions

Sample Code:

/* to get class name attribute- find using by css class name*/
var className = $('.classname').attr('class');
or
var className = $('.classname[class]');

/* to get id attribute- find using by css class name*/
var className = $('.classname').attr('class');
or
var className = $('.classname[class]');


/* to get class name attribute - find using by ID*/
var className = $('#idname').attr('class');
or
var className = $('#idname[class]');

/* to get id attribute- find using by ID*/
var className = $('#idname').attr('class');
or
var className = $('#idname[id]');

how to select different element id with the repeated matched class name using jquery

How to select element id when it have common style CSS class  name using jquery:

Scenario:

I have the repeated class name with different element id. on click or on mouse over, how could i get matched element id using jquery not by javascript. 

No need to do for each loop condtion

To achieve this, we need a pretty basic regular expression, like so.
The following example will not validate the html code. It just check the matched css class and get the respect whatevee attribute we want from that element.

Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FindClassJQuery.aspx.cs" Inherits="MyWebApps.FindClassJQuery" %>

<!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 runat="server">
    <title>Untitled Page</title>

    <script src="js/jquery-1.6.4.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(document).ready(function($) {
    $("[class^=testcss]").click(function(Event) {
    var id = $(this).attr('id');
    alert(id);
});
});
</script>
<style type="text/css">
.testcss1, .testcss2, .testcss3
{
color:Red;
font-weight:bold;
/*background-image:url(images/aa1.jpg);*/
}

</style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <div class="testcss1" id="div1">test1</div>
    <div class="testcss2" id="div2">test2</div>
    <div class="testcss3" id="div3">test3</div>
    </div>
    </form>
</body>
</html>

Tuesday, 13 March 2012

How to access label / textbox control value of master page on any other aspx.cs using c# asp.net

How to access label / textbox control value of master page on any other aspx.cs using c# asp.net :


ContentPlaceHolder contentPlaceHolder =
(ContentPlaceHolder) Master.FindControl("cphBody");

ControlType myControl =
(ControlType) contentPlaceHolder.FindControl("ControlID");


*ControlID - indicates the id of label/textbox or any other control

How to read global resource file from code behind asp.net c#

How to read global resource file from code behind asp.net c# :


ResourceManager rm = new System.Resources.ResourceManager("Resources.CultureResource", System.Reflection.Assembly.Load("App_GlobalResources"));

string ress = "fr-fr";  // to read frennch resource

CultureInfo ci = new System.Globalization.CultureInfo(ress);

stringretstring = rm.GetString("resourcekey", ci);

how to read / loop foreach all controls dynamically from code behind c# asp.net

Read / loop foreach all controls dynamically from code behind c# asp.net:

protected void Page_Load(object sender, EventArgse)
{
ListControlCollections();
}
 
private void ListControlCollections()
{
Dictionary<string, string> diclist = new Dictionary<string, string>();
AddControls(Page.Controls, diclist);
foreach (KeyValuePair<string, string> item in diclist)
{
Response.Write(item.Key +"<--->" + item.Value);
}
}
private void AddControls(ControlCollection page, Dictionary<string, string> diclist)
{
foreach (Control c in page)
{
if (c.ID != null)
{
if (c is TextBox)
{
diclist.Add(c.ID,"text");
};
}
if (c.HasControls())
{
AddControls(c.Controls, diclist);
}
}
}

disable back button using Javascript or C# Code behind in asp.net


How to disable back button either using Javascript or C# Code behind in asp.net
 
Using Javascript (This will disable only back button not history)

<script>
  function testSp()
  {
   window.history.forward();

  }
  window.onload=testSp;
</script>

Using code behind:- (This will avoid store history in client side. So there will be no back button)

protected void Page_Init(object Sender, EventArgs e)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
Response.Cache.SetNoStore();
}

Listbox Move Up Down Right Left show / select all check list items in asp.net using javascript


Listbox Move Up Down Right Left show / select all check list items in asp.net controls using javascript sample demo code:

Script:

<SCRIPT>
        function listbox_move(listID, direction) {

            var listbox = document.getElementById(listID);
            var selIndex = listbox.selectedIndex;

            if(-1 == selIndex) {
                alert("Please select an option to move.");
                return;
            }

            var increment = -1;
            if(direction == 'up')
                increment = -1;
            else
                increment = 1;

            if((selIndex + increment) < 0 ||
                (selIndex + increment) > (listbox.options.length-1)) {
                return;
            }

            var selValue = listbox.options[selIndex].value;
            var selText = listbox.options[selIndex].text;
            listbox.options[selIndex].value = listbox.options[selIndex + increment].value
            listbox.options[selIndex].text = listbox.options[selIndex + increment].text

            listbox.options[selIndex + increment].value = selValue;
            listbox.options[selIndex + increment].text = selText;

            listbox.selectedIndex = selIndex + increment;
        }

        function listbox_moveacross(sourceID, destID) {
            var src = document.getElementById(sourceID);
            var dest = document.getElementById(destID);

            for(var count=0; count < src.options.length; count++) {

                if(src.options[count].selected == true) {
                        var option = src.options[count];

                        var newOption = document.createElement("option");
                        newOption.value = option.value;
                        newOption.text = option.text;
                        newOption.selected = true;
                        try {
                                
                                  dest.add(newOption); // IE only
                                 src.remove(count);
                                 //dest.add(newOption, null); //Standard
                                 //src.remove(count, null);
                         }catch(error) {
                                 dest.add(newOption); // IE only
                                 src.remove(count);
                         }
                        count--;

                }

            }

        }
        function listbox_selectall(listID, isSelect) {

            var listbox = document.getElementById(listID);
            for(var count=0; count < listbox.options.length; count++) {

                listbox.options[count].selected = isSelect;

            }
        }
        function listbox_showallall() {

            var listbox = document.getElementById("d");
            for(var count=0; count < listbox.options.length; count++) {

                //listbox.options[count].selected = isSelect;
                alert(listbox.options[count].text + "-" + listbox.options[count].value);

            }
        }
    </SCRIPT>
 
 
 
HTML Source: 
 
<div>
    
       <asp:ScriptManager ID="ScriptManager1" runat="server">
       </asp:ScriptManager>
   <table>
       
<tr valign="top">
<td>



<br/><br/>
Move <a href="#" onclick="listbox_move('d', 'up')">up</a>,
<a href="#" onclick="listbox_move('d', 'down')">down</a>

&nbsp;&nbsp;&nbsp;

Select
<a href="#" onclick="listbox_selectall('d', true)">all</a>,
<a href="#" onclick="listbox_selectall('d', false)">none</a>

</td>
<td>&nbsp;&nbsp;&nbsp;</td>
<td>
<SELECT id="s" size="10" >
 <OPTION value="a">Afghanistan</OPTION>
 <OPTION value="b">Bahamas</OPTION>
 <OPTION value="c">Barbados</OPTION>
 <OPTION value="d">Belgium</OPTION>
 <OPTION value="e">Bhutan</OPTION>

 <OPTION value="f">China</OPTION>
 <OPTION value="g">Croatia</OPTION>
 <OPTION value="h">Denmark</OPTION>
 <OPTION value="i">France</OPTION>
</SELECT>
</td>
<td valign="center">
<a href="#" onclick="listbox_moveacross('s', 'd')">&gt;&gt;</a>
<br/>

<a href="#" onclick="listbox_moveacross('d', 's')">&lt;&lt;</a>

</td>
<td>
<SELECT id="d" size="10" runat="server">
 <OPTION value="a">Afghanistan</OPTION>
 <OPTION value="b">Bahamas</OPTION>
 <OPTION value="c">Barbados</OPTION>
 <OPTION value="d">Belgium</OPTION>
 <OPTION value="e">Bhutan</OPTION>

 <OPTION value="f">China</OPTION>
 <OPTION value="g">Croatia</OPTION>
 <OPTION value="h">Denmark</OPTION>
 <OPTION value="i">France</OPTION>
</SELECT>

<br />
<a href=#" onclick="listbox_showallall();">Show All </a>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
     <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="listbox_showallall();" />
    </ContentTemplate>
    </asp:UpdatePanel>

</td>
</tr>
      
</table>
 </div>

Setting a Silverlight App to be WindowLess ( transparent background ) in object Asp.net

Setting a Silverlight App to be WindowLess Asp.net:

We need to set the windowless param to true on the Silverlight object tag so that it can render behind other HTML objects.

Sample

<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
    <param name="source" value="ClientBin/sample.xap"/>
    <param name="onError" value="onSilverlightError" />
    <param name="background" value="white" />
    <param name="windowless" value="true"/>
    <param name="minRuntimeVersion" value="4.0.50401.0" />
    <param name="autoUpgrade" value="true" />
    <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50401.0" style="text-decoration:none">
        <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
    </a>
</object>
 
be warned that transparent background with windowsless=true can be REALLY slow.  It's better to avoid this using clever graphic design to 
fit the Silverlight control into the page, if possible. 
 
 
To make transparent background of silverlight, we could add the following parameter in Object for better response: 
..
..

<param name="background" value="transparent"/>
..
.. 
 
 
 
 
 
 

Monday, 12 March 2012

SQL Server Convert datatime format to string

SQL Server - Convert datatime format


CONVERT(VARCHAR(15),OH.ORDERDATE,106)  ----> dd MMM yyyy

CONVERT(VARCHAR(15),OH.ORDERDATE,105) ----> dd MM yyyy

CONVERT(VARCHAR(15),OH.ORDERDATE,104) ----> dd.MM.yyyy

Asp.net Linq sample pack of msdn link

Learn how to use LINQ in your applications with these code samples, covering the entire range of LINQ functionality and demonstrating LINQ with SQL, DataSets, and XML.

Here the link is,

Asp.net Linq sample pack of msdn link

Regular Expressions Validation Image extension using C# asp.net

ASP.Net - Regular Expressions Validation Image extension using C#
  
For Image:
((\S|\s)*)(\.(jpeg|.JPEG|jpg|.JPG|.gif|.GIF|.bmp|.BMP){1,})

"[a-zA-Z0_9].*\b(.jpeg|.JPEG|.jpg|.JPG|.jpe|.JPE|.png|.PNG|.mpp|.MPP|.gif|.GIF)\b"

For alpha :
[a-zA-Z0-9]+(((![$%@])||([a-zA-Z' '])){1,500})


[a-zA-Z0-9] --> should start with these letter only
[$%@] --> char in this part will not allow
[a-zA-Z' '] --> char in this part will allow
{1,500} --> min 1 char and 500 max

Image Cropping (Resize) using stream in C# asp.net

ASP.Net  Image / picture Cropping (Resize) using stream in C#


namespace:

using System.Drawing;
using System.Drawing.Imaging;

Method:-

 protected void UploadImage(HttpPostedFile file)
        {
            string fileName = file.FileName.Substring(file.FileName.LastIndexOf('\\') + 1);
            using (System.Drawing.Image image = System.Drawing.Image.FromStream(file.InputStream))
            using (Bitmap bitmap = new Bitmap(image, 640, 480)) {
                bitmap.Save(MapPath("~/Images/product/zoom/" + FileUploadThumb.FileName.Trim()), image.RawFormat);

            }}

Create dynamic Link Button using c# code behind asp.net

How ro creating Dynamic Link Button or other controls using c# code behind asp.net :



LinkButton lbtnDelete = new LinkButton();

            lbtnDelete.ID = "lkbtDelete";
            lbtnDelete.CommandArgument = "1";
            lbtnDelete.CommandName = "Delete";
            lbtnDelete.Text = "Delete";

            //lbtnEdit.OnClientClick = "javascript:calDiv('L')";
            //lbtnDelete.Click += new EventHandler(lbtnDelete_Click);
            // MyControl mycontrol = new MyControl();
            lbtnDelete.Attributes.Add("
href", Page.GetPostBackClientHyperlink(this, objCatID.ToString() + "|" + "L" + "|" + "Delete" + "|" + objTitle.ToString() + "|" + objDesc.ToString() + "|" + objPrivate.ToString() + "|" + "ssdfsdf" + "|" + objFileID.ToString()));

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

            System.IO.StringWriter swd = new System.IO.StringWriter(sbd);
            HtmlTextWriter htwd = new HtmlTextWriter(swd);
            lbtnDelete.RenderControl(htwd);

sbd.tosring(); // it places our Link button where we want


--- Cal Link button Event
=========================

void IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
{
     string[] strvalue = eventArgument.Split("|".ToCharArray());
     

        ObjFilesCon.IFILEID = int.Parse(strvalue[7].ToString());
                ObjFilesCon.SpType = "Delete";
                if (ObjFilesBL.FileEditandDeleteFileID(ObjFilesCon))
                {
                    string strrr = "Deleted";
                }
                else
                {
                    string strrr = "Failed";
                }
}

-- cal Linkbutton Event
==========================


        protected void lbtnDelete_Click(object sender, EventArgs e)
        {
            LinkButton lb = (LinkButton)sender;
            Response.Write(lb.CommandArgument);
        }