Monday, 9 July 2012

JQuery not fire Click event

Copied from  http://stackoverflow.com/questions/5540561/jquery-click-event-not-firing


8
down voteaccepted
Is this markup added to the DOM asynchronously? You will need to use live in that case:
<script>
    $(document).ready(function(){
        $('.play_navigation a').live('click', function(){
            console.log("this is the click");
            return false;
        });
    });
</script>
The fact that you are able to re-run your script block and have it work tells me that for some reason the elements weren't available at the time of binding or the binding was removed at some point. If the elements weren't there at bind-time, you will need to use live (or event delegation, preferably). Otherwise, you need to check your code for something else that would be removing the binding.
EDIT using jQuery 1.7 event delegation:
$( function () {

    $( '.play_navigation' ).on( 'click', 'a', function ( e ) {
        console.log( 'this is the click' );
        e.preventDefault();
    });
});

Thursday, 10 May 2012

SQL - Query value in XML field



  1. Query data in XML field
  2. Query data in XML field, condition on Node's Attribute
  3. Query data in XML field, condition on Node's TEXT

Example


DECLARE @Messages TABLE (
   ID INTEGER IDENTITY(1, 1),
   [Timestamp] Timestamp,
   xData xml)


SET NOCOUNT ON


INSERT @Messages(xData)
VALUES (
'<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<baseElement xmlns="https://xml.abc.net/xmlws/services/v2/"> 
     <nodeElement attribute1="0106" attribute2="0003"> 
<node1 />
<node2>NODE2</node2>
     </nodeElement>
     <nodeElement attribute1="0101" attribute2="0004" /> 
     <nodeElement attribute1="0106" attribute2="0003" /> 
     <nodeElement attribute1="0106" attribute2="0003" /> 
     <nodeElement attribute1="0101" attribute2="0005" /> 
</baseElement> 
</soap:Body>
</soap:Envelope>
')


INSERT @Messages(xData)
VALUES (
'<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<baseElement xmlns="https://xml.abc.net/xmlws/services/v2/"> 
     <nodeElement attribute1="0106" attribute2="0003"> 
<node1>I am node 1 in entry 2</node1>
<node2>I am node 2 in entry 2</node2>
     </nodeElement>
     <nodeElement attribute1="0101" attribute2="0004" />      
     <nodeElement attribute1="0106" attribute2="0004" /> 
     <nodeElement attribute1="0106" attribute2="0003" /> 
     <nodeElement attribute1="0101" attribute2="0005" /> 
</baseElement>
</soap:Body>
</soap:Envelope>
') 


INSERT @Messages(xData)
VALUES (
'<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<baseElement xmlns="https://xml.abc.net/xmlws/services/v2/">
     <nodeElement attribute1="0101" attribute2="0004" /> 
     <nodeElement attribute1="0106" attribute2="0003" /> 
     <nodeElement attribute1="0106" attribute2="0003" /> 
     <nodeElement attribute1="0106" attribute2="0003" /> 
     <nodeElement attribute1="0101" attribute2="0005" /> 
</baseElement>
</soap:Body>
</soap:Envelope>
')




;WITH XMLNAMESPACES
(
  'http://schemas.xmlsoap.org/soap/envelope/' AS soap,
  'https://xml.abc.net/xmlws/services/v2/' as hc
)


SELECT *
,xData.query('soap:Envelope/soap:Body/hc:baseElement/hc:nodeElement') as nodes
,xData.query('soap:Envelope/soap:Body/hc:baseElement/hc:nodeElement/hc:node1') as node1
FROM @Messages
-- Condition on ATTRIBUTE
WHERE xData.exist('soap:Envelope/soap:Body/hc:baseElement/hc:nodeElement[@attribute1="0106" and @attribute2="0004"]') = 1 
-- Condition on TEXT
or xData.exist('soap:Envelope/soap:Body/hc:baseElement/hc:nodeElement/hc:node2/text()[.="NODE2"]') = 1 


Sunday, 6 May 2012

IIS7 and Apache on the same machine / Apache virtual host

Scenario

- Create DNS for local php site (mysite.localhost)
- Apache is installed on the same machine with IIS7
- The "mysite.localhost" want to be hosted separately, not under apache localhost, location is not under folder htdocs.

Analyse Solution

Since IIS and Apache are on same machine, there are 2 options to configure.
    a. Configure to use difference port. By default, IIS uses port 80, Apache can be configured using any.
        But, this solution can only make 2 web servers running on same machine, cannot resolve virtual hosting problem.
    b. Point or reassign IIS to listen to a new IP address, leave the default (127.0.0.1) for Apache. This solution is perfect satisfy the requirement.

Resolve problem

1. Point / assign new IP address for IIS

(Copy from http://www.iislogs.com/steveschofield/iis7-post-44-iis7-and-apache-on-the-same-machine)
1.1) Added or make sure your machine has two ip's
1. 2) Open a command prompt
1. 3) Type netsh
1. 4) Type http
1. 5) Type sho iplisten.  It should be blank
1.6) Type add iplisten ipaddress=127.0.0.2
You should get IP address successfully added
1. 7) Type sho iplisten again
It should sho  127.0.0.2  in the list
1. 8) Type exit to get out of netsh
1. 9) Type type netstat -an.  See if you notice  127.0.0.2 in the list.  If you see 0.0.0.0:80, do an iisreset

