Angular.js compile document to tree struction

the first step of angular.js is to compile document to element and childnode. this struction is similar with DOM.

module is key concept of angular.js. what is angular.js module.
A module is a collection of services, directives, controllers, filters, and configuration information.

for example:

1
var element = $compile('<p>{{total}}</p>')(scope);

it calls compile(…) function to find ‘ng-module’, ‘ng-controller’, something like ‘ng-xxxx’ and so on.

shortly, this steps compile html to tree, and Addmodule to lists, AddDirectives to directives lists.

this is critical steps of beginning. I will add more example and code to explain.

Posted in Angular.js | Comments Off on Angular.js compile document to tree struction

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