Tuesday, December 2, 2008

PL-SQL Looping

DECLARE CursorTemplate CURSOR
FAST_FORWARD FOR
SELECT Val1, Val2, Val3 FROM Table1

OPEN CursorTemplate

FETCH NEXT FROM CursorTemplate
INTO @Var1, @Var2, @Var3

WHILE (@@FETCH_STATUS = 0)
BEGIN
--do something here w/ your data

FETCH NEXT FROM CursorTemplate
INTO @Var1, @Var2, @Var3

END

CLOSE CursorTemplate
DEALLOCATE CursorTemplate

Wednesday, November 26, 2008

Fix Calendar Extender on IE 6

add this style
.ajax__calendar_container { z-index : 1004 ; }

add this javascript
function dateEditor_OnShown(dateControl, emptyEventArgs)
{
var shimWidth = dateControl._width;
var shimHeight = dateControl._height;

// Open current popup
// Create the popup element
var dateEditorShim;
dateEditorShim = document.getElementById("dateEditorShim");
dateEditorShim.style.width = dateControl._popupDiv.offsetWidth;
dateEditorShim.style.height = dateControl._popupDiv.offsetHeight;
dateEditorShim.style.top = dateControl._popupDiv.style.top;
dateEditorShim.style.left = dateControl._popupDiv.style.left;
dateControl._popupDiv.style.zIndex = 999;
dateEditorShim.style.zIndex = 998;
dateEditorShim.style.display = "block";

}

// Function: dateEditor_OnShown
// Summary: Handles the OnShown event of the dateEditor control.
// Inputs: dateControl -> The date control object
// emptyEventArgs -> Empty event arguments raised by the date control
// Remarks: Make sure to insert a shim of an empty iframe underneath the calendar popup container
function dateEditor_OnHiding(dateControl, emptyEventArgs)
{
var shimWidth = 0;
var shimHeight = 0;

// Open current popup
// Create the popup element
var dateEditorShim;
dateEditorShim = document.getElementById("dateEditorShim");
dateEditorShim.style.width = 0;
dateEditorShim.style.height = 0;
dateEditorShim.style.top = 0;
dateEditorShim.style.left = 0;
dateEditorShim.style.display = "none";
}


//add this in code
calDOB.OnClientShown = "dateEditor_OnShown";
calDOB.OnClientHiding = "dateEditor_OnHiding";

Tuesday, November 25, 2008

Error in Calendar Extender because the master page has asp tag <%%>

Today, I just annoyed with this error.
Every form which using Calendar extension works fine before.
and somehow after I change the master page, it start to show an error said :

=================
System.Web.HttpException: The Controls collection cannot be modified because the control contains code blocks (i.e. ).
=================

Luckily, with Tom's Help, I found the problem.
It was on the master page on the header java script which use <%= ... %> to get the content from server....

Thursday, November 20, 2008

Pomegranate Phone

http://www.pomegranatephone.com/default.html

Wednesday, November 19, 2008

Url Rewriting VS Postback

To Resolve a problem in postback for url rewriting,
you can use control adaptor and rewrite the form.

public class FormRewriter : System.Web.UI.Adapters.ControlAdapter

more information : visit : http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx

Thursday, October 23, 2008

EnableSortingAndPagingCallback Issue With LinqDataSource

Today, I found an issue with EnableSortingAndPagingCallback and LinqDataSource

I enable the EnableSortingAndPagingCallback on my GridView and using LinqDataSource.
Somehow after I tested, I always get error on deleting the row after move to the next page.

====
The solutions which work well is Use Update panel instead of EnableSortingAndPagingCallback.

I think it's better to use Update Panel rather then enableSortingAndPagingCallback, it some reason, it's faster and also include editing and deleting as well.

Monday, October 13, 2008

SWF Library to convert image

I just find library to convert SWF to image. it's called SWFToImage.dll from bytescout.
but it is activeX. which we don't want to use.

and I find others called swfdotnet-1.0 but unfortunately, it only support swf version 7.

Any other library for this ?

Thanks.

LINQ will arround the DateTime.MaxValue

Today, I just fixed the bugs which is interesting.

if we use linq to filter data with this DateTime.MaxValue.TimeOfDay.ToString();-
which will be appear show the time 23:59:59.9999999

Linq will add up to the next day.

so the solution never use the MaxValue.TimeOfDay.. just use simple string 23:59:59 and it's enough.

(o,o)

Thursday, August 14, 2008

Firefox 3 - Caching ISSUE