2. Configure Apache virtual host (..\apache\conf\extra\httpd-vhosts.conf)

NameVirtualHost 127.0.0.1:80
<VirtualHost *:80>
    ServerAdmin postmaster@dummy-host.localhost
    DocumentRoot "D:/projects/mysite"
    ServerName mysite
    ServerAlias www.mysite.localhost
    ErrorLog "logs/mysite.localhost-error.log"
    CustomLog "logs/mysite.localhost-access.log" combined
</VirtualHost>

3. Configure apache (..\apache\conf\httpd.conf)

3.1) Include virtual host file

# Virtual hosts
Include "conf/extra/httpd-vhosts.conf"
3.1) Access right to the folder of "mysite" 

<Directory "D:/projects/mysite">
   Options Indexes FollowSymLinks Includes ExecCGI
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>


4. Binding "mysite" host name to IP address 127.0.0.1


C:\Windows\System32\drivers\etc\hosts

127.0.0.1 mysite
127.0.0.1 www.mysite.localhost

Thursday, 20 January 2011

Cascade dropdown list using Update Panel

1. All dropdown list must be in same update panel
2. Autopostback = "true" must be set to parent dropdown.
3.. Viewstate must be ENABLE, otherwise, SelectedIndexChanged of dropdownlist cannot be triggered.


 Tip to disable selection on second and thrid lists while first list item change
For some controls, ASP.NET already uses client-side event handling to perform automatic postback operations. The preferred way to add client-side evnet handling code for Web server controls is via the use of the Attributes property of the Web server controls. You can do that in Page_Load event where IsPostBack=False.
  protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ddlOne.Attributes.Add("Onchange", "ddlOne_Onchange();");
        }
    }

Code
<%@ Control Language="C#" AutoEventWireup="true" EnableViewState="true" CodeFile="sample.ascx.cs"
    Inherits="sample" %>
   
<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI" TagPrefix="asp" %>

<script language="javascript" type="text/javascript">   
function ddlOne_Onchange()    
    {
        $("#<%= ddlTwo.ClientID %>").attr("disabled", "disabled");
        $("#<%= ddlTwo.ClientID %>").removeAttr("selected");
        $("#<%= ddlTwo.ClientID %>").prepend('<option selected="selected" value="-1">Loading...</option>');

        $("#<%= ddlThree.ClientID %>").attr("disabled", "disabled");.
        $("#<%= ddlThree.ClientID %>").removeAttr("selected");
        $("#<%= ddlThree.ClientID %>").prepend('<option selected="selected" value="-1">Loading...</option>');
    }
 </script>
