Archive for April, 2007

Recursion and Lambda

Posted: April 21, 2007 in Uncategorized
I was wondering how Lambda and recursion fits together and before opening the C# 3.0 spec I thought why not googled  or msned and I found 2 great post on the same subject matter i thought why not share those .so here you go:-
Auto Refresh:-Server Side:-With Reposting:-Whenever you are going to display a stock reporting kind of solution with real data changes in a web application. You might face with 2 primitive issues those are whether to go with a PULL model or to go for a PUSH model. Further to that you also need to consider if any Hybrid approach are possible. The same apply to any real-time collaborative systems and with the stateless HTTP coming into the picture the complexity increases .With a Desktop application you might consider Callback and Pub-Sub patterns together with some sort of Auto-notification [like a sql dependency] to provide similar experience. [Although the Sql dependency is less scalable if used improperly and I ll discuss that in another post].
 
In this post we ll consider simple PULL model without the SereverFarm Scenario and its not for a real time production scenario for high traffic where you need to consider little more to provide some set of braodcasting or multicasting to  a set of server but this is not a quick solution which can work in production if your traffic and polling interval  managed properly.
 
Now coming to the simple process of how the activities carry in current applications without Ajax is as follows:-
            1. You post to a hidden frame, Remotescript or script call to get the data asynchronously
            2. You hook Ajax frameworks to get the data
            3. You simply use the serevrside approach with page refresh.
           
            Coming to the server side approach what you can do is Autopostback the page every few seconds.
 
Here is a demo script I used to populate the data and the autorefresh:-
DB script to populate a table and generate few random col:-
select Employeeid,lastname,firstname,birthdate,address,city into emp from northwind.dbo.employees
altertable emp add  sal int
—-
CREATEFUNCTION dbo.ISOdd (@id int)
RETURNSbit
WITHEXECUTEAS CALLER
AS
 
BEGIN
declare @result bit
set @result=1
     if(@id%2=0)
                        begin
                                    set @result=0
                        end
return @result
END;
GO
select dbo.isodd(5)
—-
update emp set sal=case(dbo.isodd(employeeid))
                                    when  0 then employeeid*1000
                                    when 1 then  employeeid*2000
                                    end
update Emp set sal=sal-50 where employeeid=1
droptable emp
 
Now you can do something like:-
 
protectedvoid Page_Load(object sender, EventArgs e)
        {
            getdata();
        }
       privatevoid getdata()
        {
            SqlConnection con = newSqlConnection(“connstr here”);
            SqlDataAdapter ad = newSqlDataAdapter(“SELECT [employeeid],[firstname],[sal] FROM [emp]”, con);
            DataSet ds = newDataSet();
            ad.Fill(ds);
            GridView1.DataSource = ds.Tables[0].DefaultView;
            GridView1.DataBind();
        }
 
And something like the following in the Aspx:-
      <bodystyle=”font-size: 12pt”>
    <formid=”form1″runat=”server”>
 
        <script>
            function reload() {
                document.getElementById(“form1”).submit();
                }
            window.setTimeout( “reload()”, 2000 );
        </script>
    </form>
</body>
</html>
You can also do something like
<METAHTTP-EQUIV=”Refresh”CONTENT=”2;URL=http://localhost:49573/Default.aspx”>
URL:- is ur page url
 
Here by I am refreshing the page every 2 seconds which might cause a network congestion and you need to set a appropriate interval for your production application.In fact there is a lot you need to consider while providing a real time webbased solution.I ll try to go one afetr other issues and this is first of the post to start with .So now that we saw how we can provide a serevr side solution Next we ll see how we cna hook up a AJAX based solution with Async postback and Updatepanel with timer as well as Client Side frx of asp.net ajax. 

Atlas Update Panel and Timer Server Side:-

Here I am loading the data in pageload() infact thru a Webservice Call .I will also discuss how you can expose this webservice from Client script as well as what does the Atlas Webservice offers .If you wants the Websrevice needed to supprot the JSON format you need to provide the Extension to the Web.config for the AJAX hookup as well as you need to decorate it with the ScriptService attaributes and Scrpitmethod when necessary for example returning the XML reponse format.

 Do remember that these extra complexities are necessary only when you are going for a true client side approach to avind the Update panel approach.For the Update panel approach all these are not required and you can hookup a normal Asmx.  

Update Panel Approach:-

protectedvoid Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                getdata();
            }
        }
        privatevoid getdata()
        {
            proxy.Service1 proxy = newService1();
            proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
            DataSet ds= (DataSet)proxy.GetEmployeedata();
            GridView1.DataSource = ds.Tables[0].DefaultView;
            GridView1.DataBind();
        }
        protectedvoid Timer1_Tick(object sender, EventArgs e)
        {
            getdata();
            //UpdatePanel1.Update();
 
        }

  ASPX:-

    <form id=”form1″ runat=”server”>
   <asp:ScriptManager ID=”ScriptManager1″ runat=”server” >
   </asp:ScriptManager>
    <asp:UpdatePanel ID=”UpdatePanel1″ runat=”server” UpdateMode=”Conditional” >
            <ContentTemplate>
    <asp:GridView ID=”GridView1″ ……..

 

 