in Firefox 3 there is a weird bug which it somehow cache the page for no reason.
It just does not request to the server anymore... -(only if you update your updatepanel.


I have try many thing to avoid this.
1. Put meta tag which FF3 will ignore this -(
meta equiv="expires" content="Mon, 01 Jan 1990 00:00:00 GMT"
meta equiv="Cache-control" content="no-cache"
meta equiv="Cache-control" content="no-store"
meta equiv="Cache-control" content="must-revalidate"
meta equiv="pragma" content="no-cache"

2.Add Response Header - FF3 read this and by using Firebug, I notice that this info has been added to header
but it only worked in the first time, but after a while, it starts caching again.


Response.Cache.SetAllowResponseInBrowserHistory(false);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches) ;
Response.Expires = 0;

=======
Desperately I find doggy solution to handle this.
1. I notice that if the query string is change, FF3 will not cache. so it still go back to the server.
just add ur querystring with DateTime.Now.TimeSpan.Tick at the back, and FF3 will not cache anymore.

2. go to about:config and disable browser.cache.disk.enable and browser.cache.memory.enable. But this is very doggy solution, you can't force all of user to disable there settings which is not default from FF3. - (So just ignore this solution)

======
More reference about this bug.
https://bugzilla.mozilla.org/show_bug.cgi?id=441751

https://bugzilla.mozilla.org/show_bug.cgi?id=327790#c8

http://www.microsoft.com/communities/newsgroups/en-us/default.aspx?dg=microsoft.public.dotnet.framework.aspnet.caching&tid=6d5121f2-d78c-4e26-9d58-bbce507842b6&cat=en_US_f2b00e34-9211-4139-87be-4b28e2f0ef79&lang=en&cr=US&sloc=&p=1

http://www.alittlemadness.com/2008/07/30/ajax-vs-caching-vs-firefox-3/

http://www.killersites.com/mvnforum/mvnforum/viewthread?thread=11626

=====
Any other suggestion are welcome.

Tuesday, July 29, 2008

Force Page Client Validation First....

Today, I need to force check if the Page is valid in the client to perform another javascript function called.

Luckily, If you use Script Manager, WebResources.axd has been provided a function.

This function called Page_ClientValidate which will return the boolean result which indicate if the page client is valid / not. This function also will so the error message from page client validator and summary validator.

validationResult = Page_ClientValidate("groupName");

However if you use validation which is happen on the server, you still to mark your button CausesValidation="true" (Default) and code behind to check if Page is valid.

Here is example server validator using Custom validator

<asp:CustomValidator ID="custVal" runat="server" Display="dynamic" OnServerValidate="custVal_ServerValidate">
*
</asp:CustomValidator>
//code behind validation
protected void sitevalName_ServerValidate(object source, ServerValidateEventArgs args)
{
if (not valid)
args.IsValid = false;
}
//and don't forget in your button click code behind
//you need to check if page is valid,
//otherwise it will keep going.
if (!Page.IsValid) Return;

Friday, July 25, 2008

SWF with inside Modal Popup

I just solve a problem with SWF inside Modal Popup.

The weird thing happen between SWF and Ajax. It sometimes work and not work.

To make show swf in IE , I need to use SWF Object to render.
var fo = new SWFObject('temp.swf', 'viewer', '100%', '100%', '7', '#ffffff');

but there is still problem in Firefox which sometimes load up sometimes not.

Finally I need to put it on other IFrame instead of div.

<iframe style="border:none; width: 100%; height: 100%;" src="/temp.aspx?ID=<%= Content.ID%>" >
</iframe>


however It still cause a problem because I put the SWF Register Object using RegisterClient On backend... which Firefox does not accepted but IE accepted.

so Finally I need to put SWF object in front of Client aspx.




Friday, July 18, 2008

FingerMote

Just find how your finger can do in WiiMote.
http://www.cs.cmu.edu/~johnny/projects/wii/

Tuesday, July 15, 2008

JQuery - Mouseleave VS Mouseout

Today, I just realize that Mouseout will trigger if we go to the child of that container. Luckily JQuery has MouseLeave event which solve this problem.

Mouseover fires when the pointer moves into or out from child element, while mouseenter does't.

It is not standard DOM event so you need to use Bind method from JQUERY.

   $("div.overout").mouseover(function(){
$("p:first",this).text("mouse over");
$("p:last",this).text(++i);
}).mouseout(function(){
$("p:first",this).text("mouse out");
});
});




$("div.enterleave").bind("mouseenter",function(){
$("p:first",this).text("mouse enter");
$("p:last",this).text(++n);
}).bind("mouseleave",function(){
$("p:first",this).text("mouse leave");
});

RepeatColumns in ListView

The last major feature of the ListView is the ability to group data into subsets, much like the DataList control provides. The DataList is a tabular control that renders a single row of data in each cell of the rendered table. You control how many rows of the underlying dataset are grouped into a single table row by setting the RepeatColumns property.

Since the ListView is not constrained to render as a table, it needs a more generic way of specifying groups of items to be rendered together, which is what GroupTemplate does. Pic below shows the relationship among the LayoutTemplate, GroupTemplate, and ItemTemplate elements within a ListView. The GroupTemplate lets you specify the surrounding HTML for every n elements in the underlying dataset, where n is specified by the GroupItemCount property of the ListView.

 

When you use a GroupTemplate within a ListView, you won't specify a control with an ID of itemPlaceholder within your LayoutTemplate—that control now needs to be in your GroupTemplate. Instead, you will specify a control with an ID of groupPlaceholder in the LayoutTemplate (you can change the control ID by setting the GroupPlaceholderID property of the ListView) to describe where the contents of the GroupTemplate should be injected for each n items encountered in the underlying dataset.

