Angular.js – angularInit(..) and forEach

This is first post about Angular.js source code analysis.

Angular.js start with following code.

1
2
3
4
5
  bindJQuery();
  publishExternalAPI(angular);
  jqLite(document).ready(function() {
    angularInit(document, bootstrap);
  });

Before it starts, it will go though some interesting code.

Angular.js forEach.

what it to do is assigning value to array.

1
2
3
forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  BOOLEAN_ATTR[lowercase(value)] = value;
});

forEach function is to loop through the list of object.
and “Call” anonymous function.

1
2
3
4
5
 function forEach(obj, iterator, context) {
     for(...){
          iterator.call(context,obj[key],key,obj);
     }
 }

The following code is example of function call.

You will see output value is 2 and 3.

It will ignore 1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 <html>
  <head>
    <script language="javascript">
      function displayDate(iterator){
        iterator.call(1,2,3,4);
      }
 
      displayDate(function(value,key){
        console.log(value);
        console.log(key);
      });
    </script>
  </head>
  <h1>forEach Test</h1>
 
  <p id = "demo"> This is a paragraph.</p>
  <button type="button" onclick="displayDate()">Display Date</button>
 
  <body>
  </body>
</html>
Posted in Angular.js | Comments Off on Angular.js – angularInit(..) and forEach

Umbraco – WriteLock and ReadLock with ReaderWriterLockSlim

this post is to clear how to use WriteLock and ReadLock to make sure critical resources have been visited properly.

Take the following code for example in “public abstract class ResolverBase : ResolverBase where TResolver : ResolverBase”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public static TResolver Current
{
  get
    {
      using (new ReadLock(ResolversLock))
        {
          if (_resolver == null)
            throw new InvalidOperationException(string.Format("Current has not been initialized on {0}. You must initialize Current before trying to read it.",
                                                              typeof(TResolver).FullName));
          return _resolver;
        }
    }
 
  set
    {
      using (Resolution.Configuration)
        using (new WriteLock(ResolversLock))
        {
          if (value == null)
            throw new ArgumentNullException("value");
          if (_resolver != null)
            throw new InvalidOperationException(string.Format("Current has already been initialized on {0}. It is not possible to re-initialize Current once it has been initialized.",
                                                              typeof(TResolver).FullName));
          _resolver = value;
        }
    }
}

//The lock for the singleton.
static readonly ReaderWriterLockSlim ResolversLock = new ReaderWriterLockSlim();
“new WriteLock(ResolversLock)” is called, “ResolversLock” will be referenced by _rwLock. WriteLock constructor will enter lock automatically by “_rwLock.EnterWriteLock();”

when it disposed by calling IDisposable.Dispose(), invoking “_rwLock.ExitWriteLock();” to exit WriteLock.

“new ReadLock(ResolversLock)” is called, “ResolversLock” will be referenced by _rwLock. ReadLock constructor will enter lock automatically and exit readlock when disposed.

Posted in Umbraco | Comments Off on Umbraco – WriteLock and ReadLock with ReaderWriterLockSlim

Umbraco – start of source code analysis with Logging System

This is first article about umbraco’s source code analysis.
umbraco is big project using Asp.net MVC with 3338 cs file and lots of javascript/css/html.
Normally it is bigger than enterprise project and it will take long time to analysis it as well.

The first part is logging module of umbraco.

logging config is located at “umbraco.web.UI” project in “config\log4net.config”.
and core class is in “umbraco.core” project in “Logging\Loggger.cs”. lots of logger are located at “Logging” folder by the way.

A log4net.config which C# developer is very familiar with.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version="1.0"?>
<log4net>
  <root>
    <priority value="Debug"/>
    <appender-ref ref="AsynchronousLog4NetAppender" />
  </root>
  <appender name="rollingFile" type="log4net.Appender.RollingFileAppender">
	  <file type="log4net.Util.PatternString" value="App_Data\Logs\UmbracoTraceLog.%property{log4net:HostName}.txt" />
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <appendToFile value="true" />
    <rollingStyle value="Date" />
    <maximumFileSize value="5MB" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value=" %date [P%property{processId}/D%property{appDomainId}/T%thread] %-5level %logger - %message%newline" />
    </layout>
    <encoding value="utf-8" />
  </appender>
  <appender name="AsynchronousLog4NetAppender" type="Umbraco.Core.Logging.ParallelForwardingAppender,Umbraco.Core">
    <appender-ref ref="rollingFile" />
  </appender>
  <!--Here you can change the way logging works for certain namespaces  -->
  <logger name="NHibernate">
    <level value="WARN" />
  </logger>
