Have a fun while searching

Thursday, September 1, 2011

Menu

script type="text/javascript" src="js/jquery-1.2.2.pack.js" /script

script type="text/javascript" src="js/ddaccordion.js"
/script

script type="text/javascript"

//Initialize first demo:

ddaccordion.init({
headerclass: "silverheader", //Shared CSS class name of headers group
contentclass: "submenu", //Shared CSS class name of contents group
revealtype: "clickgo", //Reveal content when user clicks or onmouseover the header? Valid value: "click", "clickgo", or "mouseover"
mouseoverdelay: 0, //if revealtype="mouseover", set delay in milliseconds before header expands onMouseover
collapseprev: true, //Collapse previous content (so only one open at any time)? true/false
defaultexpanded: [0], //index of content(s) open by default [index1, index2, etc] [] denotes no content
onemustopen: false, //Specify whether at least one header should be open always (so never all headers closed)
animatedefault: false, //Should contents open by default be animated into view?
persiststate: true, //persist state of opened contents within browser session?
toggleclass: ["black-txt-main", "grey-bg_new"], //Two CSS classes to be applied to the header when it's collapsed and expanded, respectively ["class1", "class2"]
togglehtml: ["", "", ""], // ["", "", ""], //Additional HTML added to the header when it's collapsed and expanded, respectively ["position", "html1", "html2"] (see docs)
animatespeed: "fast", //speed of animation: integer in milliseconds (ie: 200), or keywords "fast", "normal", or "slow"
oninit: function(headers, expandedindices) { //custom code to run when headers have initalized
//do nothing
},
onopenclose: function(header, index, state, isuseractivated) { //custom code to run whenever a header is opened or closed
//do nothing
}
})


/script


.black-txt-main
{
font-family: arial;
font-size: 11px;
color: #333333;
font-weight: bold;
line-height: 15px;
}

.grey-bg_new
{
width: 183px;
height: 15px;
background-color: #cccccc;
}

asp:DataList ID="dlJobType" CellPadding="0" Width="100%" CellSpacing="0" runat="server"


OnItemCommand="dlJobType_ItemCommand"


ItemTemplate
div class="silverheader input-box-grupper-right_new" style="padding: 4px 0 3px 10px;"
asp:LinkButton ID="lnk" runat="server" Text='%# Eval("JobTypeTitle") %' CommandName='%# Eval("jobtypeid") %'/asp:LinkButton
%--PostBackUrl='%#SetNavigation(Convert.ToString(Eval("jobtypeid")))%'
img src="images/green-arrow.png" style="float: right; margin-right: 5px; margin-top: 5px;"
div
div class="dark-grey-back" style="height: 1px;
div
div class="submenu"
div
ItemTemplate
asp:DataList




Tuesday, August 16, 2011

change image by java script + call asp.net validator by java script

< %@ Page Title="" Language="C#"

MasterPageFile="~/BarnehageHomePage.master" AutoEventWireup="true"
CodeFile="ContactUs.aspx.cs" Inherits="ContactUs" %>

< asp:Content ID="Content1" ContentPlaceHolderID="head"

runat="Server">

< script type="text/javascript">
var imageURL = "images/checkbox-check.jpg";
function changeImage() {

if (document.images) {

if (imageURL == "images/checkbox-check.jpg") imageURL =

"images/checkbox-uncheck.jpg";
else if (imageURL == "images/checkbox-uncheck.jpg")

imageURL = "images/checkbox-check.jpg";
// document.getElementById

("ctl00_ContentPlaceHolder1_txtTelefon").value = "";
// document.getElementById

("ctl00_ContentPlaceHolder1_txtEpost").value = "";
if (imageURL == "images/checkbox-uncheck.jpg") {
document.images["img1"].src = "images/checkbox-

uncheck.jpg";
document.images["img2"].src = "images/checkbox-

check.jpg";
document.getElementById

("ctl00_ContentPlaceHolder1_HiddenField1").value = 1;
document.getElementById

("ctl00_ContentPlaceHolder1_txtTelefon").disabled = true;
document.getElementById

("ctl00_ContentPlaceHolder1_txtEpost").disabled = false;
document.getElementById

("ctl00_ContentPlaceHolder1_txtTelefon").focus();
document.getElementById

("ctl00_ContentPlaceHolder1_lblemailvalidate").style.display = 'none';
ValidatorEnable(document.getElementById

("ctl00_ContentPlaceHolder1_RequiredFieldValidator1"), false);
ValidatorEnable(document.getElementById

("ctl00_ContentPlaceHolder1_RequiredFieldValidator2"), true);
// ValidatorEnable(document.getElementById

("ctl00_ContentPlaceHolder1_RegtxtUserNam"), false);
}
else {
document.images["img1"].src = "images/checkbox-

check.jpg";
document.images["img2"].src = "images/checkbox-

uncheck.jpg";
document.getElementById

("ctl00_ContentPlaceHolder1_HiddenField1").value = 2;
document.getElementById

("ctl00_ContentPlaceHolder1_txtTelefon").disabled = false;
document.getElementById

("ctl00_ContentPlaceHolder1_txtEpost").disabled = true;
document.getElementById

("ctl00_ContentPlaceHolder1_txtEpost").focus();
document.getElementById

("ctl00_ContentPlaceHolder1_lblemailvalidate").style.display = 'none';
ValidatorEnable(document.getElementById

("ctl00_ContentPlaceHolder1_RequiredFieldValidator1"), true);
ValidatorEnable(document.getElementById

("ctl00_ContentPlaceHolder1_RequiredFieldValidator2"), false);
// ValidatorEnable(document.getElementById

("ctl00_ContentPlaceHolder1_RegtxtUserNam"), true);
}
}
}
function checkEmail() {
var pattern = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w

{2,3})+$/;
if (pattern.test(document.getElementById

("ctl00_ContentPlaceHolder1_txtEpost").value)) {
document.getElementById

("ctl00_ContentPlaceHolder1_lblemailvalidate").style.display = 'none';
// alert("true");
} else {
document.getElementById

("ctl00_ContentPlaceHolder1_lblemailvalidate").style.display = 'block';
// ValidatorEnable(document.getElementById

("ctl00_ContentPlaceHolder1_RequiredFieldValidator2"), false);
// alert("false");
}
}

< /script>

< /asp:Content>
< asp:Content ID="Content2"

ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
< div id="panel-right">
< div id="main-left-panel-two">
< div class="fleft internal-heading">
KONTAKT< /div>
< div style="clear: both">
< /div>
< div class="light-grey-back-internal" style="height:

1px;">
< /div>
< div class="gap10">
< /div>
< div class="top-heading-two">
< strong>KONTAKT OSS OM DU HAR NOEN SPORSMAL<

/strong>< /div>
< div style="clear: both">
< /div>
< div class="gap10">
< /div>
< div class="black-txt-main-new">
Den enkleste måten å få kontakt med

oss er å sende inn en
epost. Du kan sende epost direkte til < span

class="blue_normal_txt">post@barnehageforum.no< /span>
eller bruke skjemaet nedenfor.
< br />
Vi lover å svare så fort vi kan, normalt

får man svar samme virkedag.< br />
Du kan også lese "Ofte stilte

spørsmål" lenger ned
på siden. Kanskje du finner svaret du leter etter

her.
< br />
Du kan også selvfølgelig ringe oss

på telefon 21 53 03 30 (9-16)< /div>
< div class="gap25">
< /div>
< div style="padding-top: 10px;">
< /div>
< div class="left-back-top">
< div class="top-heading-black-one">
< strong>PAMELDING < /strong>
< /div>
< /div>
< div class="light-yellow-bg-four1" style="width: 478px;

border-top: 1px #CCCCCC solid;">
< div class="gap25">
< /div>
< div class="menu-txt-top" style="margin-left: 10px;

float: left;">
< strong>JEG VIL MOTTA SVAR PA:< /strong>
< /div>
< div style="clear: both">
< /div>
< div class="gap10">
< /div>
< div>
< img src="~/images/checkbox-check.jpg"

id="img1" runat="server" name="img1" onclick="changeImage();"
class="check-box_new" style="float: left;

margin-left: 10px; border: 0;" />
< asp:HiddenField ID="HiddenField1"

runat="server" />
< div class="black-txt-two-new" style="float:

left; margin-left:5px;">
< strong>Telefon:< /strong>
< asp:TextBox ID="txtTelefon" runat="server"

class="new-input" />
< /div>
< /div>
< div>
< img src="images/checkbox-uncheck.jpg"

id="img2" runat="server" name="img2" onclick="changeImage();"
class="check-box_new" style="float: left;

margin-left: 10px; border: 0" />
< div class="black-txt-two-new" style="float:

left; margin-left:5px;">
< strong>E-post:< /strong>
< asp:TextBox ID="txtEpost" runat="server"

class="new-input-one" Enabled="false" />
< /div>
< /div>
< div>
< div class="black-txt-two-new" style="float:

left; margin-left: 104px;">
< asp:RequiredFieldValidator

ID="RequiredFieldValidator1" runat="server" ErrorMessage="sjekke

Telefon"
ControlToValidate="txtTelefon"

EnableClientScript="true" ValidationGroup="vgSubmit" />
< /div>
< /div>
< div>
< div class="black-txt-two-new" style="float:

left; margin-left:105px;">
< div id="lblemailvalidate" runat="server"

style="display:none">
< asp:Label ID="lblemailvalidate1"

runat="server" Text="sjekke e-post formiatbaserte" ForeColor="red"><

/asp:Label>
< /div>

< asp:RequiredFieldValidator

ID="RequiredFieldValidator2" runat="server" ErrorMessage="sjekke e-

post"
ControlToValidate="txtEpost"

EnableClientScript="true" ValidationGroup="vgSubmit" />


< /div>
< /div>
< div style="clear: both">
< /div>
< div class="red-txt" style="margin-left: 15px;

float: left; color: Red">
< asp:Label ID="lblInfo" runat="server"><

/asp:Label>
< /div>
< div style="clear: both">
< /div>
< %--< img src="images/green-buttons.jpg"

style="margin-left: 15px; float: left;" />--%>
< div class="menu-txt-top" style="padding-left:

10px; padding-top: 7px;">
< strong>SKRIV DITT SPORSMAL OG TRYKK SEND<

/strong>< /div>
< CE:Editor ID="txtInfo"