</asp:GridView>
            </ContentTemplate>
            <Triggers>
              <asp:AsyncPostBackTriggerControlID=”Timer1″EventName=”Tick”/>
            </Triggers>
        </asp:UpdatePanel>
       <asp:TimerID=”Timer1″runat=”server”OnTick=”Timer1_Tick”Interval=”2000“>
        </asp:Timer>
   </form>

  ASMX:- 

  using System.Web.Script.Services;

  namespace GetEmp
{
[WebService(Namespace = “
http://tempuri.org/“)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
//[ScriptService]
public class Service1 : System.Web.Services.WebService
{

        [WebMethod]

      //[ScriptMethod(ResponseFormat=ResponseFormat.Xml)]
        public DataSet  GetEmployeedata()
{
SqlConnection con = new SqlConnection(“conn str here”);
SqlDataAdapter ad = new SqlDataAdapter(“SELECT [employeeid], [lastname], [firstname], [birthdate], [address], [sal], [city] FROM [emp]”, con);
DataSet ds = new DataSet();
ad.Fill(ds);
return ds;
}

  if you see the above code I have set the upadetpanel mode to conditional and I am jeust resetting the DataSource of the gridview and rebidning it in the timer_click.There are other mode also but i am preferring the programmatical mode for this post and ill cover those in anotehr post if needed.

  As I told before if you want to expose your webservice to JSON format that you can see while you apend a /js to ur asmx path you need to provide the Ajax extension to the Web.config if you are hosting the webservice outside your asp.net app.Further to that you need to import the Script.Services and decorate the service with ScriptService.Also you cann’t have the Dataset returns directly you can return datatable and also return XML from the Webmthod call using the ScriptMethod attaribute an dpassing the responseformat as XML.

  Here is the Client Mode Operation:-

  Here we ll call the websrvice to  get the data and display in Div all from Client script:-

The webservice remains the same with the addition of the scriptservice and script method attribute[uncomment the script svc call etc].

  Now that you have the webService ready.[Donot forget to add the extensions to the web.config to make it JSON aware].To make that the simpler approach would be see the web,config for a Asp.NEt Ajax appliucation and copy the WebExtension,Script extension realtaded configuratiosn and Http handlers to the ASMX if you are enabling an existing Asmx Json Aware.That is if you browse the Asmxpath/js you ll get the JSON call format.

  Here is the aspx to call the webservice and display the data all from client side:-

<form id=”form1″ runat=”server”>
<asp:ScriptManager ID=”ScriptManager1″ runat=”server” >
<Scripts>
<asp:ScriptReference Path=”CallWebServiceMethods.js” />
</Scripts>
<Services>
<asp:ServiceReference Path=”WebService.asmx” />[note i ve in same app u can provide ur url]
</Services>
</asp:ScriptManager>
<input id=”Button1″ type=”button” value=”button”  onclick=”ClientGetEmployee()” />
<div id=”div1″  >
</div>
</form>

  Here is the .JS:-

function ClientGetEmployee()
{
TestApplication.WebService.GetEmployeedata(SucceededCallback,FailedCallback);
}
function SucceededCallback(result, eventArgs)
{
// Page element to display feedback.
var RsltElem = document.getElementById(“div1”);
RsltElem.innerHTML = result.xml;
}

function FailedCallback(error)
{
// Display the error.
var RsltElem =
document.getElementById(“Label1”);
RsltElem.innerHTML =
“Service Error: ” + error.get_message();
}

 

 If you see rather then hooking of  arealtime collaboration here I am mere providing how to call webservice from client script an display the XML data in  a DIV.Since you ll not  get the Gridview datasource set to the result automagically.
That is in Succceedcallback:-
var RsltElem = document.getElementById(“gridview1”);
RsltElem.innerHTML = result.;
throws you error.You can hook up your own list and display the result from client side itself but that needed little more Javascript programming to parse the Dom and create your output.

  One last tip:-if you want to debug the java script  then enable script debugging in IE and from tools-customize from the debug commnad add the script explore and add the break point to the java script to step thru it.

This is enough for one post and I ll cover lot of the topics in next posts

 

SQL White papers

Posted: April 9, 2007 in Uncategorized
There is a Nice Collection of WhitePapers available at SQLSkills.Worth checkout:-

EnterPriseLibrary 3.0

Posted: April 9, 2007 in Uncategorized
EnterPrise Library 3.0 April-2007 is now released .Here is the Download link  .
Watchout  the webcast here for what’s new in Entlib 3.0 .
In short it contains
 

New application blocks

  • Validation Application Block
  • Policy Injection Application Block

Improvements to existing application blocks

  • Data Access Application Block
    •   SQL CE support, TransactionScope integraton
  • Logging Application Block
    •   Rolling Flat File Trace Listener

.NET Framework 3.0 integration

  • WCF integration in Logging, Exception Handling and Validation Application Blocks

Configuration improvements

  • Visual Studio-integrated configuration tool
  • Environmental Overrides
  • Manageable Configuration Source

Automation

  • Application Block Software Factory
  • Strong Naming Guidance Package