</log4net>

I will add some comment on this log4net config xml as well later.

The call stack are following

at Umbraco.Core.CoreBootManager.InitializeLoggerResolver()
at Umbraco.Core.CoreBootManager.Initialize()
at Umbraco.Web.WebBootManager.Initialize()
at Umbraco.Core.UmbracoApplicationBase.StartApplication(Object sender, EventArgs e)

InitializeLoggerResolver() source code is:

1
2
3
4
5
6
7
8
9
        protected virtual void InitializeLoggerResolver()
        {
            LoggerResolver.Current = new LoggerResolver(ProfilingLogger == null ? Logger.CreateWithDefaultLog4NetConfiguration() : ProfilingLogger.Logger)
            {
                //This is another special resolver that needs to be resolvable before resolution is frozen
                //since it is used for profiling the application startup
                CanResolveBeforeFrozen = true
            };
        }

the key to init log4.net object and read configuration is:

1
     Logger.CreateWithDefaultLog4NetConfiguration()

After LoggerResolver has been initialized, it will be added into collection inside ResolverCollection using “ResolverCollection.Add”.

the Resolver adding is another topic. it has to call WriteLock, ReaderLock to add Resolver in thread-safe.
More information will be add to next topic.

Posted in Umbraco | Comments Off on Umbraco – start of source code analysis with Logging System

Pet Shop 4.0 – Abstract Factory Pattern

This is the last article about Pet Shop 4.0 source code. some other code such as singleton pattern will be too simple to explain.

When BLL Layer to get data from database, Pet Shop 4.0 uses “Abstract factory pattern”.
This pattern is classic in nowaday development and It is right example in real project.

1
2
3
     Category category = new Category();
     // Category from PetShop.BLL.
     // Check following code.  It has "dal" factory, which is created by DataAccess Object.
1
2
3
4
5
6
7
namespace PetShop.BLL {
 
    public class Category {
 
        private static readonly ICategory dal = PetShop.DALFactory.DataAccess.CreateCategory();
    }
}

DataAccess Loads DLL and creates new class Category in namespace “PetShop.SQLServerDAL”.
Now “dal” inside class “PetShop.BLL.Category” point to “PetShop.SQLServerDAL.Category”
Any Interface Method “dal” calls will be executed by “PetShop.SQLServerDAL.Category”.

check the following code.

1
2
3
4
5
6
7
8
9
namespace PetShop.DALFactory {
public sealed class DataAccess {
 
	public static PetShop.IDAL.ICategory CreateCategory() {
            string className = path + ".Category";
            return (PetShop.IDAL.ICategory)Assembly.Load(path).CreateInstance(className);
        }
   }
}
1
2
3
4
5
6
7
8
9
10
namespace PetShop.SQLServerDAL {
 
    public class Category : ICategory {
 
	public IList<CategoryInfo> GetCategories() {}
 
 
	public CategoryInfo GetCategory(string categoryId) {}
    }
}
Posted in PetShop4.0 | Comments Off on Pet Shop 4.0 – Abstract Factory Pattern

Pet Shop 4.0 – BreadCrumb

BreadCrumb is very simple part in Pet Shop 4.0 source code.
“BreadCrumbControl.ascx” is main file and it is implemented in Master Template.

add following code into “class BreadCrumbControl” in “Page_Load” function.

1
2
3
4
5
     HtmlAnchor testAnchor = new HtmlAnchor();
     testAnchor.InnerText = "Test";
     testAnchor.HRef = "~/Default.aspx";
     plhControl.Controls.Add(testAnchor);
     plhControl.Controls.Add(GetDivider());

check screen dump.
The final result will be Home > Test > Birds
petshop4.0_breadcrumb

Posted in PetShop4.0 | Comments Off on Pet Shop 4.0 – BreadCrumb

PetShop 4.0 – Authentication and Login (1)

PetShop 4.0 Authentication uses ASP.net build-in User Authentication. Let’s See where User Profile is firstly.