EditorWysiwygModeCss="/css/ce.css" Style="margin-left: 10px;"
AutoConfigure="minimal" runat="server"

ThemeType="Office2007" Width="450px" Height="170px">
< %--< FrameStyle BackColor="White"

BorderColor="#DDDDDD" BorderWidth="1px" BorderStyle="Solid"




CssClass="CuteEditorFrame" Height="100%" Width="100%"><

/FrameStyle>--%>
< %--< FrameStyle BackColor="White"

BorderColor="#DDDDDD" BorderWidth="1px" BorderStyle="Solid"




CssClass="CuteEditorFrame" Height="100%" Width="100%"><

/FrameStyle>--%>
< FrameStyle BackColor="White"

BorderColor="#DDDDDD" BorderWidth="1px" BorderStyle="Solid"
CssClass="CuteEditorFrame" Height="100%"

Width="100%">< /FrameStyle>
< /CE:Editor>
< %--< input name="text" type="text"

class="input-box-bg3" style="margin-left: 16px;" />--%>
< div style="clear: both">
< /div>
< div class="gap10">
< /div>
< div>
< asp:ImageButton ID="btnSend"

ValidationGroup="vgSubmit" runat="server" ImageUrl="~/images/send-

btrn.jpg"
OnClick="btnSubmit_Click" Style="float: right;

margin-right: 12px;" />
< %--< img src="images/send-btrn.jpg"

style="float: right; margin-right: 15px;" />--%>
< /div>
< div style="clear: both">
< /div>
< div class="gap10">
< /div>
< /div>
< div class="gap15">
< /div>
< div class="left-back-top">
< div class="left-main-heading">
ofte stilte spørsmål< /div>
< /div>
< div class="gap15">
< /div>
< div class="heading-internal-box" style="padding-

left:10px;">
LORREM IPSUM< /div>
< div class="gap5">
< /div>
< div class="box-txt" style="padding-left: 10px;">
Lorem ipsum dolor sit amet, consectetur adipiscing

elit. Nulla blandit diam a ligula
scelerisque non pharetra felis sodales. Nullam

imperdiet ligula nec eros scelerisque
pellentesque?< /div>
< div class="gap10">
< /div>
< div class="heading-internal-box" style="margin-left:

20px;">
SVAR:< /div>
< div class="gap5">
< /div>
< div class="box-txt" style="margin-left: 20px;">
Lorem ipsum dolor sit amet, consectetur adipiscing

elit. Nulla blandit diam a ligula
scelerisque non pharetra felis sodales. Nullam

imperdiet ligula nec eros scelerisque
pellentesque.< /div>
< div class="gap10">
< /div>
< div class="light-grey-back-internal" style="height:

1px; width: 450px; margin-left: 10px;">
< /div>
< div class="gap10">
< /div>
< div class="gap15">
< /div>
< div class="heading-internal-box" style="padding-

left:10px;">
LORREM IPSUM< /div>
< div class="gap5">
< /div>
< div class="box-txt" style="padding-left: 10px;">
Lorem ipsum dolor sit amet, consectetur adipiscing

elit. Nulla blandit diam a ligula
scelerisque non pharetra felis sodales. Nullam

imperdiet ligula nec eros scelerisque
pellentesque?< /div>
< div class="gap10">
< /div>
< div class="heading-internal-box" style="margin-left:

20px;">
SVAR:< /div>
< div class="gap5">
< /div>
< div class="box-txt" style="margin-left: 20px;">
Lorem ipsum dolor sit amet, consectetur adipiscing

elit. Nulla blandit diam a ligula
scelerisque non pharetra felis sodales. Nullam

imperdiet ligula nec eros scelerisque
pellentesque.< /div>
< div class="gap10">
< /div>
< div class="light-grey-back-internal" style="height:

1px; width: 450px; margin-left: 10px;">
< /div>
< div class="gap10">
< /div>
< div class="gap15">
< /div>
< div class="heading-internal-box" style="padding-left:

10px;">
LORREM IPSUM< /div>
< div class="gap5">
< /div>
< div class="box-txt" style="padding-left: 10px;">
Lorem ipsum dolor sit amet, consectetur adipiscing

elit. Nulla blandit diam a ligula
scelerisque non pharetra felis sodales. Nullam

imperdiet ligula nec eros scelerisque
pellentesque?< /div>
< div class="gap10">
< /div>
< div class="heading-internal-box" style="margin-left:

20px;">
SVAR:< /div>
< div class="gap5">
< /div>
< div class="box-txt" style="margin-left: 20px;">
Lorem ipsum dolor sit amet, consectetur adipiscing

elit. Nulla blandit diam a ligula
scelerisque non pharetra felis sodales. Nullam

imperdiet ligula nec eros scelerisque
pellentesque.< /div>
< div class="gap10">
< /div>
< div class="light-grey-back-internal" style="height:

1px; width: 450px; margin-left: 10px;">
< /div>
< div class="gap10">
< /div>
< div class="gap15">
< /div>
< div class="heading-internal-box" style="padding-left:

10px;">
LORREM IPSUM< /div>
< div class="gap5">
< /div>
< div class="box-txt" style="padding-left: 10px;">
Lorem ipsum dolor sit amet, consectetur adipiscing

elit. Nulla blandit diam a ligula
scelerisque non pharetra felis sodales. Nullam

imperdiet ligula nec eros scelerisque
pellentesque?< /div>
< div class="gap10">
< /div>
< div class="heading-internal-box" style="margin-left:

20px;">
SVAR:< /div>
< div class="gap5">
< /div>
< div class="box-txt" style="margin-left: 20px;">
Lorem ipsum dolor sit amet, consectetur adipiscing

elit. Nulla blandit diam a ligula
scelerisque non pharetra felis sodales. Nullam

imperdiet ligula nec eros scelerisque
pellentesque.< /div>
< div class="gap10">
< /div>
< div class="light-grey-back-internal" style="height:

1px; width: 450px; margin-left: 10px;">
< /div>
< div class="gap10">
< /div>
< div class="gap15">
< /div>
< div class="heading-internal-box" style="padding-left:

10px;">
LORREM IPSUM< /div>
< div class="gap5">
< /div>
< div class="box-txt" style="padding-left: 10px;">
Lorem ipsum dolor sit amet, consectetur adipiscing

elit. Nulla blandit diam a ligula
scelerisque non pharetra felis sodales. Nullam

imperdiet ligula nec eros scelerisque
pellentesque?< /div>
< div class="gap10">
< /div>
< div class="heading-internal-box" style="margin-left:

20px;">
SVAR:< /div>
< div class="gap5">
< /div>
< div class="box-txt" style="margin-left: 20px;">
Lorem ipsum dolor sit amet, consectetur adipiscing

elit. Nulla blandit diam a ligula
scelerisque non pharetra felis sodales. Nullam

imperdiet ligula nec eros scelerisque
pellentesque.< /div>
< div class="gap10">
< /div>
< div class="light-grey-back-internal" style="height:

1px; width: 450px; margin-left: 10px;">
< /div>
< div class="gap10">
< /div>
< div class="gap15">
< /div>
< div class="heading-internal-box" style="padding-left:

7px;">
LORREM IPSUM< /div>
< div class="gap5">
< /div>
< div class="box-txt" style="padding-left: 7px;">
Lorem ipsum dolor sit amet, consectetur adipiscing

elit. Nulla blandit diam a ligula
scelerisque non pharetra felis sodales. Nullam

imperdiet ligula nec eros scelerisque
pellentesque?< /div>
< div class="gap10">
< /div>
< div class="heading-internal-box" style="margin-left:

20px;">
SVAR:< /div>
< div class="gap5">
< /div>
< div class="box-txt" style="margin-left: 20px;">
Lorem ipsum dolor sit amet, consectetur adipiscing

elit. Nulla blandit diam a ligula
scelerisque non pharetra felis sodales. Nullam

imperdiet ligula nec eros scelerisque
pellentesque.< /div>
< div class="gap10">
< /div>
< div class="light-grey-back-internal" style="height:

1px; width: 450px; margin-left: 10px;">
< /div>
< div class="gap10">
< /div>
< div style="clear: both">
< /div>
< div class="gap25">
< /div>
< /div>
< div style="padding-top: 8px;">
< /div>
< div class="right-shadow-panel">
< div id="right-panel-two">
< div class="left-back-top">
< div class="left-main-heading">
< strong>KONTAKT INFORMASJON<

/strong>< /div>
< /div>
< div class="left-panel-shadow-new">
< div class="gap15">
< /div>
< div class="black-txt-two-new_new"

style="padding-left: 10px;">
< strong>Telefon:< /strong>< span

class="black-txt-main-new">21 53 03 30< /span>< /div>
< div class="gap5">
< /div>
< div class="black-txt-two-new_new"

style="padding-left: 10px;">
< strong>Fax:< /strong>< span

class="black-txt-main-new">21 53 03 31< /span>< /div>
< div class="gap5">
< /div>
< div class="black-txt-two-new_new"

style="padding-left: 10px;">
< strong>Epost:< /strong>< span

class="black-txt-main-new">post@barnehageforum.no< /span>< /div>
< div class="gap15">
< /div>
< div class="black-txt-two-new_new"

style="padding-left: 10px;">
< strong>Postadresse:< /strong>< /div>
< div style="padding-top: 3px;">
< /div>
< div class="black-txt-main-new"

style="padding-left: 10px;">
< strong>Habitus AS / BarnehageForum

Postboks 9266 Grønland 0134 Oslo< /strong>< /div>
< div class="gap15">
< /div>
< div class="black-txt-two-new_new"

style="padding-left: 10px;">
< strong>Besøksadresse:<

/strong>< /div>
< div style="padding-top: 3px;">
< /div>
< div class="black-txt-main-new"

style="padding-left: 10px;">
< strong>Habitus As / BarnehageForum Egedes

gate 1, 0192 Oslo< /strong>< /div>
< div class="gap15">
< /div>

Tuesday, August 9, 2011

Horizental menu with horizental sub menu


----------------------Aspx page----------------------------------------

< link rel="stylesheet" type="text/css" href="Menu/2leveltab.css" />

< script type="text/javascript" src="Menu/2leveltab.js" />