<!-- Search Box -->
<div id="SearchControlDropDowns">
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <div id="ddWrapper">
                <span class="ddTitle">Browse Holidays</span>
                <div id="ddDiv1">
                    <label class="ddLabel">
                        Select Holiday Type</label>
                    <asp:DropDownList ID="ddlOne" runat="server" AutoPostBack="true" CssClass="SearchDropDown"
                        DataTextField="DisplayText" DataValueField="Id" OnSelectedIndexChanged="ddlOne_SelectedIndexChanged" />
                </div>
                <div id="ddDiv2">
                    <label class="ddLabel">
                        Country</label>
                    <asp:DropDownList ID="ddlTwo" runat="server" AutoPostBack="true" CssClass="SearchDropDown"
                        DataTextField="DisplayText" DataValueField="Id" OnSelectedIndexChanged="ddlTwo_SelectedIndexChanged" />
                </div>
                <div id="ddDiv3">
                    <label class="ddLabel">
                        Region</label>
                    <asp:DropDownList ID="ddlThree" runat="server" CssClass="SearchDropDown"
                        DataTextField="DisplayText" DataValueField="Id"/>
                </div>
                <div id="ddDiv4">
                    <asp:ImageButton ID="btnSearch" runat="server" ImageAlign="AbsMiddle" ImageUrl="~/images/buttonFind.gif"
                        OnClientClick=" search(); return false;" CssClass="SearchDropDownButton" />
                </div>
            </div>
        </ContentTemplate>
    </asp:UpdatePanel>   
</div>

Thursday, 16 December 2010

HTML ruler

Source from http://reeddesign.co.uk/test/points-pixels.html


http://www.soft.tahionic.com/download-ruler/index.html



ReedDesign

Approximate Conversion from Points to Pixels

(and Ems and %)

Here's a chart that converts points to pixels (and ems and %). It's an approximation, which will depend on font, browser and OS, but it's a good starting point.
Points Pixels Ems Percent
6pt 8px 0.5em 50%
7pt 9px 0.55em 55%
7.5pt 10px 0.625em 62.5%
8pt 11px 0.7em 70%
9pt 12px 0.75em 75%
10pt 13px 0.8em 80%
10.5pt 14px 0.875em 87.5%
11pt 15px 0.95em 95%
12pt 16px 1em 100%
13pt 17px 1.05em 105%
13.5pt 18px 1.125em 112.5%
14pt 19px 1.2em 120%
14.5pt 20px 1.25em 125%
15pt 21px 1.3em 130%
16pt 22px 1.4em 140%
17pt 23px 1.45em 145%
18pt 24px 1.5em 150%
20pt 26px 1.6em 160%
22pt 29px 1.8em 180%
24pt 32px 2em 200%
26pt 35px 2.2em 220%
27pt 36px 2.25em 225%
28pt 37px 2.3em 230%
29pt 38px 2.35em 235%
30pt 40px 2.45em 245%
32pt 42px 2.55em 255%
34pt 45px 2.75em 275%
36pt 48px 3em 300%

Monday, 22 November 2010

Could not load file or assembly 'Name' or one of its dependencies. An attempt was made to load a program with an incorrect format.

I have seen these a few times lately and the cause is usually that you have the following configuration:
  • IIS running on a 64Bit Operating System
  • The Assembly DLL in question has been compiled for 32Bit - check the project properties under the build tab, if under platform target you have x86 then it is 32bit only.

    x86 
Why would you have a 32bit only DLL? well it could be that you are using something that is not 64bit compatible, such as MAPI or ODBC...
The real problem is that the 64Bit IIS machine is using an Application Pool that is not allowing a 32bit DLL to be processed.
Open IIS Manager and find the application pool for the site and select the Advanced Settings.
AppPoolAdvSettings