Open PetShop 4.0 with Visual Studio. and Select Web Project
Then select menu “WebSite” -> “ASP.net Configuration”
petshop_asp.net_configuration

petshop_asp.net_configuration2

The following question is where databases to get these info?
open .net Tool firstly C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regsql.exe. double click it. Click next following wizards.
petshop-asp.net_iis

After click on “finish” button, it will create database automatically.
petshop_asp.net_database

Posted in PetShop4.0 | Comments Off on PetShop 4.0 – Authentication and Login (1)

Pet Shop 4.0 – DataBase Map to Object

Pet shop uses very simple to map database columns to objects.

Here are database’s table:
mspetshop-database

Take Production Table for example,

dbo.Production will map to ProudctionInfo in PetShop.Model.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 
            string connectionString = @"server=server-running-sqlserver;database=MSPetShop4;integrated security=SSPI;min pool size=4;max pool size=4;";
// to get this connection string , you have to decrypted connection section on web.config
//http://windows.emacslisp.com/index.php/2015/12/11/pet-shop-4-0-encrypt-webconfig-section-and-decrypt-webconfig-section-connectionstring/
 
            string productionString = @"SELECT Product.ProductId, Product.Name, Product.Descn, Product.Image, Product.CategoryId FROM Product";
            List<ProductInfo> products = new List<ProductInfo>();
            ProductInfo product = null;
 
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);
 
            if (conn.State != ConnectionState.Open)
                conn.Open();
 
            cmd.Connection = conn;
            cmd.CommandText = productionString;
 
 
            cmd.CommandType = CommandType.Text;
 
            SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            cmd.Parameters.Clear();
 
            while (rdr.Read())
            {
                product = new ProductInfo(rdr.GetString(0), rdr.GetString(1), rdr.GetString(2), rdr.GetString(3), rdr.GetString(4));
                products.Add(product);
            }
 
            foreach (ProductInfo p in products)
            {
                Console.WriteLine(p.Image);
            }
Posted in PetShop4.0 | Comments Off on Pet Shop 4.0 – DataBase Map to Object

Pet Shop 4.0 – CacheDependency and AggregateCacheDependency

CacheDependency is an important part in pet shop 4.0.

Here is some example code on how to use CacheDependency

1. create a new xml file as following:

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0"?>
<bookstore>
  <book>
    <title>ado.net tutorial</title>
    <author>wudi</author>
  </book>
  <book>
    <title>ado.net tutorial</title>
    <author>wudi</author>
  </book>
</bookstore>

2. create a new webform page running

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public partial class Index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetData();
            }
 
 
        }
 
        private void GetData()
        {
            DataTable source = new DataTable();
            if (Cache["data"] == null)
            {
                DataSet ds = new DataSet();
                ds.ReadXml(Server.MapPath("bookstore.xml"));
 
                Response.Write("<p>" + ds.Tables[0].Rows.Count + "</p>");
                source = ds.Tables[0];
                CacheDependency cdy = new CacheDependency(Server.MapPath("bookstore.xml"));
                Cache.Insert("data", source, cdy);
                if (cdy.HasChanged)
                {
                    System.Diagnostics.Debug.WriteLine("Xml Has changed!!!!");
                }
            }
            else
            {
                source = Cache["data"] as DataTable;
            }
 
            GridView1.DataSource = source;
            GridView1.DataBind();
        }

3. Try to change bookstore.xml, then you will find cache is null , then the cache will be reloaded.

Sometime, one cache may depends on multiple dependency.
The following example show one cache depends on two xml files “ProductList1.xml” and “ProductList2.xml”

1
2
3
4
5
6
7
8
9
10
CacheDependency dep1 = new CacheDependency(
 Server.MapPath("ProductList1.xml"));
CacheDependency dep2 = new CacheDependency(
 Server.MapPath("ProductList2.xml"));
// Create the aggregate.
CacheDependency[] dependencies = new CacheDependency[]{dep1, dep2};
AggregateCacheDependency aggregateDep = new AggregateCacheDependency();
aggregateDep.Add(dependencies);
// Add the dependent cache item.
Cache.Insert("ProductInfo", prodInfo, aggregateDep);
Posted in PetShop4.0 | Comments Off on Pet Shop 4.0 – CacheDependency and AggregateCacheDependency