< div class="grid_12">
< ul id="maintab" class="main-menu">
< li rel="Ämnen">< a href="#" class="selected">Ämnen< /a>< /li>
< li rel="Tema">< a href="#">Tema< /a>< /li>
< li rel="Expertpanelen">< a href="#">Expertpanelen< /a>< /li>
< li>< a href="#">Forskare i fokus< /a>< /li>
< li>< a href="#">Om oss< /a>< /li>
< /ul>
< div class="clear">
< /div>
< div id="Ämnen">
< ul class="sub-menu">
< li>< a href="#">Värdegrund< /a>< /li>
< li>< a href="#">Lek, lärande och omsorg< /a>< /li>
< li>< a href="#">Organisation< /a>< /li>
< li>< a href="#">Hälsa och miljö< /a>< /li>
< li>< a href="#">Idébank< /a>< /li>
< /ul>
< /div>
< div id="Tema" style="display:none">
< ul class="sub-menu">
< li>< a href="#">Värdegrund 1< /a>< /li>
< li>< a href="#">Lek, lärande och omsorg 1< /a>< /li>
< li>< a href="#">Organisation 1< /a>< /li>
< li>< a href="#">Hälsa och miljö 1< /a>< /li>
< li>< a href="#">Idébank 1< /a> < /li>
< /ul>
< /div>
< div id="Expertpanelen" style="display:none">
< ul class="sub-menu">
< li>< a href="#">Värdegrund 2< /a>< /li>
< li>< a href="#">Lek, lärande och omsorg 2< /a>< /li>
< li>< a href="#">Organisation 2< /a>< /li>
< li>< a href="#">Hälsa och miljö 2< /a>< /li>
< li>< a href="#">Idébank 2< /a> < /li>
< /ul>
< /div>
< div class="clear">
< /div>

< script type="text/javascript">
//initialize tab menu, by passing in ID of UL
initalizetab("maintab")
< /script>

< /div>

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
----------------------css-------------------------------------------
.basictab{
padding: 3px 0;
margin-left: 0;
font: bold 12px Verdana;
border-bottom: 1px solid gray;
list-style-type: none;
margin-bottom: 0;
text-align: left; /*set to left, center, or right to align the menu as desired*/
}

.basictab li{
display: inline;
margin: 0;
}

.basictab li a{
text-decoration: none;
padding: 3px 7px;
margin-right: 2px;
border: 1px solid gray;
border-bottom: none;
background-color: white;
color: black;
}


.basictab li a:visited{
color: black;
}

.basictab li a:hover{
background-color: #dbffff;
color: black;
}

.basictab li a:active{
color: black;
}

.basictab li.selected a{ /*selected tab effect*/
position: relative;
top: 1px;
padding-top: 4px;
background-color: #dbffff;
color: black;
}


.submenustyle{
padding: 2px 1px;
border: 1px solid black;
border-top-width: 0;
width: auto;
display: none;
filter:alpha(opacity=0);
-moz-opacity:0;
}

* html .submenustyle{ /*IE only width definition*/
width: 100%;
}

.submenustyle a{
border-right: 1px dashed black;
padding: 1px 5px;
text-decoration: none;
}

.submenustyle a:hover{
background-color: #ebffff;
}
---------------------------------java script--------------------------------
var mastertabvar = new Object()
mastertabvar.baseopacity = 0
mastertabvar.browserdetect = ""

function showsubmenu(masterid, id) {
if (typeof highlighting != "undefined")
clearInterval(highlighting)
submenuobject = document.getElementById(id)
mastertabvar.browserdetect = submenuobject.filters ? "ie" : typeof submenuobject.style.MozOpacity == "string" ? "mozilla" : ""
hidesubmenus(mastertabvar[masterid])
submenuobject.style.display = "block"
instantset(mastertabvar.baseopacity)
highlighting = setInterval("gradualfade(submenuobject)", 50)
}

function hidesubmenus(submenuarray) {
for (var i = 0; i < submenuarray.length; i++)
document.getElementById(submenuarray[i]).style.display = "none"
}

function instantset(degree) {
if (mastertabvar.browserdetect == "mozilla")
submenuobject.style.MozOpacity = degree / 100
else if (mastertabvar.browserdetect == "ie")
submenuobject.filters.alpha.opacity = degree
}


function gradualfade(cur2) {
if (mastertabvar.browserdetect == "mozilla" && cur2.style.MozOpacity < 1)
cur2.style.MozOpacity = Math.min(parseFloat(cur2.style.MozOpacity) + 0.1, 0.99)
else if (mastertabvar.browserdetect == "ie" && cur2.filters.alpha.opacity < 100)
cur2.filters.alpha.opacity += 10
else if (typeof highlighting != "undefined") //fading animation over
clearInterval(highlighting)
}

function initalizetab(tabid) {
mastertabvar[tabid] = new Array()
var menuitems = document.getElementById(tabid).getElementsByTagName("li")
for (var i = 0; i < menuitems.length; i++) {
if (menuitems[i].getAttribute("rel")) {
menuitems[i].setAttribute("rev", tabid) //associate this submenu with main tab
mastertabvar[tabid][mastertabvar[tabid].length] = menuitems[i].getAttribute("rel") //store ids of submenus of tab menu
if (menuitems[i].className == "selected")
showsubmenu(tabid, menuitems[i].getAttribute("rel"))
menuitems[i].getElementsByTagName("a")[0].onmouseover = function() {
showsubmenu(this.parentNode.getAttribute("rev"), this.parentNode.getAttribute("rel"))
}
}
}
}

Sunday, August 7, 2011

download from remote server

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Net;
using System.IO;


public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//base.OnLoad(e);
string url = string.Empty;// Request.QueryString["DownloadUrl"];
if (url == null || url.Length == 0)
{
url = "http://www.student.barnehageforum.no/data/CV/arces%20-%20front%20end%20requirements53.pdf";
}
//Initialize the input stream
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
int bufferSize = 1;
//Initialize the output stream
Response.Clear();
Response.AppendHeader("Content-Disposition:", "attachment; filename=download.pdf");
Response.AppendHeader("Content-Length", resp.ContentLength.ToString());
Response.ContentType = "application/download";
//Populate the output stream
byte[] ByteBuffer = new byte[bufferSize + 1];
MemoryStream ms = new MemoryStream(ByteBuffer, true);
Stream rs = req.GetResponse().GetResponseStream();
byte[] bytes = new byte[bufferSize + 1];
while (rs.Read(ByteBuffer, 0, ByteBuffer.Length) > 0)
{
Response.BinaryWrite(ms.ToArray());
Response.Flush();
}
//Cleanup
Response.End();
ms.Close();
ms.Dispose();
rs.Dispose();
ByteBuffer = null;
}
}

Friday, August 5, 2011

101 LINQ Samples

http://msdn.microsoft.com/en-us/vcsharp/aa336746

Thursday, August 4, 2011

Speed Optimization in ASP.NET 2.0 Web Applications

Overview
Developing a web application that responds to users requests quickly is a target and a challenge for all web developers. ASP.NET was designed with speed optimization and performance improvements in mind. The set of enhancements like: Pages compilation, and Automatic storage on the server are new to ASP.NET.
However, these enhancements are not enough to protect you from slow performance when a large number of  http requests are simultaneously processed by your web application.
To write a well performing web application you must make a balance between four common performance measures. These measures are:
Execution Time: It is the time taken to process a request. This is measured as the time elapsed between the first byte received from the server and the last one.
Response Time: It is the time between issuing a request and the first byte received as a response from the server.
Scalability: It measures the performance of a web application against resources (memory, processors, or computers) allocated for it.
Throughput: It is the number of requests your application can serve in a time unit, usually a second.
What follows is a list of areas that you can invoke to harvest for techniques that you can use to develop a high performance ASP.NET application.
State management
Data access
Page and server controls
Web applications
Coding practices
In what follows we will cover the first two areas. Part 2 covers the last three areas, and caching techiniques are deeply explained in Caching optimization.
State Management
The following issues give you some ideas about how to make state management efficient.
SessionState State
Disable session state when you are not using it. Not all web application require a session state for each user. When you disable unneeded session state you are definitely improving your application performance.
To disable session state for a complete page in your application, use the following code:
 
<%@ page EnableSessionState="false" %>
 
If your page requires access to session variables only to read them then set the session state for this page to read only.
To disable  session state for the entire application, open the 'web.config' file, and set the mode attribute to off under the session state section as in the following code:
 
       < sessionstate mode="off" />
 
Session State Provider
There are more than one approach for storing your session state data. You can choose the approach you prefer by setting the mode attribute under the session state section of your application 'web.config' file. The supported modes are: in-process mode, state server mode, SQL server mode, and custom mode. Each mode is suitable in some circumstance, and has its own set of advantages. The in-process session state is by far the fastest one. So, it is recommended to use the in-process provider if you want to store small amounts of volatile data in the session state. Other state server and SQL server providers are needed if your application using a web farm or garden, or if you want to retain your session state date if the web server is restarted.
Data Access
The following points give you some ideas about how to render data access efficient:
Use SQL server provider
Among the data providers available to be used, choose SQL data provider to build a high performance, scalable web application.
Use SQL Data Reader
The SQLDataReader class gives you the ability to read only retrieved records from the database for once. So, if this is all what you actually need, then it is extremely recommended to use a data reader class instead of a DataSet or, a Table Class. This will gives your application much higher performance.
Use Stored Procedures
Whenever possible use compiled stored procedure instead of SQL plain text commands, this gives your application an extra speed performance. SQL server builds and stores execution plans for previously stored procedures.
Make use of  SQLDataSource useful properties
Instead of writing a query that includes the "Where", or "Sort By" clauses use the caching, filtering, and sorting properties of the SQLDataSourse provider. You can set the SQLDataSource object's "EnableCaching" property to true to enable caching of the retrieved data by this data source. When you enable data source caching, SQLDataSource will do the operations like filtering and sorting on the cached data. You can use the "FilterExpression" property, and the "SortParameterName" property to perform filtering and sorting using the SQLDataSource object. This will certainly makes your application faster.
View State Encryption
You must balance between the importance of encrypting your application view state data to make your transferred data more secure, and the cost / the impact of using encryption on your application speed. Encryption has a fixed cost for initialization plus a unfixed cost depends on the size of data to be encrypted. In brief, it is recommended to avoid using unnecessary view state data encryption.
Paging
It is known that to display data from a given data source you have to use data controls like: GridView, and/or DetailsView controls and to bind them to the data source you want to display data from. You may want to adjust the display layout of some data records and columns within your screen by using the GridView, or the DetailsView paging property and set it to true. This paging technique is called UI paging (User Interface paging). To perform this service, the GridView control requests data from the specified data source, it then filters the elements that will be displayed in the current page and simply ignores the rest. It does this process each time a new page is required ... which is certainly a great waste of resources.
There is another technique for doing the same task, it is typically referred to as data source paging. In this technique you make use of a data source control that implements the DataSourceView class, and set its CanPage property to true, then you feed the GridView control or the DetailsView control from this data source. In this case the data source object queries only for the elements needed in each page. Thus, data source paging is more efficient than UI paging. The only data source class that allows data source paging is ObjectDataSource class.
Caching
Using the caching technique appropriately can improve the performance of your application more than using any other technique. .Net framework provides some mechanisms for caching pages and data within your ASP.NET application. You can use caching for pages that exhibit heavy traffic and do not change between requests. You can also cache small sized data that is used extensively by your application instead of processing them each time.
To use caching effectively, give attention to the following notes:
- Don't assign a small duration for your cached items, items that expire quickly take extra cost for cleaning up and garbage collection.
- Don't cache too many data items, there is a memory cost for each data item. It is not necessary to cache items that can be easily calculated or those which are rarely calculated or used.
Caching is so important and the ASP.NET framework gives a varity of caching mechanisms you can use to improve your application performance more and more. Some of those  mechanisms are: Caching application data, Page output casching, Caching web forms, and Caching parts of web forms.