Notice that there is an option called "Enable 32-Bit Applications" this is the cause of the error. Enable this and you should be good to go.
Here is an example of the full error for this message.

Server Error in '/' Application.


Could not load file or assembly 'XMLView' or one of its dependencies. An attempt was made to load a program with an incorrect format.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.BadImageFormatException: Could not load file or assembly 'XMLView' or one of its dependencies. An attempt was made to load a program with an incorrect format.
Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Assembly Load Trace: The following information can be helpful to determine why the assembly 'XMLView' could not be loaded.

=== Pre-bind state information === LOG: User = NT AUTHORITY\NETWORK SERVICE LOG: DisplayName = XMLView (Partial) LOG: Appbase = file:///C:/dev/Projects/OSCARUtils/ LOG: Initial PrivatePath = C:\dev\Projects\OSCARUtils\bin Calling assembly : (Unknown). === LOG: This bind starts in default load context. LOG: Using application configuration file: C:\dev\Projects\OSCARUtils\web.config LOG: Using host configuration file: C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Aspnet.config LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v2.0.50727\config\machine.config. LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind). LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework64/v2.0.50727/Temporary ASP.NET Files/root/8a8c3f22/9d24bab0/XMLView.DLL. LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework64/v2.0.50727/Temporary ASP.NET Files/root/8a8c3f22/9d24bab0/XMLView/XMLView.DLL. LOG: Attempting download of new URL file:///C:/dev/Projects/OSCARUtils/bin/XMLView.DLL. ERR: Failed to complete setup of assembly (hr = 0x8007000b). Probing terminated.
Stack Trace:

[BadImageFormatException: Could not load file or assembly 'XMLView' or one of its dependencies. An attempt was made to load a program with an incorrect format.] System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) +0 System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +465 System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +181 System.Reflection.Assembly.Load(String assemblyString) +42 System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +190 [ConfigurationErrorsException: Could not load file or assembly 'XMLView' or one of its dependencies. An attempt was made to load a program with an incorrect format.] System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +3637752 System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +397 System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +155 System.Web.Configuration.AssemblyInfo.get_AssemblyInternal() +36 System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +235 System.Web.Compilation.WebDirectoryBatchCompiler..ctor(VirtualDirectory vdir) +214 System.Web.Compilation.BuildManager.BatchCompileWebDirectoryInternal(VirtualDirectory vdir, Boolean ignoreErrors) +57 System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath) +259 System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) +406 System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) +125 System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory(VirtualPath virtualPath, HttpContext context, Boolean allowCrossApp, Boolean noAssert) +203 System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp, Boolean noAssert) +52 System.Web.UI.PageHandlerFactory.GetHandlerHelper(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) +50 System.Web.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +410 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +274

Version Information: Microsoft .NET Framework Version:2.0.50727.1378; ASP.NET Version:2.0.50727.1378
posted on Monday, November 05, 2007 2:49 PM |

Wednesday, 27 October 2010

How to Make LINQ to SQL Check for Changes After Attach (or AttachAll)

dbContext.Entity.Attach(entity, true);
//submit insert or update to db
dbContext.SubmitChanges();

Problem: entity was saved, but its dependencies weren't.

Solution 1: Try to loop its dependencies and attach manually
    foreach (var child in entity.children)
   {
          dbContext.Child.Attach(child);
   
          get error at this line: An entity can only be attached as modified without original state if it declares a version member or does not have an update check policy.
   }

- Solution 1 is completely wrong to resolve the problem
Root cause of Problem: LINQ to SQL assumes that the object you are attaching is un-modified. True, there is an overloaded method "AttachAll(items, true)" that forces LINQ to view those objects as 'modified', but that method only works if your table has a TimeStamp field.