Here is example how to use GroupTemplate in ListView

<asp:ListView ID="ListView1" runat="server" OnPagePropertiesChanging="ListView1_PagePropertiesChanging" GroupItemCount="2" DataKeyNames="CourtID">
<LayoutTemplate>
<asp:PlaceHolder id="groupPlaceholder" runat="server"/>
</LayoutTemplate>
<GroupTemplate>
<table>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</GroupTemplate>
<ItemTemplate>
<td>
test<%# Eval("CourtID") %>
</td>
</ItemTemplate>
/asp:ListView>





This is very similar to what you could do with a DataList, but because you are working with a ListView, you can just as easily add both pagination and sorting as you did earlier with your grid rendering, a task that would be rather daunting with the DataList. The code download for this article contains an example that implements both pagination and sorting for your reference.

Data paging List View in .Net 3.5

ListView is one of the new data controls that was shipped with the latest release of ASP.NET, which is 3.5. It displays the values from a data source by utilizing user-defined templates. This gives the developer more flexibility about the design of the data displayed on the user interface. In order for the ListView control to display its content, templates should be created for different parts of the control. The LayoutTemplate and ItemTemplate are mandatory. All other templates are optional.

Here is a sample to use Data paging without Data Source (Data Bind)

<asp:ListView ID="ListView1" runat="server" 
onpagepropertieschanging="ListView1_PagePropertiesChanging">
<LayoutTemplate>
LIST VIEW <br />
<table>
<tr>
<th>Court ID</th>
</tr>
<tr id="itemPlaceHolder" runat="server" />
</table>

</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
test<%
   1: # Eval("CourtID")
%>
</td>
</tr>

</ItemTemplate>
</asp:ListView>
<asp:DataPager ID="DataPager1" runat="server" PagedControlID="ListView1" PageSize="3" >
<Fields>
<asp:NumericPagerField ButtonCount="4" />
</Fields>
</asp:DataPager>




//inside page load
protected void Page_Load(object sender, EventArgs e)
{
//nomd for the first time
if (!IsPostBack)
{
ListView1.DataSource = CourtProvider.GetAllCourtsForDataBinding();
ListView1.DataBind();
}
}




//when ListView Page Property Changed
protected void ListView1_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
DataPager1.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);

ListView1.DataSource = CourtProvider.GetAllCourtsForDataBinding();
ListView1.DataBind();

}







Here is simple way to display using Object Data Source




<asp:ListView ID="ListView1" runat="server" DataSourceID="pdsData">
<LayoutTemplate>
LIST VIEW <br />
<table>
<tr>
<th>Court ID</th>
</tr>
<tr id="itemPlaceHolder" runat="server" />
</table>

</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
test<%
   1: # Eval("CourtID")
%>
</td>
</tr>

</ItemTemplate>
</asp:ListView>
<asp:DataPager ID="DataPager1" runat="server" PagedControlID="ListView1" PageSize="3" >
<Fields>
<asp:NumericPagerField ButtonCount="4" />
</Fields>
</asp:DataPager>

<cc:ParentDataSource ID="pdsData" runat="server" SelectMethod="GetData" SelectCountMethod="GetDataRowCount" />




public IEnumerable<CourtBindingHelper> GetData(string sortExpression, int maximumRows, int startRowIndex)
{
try
{

return this.CourtsData.GetSortPagingData(sortExpression, maximumRows, startRowIndex);

}
catch (Exception ex)
{
lblError.Text = ex.Message;
//if error just return the agencies
return this.CourtsData;
}
}

public int GetDataRowCount()
{
return (this.CourtsData != null ? this.CourtsData.Count : 0);
}

Wednesday, July 9, 2008

PEX

Pex is Automated EXploration Testing. It is an intelligent assistant to the programmer and will help us to generate a prarameterized unit test.

very cool...

Thursday, June 12, 2008

Trie Algorithm for Autocomplete and Suggest word

Currently I try using Trie for Suggest and Autocomplete algorithm.

public List<string> Suggest2(string str)
{
List<String> result = new List<String>();
TrieNode curr = root;
foreach (char c in str.Trim().ToLower().ToCharArray())
{
curr = curr.GetChild(c);
if (curr == null)
return result;
}

Suggest2(curr, new StringBuilder(str), result);
return result;

}

public void Suggest2(TrieNode curr,StringBuilder sbTemp, List<string> result)
{
if (curr == null) return;
if (curr.IsEnd) result.Add(sbTemp.ToString());

foreach (char c in curr.Childs.Keys)
{
sbTemp.Append(c);
Suggest2(curr.Childs[c], sbTemp, result);
sbTemp.Length--;
}
}



Any Suggestion to improve this algorithm except changing String to StringBuilder ?

Friday, June 6, 2008

IDisposable Pattern in .NET

In some cases we also need to implement IDisposable pattern in our code.