Saturday, July 30, 2011

different important questions

1. How to store Grid values to database,get, display(insert,update,delete, cancel,find)?

2. Sessions, Type of session, how to use sessions?

3. cookies , type of cookies , user cookies, fetch cookies values.

4. Cursors? why we use cursors?

5. Triggers and user triggers?

6. indexes ?type of indexes and why we use nd how to use indexes?

7. State Management nd type of statement mgmt.?

8. wat is view state nd how we use?

9. interfaces nd how can use use?

10. CSS nd how to use?

11. validation nd type of validation

12. wat is scripting language ?

13. use of java script?

14. if else looping in database queries?

15. COM nd its attributes?

16. How file nd image uploaed into database?

17. abstract classes?

18. CLR?

19. diff b//t CLR nd CLS?

20. DLL?

21. Assesmbly?

22. Managed code?

23. diff between storeprocedure nd functions?

24. constraints(Primary key, Foreign key, Candidate key

25. join nd its types

26. queries string? how can we use?

27. diff bet server.transfer nd response.redirect?

28. diff. between datagrid nd gridview?

29. diff in dataaset nd dataview?

30. how can we add new table in dataset at runtime?

31. diff in data adapter nd datareader?

32. Page lifecycle?

50 New Features of SQL Server 2008

50 New Features of SQL Server 2008

Transparent Data Encryption
Enable encryption of an entire database, data files, or log files, without the need for application changes. Benefits of this include: Search encrypted data using both range and fuzzy searches, search secure data from unauthorized users, and data encryption without any required changes in existing applications.
Extensible Key Management
SQL Server 2005 provides a comprehensive solution for encryption and key management. SQL Server 2008 delivers an excellent solution to this growing need by supporting third-party key management and HSM products.
Auditing
Create and manage auditing via DDL, while simplifying compliance by providing more comprehensive data auditing. This enables organizations to answer common questions, such as, "What data was retrieved?"
Enhanced Database Mirroring
SQL Server 2008 builds on SQL Server 2005 by providing a more reliable platform that has enhanced database mirroring, including automatic page repair, improved performance, and enhanced supportability.
Automatic Recovery of Data Pages
SQL Server 2008 enables the principal and mirror machines to transparently recover from 823/824 types of data page errors by requesting a fresh copy of the suspect page from the mirroring partner transparently to end users and applications.
Log Stream Compression
Database mirroring requires data transmissions between the participants of the mirroring implementations. With SQL Server 2008, compression of the outgoing log stream between the participants delivers optimal performance and minimizes the network bandwidth used by database mirroring.
Resource Governor
Provide a consistent and predictable response to end users with the introduction of Resource Governor, allowing organizations to define resource limits and priorities for different workloads, which enable concurrent workloads to provide consistent performance to their end users.
Predictable Query Performance
Enable greater query performance stability and predictability by providing functionality to lock down query plans, enabling organizations to promote stable query plans across hardware server replacements, server upgrades, and production deployments.
Data Compression
Enable data to be stored more effectively, and reduce the storage requirements for your data. Data compression also provides significant performance improvements for large I/O bound workloads, like data warehousing.
Hot Add CPU
Dynamically scale a database on demand by allowing CPU resources to be added to SQL Server 2008 on supported hardware platforms without forcing any downtime on applications. Note that SQL Server already supports the ability to add memory resources online.
Policy-Based Management
Policy-Based Management is a policy-based system for managing one or more instances of SQL Server 2008. Use this with SQL Server Management Studio to create policies that manage entities on the server, such as the instance of SQL Server, databases, and other SQL Server objects.
Streamlined Installation
SQL Server 2008 introduces significant improvements to the service life cycle for SQL Server through the re-engineering of the installation, setup, and configuration architecture. These improvements separate the installation of the physical bits on the hardware from the configuration of the SQL Server software, enabling organizations and software partners to provide recommended installation configurations.
Performance Data Collection
Performance tuning and troubleshooting are time-consuming tasks for the administrator. To provide actionable performance insights to administrators, SQL Server 2008 includes more extensive performance data collection, a new centralized data repository for storing performance data, and new tools for reporting and monitoring.
Language Integrated Query (LINQ)
Enable developers to issue queries against data, using a managed programming language, such as C# or VB.NET, instead of SQL statements. Enable seamless, strongly typed, set-oriented queries written in .NET languages to run against ADO.NET (LINQ to SQL), ADO.NET DataSets (LINQ to DataSets), the ADO.NET Entity Framework (LINQ to Entities), and to the Entity Data Service Mapping provider. Use the new LINQ to SQL provider that enables developers to use LINQ directly on SQL Server 2008 tables and columns.
ADO.NET Data Services
The Object Services layer of ADO.NET enables the materialization, change tracking, and persistence of data as CLR objects. Developers using the ADO.NET framework can program against a database, using CLR objects that are managed by ADO.NET. SQL Server 2008 introduces more efficient, optimized support that improves performance and simplifies development.

DATE/TIME
SQL Server 2008 introduces new date and time data types:
DATE—A date-only type
TIME—A time-only type
DATETIMEOFFSET—A time-zone-aware datetime type
DATETIME2—A datetime type with larger fractional seconds and year range than the existing DATETIME type
The new data types enable applications to have separate data and time types while providing large data ranges or user defined precision for time values.
HIERARCHY ID
Enable database applications to model tree structures in a more efficient way than currently possible. New system type HierarchyId can store values that represent nodes in a hierarchy tree. This new type will be implemented as a CLR UDT, and will expose several efficient and useful built-in methods for creating and operating on hierarchy nodes with a flexible programming model.
FILESTREAM Data
Allow large binary data to be stored directly in an NTFS file system, while preserving an integral part of the database and maintaining transactional consistency. Enable the scale-out of large binary data traditionally managed by the database to be stored outside the database on more cost-effective storage without compromise.
Integrated Full Text Search
Integrated Full Text Search makes the transition between Text Search and relational data seamless, while enabling users to use the Text Indexes to perform high-speed text searches on large text columns.
Sparse Columns
NULL data consumes no physical space, providing a highly efficient way of managing empty data in a database. For example, Sparse Columns allows object models that typically have numerous null values to be stored in a SQL Server 2005 database without experiencing large space costs.
Large User-Defined Types
SQL Server 2008 eliminates the 8-KB limit for User-Defined Types (UDTs), allowing users to dramatically expand the size of their UDTs.
Spatial Data Types
Build spatial capabilities into your applications by using the support for spatial data.
Implement Round Earth solutions with the geography data type. Use latitude and longitude coordinates to define areas on the Earth's surface.
Implement Flat Earth solutions with the geometry data type. Store polygons, points, and lines that are associated with projected planar surfaces and naturally planar data, such as interior spaces.

Backup Compression
Keeping disk-based backups online is expensive and time-consuming. With SQL Server 2008 backup compression, less storage is required to keep backups online, and backups run significantly faster since less disk I/O is required.
Partitioned Table Parallelism
Partitions enable organizations to manage large growing tables more effectively by transparently breaking them into manageable blocks of data. SQL Server 2008 builds on the advances of partitioning in SQL Server 2005 by improving the performance on large partitioned tables.
Star Join Query Optimizations
SQL Server 2008 provides improved query performance for common data warehouse scenarios. Star Join Query optimizations reduce query response time by recognizing data warehouse join patterns.
Grouping Sets
Grouping Sets is an extension to the GROUP BY clause that lets users define multiple groupings in the same query. Grouping Sets produces a single result set that is equivalent to a UNION ALL of differently grouped rows, making aggregation querying and reporting easier and faster.
Change Data Capture
With Change Data Capture, changes are captured and placed in change tables. It captures complete content of changes, maintains cross-table consistency, and even works across schema changes. This enables organizations to integrate the latest information into the data warehouse.
MERGE SQL Statement
With the introduction of the MERGE SQL Statement, developers can more effectively handle common data warehousing scenarios, like checking whether a row exists, and then executing an insert or update.
SQL Server Integration Services (SSIS) Pipeline Improvements
Data Integration packages can now scale more effectively, making use of available resources and managing the largest enterprise-scale workloads. The new design improves the scalability of runtime into multiple processors.
SQL Server Integration Services (SSIS) Persistent Lookups
The need to perform lookups is one of the most common ETL operations. This is especially prevalent in data warehousing, where fact records need to use lookups to transform business keys to their corresponding surrogates. SSIS increases the performance of lookups to support the largest tables.

Analysis Scale and Performance
SQL Server 2008 drives broader analysis with enhanced analytical capabilities and with more complex computations and aggregations. New cube design tools help users streamline the development of the analysis infrastructure enabling them to build solutions for optimized performance.
Block Computations
Block Computations provides a significant improvement in processing performance enabling users to increase the depth of their hierarchies and complexity of the computations.
Writeback
New MOLAP enabled writeback capabilities in SQL Server 2008 Analysis Services removes the need to query ROLAP partitions. This provides users with enhanced writeback scenarios from within analytical applications without sacrificing the traditional OLAP performance.
Enterprise Reporting Engine
Reports can easily be delivered throughout the organization, both internally and externally, with simplified deployment and configuration. This enables users to easily create and share reports of any size and complexity.
Internet Report Deployment
Customers and suppliers can effortlessly be reached by deploying reports over the Internet.
Manage Reporting Infrastructure
Increase supportability and the ability to control server behaviour with memory management, infrastructure consolidation, and easier configuration through a centralized store and API for all configuration settings.
Report Builder Enhancements
Easily build ad-hoc and author reports with any structure through Report Designer.
Forms Authentication Support
Support for Forms authentication enables users to choose between Windows and Forms authentication.
Report Server Application Embedding
Report Server application embedding enables the URLs in reports and subscriptions to point back to front-end applications.
Microsoft Office Integration
SQL Server 2008 provides new Word rendering that enables users to consume reports directly from within Microsoft Office Word. In addition, the existing Excel renderer has been greatly enhanced to accommodate the support of features, like nested data regions, sub-reports, as well as merged cell improvements. This lets users maintain layout fidelity and improves the overall consumption of reports from Microsoft Office applications.
Predictive Analysis
SQL Server Analysis Services continues to deliver advanced data mining technologies. Better Time Series support extends forecasting capabilities. Enhanced Mining Structures deliver more flexibility to perform focused analysis through filtering as well as to deliver complete information in reports beyond the scope of the mining model. New cross-validation enables confirmation of both accuracy and stability for results that you can trust. Furthermore, the new features delivered with SQL Server 2008 Data Mining Add-ins for Office 2007 empower every user in the organization with even more actionable insight at the desktop.

IIS 7.0 New features

IIS 7.0 New features

Wondering what the new features in IIS 7.0 going to be? Here you go! you can get a glimpse of IIS 7.0 in this article.
     IIS7 will ship with both Windows Vista and Windows Longhorn Server. It's obvious that Microsoft has put a lot of time and effort into this release and you can expect IIS7 to be the platform of choice as soon as people can get their servers upgraded. It includes a several new functionalities with very rich integration with ASP.NET.

Feature 1: HttpModules and HttpHandlers can participate in all the requests i.e we can have a ASP.NET HttpModule for a JSP or PHP page even. Building HTTPmodules for authentication, authorization, logging, url-rewriting, auditing now will be very easy with .NET.

Feature 2: ASP.NET configuration can be integrated with IIS. IIS now uses the same web.config configuration model, which means you can have both configure ASP.NET and IIS in a single web.config file. You can now set things like default pages, IIS security, logging, etc within a web.config file and xcopy/ftp it to a server.

Feature 3: This has an integrated Admin UI tool that can manage both IIS and ASP.NET settings. Rich GUI supports settings for Membership, Roles and Profile providers. This tool also supports remote delegated admin over http -- which means you can point the rich-client admin tool at a shared host server and manage your users/roles/profile settings remotely over http.

Feature 4: It provides better request auditing and error debugging. A new functionality called "Failed Request Event Buffering" (affectionately known as "FREB") is introduced. This allows administrators to configure applications to automatically save request information anytime an error occurs during a request, or if a request takes longer than a specified amount of time to complete. This allows us to analyze what exactly happened during a request failure and what errors or exceptions have occurred. This can capture tracing messages generated within ASP.NET or within any component or class library that uses System.Diagnostics -- which makes it much easier for developers and admins to instrument and analyze what is going on with systems at runtimes.

Feature 5: It provides better configuration APIs and command-line tools. In addition to new config and admin APIs, we now have a great command-line admin story that you can use to set/modify/retrieve all configuration information as well as manage the server (start/stop individual apps, lookup their health state, register new apps, refresh SSL certs, etc). The class hierarchy in brief can be figured as:


A code snippet uses the new .NET APIs to query IIS7 to list the active worker processes on the computer. It also lists the Requests and other details about the request like Url, Clinet IP address ..etc.
ServerManager iisManager = new ServerManager();
foreach(WorkerProcess w3wp in iisManager.WorkerProcesses)
{
Console.WriteLine("W3WP ({0})", w3wp.ProcessId);
foreach (Request request in w3wp.GetRequests(0))
{
Console.WriteLine("{0} - {1},{2},{3}",
request.Url,
request.ClientIPAddr,
request.TimeElapsed,
request.TimeInState);
}
}









Feature 7: Let us examine the new management UI. Here's what the new IIS Manager looks like:










The first thing to notice is the new "Features View" which is shown above. While you can still use the "Content View" to show the files that make up your Web Site in the main pane of the tool, most of the time you'll be using the "Features View" to change site and application settings.








Feature 8: "Actions" pane is a task-based pane shows you the most common tasks that are related to the currently selected object. For example, here's a close up of the "Actions" pane as it looks when the "Default Web Site" is the currently selected object.








The contents of the "Actions" pane will naturally change as the selected object changes, but this pane is where you'll generally find links that lead you through most of your common admin tasks.




Feature 9: Modular Architecture


Unless you've been living under a rock somewhere for the past few years, you've heard about all the problems that IIS has had when it comes to security. In earlier versions of IIS, it was either installed or it wasn't. If IIS was installed then all the features were installed. In an attempt to minimize potential vulnerability, in IIS 6, the majority of features were disabled by default, but they still got installed. This time around Microsoft has taken the next logical step. IIS7 is almost completely modular. Take a look at the installation screen:






Now granted, I've installed everything to play around with it all, but on a production server, you now have the flexibility to install only the features you need. That way if you don't use CGI, then you don't need to worry about some new bug that someone finds in the CGI handler. You also won't need to install a patch and reboot, because the affected code was never even installed on your server so there's nothing to patch

New features of C# 4.0

New features of C# 4.0

Introduction
It is now close to a year since Microsoft Visual C# 3.0 shipped as part of Visual Studio 2008. In the VS Managed Languages team we are hard at work on creating the next version of the language (with the unsurprising working title of C# 4.0), and this document is a first public description of the planned language features as we currently see them.
Please be advised that all this is in early stages of production and is subject to change. Part of the reason for sharing our plans in public so early is precisely to get the kind of feedback that will cause us to improve the final product before it rolls out.
Simultaneously with the publication of this whitepaper, a first public CTP (community technology preview) of Visual Studio 2010 is going out as a Virtual PC image for everyone to try. Please use it to play and experiment with the features, and let us know of any thoughts you have. We ask for your understanding and patience working with very early bits, where especially new or newly implemented features do not have the quality or stability of a final product. The aim of the CTP is not to give you a productive work environment but to give you the best possible impression of what we are working on for the next release.
The CTP contains a number of walkthroughs, some of which highlight the new language features of C# 4.0. Those are excellent for getting a hands-on guided tour through the details of some common scenarios for the features. You may consider this whitepaper a companion document to these walkthroughs, complementing them with a focus on the overall language features and how they work, as opposed to the specifics of the concrete scenarios.
C# 4.0
The major theme for C# 4.0 is dynamic programming. Increasingly, objects are “dynamic” in the sense that their structure and behavior is not captured by a static type, or at least not one that the compiler knows about when compiling your program. Some examples include
a. objects from dynamic programming languages, such as Python or Ruby
b. COM objects accessed through IDispatch
c. ordinary .NET types accessed through reflection
d. objects with changing structure, such as HTML DOM objects
While C# remains a statically typed language, we aim to vastly improve the interaction with such objects.
A secondary theme is co-evolution with Visual Basic. Going forward we will aim to maintain the individual character of each language, but at the same time important new features should be introduced in both languages at the same time. They should be differentiated more by style and feel than by feature set.
The new features in C# 4.0 fall into four groups:
Dynamic lookup
Dynamic lookup allows you to write method, operator and indexer calls, property and field accesses, and even object invocations which bypass the C# static type checking and instead gets resolved at runtime.
Named and optional parameters
Parameters in C# can now be specified as optional by providing a default value for them in a member declaration. When the member is invoked, optional arguments can be omitted. Furthermore, any argument can be passed by parameter name instead of position.
COM specific interop features
Dynamic lookup as well as named and optional parameters both help making programming against COM less painful than today. On top of that, however, we are adding a number of other small features that further improve the interop experience.
Variance
It used to be that an IEnumerable<string> wasn’t an IEnumerable<object>. Now it is – C# embraces type safe “co-and contravariance” and common BCL types are updated to take advantage of that.
Dynamic Lookup
Dynamic lookup allows you a unified approach to invoking things dynamically. With dynamic lookup, when you have an object in your hand you do not need to worry about whether it comes from COM, IronPython, the HTML DOM or reflection; you just apply operations to it and leave it to the runtime to figure out what exactly those operations mean for that particular object.
This affords you enormous flexibility, and can greatly simplify your code, but it does come with a significant drawback: Static typing is not maintained for these operations. A dynamic object is assumed at compile time to support any operation, and only at runtime will you get an error if it wasn’t so. Oftentimes this will be no loss, because the object wouldn’t have a static type anyway, in other cases it is a tradeoff between brevity and safety. In order to facilitate this tradeoff, it is a design goal of C# to allow you to opt in or opt out of dynamic behavior on every single call.
The dynamic type
C# 4.0 introduces a new static type called dynamic. When you have an object of type dynamic you can “do things to it” that are resolved only at runtime:
dynamic d = GetDynamicObject(…);
d.M(7);
The C# compiler allows you to call a method with any name and any arguments on d because it is of type dynamic. At runtime the actual object that d refers to will be examined to determine what it means to “call M with an int” on it.
The type dynamic can be thought of as a special version of the type object, which signals that the object can be used dynamically. It is easy to opt in or out of dynamic behavior: any object can be implicitly converted to dynamic, “suspending belief” until runtime. Conversely, there is an “assignment conversion” from dynamic to any other type, which allows implicit conversion in assignment-like constructs:
dynamic d = 7; // implicit conversion
int i = d; // assignment conversion
Dynamic operations
Not only method calls, but also field and property accesses, indexer and operator calls and even delegate invocations can be dispatched dynamically:
dynamic d = GetDynamicObject(…);
d.M(7); // calling methods
d.f = d.P; // getting and settings fields and properties
d[“one”] = d[“two”]; // getting and setting thorugh indexers
int i = d + 3; // calling operators
string s = d(5,7); // invoking as a delegate
The role of the C# compiler here is simply to package up the necessary information about “what is being done to d”, so that the runtime can pick it up and determine what the exact meaning of it is given an actual object d. Think of it as deferring part of the compiler’s job to runtime.
The result of any dynamic operation is itself of type dynamic.
Runtime lookup
At runtime a dynamic operation is dispatched according to the nature of its target object d:
COM objects
If d is a COM object, the operation is dispatched dynamically through COM IDispatch. This allows calling to COM types that don’t have a Primary Interop Assembly (PIA), and relying on COM features that don’t have a counterpart in C#, such as indexed properties and default properties.
Dynamic objects
If d implements the interface IDynamicObject d itself is asked to perform the operation. Thus by implementing IDynamicObject a type can completely redefine the meaning of dynamic operations. This is used intensively by dynamic languages such as IronPython and IronRuby to implement their own dynamic object models. It will also be used by APIs, e.g. by the HTML DOM to allow direct access to the object’s properties using property syntax.
Plain objects
Otherwise d is a standard .NET object, and the operation will be dispatched using reflection on its type and a C# “runtime binder” which implements C#’s lookup and overload resolution semantics at runtime. This is essentially a part of the C# compiler running as a runtime component to “finish the work” on dynamic operations that was deferred by the static compiler.
Example
Assume the following code:
dynamic d1 = new Foo();
dynamic d2 = new Bar();
string s;
d1.M(s, d2, 3, null);
Because the receiver of the call to M is dynamic, the C# compiler does not try to resolve the meaning of the call. Instead it stashes away information for the runtime about the call. This information (often referred to as the “payload”) is essentially equivalent to:
“Perform an instance method call of M with the following arguments:
1. a string
2. a dynamic
3. a literal int 3
4. a literal object null”
At runtime, assume that the actual type Foo of d1 is not a COM type and does not implement IDynamicObject. In this case the C# runtime binder picks up to finish the overload resolution job based on runtime type information, proceeding as follows:
1. Reflection is used to obtain the actual runtime types of the two objects, d1 and d2, that did not have a static type (or rather had the static type dynamic). The result is Foo for d1 and Bar for d2.
2. Method lookup and overload resolution is performed on the type Foo with the call M(string,Bar,3,null) using ordinary C# semantics.
3. If the method is found it is invoked; otherwise a runtime exception is thrown.
Overload resolution with dynamic arguments
Even if the receiver of a method call is of a static type, overload resolution can still happen at runtime. This can happen if one or more of the arguments have the type dynamic:
Foo foo = new Foo();
dynamic d = new Bar();
var result = foo.M(d);
The C# runtime binder will choose between the statically known overloads of M on Foo, based on the runtime type of d, namely Bar. The result is again of type dynamic.
The Dynamic Language Runtime
An important component in the underlying implementation of dynamic lookup is the Dynamic Language Runtime (DLR), which is a new API in .NET 4.0.
The DLR provides most of the infrastructure behind not only C# dynamic lookup but also the implementation of several dynamic programming languages on .NET, such as IronPython and IronRuby. Through this common infrastructure a high degree of interoperability is ensured, but just as importantly the DLR provides excellent caching mechanisms which serve to greatly enhance the efficiency of runtime dispatch.
To the user of dynamic lookup in C#, the DLR is invisible except for the improved efficiency. However, if you want to implement your own dynamically dispatched objects, the IDynamicObject interface allows you to interoperate with the DLR and plug in your own behavior. This is a rather advanced task, which requires you to understand a good deal more about the inner workings of the DLR. For API writers, however, it can definitely be worth the trouble in order to vastly improve the usability of e.g. a library representing an inherently dynamic domain.
Open issues
There are a few limitations and things that might work differently than you would expect.
· The DLR allows objects to be created from objects that represent classes. However, the current implementation of C# doesn’t have syntax to support this.
· Dynamic lookup will not be able to find extension methods. Whether extension methods apply or not depends on the static context of the call (i.e. which using clauses occur), and this context information is not currently kept as part of the payload.
· Anonymous functions (i.e. lambda expressions) cannot appear as arguments to a dynamic method call. The compiler cannot bind (i.e. “understand”) an anonymous function without knowing what type it is converted to.
One consequence of these limitations is that you cannot easily use LINQ queries over dynamic objects:
dynamic collection = …;
var result = collection.Select(e => e + 5);
If the Select method is an extension method, dynamic lookup will not find it. Even if it is an instance method, the above does not compile, because a lambda expression cannot be passed as an argument to a dynamic operation.
There are no plans to address these limitations in C# 4.0.
Named and Optional Arguments
Named and optional parameters are really two distinct features, but are often useful together. Optional parameters allow you to omit arguments to member invocations, whereas named arguments is a way to provide an argument using the name of the corresponding parameter instead of relying on its position in the parameter list.
Some APIs, most notably COM interfaces such as the Office automation APIs, are written specifically with named and optional parameters in mind. Up until now it has been very painful to call into these APIs from C#, with sometimes as many as thirty arguments having to be explicitly passed, most of which have reasonable default values and could be omitted.
Even in APIs for .NET however you sometimes find yourself compelled to write many overloads of a method with different combinations of parameters, in order to provide maximum usability to the callers. Optional parameters are a useful alternative for these situations.
Optional parameters
A parameter is declared optional simply by providing a default value for it:
public void M(int x, int y = 5, int z = 7);
Here y and z are optional parameters and can be omitted in calls:
M(1, 2, 3); // ordinary call of M
M(1, 2); // omitting z – equivalent to M(1, 2, 7)
M(1); // omitting both y and z – equivalent to M(1, 5, 7)
Named and optional arguments
C# 4.0 does not permit you to omit arguments between commas as in M(1,,3). This could lead to highly unreadable comma-counting code. Instead any argument can be passed by name. Thus if you want to omit only y from a call of M you can write:
M(1, z: 3); // passing z by name
or
M(x: 1, z: 3); // passing both x and z by name
or even
M(z: 3, x: 1); // reversing the order of arguments
All forms are equivalent, except that arguments are always evaluated in the order they appear, so in the last example the 3 is evaluated before the 1.
Optional and named arguments can be used not only with methods but also with indexers and constructors.
Overload resolution
Named and optional arguments affect overload resolution, but the changes are relatively simple:
A signature is applicable if all its parameters are either optional or have exactly one corresponding argument (by name or position) in the call which is convertible to the parameter type.
Betterness rules on conversions are only applied for arguments that are explicitly given – omitted optional arguments are ignored for betterness purposes.
If two signatures are equally good, one that does not omit optional parameters is preferred.
M(string s, int i = 1);
M(object o);
M(int i, string s = “Hello”);
M(int i);
M(5);
Given these overloads, we can see the working of the rules above. M(string,int) is not applicable because 5 doesn’t convert to string. M(int,string) is applicable because its second parameter is optional, and so, obviously are M(object) and M(int).
M(int,string) and M(int) are both better than M(object) because the conversion from 5 to int is better than the conversion from 5 to object.
Finally M(int) is better than M(int,string) because no optional arguments are omitted.
Thus the method that gets called is M(int).
Features for COM interop
Dynamic lookup as well as named and optional parameters greatly improve the experience of interoperating with COM APIs such as the Office Automation APIs. In order to remove even more of the speed bumps, a couple of small COM-specific features are also added to C# 4.0.
Dynamic import
Many COM methods accept and return variant types, which are represented in the PIAs as object. In the vast majority of cases, a programmer calling these methods already knows the static type of a returned object from context, but explicitly has to perform a cast on the returned value to make use of that knowledge. These casts are so common that they constitute a major nuisance.
In order to facilitate a smoother experience, you can now choose to import these COM APIs in such a way that variants are instead represented using the type dynamic. In other words, from your point of view, COM signatures now have occurrences of dynamic instead of object in them.
This means that you can easily access members directly off a returned object, or you can assign it to a strongly typed local variable without having to cast. To illustrate, you can now say
excel.Cells[1, 1].Value = "Hello";
instead of
((Excel.Range)excel.Cells[1, 1]).Value2 = "Hello";
and
Excel.Range range = excel.Cells[1, 1];
instead of
Excel.Range range = (Excel.Range)excel.Cells[1, 1];
Compiling without PIAs
Primary Interop Assemblies are large .NET assemblies generated from COM interfaces to facilitate strongly typed interoperability. They provide great support at design time, where your experience of the interop is as good as if the types where really defined in .NET. However, at runtime these large assemblies can easily bloat your program, and also cause versioning issues because they are distributed independently of your application.
The no-PIA feature allows you to continue to use PIAs at design time without having them around at runtime. Instead, the C# compiler will bake the small part of the PIA that a program actually uses directly into its assembly. At runtime the PIA does not have to be loaded.
Omitting ref
Because of a different programming model, many COM APIs contain a lot of reference parameters. Contrary to refs in C#, these are typically not meant to mutate a passed-in argument for the subsequent benefit of the caller, but are simply another way of passing value parameters.
It therefore seems unreasonable that a C# programmer should have to create temporary variables for all such ref parameters and pass these by reference. Instead, specifically for COM methods, the C# compiler will allow you to pass arguments by value to such a method, and will automatically generate temporary variables to hold the passed-in values, subsequently discarding these when the call returns. In this way the caller sees value semantics, and will not experience any side effects, but the called method still gets a reference.
Open issues
A few COM interface features still are not surfaced in C#. Most notably these include indexed properties and default properties. As mentioned above these will be respected if you access COM dynamically, but statically typed C# code will still not recognize them.
There are currently no plans to address these remaining speed bumps in C# 4.0.
Variance
An aspect of generics that often comes across as surprising is that the following is illegal:
IList<string> strings = new List<string>();
IList<object> objects = strings;
The second assignment is disallowed because strings does not have the same element type as objects. There is a perfectly good reason for this. If it were allowed you could write:
objects[0] = 5;
string s = strings[0];
Allowing an int to be inserted into a list of strings and subsequently extracted as a string. This would be a breach of type safety.
However, there are certain interfaces where the above cannot occur, notably where there is no way to insert an object into the collection. Such an interface is IEnumerable<T>. If instead you say:
IEnumerable<object> objects = strings;
There is no way we can put the wrong kind of thing into strings through objects, because objects doesn’t have a method that takes an element in. Variance is about allowing assignments such as this in cases where it is safe. The result is that a lot of situations that were previously surprising now just work.
Covariance
In .NET 4.0 the IEnumerable<T> interface will be declared in the following way:
public interface IEnumerable<out T> : IEnumerable
{
IEnumerator<T> GetEnumerator();
}
public interface IEnumerator<out T> : IEnumerator
{
bool MoveNext();
T Current { get; }
}
The “out” in these declarations signifies that the T can only occur in output position in the interface – the compiler will complain otherwise. In return for this restriction, the interface becomes “covariant” in T, which means that an IEnumerable<A> is considered an IEnumerable<B> if A has a reference conversion to B.
As a result, any sequence of strings is also e.g. a sequence of objects.
This is useful e.g. in many LINQ methods. Using the declarations above:
var result = strings.Union(objects); // succeeds with an IEnumerable<object>
This would previously have been disallowed, and you would have had to to some cumbersome wrapping to get the two sequences to have the same element type.
Contravariance
Type parameters can also have an “in” modifier, restricting them to occur only in input positions. An example is IComparer<T>:
public interface IComparer<in T>
{
public int Compare(T left, T right);
}
The somewhat baffling result is that an IComparer<object> can in fact be considered an IComparer<string>! It makes sense when you think about it: If a comparer can compare any two objects, it can certainly also compare two strings. This property is referred to as contravariance.
A generic type can have both in and out modifiers on its type parameters, as is the case with the Func<…> delegate types:
public delegate TResult Func<in TArg, out TResult>(TArg arg);
Obviously the argument only ever comes in, and the result only ever comes out. Therefore a Func<object,string> can in fact be used as a Func<string,object>.
Limitations
Variant type parameters can only be declared on interfaces and delegate types, due to a restriction in the CLR. Variance only applies when there is a reference conversion between the type arguments. For instance, an IEnumerable<int> is not an IEnumerable<object> because the conversion from int to object is a boxing conversion, not a reference conversion.
Also please note that the CTP does not contain the new versions of the .NET types mentioned above. In order to experiment with variance you have to declare your own variant interfaces and delegate types.
COM Example
Here is a larger Office automation example that shows many of the new C# features in action.
using System;
using System.Diagnostics;
using System.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;
class Program
{
static void Main(string[] args) {
var excel = new Excel.Application();
excel.Visible = true;
excel.Workbooks.Add(); // optional arguments omitted
excel.Cells[1, 1].Value = "Process Name"; // no casts; Value dynamically
excel.Cells[1, 2].Value = "Memory Usage"; // accessed
var processes = Process.GetProcesses()
.OrderByDescending(p => p.WorkingSet)
.Take(10);
int i = 2;
foreach (var p in processes) {
excel.Cells[i, 1].Value = p.ProcessName; // no casts
excel.Cells[i, 2].Value = p.WorkingSet; // no casts
i++;
}
Excel.Range range = excel.Cells[1, 1]; // no casts
Excel.Chart chart = excel.ActiveWorkbook.Charts.
Add(After: excel.ActiveSheet); // named and optional arguments
chart.ChartWizard(
Source: range.CurrentRegion,
Title: "Memory Usage in " + Environment.MachineName); //named+optional
chart.ChartStyle = 45;
chart.CopyPicture(Excel.XlPictureAppearance.xlScreen,
Excel.XlCopyPictureFormat.xlBitmap,
Excel.XlPictureAppearance.xlScreen);
var word = new Word.Application();
word.Visible = true;
word.Documents.Add(); // optional arguments
word.Selection.Paste();
}
}
The code is much more terse and readable than the C# 3.0 counterpart.
Note especially how the Value property is accessed dynamically. This is actually an indexed property, i.e. a property that takes an argument; something which C# does not understand. However the argument is optional. Since the access is dynamic, it goes through the runtime COM binder which knows to substitute the default value and call the indexed property. Thus, dynamic COM allows you to avoid accesses to the puzzling Value2 property of Excel ranges.
Relationship with Visual Basic
A number of the features introduced to C# 4.0 already exist or will be introduced in some form or other in Visual Basic:
· Late binding in VB is similar in many ways to dynamic lookup in C#, and can be expected to make more use of the DLR in the future, leading to further parity with C#.
· Named and optional arguments have been part of Visual Basic for a long time, and the C# version of the feature is explicitly engineered with maximal VB interoperability in mind.
· NoPIA and variance are both being introduced to VB and C# at the same time.
VB in turn is adding a number of features that have hitherto been a mainstay of C#. As a result future versions of C# and VB will have much better feature parity, for the benefit of everyone.

New Features of .NET Framework 4.0

27 New Features of .NET Framework 4.0

The new features and improvements are described in the following sections:

Programming Languages
Common Language Runtime (CLR)
Base Class Libraries
Networking
Web
Client
Data
Communications
Workflow
Common Language Runtime (CLR)
The following sections describe new features in security, parallel computing, performance and diagnostics, dynamic language runtime, and other CLR-related technologies.
Security
The .NET Framework 4.0 provides simplifications, improvements, and expanded capabilities in the security model. For more information, see Security Changes in the .NET Framework 4.
Parallel Computing
The .NET Framework 4.0 introduces a new programming model for writing multithreaded and asynchronous code that greatly simplifies the work of application and library developers. The new model enables developers to write efficient, fine-grained, and scalable parallel code in a natural idiom without having to work directly with threads or the thread pool. The new Parallel and Task classes, and other related types, support this new model. Parallel LINQ (PLINQ), which is a parallel implementation of LINQ to Objects, enables similar functionality through declarative syntax. For more information, see Parallel Programming in the .NET Framework.
Performance and Diagnostics
In addition to the following features, the .NET Framework 4.0 provides improvements in startup time, working set sizes, and faster performance for multithreaded applications.
ETW Events
You can now access the Event Tracing for Windows (ETW) events for diagnostic purposes to improve performance. For more information, see the following topics:
CLR ETW Events
Using Event Tracing for Windows to Log CLR Events
Performance Monitor (Perfmon.exe) now enables you to disambiguate multiple applications that use the same name and multiple versions of the common language runtime loaded by a single process. This requires a simple registry modification. For more information, see Performance Counters and In-Process Side-By-Side Applications.
Code Contracts
Code contracts let you specify contractual information that is not represented by a method's or type's signature alone. The new System.Diagnostics.Contracts namespace contains classes that provide a language-neutral way to express coding assumptions in the form of pre-conditions, post-conditions, and object invariants. The contracts improve testing with run-time checking, enable static contract verification, and documentation generation.
The applicable scenarios include the following:
Perform static bug finding, which enables some bugs to be found without executing the code.
Create guidance for automated testing tools to enhance test coverage.
Create a standard notation for code behavior, which provides more information for documentation.
Lazy Initialiation
With lazy initialization, the memory for an object is not allocated until it is needed. Lazy initialization can improve performance by spreading object allocations evenly across the lifetime of a program. You can enable lazy initialization for any custom type by wrapping the type inside a System..::.Lazy<(Of <(T>)>) class.
Dynamic Language Runtime
The dynamic language runtime (DLR) is a new runtime environment that adds a set of services for dynamic languages to the CLR. The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages. To support the DLR, the new System.Dynamic namespace is added to the .NET Framework. In addition, several new classes that support the .NET Framework infrastructure are added to the System.Runtime.CompilerServices namespace. For more information, see Dynamic Language Runtime Overview.
In-Process Side-by-Side Execution
In-process side-by-side hosting enables an application to load and activate multiple versions of the common language runtime (CLR) in the same process. For example, you can run applications that are based on the .NET Framework 2.0 SP1 and applications that are based on .NET Framework 4.0 in the same process. Older components continue to use the same CLR version, and new components use the new CLR version. For more information, see Hosting Changes in the .NET Framework 4.
Interoperability
New interoperability features and improvements include the following:
You no longer have to use primary interop assemblies (PIAs). Compilers embed the parts of the interop assemblies that the add-ins actually use, and type safety is ensured by the common language runtime.
You can use the System.Runtime.InteropServices..::.ICustomQueryInterface interface to create a customized, managed code implementation of the IUnknown::QueryInterface method. Applications can use the customized implementation to return a specific interface (except IUnknown) for a particular interface ID.
Profiling
In the .NET Framework 4.0, you can attach profilers to a running process at any point, perform the requested profiling tasks, and then detach. For more information, see the [IClrProfiling::AttachProfiler]IClrProfiling Interface::AttachProfiler Method method.
Garbage Collection
The .NET Framework 4.0 provides background garbage collection; for more information, see the entry So, what’s new in the CLR 4.0 GC? in the CLR Garbage Collector blog. 
Covariance and Contravariance
Several generic interfaces and delegates now support covariance and contravariance. For more information, see Covariance and Contravariance in the Common Language Runtime.
Base Class Libraries
The following sections describe new features in collections and data structures, exception handling, I/O, reflection, threading, and Windows registry.
Collections and Data Structures
Enhancements in this area include the new System.Numerics..::.BigInteger structure, the System.Collections.Generic..::.SortedSet<(Of <(T>)>) generic class, and tuples.
BigInteger
The new System.Numerics..::.BigInteger structure is an arbitrary-precision integer data type that supports all the standard integer operations, including bit manipulation. It can be used from any .NET Framework language. In addition, some of the new .NET Framework languages (such as F# and IronPython) have built-in support for this structure.
SortedSet Generic Class
The new System.Collections.Generic..::.SortedSet<(Of <(T>)>) class provides a self-balancing tree that maintains data in sorted order after insertions, deletions, and searches. This class implements the new System.Collections.Generic..::.ISet<(Of <(T>)>) interface.
The System.Collections.Generic..::.HashSet<(Of <(T>)>) class also implements the ISet<(Of <(T>)>) interface.
Tuples
A tuple is a simple generic data structure that holds an ordered set of items of heterogeneous types. Tuples are supported natively in languages such as F# and IronPython, but are also easy to use from any .NET Framework language such as C# and Visual Basic. The ..NET Framework 4.0 adds eight new generic tuple classes, and also a Tuple class that contains static factory methods for creating tuples.
Exceptions Handling
The .NET Framework 4.0 class library contains the new System.Runtime.ExceptionServices namespace, and adds the ability to handle corrupted state exceptions. 
Corrupted State Exceptions
The CLR no longer delivers corrupted state exceptions that occur in the operating system to be handled by managed code, unless you apply the HandleProcessCorruptedStateExceptionsAttribute attribute to the method that handles the corrupted state exception.
Alternatively, you can add the following setting to an application's configuration file:
legacyCorruptedStateExceptionsPolicy=true
I/O
The key new features in I/O are efficient file enumerations, memory-mapped files, and improvements in isolated storage and compression.
File System Enumeration Improvements
New enumeration methods in the Directory and DirectoryInfo classes return IEnumerable<(Of <(T>)>) collections instead of arrays. These methods are more efficient than the array-based methods, because they do not have to allocate a (potentially large) array and you can access the first results immediately instead of waiting for the complete enumeration to occur.
There are also new methods in the static File class that read and write lines from files by using IEnumerable<(Of <(T>)>) collections. These methods are useful in LINQ scenarios where you may want to quickly and efficiently query the contents of a text file and write out the results to a log file without allocating any arrays.
Memory-Mapped Files
The new System.IO.MemoryMappedFiles namespace provides memory mapping functionality, which is available in Windows. You can use memory-mapped files to edit very large files and to create shared memory for inter-process communication. The new System.IO..::.UnmanagedMemoryAccessor class enables random access to unmanaged memory, similar to how System.IO..::.UnmanagedMemoryStream enables sequential access to unmanaged memory.
Isolated Storage Improvements
Partial-trust applications, such as Windows Presentation Framework (WPF) browser applications (XBAPs) and ClickOnce partial-trust applications, now have the same capabilities in the .NET Framework as they do in Silverlight. The default quota size is doubled, and applications can prompt the user to approve or reject a request to increase the quota. The System.IO.IsolatedStorage..::.IsolatedStorageFile class contains new members to manage the quota and to make working with files and directories easier.
Compression Improvements
The compression algorithms for the System.IO.Compression..::.DeflateStream and System.IO.Compression..::.GZipStream classes have improved so that data that is already compressed is no longer inflated. This results in much better compression ratios. Also, the 4-gigabyte size restriction for compressing streams has been removed.
Reflection
The .NET Framework 4.0 provides the capability to monitor the performance of your application domains.
Application Domain Resource Monitoring
Until now, there has been no way to determine whether a particular application domain is affecting other application domains, because the operating system APIs and tools, such as the Windows Task Manager, were precise only to the process level. Starting with the .NET Framework 4.0, you can get processor usage and memory usage estimates per application domain.
Application domain resource monitoring is available through the managed AppDomain class, native hosting APIs, and event tracing for Windows (ETW). When this feature has been enabled, it collects statistics on all application domains in the process for the life of the process.
For more information, see the Element, and the following properties in the AppDomain class:
MonitoringIsEnabled
MonitoringSurvivedMemorySize
MonitoringSurvivedProcessMemorySize
MonitoringTotalAllocatedMemorySize
MonitoringTotalProcessorTime
64-bit View and Other Registry Improvements
Windows registry improvements include the following:
Ability to specify a 32-bit or 64-bit view of the registry with the Microsoft.Win32..::.RegistryView enumeration when you open base keys.
the new Microsoft.Win32..::.RegistryOptions enumeration, which lets you specify a volatile registry key that does not persist after the computer restarts.
Threading
General threading improvements include the following:
The new Monitor..::.Enter(Object, Boolean%) method overload takes a Boolean reference and atomically sets it to true only if the monitor is successfully entered.
You can use the Thread..::.Yield method to have the calling thread yield execution to another thread that is ready to run on the current processor.
The following sections describe new threading features.
Unified Model for Cancellation
The .NET Framework 4.0 provides a new unified model for cancellation of asynchronous operations. The new System.Threading..::.CancellationTokenSource class is used to create a CancellationToken that may be passed to any number of operations on multiple threads. By calling Cancel()()() on the token source object, the IsCancellationRequested property on the token is set to true and the token’s wait handle is signaled, at which time any registered actions with the token are invoked. Any object that has a reference to that token can monitor the value of that property and respond as appropriate.
Thread-Safe Collection Classes
The new System.Collections.Concurrent namespace introduces several new thread-safe collection classes that provide lock-free access to items whenever useful, and fine-grained locking when locks are appropriate. The use of these classes in multi-threaded scenarios should improve performance over collection types such as ArrayList, and List<(Of <(T>)>).
Synchronization Primitives
New synchronization primitives in the System.Threading namespace enable fine-grained concurrency and faster performance by avoiding expensive locking mechanisms. The Barrier class enables multiple threads to work on an algorithm cooperatively by providing a point at which each task can signal its arrival and then block until the other participants in the barrier have arrived. The CountdownEvent class simplifies fork and join scenarios by providing an easy rendezvous mechanism. The ManualResetEventSlim class is a lock-free synchronization primitive similar to the ManualResetEvent class. ManualResetEventSlim is lighter weight but can only be used for intra-process communication. The SemaphoreSlim class is a lightweight synchronization primitive that limits the number of threads that can access a resource or a pool of resources at the same time; it can be used only for intra-process communication. The SpinLock class is a mutual exclusion lock primitive that causes the thread that is trying to acquire the lock to wait in a loop, or spin, until the lock becomes available. The SpinWait class is a small, lightweight type that will spin for a time and eventually put the thread into a wait state if the spin count is exceeded.
Networking
Enhancements have been made that affect how integrated Windows authentication is handled by the HttpWebRequest, HttpListener, SmtpClient, SslStream, NegotiateStream, and related classes in the System.Net and related namespaces. Support was added for extended protection to enhance security. The changes to support extended protection are available only for applications on Windows 7. The extended protection features are not available on earlier versions of Windows. For more information, seeIntegrated Windows Authentication with Extended Protection.
Web
The following sections describe new features in ASP.NET core services, Web Forms, Dynamic Data, and Visual Web Developer.
ASP.NET Core Services
ASP.NET introduces several features that improve core ASP.NET services, Web Forms, Dynamic Data, and Visual Web Developer. For more information, see What’s New in ASP.NET and Web Development.
ASP.NET Web Forms
Web Forms has been a core feature in ASP.NET since the release of ASP.NET 1.0. Many enhancements have been made in this area for ASP.NET 4, including the following:
The ability to set meta tags.
More control over view state.
Easier ways to work with browser capabilities.
Support for using ASP.NET routing with Web Forms.
More control over generated IDs.
The ability to persist selected rows in data controls.
More control over rendered HTML in the FormView and ListView controls.
Filtering support for data source controls.
Dynamic Data
For ASP.NET 4, Dynamic Data has been enhanced to give developers even more power for quickly building data-driven Web sites. This includes the following:
Automatic validation that is based on constraints defined in the data model.
The ability to easily change the markup that is generated for fields in the GridView and DetailsView controls by using field templates that are part of your Dynamic Data project.
Visual Web Developer Enhancements
The Web page designer in Visual Studio 2010 has been enhanced for better CSS compatibility, includes additional support for HTML and ASP.NET markup code examples, and features a redesigned version of IntelliSense for JScript. In addition, two new deployment features called Web packaging and One-Click Publish make deploying Web applications easier.
Client
The following sections describe new features in Windows Presentation Foundation (WPF) and Managed Extensibility Framework (MEF).
Windows Presentation Foundation
In the .NET Framework 4.0, Windows Presentation Foundation (WPF) contains changes and improvements in many areas. This includes controls, graphics, and XAML.
For more information, see What's New in Windows Presentation Foundation Version 4.
Managed Extensibility Framework
The Managed Extensibility Framework (MEF) is a new library in the .NET Framework 4.0 that enables you to build extensible and composable applications. MEF enables application developers to specify points where an application can be extended, expose services to offer to other extensible applications, and create parts for consumption by extensible applications. It also enables easy discoverability of available parts based on metadata, without the need to load the assemblies for the parts.
For more information, see Managed Extensibility Framework. For a list of the MEF types, see the System.ComponentModel.Composition namespace.
Data
For more information, see What's New in ADO.NET.
Expression Trees
Expression trees are extended with new types that represent control flow, for example, LoopExpression and TryExpression. These new types are used by the dynamic language runtime (DLR) and not used by LINQ.
Communications
Windows Communication Foundation (WCF) provides the new features and enhancements described in the following sections.
Support for WS-Discovery
The Service Discovery feature enables client applications to dynamically discover service addresses at run time in an interoperable way using WS-Discovery. The WS-Discovery specification outlines the message-exchange patterns (MEPs) required for performing lightweight discovery of services, both by multicast (ad hoc) and unicast (using a network resource).
Standard Endpoints
Standard endpoints are pre-defined endpoints that have one or more of their properties (address, binding, contract) fixed. For example, all metadata exchange endpoints specify IMetadataExchange as their contract, so there is no need for a developer to have to specify the contract. Therefore, the standard MEX endpoint has a fixed IMetadataExchange contract.
Workflow Services
With the introduction of a set of messaging activities, it is easier than ever to implement workflows that send and receive data. These messaging activities enable you to model complex message exchange patterns that go outside the traditional send/receive or RPC-style method invocation.
Workflow
Windows Workflow Foundation (WF) in .NET Framework 4.0 changes several development paradigms from earlier versions. Workflows are now easier to create, execute, and maintain.
Workflow Activity Model
The activity is now the base unit of creating a workflow, instead of using the SequentialWorkflowActivity or StateMachineWorkflowActivity classes. The WorkflowElement class provides the base abstraction of workflow behavior. Activity authors implement WorkflowElement objects imperatively when they have to use the breadth of the runtime. The Activity class is a data-driven WorkflowElement object where activity authors express new behaviors declaratively in terms of other activity objects.
Richer Composite Activity Options
The Flowchart class is a powerful new control flow activity that enables authors to construct process flows more naturally. Procedural workflows benefit from new flow-control activities that model traditional flow-control structures, such as TryCatch and Switch.
Expanded Built-in Activity Library
New features of the activity library include the following:
Data access activities for interacting with ODBC data sources.
New flow control activities such as DoWhile, ForEach, and ParallelForEach.
Activities for interacting with PowerShell and SharePoint.
Enhanced Persistence and Unloading
Workflow state data can be explicitly persisted by using the Persist activity. A host can persist a WorkflowInstance without unloading it. A workflow can specify no-persist zones when working with data that cannot be persisted so that persistence is postponed until the no-persist zone exits.
Improved Ability to Extend WF Designer Experience
The new WF Designer is built on Windows Presentation Foundation (WPF) and provides an easier model to use when rehosting the WF Designer outside Visual Studio. It also provides easier mechanisms for creating custom activity designers. For more information, see Extending the Workflow Designer.