Umbraco – How to build Umbraco

1. Download Umbraco from github

2. %path%\Umbraco-CMS-dev-v7\build

run “build.bat”

3. open %path%\src\umbraco.sln

4. build and run umbraco. It will setup database.
The database only has table without view and stored procedure.

database

Posted in Umbraco | Comments Off on Umbraco – How to build Umbraco

WCF – Ajax Calling WCF Services

This is will demo a simple example on how Ajax calling WCF Services.

see what does it look like?

Ajax_Service

1. define service data contract

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
    // Define a service contract.
    [ServiceContract(Namespace = "ConfigFreeAjaxService")]
    public interface ICalculator
    {
        [OperationContract]
        double Add(double n1, double n2);
        [OperationContract]
        double Subtract(double n1, double n2);
        [OperationContract]
        double Multiply(double n1, double n2);
        [OperationContract]
        double Divide(double n1, double n2);
    }
 
    public class CalculatorService : ICalculator
    {
 
        public double Add(double n1, double n2)
        {
            return n1 + n2;
        }
 
        public double Subtract(double n1, double n2)
        {
            return n1 - n2;
        }
 
        public double Multiply(double n1, double n2)
        {
            return n1 * n2;
        }
 
        public double Divide(double n1, double n2)
        {
            return n1 / n2;
        }
    }

2. services.svc

1
2
3
4
5
6
<%@ServiceHost 
    language="c#"
    Debug="true"
    Service="Microsoft.Ajax.Samples.CalculatorService"
    Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" 
%>

3. aspx file to call services hosting by IIS

the following javascript to call WCF data contract class and call methods:

1
2
var proxy = new  ConfigFreeAjaxService.ICalculator();
proxy.Add(parseFloat(n1), parseFloat(n2), onSuccess, onFail, null);

Here is all data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Config Free AJAX Service Client Page</title>
 
    <script type="text/javascript">
    // <![CDATA[
 
    // This function creates an asynchronous call to the service
    function makeCall(operation){
        var n1 = document.getElementById("num1").value;
        var n2 = document.getElementById("num2").value;
 
        // If user filled out these fields, call the service
        if(n1 && n2){
 
            // Instantiate a service proxy
            var proxy = new  ConfigFreeAjaxService.ICalculator();
 
            // Call correct operation on proxy       
            switch(operation){
                case "Add":
                    proxy.Add(parseFloat(n1), parseFloat(n2), onSuccess, onFail, null);            
                break;
 
                case "Subtract":
                    proxy.Subtract(parseFloat(n1), parseFloat(n2), onSuccess, onFail, null);                        
                break;
 
                case "Multiply":
                    proxy.Multiply(parseFloat(n1), parseFloat(n2), onSuccess, onFail, null);            
                break;
 
                case "Divide":
                    proxy.Divide(parseFloat(n1), parseFloat(n2), onSuccess, onFail, null);            
                break;
            }
        }
    }
 
    // This function is called when the result from the service call is received
    function onSuccess(mathResult){
        document.getElementById("result").value = mathResult;
    }
 
    // This function is called if the service call fails
    function onFail(){
        document.getElementById("result").value = "Error";
    }
    // ]]>
    </script>
</head>
<body>
    <h1>
        Config Free AJAX Service Client Page</h1>
    <p>
        First Number:
        <input type="text" id="num1" /></p>
    <p>
        Second Number:
        <input type="text" id="num2" /></p>
    <input id="btnAdd" type="button" onclick="return makeCall('Add');" value="Add" />
    <input id="btnSubtract" type="button" onclick="return makeCall('Subtract');" value="Subtract" />
    <input id="btnMultiply" type="button" onclick="return makeCall('Multiply');" value="Multiply" />
    <input id="btnDivide" type="button" onclick="return makeCall('Divide');" value="Divide" />
    <p>
        Result:
        <input type="text" id="result" /></p>
    <form id="mathForm" action="" runat="server">
    <asp:ScriptManager ID="ScriptManager" runat="server">
        <Services>
            <asp:ServiceReference Path="service.svc" />
        </Services>
    </asp:ScriptManager>
    </form>
</body>
</html>
Posted in WCF | Comments Off on WCF – Ajax Calling WCF Services