For example, If you have unmanaged objects such as (File, Image, TCP Connection, etc) or you want to make sure that you have closed your connection / web service.

Here is the code

#region IDisposable Pattern
/// <summary>
///
Desctructor in VB.NET - Finalize
/// It will be called by Garbage Collector
/// or you may force GC by calling GC.Collect()
/// </summary>
~MyClass()
{
//only dispose unmanaged obj, for managed obj,
//it probably already been clear by GC,
//so we cannot called it again.
Dispose(false);
}
/// <summary>
///
Will be called when you use 'using'
/// keyword or implicitly called by you obj.Dispose()
/// </summary>
public void Dispose()
{
Dispose(true);
//tell GC not to run Desctrutor,
//because it has been called implicitly
GC.SuppressFinalize(this);
}

/// <summary>
///
Dispose Unmanaged and manage
/// </summary>
/// <param name="bDisposeManaged">
///
true - dispose unmanaged and managed code as well
/// fase - dispose only and unmanaged
/// </param>
protected virtual void Dispose(bool bDisposeManaged)
{
try
{
if (bDisposeManaged)
{
//TODO: dispose managed code
//Such as(Service, connection, etc)
if (_ServiceUser != null)
{
try
{
_ServiceUser.Dispose();
}
catch { }
}
}
//TODO: dispose unmanaged code
//such as (File, Bitmap / Image, TCP Connection, etc)
}
catch{}
}
#endregion

Friday, May 30, 2008

New Beta Sites

Check this out...
www.evernote.com
This web site has OCR Build in which can search on handwriting inside your image 
     image image
http://www.tripit.com/ - If you like traveling 

Thursday, May 29, 2008

Dynamic Data on ASP.NET 3.5 Extensions CTP

I recently try Dynamic Data on ASP.NET 3.5 Extensions CTP.

The most thing that impress me is an idea of Dynamic Control /Field.

<asp:DynamicControl runat="server" DataField="EmailAddress"/>



So you can just simple define Dynamic Field in your Grid View and it will rendered into particular template (Include Edit Template) based on data type of your value.




You can define your template to have validation control or even can you 3rd party control such as telerik.



Here is How you can tell dynamic control to render based on particular template or even BLOB/Image Type as well.




//this is a partial class to override the code which has been generated by DBML
[MetadataType(typeof(MyClassMetadata))]
public partial class MyClass
{
//TODO: You may put Validation when your data change or whatever...
}

//Here is your metadata which you will define rendering using UIHint
public class MyClassMetadata
{
//Date Type
[DisplayFormat(DataFormatString="{0:dd MMM yyyy}")]
public object StartDate {get; set;}

//Integer Type
[Range(0,10, ErrorMessage="Please enter valid quantity between 1-10")]
public object Quantity {get; set;}

//Text type using 3rd Party WSYWIG control
[UIHint("TextEditorTelerik")]
public object Description {get; set;}

//Blob - image type
[UIHint("DbImage")]
[ImageFormat(200,200)]
public object Picture {get; set;}
}



UIHint is where you define your template.


You can create whatever for your template name and just put "_Edit" for edit mode.


Just see the sample in under FieldTemplates of your Dynamic Data Project



Singleton Confusion

I heard some developers asked about this question "If you can create a static class, Why do we need to create a Singleton Class ?"

I think the answer is straight forward.

Singleton Pattern is a pattern that will make sure there is only 1 instance. on the other hand It will make sure that developers will not be able to another instance.

Static Class will share your instance through your application. But this static class will not make sure that it will only be 1 instance of your class. Other developer which don't know where you put your static instance will able to create the new instance... and It will be any duplication and waste of resources.

Here is very simple Singleton pattern.

public class MySingleton
{
//Your exclusive instance
private static MySingleton _Instance;

//this will make sure no one can create an instance of this class.
private SampleSingleton(){}

//this static constructor will be the only who can create an instance of this class
static MySingleton()
{
//TODO: you may preinit / validation code before create an instance
_Instance = new MySingleton();
}

public static MySingleton Instance
{
get{ return _Instance;}
}
}

Wednesday, May 14, 2008

Increase AJAX Performance by using Composite Script

As you can see in Web Developer tool, there is a lot of request happening on the background.

The first thing you need to do before combining Ajax scripts, You need to know what scripts are being used by your pages.

Add this on your pages to detect what scripts are being used.

<microsoft:ScriptReferenceProfiler runat="server"/>



After that Copy all the Script References which is written by Script Reference Profiler.



And Paste it into Script Manager Composite Scripts.




<asp:ScriptManager runat="server">
<CompositeScript>
<!-- Paste Here -->
<asp:ScriptReference name="~/Scripts/MyCustomScripts.js"/>
<asp:ScriptReference name="MicrosoftAjax.js"/>
<asp:ScriptReference name="MicrosoftAjaxWebForms.js"/>
....
....
<!-- -->
</CompositeScript>
</asp:ScriptManager>



And as a results you can decrease the number of request and traffic for this scripts.