How to resolve: So, how do I tell LINQ to SQL to see if there have been changes made to already-existing entities? By using the "Refresh" method:
// Add this line before "SubmitChanges"
dataContext.Refresh(RefreshMode.KeepCurrentValues, entity);

Completed code as following
.Entity.Attach(entity, true);
dbContext.Child.InsertAllOnSubmit(entity.Children.Where(r => r.Id == 0));

dbContext.Refresh(RefreshMode.KeepCurrentValues, entity);
dbContext.Refresh(RefreshMode.KeepCurrentValues, entity.Children.Where(r => r.Id != 0));


//submit insert or update to db
dbContext.SubmitChanges();

Sunday, 10 October 2010

ASP.NET MVC

============ LESSON LEARN ========
Model: consist of business logic, data access logic
View: Markup and content that is returned to the browser
Controller: Fires off some logic and response to a browser request

MAPPING URL ROUTING
Global.asax.cs: Using <routes> table to map url and its parameters

MUST DO
1. Follow MVC framework naming convention

============ RESOURCE ===========
1. Download ASP.NET MVC 2 framework
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=c9ba1fe1-3ba8-439a-9e21-def90a8615a9&displaylang=en

2. Understanding overview of ASP.NET MVC
http://www.asp.net/mvc/videos/understanding-models-views-and-controllers

3.Five Must Have Tools for MVC Developers
http://www.codecapers.com/post/Five-Must-Have-Tools-for-MVC-Developers.aspx

Visual Studio 2008 (Some shorcut keys)

Here are some extremely helpful keyboard shortcut keys for Visual Studio 2008. You probably know most, but some you won't know. For instance, did you know that Ctrl+. is the same as Sift+Alt+F10?
Note: Some of the shortcuts won't work in all environment configurations (web, C#, etc).
To use, hold down the control key and hit the key combination. Works on the whole document, a specific line, or a selection of code.
Go to Definition (F12) Navigate to the definition of the method or variable. Super useful.
Find all References (Shift + F12)
Update References/ Add Using Statement (Ctrl +. or Shift +Alt +F10) I'm referring to the underline that appears under a variable to perform an action like add a using statement, or refacter a method or class name. Not sure what it's called but I use it all the time. Ex: ClassName
List Members (Ctrl +J or Ctrl +K, L) Displays the autocomplete list for classes, methods, or properties.
List Parameter Info (Ctrl +Shift +Space or Ctrl +K +P) Lists the parameters for a method. Use this shortcut when your cursor is inside the parenthesis of a method.
Auto Format (Ctrl +K, D or Ctrl +E, D) Formats C#, VB, ASPX, Javascript, CSS, XML, XSL, and HTML code according to generally accepted formatting standards for the respective programming language. Makes code look nice and neat.
Quick Watch (Ctrl +Alt +Q) Highlight some code and hit these shortcut keys to display the Quick Watch dialog.
Comment / Uncomment (Ctrl +K, C / Ctrl +K, U) Comments or uncomments a block of code. Works with C#, VB, ASPX.
Code Bookmarks Use these to bookmark a line of code. You can cycle through the bookmarks across any file within a project. Bookmarks come in very handy, try it out.
Set/Unset Bookmark (Ctrl +K, K) Next Bookmark (Ctrl +K, N)
Surround With (Ctrl +S) Surrounds a block of code with a code snippet.
Build & Debug Shortcuts Set/Unset Breakpoint (F9) Build (F6 or Ctrl +Shift +B) Start Debugging (F5) Start Without Debugging (Ctrl +F5) Stop Debugging (Shift +F5) Continue (F5) Step Over (F10) Step Into (F11) Step Out (Shift +F11) Attach to Process (Ctrl + Alt + P)
That's it for now, feel free to add more in the comments below. I'll try to update this post periodically.

Copy from Rob Volk's Dev Blog
http://blog.robvolk.com/2009/01/visual-studio-2008-keyboard-shortcuts.html