PS: The ScriptReferenceProfiler control is not part of the Beta installation, and you must install it separately. Download this http://www.codeplex.com/Release/ProjectReleases.aspx?ProjectName=aspnet&ReleaseId=13356.

Wednesday, May 7, 2008

Bug Fix For Unknown Runtime Error for Gridview inside Update panel

 

image

If we use CSS Friendly,
This happen if I put GridView Under Update Panel without table.

But finally I found that in my master page there is this strange tag.
<a name="body" />

After remove this, Everything works fine.
Here is the reference.
http://damianpedwards.spaces.live.com/blog/cns!A079DE667E1958B3!562.entry

The most explanation that I found so far is this
=====From Lewis =====
http://cyrilgupta.com/wp/?p=110
I found that this error is caused by having a a html ‘form’ element somewhere inside the postback html.
After taking out the form tags (and any asp.net controls generating them) from the updatePanel’s contentTemplate, the error went away.
=====================

However , I still don't understand If I put your GridView outside update panel and keep EnableSortingAndPagingCallbacks="True"


When I click on Paging and Sorting, It throw error Microsoft JScript runtime error: 'panelElement' is null or not an object.
image

I think this is cause by CSS Friendly, because If I take the CSS Friendly out for GridView, It works fine
Any comment ?

Tuesday, May 6, 2008

LINQ to SQL Debugging

There are several ways to debug your Linq to sql

  • Sql Server Profiler
    But How about if you share your Sql Server with others such as staging DB ?
    It will be nightmare.
  • DataContext Command
    Console.WriteLine(ctx.GetCommand(prods).CommandText);
    But How about if you don't want to write any debug code ?
  • LINQ to SQL Debug Visualizer
    I think this is the best way to debug your LINQ to SQL.
    You can use .NET Debugging Mode

    And Click small magnifying glass in the expression above, It will launch the LINQ to SQL debug visualizer to inspect the raw SQL that the ORM will execute based on that LINQ query:

Click "Execute" button, you can even test out the SQL query and see the raw returned results that will be returned from the database:

Installing SQL debug Visualizer :

  1. Download Linq to Sql Debug Visualizer http://www.scottgu.com/blogposts/linqquery/SqlServerQueryVisualizer.zip - (From Scott Gu Blog)
  2. Copy from \SqlServerQueryVisualizer\bin\Debug\SqlServerQueryVisualizer.dll
    image
  3. Copy to C:\Program Files\Microsoft Visual Studio 9.0\Common7\Packages\Debugger\Visualizers
    image

You may start debug your LINQ...

Tuesday, April 29, 2008

Custom CSS for Calendar Extender (AJAX Control Toolkit)

You may specify your custom CSS for your calendar in your application.

Just put copy this style and change your custom style

For general Calendar

.ajax__calendar_container {padding:4px;position:absolute;cursor:default;width:170px;font-size:11px;text-align:center;font-family:tahoma,verdana,helvetica;}
.ajax__calendar_body {height:139px;width:170px;position:relative;overflow:hidden;margin:auto;}
.ajax__calendar_days, .ajax__calendar_months, .ajax__calendar_years {top:0px;left:0px;height:139px;width:170px;position:absolute;text-align:center;margin:auto;}
.ajax__calendar_container TABLE {font-size:11px;}
.ajax__calendar_header {height:20px;width:100%;}
.ajax__calendar_prev {cursor:pointer;width:15px;height:15px;float:left;background-repeat:no-repeat;background-position:50% 50%;background-image:url(<%=WebResource("AjaxControlToolkit.Calendar.arrow-left.gif")%>);}
.ajax__calendar_next {cursor:pointer;width:15px;height:15px;float:right;background-repeat:no-repeat;background-position:50% 50%;background-image:url(<%=WebResource("AjaxControlToolkit.Calendar.arrow-right.gif")%>);}
.ajax__calendar_title {cursor:pointer;font-weight:bold;}
.ajax__calendar_footer {height:15px;}
.ajax__calendar_today {cursor:pointer;padding-top:3px;}
.ajax__calendar_dayname {height:17px;width:17px;text-align:right;padding:0 2px;}
.ajax__calendar_day {height:17px;width:18px;text-align:right;padding:0 2px;cursor:pointer;}
.ajax__calendar_month {height:44px;width:40px;text-align:center;cursor:pointer;overflow:hidden;}
.ajax__calendar_year {height:44px;width:40px;text-align:center;cursor:pointer;overflow:hidden;}

.ajax__calendar .ajax__calendar_container {border:1px solid #646464;background-color:#ffffff;color:#000000;}
.ajax__calendar .ajax__calendar_footer {border-top:1px solid #f5f5f5;}
.ajax__calendar .ajax__calendar_dayname {border-bottom:1px solid #f5f5f5;}
.ajax__calendar .ajax__calendar_day {border:1px solid #ffffff;}
.ajax__calendar .ajax__calendar_month {border:1px solid #ffffff;}
.ajax__calendar .ajax__calendar_year {border:1px solid #ffffff;}

.ajax__calendar .ajax__calendar_active .ajax__calendar_day {background-color:#edf9ff;border-color:#0066cc;color:#0066cc;}
.ajax__calendar .ajax__calendar_active .ajax__calendar_month {background-color:#edf9ff;border-color:#0066cc;color:#0066cc;}
.ajax__calendar .ajax__calendar_active .ajax__calendar_year {background-color:#edf9ff;border-color:#0066cc;color:#0066cc;}

.ajax__calendar .ajax__calendar_other .ajax__calendar_day {background-color:#ffffff;border-color:#ffffff;color:#646464;}
.ajax__calendar .ajax__calendar_other .ajax__calendar_year {background-color:#ffffff;border-color:#ffffff;color:#646464;}

.ajax__calendar .ajax__calendar_hover .ajax__calendar_day {background-color:#edf9ff;border-color:#daf2fc;color:#0066cc;}
.ajax__calendar .ajax__calendar_hover .ajax__calendar_month {background-color:#edf9ff;border-color:#daf2fc;color:#0066cc;}
.ajax__calendar .ajax__calendar_hover .ajax__calendar_year {background-color:#edf9ff;border-color:#daf2fc;color:#0066cc;}

.ajax__calendar .ajax__calendar_hover .ajax__calendar_title {color:#0066cc;}
.ajax__calendar .ajax__calendar_hover .ajax__calendar_today {color:#0066cc;}



If you specify your CSS Class in calendar Extender, you may use this.




        <ajaxToolkit:CalendarExtender ID="customCalendarExtender" runat="server" TargetControlID="Date2"
CssClass="MyCalendar" Format="MMMM d, yyyy" SelectedDate="April 28, 1906" PopupPosition="Left"/>







.MyCalendar .ajax__calendar_container {
border:1px solid #646464;
background-color: lemonchiffon;
color: red;
}
.MyCalendar .ajax__calendar_other .ajax__calendar_day,
.MyCalendar .ajax__calendar_other .ajax__calendar_year {
color: black;
}
.MyCalendar .ajax__calendar_hover .ajax__calendar_day,
.MyCalendar .ajax__calendar_hover .ajax__calendar_month,
.MyCalendar .ajax__calendar_hover .ajax__calendar_year {
color: black;
}
.MyCalendar .ajax__calendar_active .ajax__calendar_day,
.MyCalendar .ajax__calendar_active .ajax__calendar_month,
.MyCalendar .ajax__calendar_active .ajax__calendar_year {
color: black;
font-weight:bold;
}

Multiple IE

Running Multiple IE in your desktop is very useful for web tester.
Download Multiple IE installer (10.3MB)

setup pic1

setup pic2

Monday, April 28, 2008

MVP Pattern in ASP.Net

why we need to use MVP ?

No Code Reuse - Each view (page/control) must create an instance of a specific presenter in order to invoke the presenter's methods. That's four or five lines of code per page/control; quite a bit of work if you have hundreds of pages and controls in your site. Code can and should be centralized.
Presenter Creation - Presenters operate on a specific type of interface. Generally speaking, there's a one-to-one relationship between presenters and interfaces. This problem relates to the "no code reuse" point, and leads to inconsistent public-facing functionality exposed by various presenters. Object creation should be standardized.
View Intelligence – Using the MVP pattern forces a view to know as much about its presenter (methods, properties etc…) as the presenter knows about its view. The use of interfaces prevents a circular reference, but there should still be further decoupling of the view. One area I may disagree with Bill is that views should also not know what data layer type (or DAO interface type) to pass to a presenter. I'm of the opinion that the view's shouldn't have a reference to any data layer (i.e. anything upstream of the presenters).
State Management – This one is a biggie. Many of the people posting on MVP are quick to point out that (very simple) MPV examples remove the ability for ASP.NET to use session and caching. How do you access context-specific information if presenters can't have a reference to anything downstream (i.e. System.Web or System.Windows.Forms)? The presentation layer should provide a way to maintain application state.

======================

Here is a basic Contact Us Web Form that we'll build with the MVP Pattern.

The first step of MVP is to create a contract. We're going to use a .Net Interface for that. Create a file called IContactUs.cs and use this code. This is our VIEW in the MVP.

public interface IReaderContactUs
{
string Name { get; }
string Email { get; }
string PhoneNumber { get; }
string Message { get; }
string Result { set; }
}



The interface is like a blue print to a house. No implementation, just directions. This interface says that we have to be able to "GET" Name, Email, PhoneNumber, and Message. And that we have to be able to "SET" a Result string.



Next we need a Presenter. The presenter is the worker bee. The presenter actually does the work. Interestingly, the Presenter knows **NOTHING** about the UX. Repeat **NOTHING**. The presenter is usually in a different class library, and only referenced from the UX code. In order to enforce out contract (the .net interface we just created) we want to only be able to create a presenter, with an instance of the Interface. To do this, notice that our only constructor takes a single param that is the interface. Here is the code for our presenter; named ContactUsPresenter.cs



public class ContactUsPresenter
{
private readonly IReaderContactUs view;

public ContactUsPresenter(IReaderContactUs view)
{
this.view = view;
}

public void ProcessForm()
{
//do something - save it, send it, process it
//in this case, just modify the UI, so we
//know it's running.
//This is where you would normally make a call into the model


        StringBuilder sb = new StringBuilder();
sb.Append(string.Format("Name : {0}<br />", view.Name));
sb.Append(string.Format("Email : {0}<br />", view.Email));
sb.Append(string.Format("Phone : {0}<br />", view.PhoneNumber));
sb.Append(string.Format("Message : {0}<br />", view.Message));
view.Result = string.Format("<h1>Success</h1>{0}<hr />", sb);
}
}


Finally we get to the code behind of our Web Form. Our web form Implements the Interface. All this means is that our web form has to be able to "GET" Name, Email, PhoneNumber, and Message. And that we have to be able to "SET" a Result string. Notice the appropriate Get / Set routines that wrap around the asp.net server controls.



Notice that we have a private ContactUsPresenter, that doesn't get instantiated until the OnInit event. This is because we have to send in an instance of the interface, which is the this keyword. Then when the button is clicked, the presenter.ProcessForm(); is called to do the work.



public partial class ContactUs : UserControl, IReaderContactUs
{
private ContactUsPresenter presenter;

public string Name { get { return NameTextBox.Text; } }
public string Email { get { return EmailTextBox.Text; } }
public string PhoneNumber { get { return PhoneTextBox.Text; } }
public string Message { get { return MessageTextBox.Text; } }
public string Result { set { ResultLabel.Text = value; } }

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
presenter = new ContactUsPresenter(this);
}

protected void Page_Load(object sender, EventArgs e)
{
}

protected void SubmitContactButton_Click(object sender, EventArgs e)
{
presenter.ProcessForm();
}
}



=========

You may need to check out MVP Pattern in Web Client Software Factory as well. This will give you a complete guidance to implement MVP Pattern in your web application




http://www.codeplex.com/websf/Wiki/View.aspx?title=MVP_landing_page&referringTitle=bundles

Wednesday, March 26, 2008

Object Dock

Hi... I just find cool ... desktop tool... they called object dock. http://www.stardock.com/products/objectdock/

image

Sunday, March 23, 2008

getYear() Javascript function in Firefox, IE, Safari

Today, I just fix very common bug which only happened in Firefox and Safari.
The problem is very simple, when javascript called getYear() - it returns 108 in Firefox instead of 2008 in IE.

To resolve this , I just change getYear() into getFullYear() - it will return 2008 for all.
So.. Never use getYear() anymore... -)

Thursday, March 20, 2008

Safari Runs Under Windows

Today, I just get an Apple's update and It downloads Safari which is runs under my windows. 
If you don't have Apple's - Click this Link http://www.apple.com/safari/download/

and It past ACID 2





Monday, March 17, 2008

Manage CSS in VS 2008

VS 2008 supports a new tool window inside the IDE called "Manage Styles".  This shows all of the CSS stylesheets, and their corresponding rules, for the page you are currently editing.  It can be used both when you are in design-view, as well as when you are in source view on a page.

Click View > Manage Styles

clip_image001[5]

A circle around a CSS rule in the manage styles window indicates that particular rule is in use within the current document.  Using the mouse to hover over the rule allows you to quickly see the CSS rule values:

clip_image002

The tool window provides top level nodes for style block(s) in the current page and external style sheet in cascading order.  Inline styles will not be displayed in this window, since inline styles are not “manageable”. Tool window will also list the @import directives.

The icons are used to differentiate the various types of styles as shown below.

clip_image003Elements

clip_image004Classes

clip_image005IDs

clip_image006Style in use (color applies as above)

You can then either right-click on a CSS rule and select "Modify Style" to bring up a graphical CSS rules editor, or you can double click on the rule in the manage styles window to automatically open the stylesheet file and jump immediately to the CSS source definition to edit (with full intellisense):

clip_image007

Click View > CSS Properties

One of the other cool new CSS features that is also supported in both design and source view is the new CSS Properties Window:

clip_image008

You can click on the individual values to see where in the CSS precedence hierarchy this value was inherited from or overridden.  In the example below you can see that the final color for the current element that my cursor is on is a dark brown color.  If I select this final color value, the CSS properties window will draw a blue box in the applied-rules list above indicating that this setting is set in the "singlecontent h3" rule:

clip_image009

If you click on the lighter brown color setting that this rule overrode (and which has the red strike-thru), you can see that it originated with the page's HTML body CSS rule (notice how the body rule below is selected in the applied rules list when you select the overridden value below):

clip_image010

Friday, March 14, 2008

Shelving your code in TFS

 

TFS allows you to set aside pending changes in your TFS workspace if you want to work on something else for awhile, or if you want another coder to review your changes before you commit them, or if you want to pass off files you've been working on to another team member. When you create a shelveset TFS saves the items along with any associated Work Items or Check-in Notes to a separate repository, though not the source control repository itself.

Shelving a set of pending changes

  1. In the Pending Changes view, click the down arrow icon and select Shelve.

  2. In the Shelve - Source Files dialog box, type a name for your shelveset, any comments to help you remember the set, and, if necessary, deselect any file(s) you do not want to include in the shelveset. You can also associate a Work Item with your shelveset. For more information, see Associating Work Items with Changesets and Shelvesets.

Finding and Unshelving a set of pending changes

  1. In the Pending Changes view, select the down arrow icon and click Unshelve.

  2. In the Unshelve dialog type the name of any team member with a TFS workspace and click Find to retrieve a list of that team member's shelvesets. In the example below we are retrieving one of our own shelvesets, and selecting the one we created above. Click Unshelve.

     

Viewing Shelveset Details

To view details of a saved shelveset:

  1. In the Unshelve dialog, after you have completed your search (Steps 1 -2 above), right-click a shelveset from the list and select Details.

  2. In the Shelveset Details dialog, right-click a file and select from the popup menu. By selecting View, the shelved file opens in your Eclipse editor window where you can examine it before unshelving it. You also have the option to use the compare editor. For more information on this option, see Comparing versions .

Thursday, February 28, 2008

File Upload AJAX V 1.2

As you know that ASP.Net File Upload control can not be placed in multi view. If you put your file upload inside the multi view. You will lost your content when the multi view change the active view.

But the good news is there is Open source control called File Upload Ajax which in V1.2 can be placed inside Wizard, Multi View, invisible Panels, hidden divs, etc.

Download the control @ http://www.codeplex.com/fileuploadajax/Release/ProjectReleases.aspx?ReleaseId=8061

And try this.

  1. Add your FUA in your project
  2. Register in your page or in web.config
  3. <%@ Register Assembly="FUA" Namespace="Subgurim.Controles" TagPrefix="cc1" %>



  4. Add your Update panel, Multiview and file upload



  5. <asp:UpdatePanel ID="up" runat="server">
    <ContentTemplate>
    <asp:MultiView ID="multiPages" runat="server" ActiveViewIndex="0">
    <asp:View ID="v1" runat="server">
    </asp:View>
    <asp:View ID="v2" runat="server">
    upload:
    <cc1:FileUploaderAJAX ID="FileUploaderAJAX1" runat="server" MaxFiles="1" Directory_CreateIfNotExists="true" File_RenameIfAlreadyExists="true"/>
    </asp:View>
    </asp:MultiView>
    </ContentTemplate>
    </asp:UpdatePanel>



  6. Add Code behind code



  7. protected void Page_Load(object sender, EventArgs e)
    {
    if (FileUploaderAJAX1.IsPosting)
    {
    HttpPostedFileAJAX pf = FileUploaderAJAX1.PostedFile;
    FileUploaderAJAX1.SaveAs("~/upload", pf.FileName);
    }
    }


Tuesday, February 26, 2008

Put ConfigSections on the top

Today, I just find the problem why my code can not detect my custom config sections. because I put config sections after <AppSettings> -)

Use Ctrl + . to Resolve in VS2008

Use Ctrl + . when you notice red underscore to Select a Resolve solution for you

Wednesday, February 20, 2008

Live Writer for Coder

These are plugins which will help me to write better content 

  • CodeSnippetSetup.msi - Wrap your code into a container
  • vspaste.msi - Copy paste from Visual studio
public static class HelloClass
{
public static void HelloWorld()
{
//Hi I just found this plugin makes our live easier for writing a blog...
}
}

Wednesday, February 13, 2008

Improve your AJAX Performance

Just quick note what I just got this morning from RDN with Damian.

  1. Disable compilation debug mode into false compilation debug="false"
    - This will decrease the javascript code downloaded from ajax frameworks

  2. If you don't use update panel, just using control toolkit,
    disable partial rendering on Script Manager
    EnablePartialRendering="false"
    - This improve the process for common postback, without checking update panel

  3. Try to saperate update panel as small as possible and put UpdateMode="Conditional".
    this will not send back other update panel content on partial rendering.
    By Default it sets to Always means it will send the content even not rendered.

  4. For using Not friendly AJAX control such as Telerik, Reporting Services Viewer which can not use update panel to do partial postback.
    You may put it into partial postback but add an attribute in Update Panel ChildrenAsTriggers="false". This will perform partial postback but not update your panel.

    so to update another panel you can do manually __doPostback(%= ID%, ...) or just handle it in the control.

    The ChildrenAsTriggers property determines whether postbacks from a child ontrol in an UpdatePanel result in its contents being refreshed. By default, this property is set to True and can be set to False only when the UpdateMode is set to conditional. Attempting to do so without this condition results in an InvalidOperationException being thrown by the ScriptManager during the page’s PreRender event.

  5. In my experience I also turn off EnableViewState and It works fine, but I don't know if this improve the performance

And Don't forget to use Web Development Helper for IE , but before that you may need to install IE Developer tool
http://msmvps.com/blogs/paulomorgado/archive/2007/02/18/developer-tools-for-internet-explorer.aspx