All posts by dotte

AngularJS Interview Questions and Answers

Contents

Angular Interview questions and answers

What is AngularJS ?

Explain Directives in Angular?

What are controllers and need of ng-controller and ng-model in Angular?

What are expressions in Angular?

How can we initialize Angular application data?

Explain $scope in Angular?

What is “$rootScope” and how is it related with “$scope”?

Do I need Jquery for Angular?

How is the data binding in Angular ?

How do we make HTTP get and post calls in Angular?

How do we pass data using HTTP POST in Angular ?

What is dependency injection and how does it work in Angular?

How does DI benefit in Angular?

What are services in Angular?

Are Service object instances global or local?

What is a Factory in Angular?

What is the difference between Factory and Service?

My other interview question articles

Angular Interview questions and answers

AngularJS is one of those hot topics which interviewer’s ask for Web programming. In this article we will run through some important Interview questions around AngularJS and how we should be go about answering the same.

Do not forget to see our Learn MVC with Angular in 2 days i.e. ( 16 hours ) video series. Start from this youtube video link. https://www.youtube.com/watch?v=Lp7nSImO5vk

What is AngularJS ?

“AngularJS is a JavaScript framework which simplifies binding JavaScript objects with HTML UI elements.”

Let us try to understand the above definition with simple sample code.

Below is a simple “Customer” function with “CustomerName” property. We have also created an object called as “Cust” which is of “Customer” class type.

function Customer() 
{
this.CustomerName = "AngularInterview";
}
var Cust = new Customer();

Now let us say the above customer object we want to bind to a HTML text box called as “TxtCustomerName”. In other words when we change something in the HTML text box the customer object should get updated and when something is changed internally in the customer object the UI should get updated.

<input type=text id="TxtCustomerName" onchange="UitoObject()"/>

So in order to achieve this communication between UI to object developers end up writing functions as shown below. “UitoObject” function takes data from UI and sets it to the object while the other function “ObjecttoUI” takes data from the object and sets it to UI.

function UitoObject() 
{
Cust.CustomerName = $("#TxtCustomerName").val();
}
function ObjecttoUi() 
{
$("#TxtCustomerName").val(Cust.CustomerName);
}

So if we analyze the above code visually it looks something as shown below. Your both functions are nothing but binding code logic which transfers data from UI to object and vice versa.

Now the same above code can be written in Angular as shown below. The javascript class is attached to a HTML parent div tag using “ng-controller” directive and the properties are binded directly to the text box using “ng-model” declarative.

So now whatever you type in the textbox updates the “Customer” object and when the “Customer” object gets updated it also updates the UI.

<div ng-controller="Customer">
<input type=text id="txtCustomerName"  ng-model="CustomerName"/>
</div>

In short if you now analyze the above code visually you end up with something as shown in the below figure.You have the VIEW which is in HTML, your MODEL objects which are javascript functions and the binding code in Angular.

Now that binding code have different vocabularies.

  • Some developers called it “ViewModel” because it connects the “Model” and the “View” .
  • Some call it “Presenter” because this logic is nothing but presentation logic.
  • Some term it has “Controller” because it controls how the view and the model will communicate.

To avoid this vocabulary confusion Angular team has termed this code as “Whatever”. It’s that “Whatever” code which binds the UI and the Model. That’s why you will hear lot of developers saying Angular implements “MVW” architecture.

Explain Directives in Angular?

Directives are attributes decorated on the HTML elements. All directives start with the word “ng”. As the name says directive it directs Angular what to do.

For example below is a simple “ng-model” directive which tells angular that the HTML textbox “txtCustomerName” has to be binded with the “CustomerName” property.

<input type=text id="txtCustomerName"  ng-model="CustomerName"/>

Some of the most commonly used directives are ng-app,ng-controller and ng-repeat.

What are controllers and need of ng-controller and ng-model in Angular?

“Controllers” are simple javascript function which provides data and logic to HTML UI. As the name says controller they control how data flows from the server to HTML UI.

For example below is simple “Customer” controller which provides data via “CustomerName” and “CustomerCode” property and Add/ Update logic to save the data to database.

Note: – Do not worry too much about the $scope , we will discuss the same in the next question.
function Customer($scope)
{
        $scope.CustomerName = "Shiv";
        $scope.CustomerCode = "1001";
        $scope.Add = function () {
        }
        $scope.Update = function () {
        }
}

“ng-controller” is a directive.Controllers are attached to the HTML UI by using the “ng-controller” directive tag and the properties of the controller are attached by using “ng-model” directive. For example below is a simple HTML UI which is attached to the “Customer” controller via the “ng-controller” directive and the properties are binded using “ng-model” directive.

<div ng-controller="Customer">
<input type=text id="CustomerName"  ng-model="CustomerName"/><br />
<input type=text id="CustomerCode"  ng-model="CustomerCode"/>
</div>

What are expressions in Angular?

Angular expressionsare unit of code which resolves to value. This code is written inside curly braces “{“.

Below are some examples of angular expressions:-

The below expression adds two constant values.

{{1+1}}

The below expression multiplies quantity and cost to get the total value.

The value total cost is {{ quantity * cost }}

The below expression displays a controller scoped variable.

<div ng-controller="CustomerVM">
The value of Customer code is {{CustomerCode}} 
</div>
The value of Customer code is {{CustomerCode}}

How can we initialize Angular application data?

We can use “ng-init” directive to achieve the same. You can see in the below example we have used “ng-init” directive to initialize the “pi” value.

<body ng-app="myApp" ng-init="pi=3.14">
The value of pi is {{pi}}
</body>

Explain $scope in Angular?

“$scope” is an object instance of a controller. “$scope” object instance get’s created when “ng-controller” directive is encountered.

For example in the below code snippet we have two controllers “Function1” and “Function2”. In both the controllers we have a “ControllerName” variable.

function Function1($scope)
{
$scope.ControllerName = "Function1";        
}
function Function2($scope)
{
$scope.ControllerName = "Function2";
}

Now to attach the above controllers to HTML UI we need to use “ng-controller” directive. For instance you can see in the below code snippet how “ng-controller” directive attaches “function1” with “div1” tag and “function2” with “div2” tag.

<div id=&rdquo;div1&rdquo; ng-controller="Function1">
Instance of {{ControllerName}} created 
</div>
<div id=&rdquo;div2&rdquo; ng-controller="Function2">
Instance of {{ControllerName}} created 
</div>

So this is what happens internally. Once the HTML DOM is created Angular parser starts running on the DOM and following are the sequence of events:-

  • The parser first finds “ng-controller” directive which is pointing to “Function1”. He creates a new instance of “$scope” object and connects to the “div1” UI.
  • The parser then starts moving ahead and encounters one more “ng-controller” directive which is pointing to “Function2”. He creates a new instance of “$scope” object and connects to the “div2” UI.

Now once the instances are created, below is a graphical representation of the same. So the “DIV1” HTML UI is binded with “function1” $scope instance and the “DIV2” HTML UI is binded with “function2” $scope instance. In other words now anything changes in the $scope object the UI will be updated and any change in the UI will update the respective $scope object.

What is “$rootScope” and how is it related with “$scope”?

“$rootScope” is a parent object of all “$scope” angular objects created in a web page.

Let us understand how Angular does the same internally. Below is a simple Angular code which has multiple “DIV” tags and every tag is attached to a controller. So let us understand step by step how angular will parse this and how the “$rootScope” and “$scope” hierarchy is created.

The Browser first loads the above HTML page and creates a DOM (Document object model) and Angular runs over the DOM.Below are the steps how Angular creates the rootscope and scope objects.

  • Step 1:- Angular parser first encounters the “ng-app” directive and creates a “$rootScope” object in memory.
  • Step 2:- Angular parser moves ahead and finds the expression {{SomeValue}}. It creates a variable
  • Step 3:- Parser then finds the first “DIV” tag with “ng-controller” directive which is pointing to “Function1” controller. Looking at the “ng-controller” directive it creates a “$scope” object instance for “Function1” controller. This object it then attaches to “$rootScope” object.
  • Step 4:- Step 3 is then repeated by the parser every time it finds a “ng-controller” directive tag. Step 5 and Step 6 is the repetition of Step 3.

If you want to test the above fundamentals you can run the below sample Angular code. In the below sample code we have created controllers “Function1” and “Function2”. We have two counter variables one at the root scope level and other at the local controller level.

<script language="javascript">
function Function1($scope, $rootScope) 
{
        $rootScope.Counter = (($rootScope.Counter || 0) + 1);
        $scope.Counter = $rootScope.Counter;
        $scope.ControllerName = "Function1";
}
function Function2($scope, $rootScope) 
{
        $rootScope.Counter = (($rootScope.Counter || 0) + 1);
        $scope.ControllerName = "Function2";
}
    var app = angular.module("myApp", []); // creating a APP     app.controller("Function1", Function1); // Registering the VM     app.controller("Function2", Function2);

</script>

Below is the HTML code for the same. You can we have attached “Function1” and “Function2” two times with “ng-controller” which means four instances will be created.

<body ng-app="myApp" id=1>
   Global value is {{Counter}}<br />
<div ng-controller="Function1">
       Child Instance of {{ControllerName}} created :- {{Counter}}
</div><br />
<div ng-controller="Function2">
       Child Instance of {{ControllerName}} created :- {{Counter}}
</div><br />
<div ng-controller="Function1">
        Child Instance of {{ControllerName}} created :- {{Counter}}
</div><br />
<div ng-controller="Function2">
        Child Instance of {{ControllerName}} created :- {{Counter}}
</div><br />
</body>

Above is the output of the code you can see the global variable of root scope has be incremented four times because four instances of $scope have been created inside “$rootScope” object.

Do I need Jquery for Angular?

No , you do not need Jquery for Angular. It’s independent of Jquery.

How is the data binding in Angular ?

Its two way binding. So whenever you make changes in one entity the other entity also gets updated.

How do we make HTTP get and post calls in Angular?

To make HTTP calls we need to use the “$http” service of Angular. In order to use the http services you need to make provide the “$http” as a input in your function parameters as shown in the below code.

function CustomerController($scope,$http)
{
	$scope.Add = function()
	{
            $http({ method: "GET", url: "http://localhost:8438/SomeMethod"     }).success(function (data, status, headers, config)
		{
                   // Here goes code after success 		}
	}
}

“$http” service API needs atleast three things:-

  • First what is the kind of call “POST” or “GET”.
  • Second the resource URL on which the action should happen.
  • Third we need to define the “success” function which will be executed once we get the response from the server.
$http({ method: "GET", url: "http://localhost:8438/SomeMethod"    }).success(function (data, status, headers, config)
{
// Here goes code after success }

How do we pass data using HTTP POST in Angular ?

You need to pass data using the “data” keyword in the “$http” service API function. In the below code you can see we have created a javascript object “myData” with “CustomerName” property. This object is passed in the “$http” function using HTTP POST method.

Var myData = {};
myData.CustomerName = &ldquo;Test&rdquo;;
$http({ method: "POST",
	data: myData,
	url: "http://www.xyz.com"})
	.success(function (data, status, headers, config)
	{
	  // Here goes code after success 	}

What is dependency injection and how does it work in Angular?

Dependency injection is a process where we inject the dependent objects rather than consumer creating the objects. DI is everywhere in Angular or we can go one step ahead and say Angular cannot work without DI.

For example in the below code “$scope” and “$http” objects are created and injected by the angular framework. The consumer i.e. “CustomerController” does not create these objects himself rather Angular injects these objects.

function CustomerController($scope,$http)
{
// your consumer would be using the scope and http objects }

How does DI benefit in Angular?

There are two big benefits of DI: – Decoupling and Testing.

Let’s first start with Decoupling. Consider your application has a logger functionality which helps to log errors , warning etc in some central place. This central place can be a file, event viewer, database etc.

function FileLogger()
{
        this.Log = function () {
            alert("File logger");
        };
}
function EventLogger()
{
        this.Log = function () {
            alert("Event viewer logger");
        };
}

Now let’s say you have a “Customer” class who wants to use the “Logger” classes. Now which “Logger” class to use depends on configuration.

So the code of “Customer” is something as shown below. So depending on the configuration “Customer” class either creates “FileLogger” or it creates “EventLogger” object.

function Customer($scope, Logger)
{
        $scope.Logger = {};
        if (config.Loggertype = "File")
{
            $scope.Logger = new FileLogger();
        }
        else
{
            $scope.Logger = new EventLogger();
        }
}

But with DI our code becomes something as shown below. The “Customer” class says he is not worried from where the “Logger” object comes and which type of “Logger” objects are needed .He just wants to use the “Logger” object.

function Customer($scope,$http, Logger)
{
        $scope.Logger = Logger;
}

With this approach when a new “Logger” object gets added the “Customer” class does not have to worry about the new changes because the dependent objects are injected by some other system.
The second benefit of DI is testing. Let’s say you want to test the “Customer” class and you do not have internet connection. So your “$http” object method calls can throw errors. But now you can mock a fake “$http” object and run your customer class offline without errors.The fake object is injected using DI.

What are services in Angular?

Service helps to implement dependency injection. For instance let’s say we have the below “Customer” class who needs “Logger” object. Now “Logger” object can be of “FileLogger” type or “EventLogger” type.

function Customer($scope,$http, Logger)
{
        $scope.Logger = Logger;
}

So you can use the “service” method of the application and tie up the “EventLogger” object with the “Logger” input parameter of the “Customer” class.

var app = angular.module("myApp", []); // creating a APP app.controller("Customer", Customer); // Registering the VM app.service("Logger", EventLogger); // Injects a global Event logger object 

So when the controller object is created the “EventLogger” object is injected automatically in the controller class.

Are Service object instances global or local?

Angular Services create and inject global instances. For example below is a simple “HitCounter” class which has a “Hit” function and this function increments the variable count internally every time you call hit the button.

function HitCounter()
{
       var i = 0;
        this.Hit = function ()
        {
            i++;
            alert(i);
        };
}

This “HitCounter” class object is injected in “MyClass” class as shown in the below code.

function MyClass($scope, HitCounter)
{
	$scope.HitCounter = HitCounter;
}

Below code advises the Angular framework to inject “HitCounter” class instance in the “MyClass” class. Read the last line of the below code specially which says to inject the inject the “HitCounter” instance.

var app = angular.module("myApp", []); // creating a APP app.controller("MyClass", MyClass); // Registering the VM app.service("HitCounter", HitCounter); // Injects the object 

Now let’s say that the “Controller” “MyClass” is attached to twodiv tag’s as shown in the below figure.

So two instances of “MyClass” will be created. When the first instance of “MyClass” is created a “HitCounter” object instance is created and injected in to “MyClass” first instance.

When the second instance of “MyClass” is created the same “HitCounter” object instance is injected in to second instance of “MyClass”.
Again I repeat the same instance is injected in to the second instance, new instances are not created.

If you execute the above code you will see counter values getting incremented even if you are coming through different controller instances.

What is a Factory in Angular?

“Factory” in real world means a premise where products are manufactured. Let’s take an example of a computer manufacturing firm. Now the company produces different kinds and sizes of computers likelaptops,desktops, tablets etc.

Now the process of manufacturing the computer products are same with slight variation. To manufacture any computer we need processor, RAM and hard disk. But depending on what kind of final case packing is the final product shapes.

That’s what the use of Factory in Angular.

For example see the below code we have a “Customer”, “Phone” and “Address” class.

function Customer()
{
        this.CustomerCode = "1001";
        this.CustomerName = "Shiv";
}
function Phone()
{
        this.PhoneNumber = "";
}
function Address()
{
        this.Address1 = "";
        this.Address2 = "";
}

So now we would create different types of “Customer” object types using the combination of “Address” and “Phones” object.

  • We would like to combine “Customer” with “Address” and create a “Customer” object which has “Address” collection inside it.
  • Or must be we would like to create “Customer” object with “Phone” objects inside it.
  • Or must be “Customer” object with both “Phone” and “Address” objects.

In other words we would like to have different permutation and combination to create different types of “Customer” objects.

So let’s start from bottom. Let’s create two factory function’s one which creates “Address” object and the other which creates “Phone” objects.

functionCreateAddress()
{
var add = new Address();
return add;
}
functionCreatePhone()
{
var phone =  new Phone();
return phone;
}

Now let’s create a main factory function which uses the above two small factory functions and gives us all the necessary permutation and combination.

In the below factory you can see we have three functions:-

  • “CreateWithAddress” which creates “Customer” with “Address” objects inside it.
  • “CreateWithPhone” which creates “Customer” object with “Phone” objects inside it.
  • “CreateWithPhoneAddress” which creates “Customer” object with aggregated “Phone” and “Address” objects.
function CreateCustomer() {

return {
CreateWithAddress: function () {
varcust = new Customer();
cust.Address = CreateAddress();
returncust;
            },
CreateWithPhone: function () {
varcust = new Customer();
cust.Phone = {};
cust.Phone = CreatePhone();
returncust;
            }
            ,
CreateWithPhoneAddress: function () {
debugger;
varcust = new Customer();
cust.Phone = CreatePhone();
cust.Address = CreateAddress();
returncust;
            }
        }
    }

Below is a simple “CustomerController” which takes “CustomerFactory” as the input. Depending on “TypeOfCustomer” it creates with “Address” , “Phones” or both of them.

functionCustomerController($scope, Customerfactory)
    {

        $scope.Customer = {};
        $scope.Init = function(TypeofCustomer)
        {

if (TypeofCustomer == "1")
            {
                $scope.Customer = Customerfactory.CreateWithAddress();
            }
if (TypeofCustomer ==  "2")
            {
                $scope.Customer = Customerfactory.CreateWithPhone();
            }
if (TypeofCustomer == "3") {
                $scope.Customer = Customerfactory.CreateWithPhoneAddress();
            }
        }
    }

You also need to tell Angular that the “CreateCustomer” method needs to be passed in the input. For that we need to call the “Factory” method and map the “CreateCustomer” method with the input parameter “CustomerFactory” for dependency injection.

var app = angular.module("myApp", []); // creating a APP app.controller("CustomerController", CustomerController); // Register the VM app.factory("Customerfactory", CreateCustomer);

So if we consume the “CustomerController” in UI , depending on situation it creates different flavors of “Customer” object. You can in the below code we have three different “DIV” tags and depending on the “TypeofCustomer” we are displaying data.

What is the difference between Factory and Service?

“Factory” and “Service” are different ways of doing DI (Dependency injection) in angular. Please read the previous question to understand what is DI.

So when we define DI using “service” as shown in the code below. This creates a new GLOBAL instance of the “Logger” object and injects it in to the function.

app.service("Logger", Logger); // Injects a global object

When you define DI using a “factory” it does not create a instance. It just passes the method and later the consumer internally has to make calls to the factory for object instances.

app.factory("Customerfactory", CreateCustomer);

Below is a simple image which shows visually how DI process for “Service” is different than “Factory”.

Factory Service
Usage When we want to create different types of objects depending on scenarios. For example depending on scenario we want to create a simple “Customer” object , or “Customer” with “Address” object or “Customer” with “Phone” object. See the previous question for more detailed understanding. When we have utility or shared functions to be injected like Utility , Logger , Error handler etc.
Instance No Instance created. A method pointer is passed. Global and Shared instance is created.

My other interview question articles

jQuery, JSON and Less Interview questions with answers

http://www.codeproject.com/Articles/778374/JQUERY-JSON-Angular-and-Less-Interview-questions

100 important ASP.NET MVC interview questions

http://www.codeproject.com/Articles/556995/ASP-NET-MVC-interview-questions-with-answers

HTML 5 Interview questions with answers

http://www.codeproject.com/Articles/702051/important-HTML-Interview-questions-with-answe

WPF interview questions with answers

http://www.codeproject.com/Articles/744082/WPF-Interview-questions-with-answers

from:http://www.codeproject.com/Articles/891718/AngularJS-Interview-Questions-and-Answers

人工智能AI资料

这里收集的是关于人工智能(AI)的教程、书籍、视频演讲和论文。

欢迎提供更多的信息。

在线教程

  • 麻省理工学院人工智能视频教程麻省理工人工智能课程
  • 人工智能入门人工智能基础学习。Peter Norvig举办的课程
  • EdX 人工智能此课程讲授人工智能计算机系统设计的基本概念和技术。
  • 人工智能中的计划计划是人工智能系统的基础部分之一。在这个课程中,你将会学习到让机器人执行一系列动作所需要的基本算法。
  • 机器人人工智能这个课程将会教授你实现人工智能的基本方法,包括:概率推算,计划和搜索,本地化,跟踪和控制,全部都是围绕有关机器人设计。
  • 机器学习有指导和无指导情况下的基本机器学习算法
  • 机器学习中的神经网络智能神经网络上的算法和实践经验
  • 斯坦福统计学习 -Introductory course on machine learning focusing on: linear and polynomial regression, logistic regression and linear discriminant analysis; cross-validation and the bootstrap, model selection and regularization methods (ridge and lasso); nonlinear models, splines and generalized additive models; tree-based methods, random forests and boosting; support-vector machines.

人工智能书籍

编程

人工智能原理

免费读物

程序代码

  • AIMA Lisp Source Code – “Artificial Intelligence A Modern Approach”一书中的Common Lisp源代码。

视频/演讲

机器学习

  • Deep Learning. Methods and Applications来自微软研究室的免费读物。
  • Neural Networks and Deep Learning – Neural networks and deep learning currently provide the best solutions to many problems in image recognition, speech recognition, and natural language processing. This book will teach you the core concepts behind neural networks and deep learning
  • Machine Learning: A Probabilistic Perspective这本小书对机器学习给出了详尽的介绍
  • Deep Learning – Yoshua Bengio, Ian Goodfellow and Aaron Courville put together this currently free (and draft version) book on deep learning. The book is kept up-to-date and covers a wide range of topics in depth (up to and including sequence-to-sequence learning).

其它

Open Congition Project我们正在努力开发一款具有思考能力的机器。

The most influential Books for Programmers

 

代码大全(Code Complete)——两届Software Jolt Award震撼大奖得主!

程序员修炼之道(The Pragmatic Programmer)

C程序设计语言( C Programming Language)(第2版)

重构:改善既有代码的设计(Refactoring: Improving the Design of Existing Code)

人月神话(The Mythical Man-Month)

编码——隐匿在计算机软硬件背后的语言(Code: The Hidden Language of Computer Hardware and Software)

Head First 设计模式(Head First Design Patterns)

编程珠玑(Programming Pearls)

Effective Java中文版(Effective Java (2nd Edition))or Effective C++(第三版)中文版

Test Driven Development: By Example

算法导论(Introduction to Algorithms)(CLRS) 这本书的名称是所有出版过的计算机书籍中最让人误解一个。它被广泛的使用在很多大学里,通常被当作毕业生必需的算法课程。于是,只要在大学里上过计算机课程的学生几乎都有一本这样的书。然而,除非你拥有计算机硕士学位(而且是算法研究领域的),我怀疑你顶多只读过算法导论(Introduction to Algorithms)里节选的几章内容。这个书名让人误解,是因为”Introduction”这个词让人以为它很适合初级程序员。实际上不是。这本书对算法做尽可能详尽综合的介绍,就像其它一些随处可见的类似的书一样。请不要再把这本书推荐给初学者。

编译原理(Compilers: Principles, Techniques, and Tools)(the Dragon Book).这本恐龙封面的书涵盖了开发一个编译器你所需要的全部的知识。它的内容包括词汇分析,语法分析,类型检查,代码优化,以及其它很多高深的题目。请不要把这本书推荐给初级程序员,他们需要的只是分析简单的包含数学公式或HTML的字符串。除非你真的需要实现一个能够实用的编译器(或解释器),你根本不需要掌握这本“恐龙”书的全部强大威力。把它推荐给一个遇到简单文本分析问题的人,这证明你根本没有读过它。

计算机程序设计艺术(The Art of Computer Programming)(TAOCP) 我经常听到人们把这本书描述为“每个程序员必读”的系列计算机书籍。我认为这明显不是实情。在我说出这样大不敬的话、被你们用板砖拍死之前,请让我做解释一下。这不是一本让你一页一页翻着读的书。这是一本参考大全书。把它放在你的书架上看起来会很不错(实际上也它确实很好),但如果想把它通读一遍,你需要几年时间,而且最后什么都没记住。这并不是说手边放这样一本书没有什么价值。它是一本参考书,当我遇到难题,走投无路时,很多次我都在这本书里找到办法。但这本书终究是被我当作参考书。它复杂难懂,很理论,里面的例子都是汇编语言的。好的一面是,如果你想在这本书里寻找针对某一问题的解决方案,如果你找不到,那就说明这个问题无解。它是一本对它所涉及到的领域做了最最详尽介绍的一本书。

Design Patterns: Elements of Reusable Object-Oriented Software(Gang of Four)这本书是唯一一本在这个清单里我从头到尾读过的书,读的结果是,我不知道该把这本书归到哪个类别。它出现在这个清单里,并不是因为我认为只有很少人真正读过它。很多人都读过。只是因为有更多推荐过这本书的人自己却没有读过。Design Patterns这边书的问题在于,很多书里给出的信息,你在其它很多地方都能看到。这样就使得一个初学者在维基百科上读了几篇关于设计模式的内容后,就敢在面试中宣称自己看过这本书。这就是为什么Singleton成了一种新的全局变量的原因。如果有更多的人花时间读过这本也叫做Gang of Four的书的原著,那世界上就不会有这么多人会把17种设计模式硬塞到一个日志(logging)框架里了。这本书最精彩的部分是每章里描述如何正确的使用一种模式的段落。遗憾的是,这些精华却在很多其它设计模式资料里被漏掉了。

C++程序设计语言(The C++ Programming Language)这本书不像一本编程教材,更像一本编程语言参考。有很多的迹象表明有人确实读过这本书,否则我们不可能有这么多的C++ 编译器可选择。编程初学者(或者甚至其它语言的专家),如果想学C++,不应该直接去啃C++程序设计语言(The C++ Programming Language)这本书。告诉他们去读《C++ Primer中文版》。

Structure and Interpretation of Computer Programs》,在国内可以买到中译版,即机械工业出版社的《计算机程序的构造与解释》。

您在学习SICP这本书时,也可以选择配合相关的公开视频。您有两个选择,一是Berkeley的上课视频,二是MIT的公开课件。前者的讲述较为轻松有趣,相对容易理解一些,我看了大半;而后者为SICP原书作者Hal Abelson 和Gerald Jay Sussman为Hewlett-Packard公司员工培训时的录像,我感觉更为体系、理论、也相对较为难懂——当然,这只是我看了Lecture 1的两段录像后的感觉。此外,北大也开设了《程序设计技术和方法》课程,使用SICP作为教材,相信也是不错的参考。

Computer Systems: A Programmer’s Perspective》(下文简称CSAPP),在国内可以买到其影印版。它也已经被翻译成为中文,即中国电力出版社的《深入理解计算机系统(修订版)》。

参考:http://stackoverflow.com/questions/1711/what-is-the-single-most-influential-book-every-programmer-should-read?tab=votes#tab-top

http://www.vaikan.com/what-is-the-single-most-influential-book-every-programmer-should-read/

http://blog.zhaojie.me/2009/07/recommended-reading-2-sicp.html

 

Introducing CLR Stored Procedures in SQL Server 2012

Contents

 

Introduction

This guide demonstrates how to use SQL Server Common Language Runtime (CLR) integration with SQL Server 2012. In this guide, the following two assemblies will be created using C#:

  • MathAsm
  • StoredProceduresAsm

 

About Common Language Runtime (CLR)

The Common Language Runtime (CLR) is the heart of the Microsoft .NET Framework and provides the execution environment for all .NET Framework code. Code that runs within the CLR is referred to as managed code. The CLR provides various functions and services required for program execution, including just-in-time (JIT) compilation, allocating and managing memory, enforcing type safety, exception handling, thread management, and security.

With the CLR hosted in Microsoft SQL Server (called CLR integration), you can author stored procedures, triggers, user-defined functions, user-defined types, and user-defined aggregates in managed code. Developers use compiled OO languages like C# or Visual Basic .NET to write code and to have the code executed as if it were a T-SQL procedure, function, or trigger. Because managed code compiles to native code prior to execution, you can achieve significant performance increases in some scenarios.

Managed code uses Code Access Security (CAS), code links, and application domains to prevent assemblies from performing certain operations. SQL Server 2005, SQL Server 2008, and SQL Server 2012 uses CAS to help secure the managed code and prevent compromise of the operating system or database server.

Enable CLR in SQL Server

In SQL Server 2005, SQL Server 2008, and SQL Server 2012, the Common Language Runtime (CLR) is off by default. In an effort to improve security, Microsoft has turned many features “off by default”. This is a big change from the old policy of turning every feature on so that developers weren’t discouraged from using the feature due to difficulties in getting the feature to work.

EXEC sp_configure 'show advanced options', '1'
Go

Configuration option 'show advanced options' changed from 0 to 1. Run the RECONFIGURE statement to install.

Reconfigure
Go

Command(s) completed successfully.

EXEC sp_configure 'clr enabled', '1'
Go

Configuration option 'clr enabled' changed from 0 to 1. Run the RECONFIGURE statement to install.

Reconfigure
Go

Command(s) completed successfully.

EXEC sp_configure 'show advanced options', '0'
Go

Configuration option 'show advanced options' changed from 1 to 0. Run the RECONFIGURE statement to install.

Reconfigure
Go

Command(s) completed successfully.

Compile and Build Assembly

In order to develop SQL CLR assemblies for SQL Server, you must have and utilize the .NET Framework 3.5 installed on your development computer. If you do not have the .NET Framework version 3.5 installed on your development computer, you must install it if you want to development SQL CLR assemblies for SQL Server. SQL Server 2005, SQL Server 2008, and SQL Server 2012 support only those assemblies that target the 2.0, 3.0, 3.5, or 4.0 version of the .NET Framework.

As mentioned in the Introduction, this guide will compile and build two assemblies using C# that will be integrated with SQL Server 2012. The source code for both assemblies is presented below.

   Math.cs

using System;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server; 

public class Math {

    [SqlFunction]
    public static SqlDouble Factorial(SqlDouble x) {
        SqlDouble y = 1.0;
        while(x > 1.0) {
            y *= x;
            x -= 1;
        }
        return y;
    }
}

   StoredProcedures.cs

using System;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;

public class StoredProcedures {

    ///  /// Execute a command and send the resulting reader to the client /// 
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void GetVersion() {
        using (SqlConnection connection = new SqlConnection("context connection=true")) {
            connection.Open();
            SqlCommand command = new SqlCommand("select @@version", connection);
            SqlDataReader r = command.ExecuteReader();
            SqlContext.Pipe.Send(r);
        }
    }

    public const double SALES_TAX = .086;

    [SqlFunction()]
    public static SqlDouble addTax(SqlDouble originalAmount) {
        SqlDouble taxAmount = originalAmount * SALES_TAX;
        return originalAmount + taxAmount;
    }
}

Copy the source code files above to your source directory. For example:

C:\> copy C:\Users\SQLServerAdmin\Downloads\*.cs C:\Programming\c#\SQLCLRIntegrationExample\src\
C:\Users\SQLServerAdmin\Downloads\Math.cs C:\Users\SQLServerAdmin\Downloads\StoredProcedures.cs 2 file(s) copied.

There are two methods to compile the C# source code; Microsoft Visual Studio and the C# command-line compiler. This guide uses the C# command-line compiler.

To use the C# command-line compiler, navigate to the appropriate .NET Framework directory. For example:

C:\> cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319

From this directory, compile the two SQL CLR source code files into an assembly (dll).

SET SRC_PATH=C:\Programming\c#\SQLCLRIntegrationExample\src
SET DLL_PATH=C:\Programming\c#\SQLCLRIntegrationExample\assemblies

csc /target:library /out:%DLL_PATH%\Math.dll %SRC_PATH%\Math.cs

Microsoft (R) Visual C# Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5 Copyright (C) Microsoft Corporation. All rights reserved.

csc /target:library /out:%DLL_PATH%\StoredProcedures.dll %SRC_PATH%\StoredProcedures.cs

Microsoft (R) Visual C# Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5 Copyright (C) Microsoft Corporation. All rights reserved.

DIR %DLL_PATH%
 Volume in drive C has no label. Volume Serial Number is DC7C-B8D3 Directory of C:\Programming\c#\SQLCLRIntegrationExample\assemblies 03/26/2013 12:13 AM <DIR> . 03/26/2013 12:13 AM <DIR> .. 03/26/2013 12:13 AM 3,584 Math.dll 03/26/2013 12:13 AM 4,096 StoredProcedures.dll 2 File(s) 7,680 bytes 2 Dir(s) 51,610,902,528 bytes free

Grant Permissions for External Access

In order to create an assembly with EXTERNAL_ACCESS (or UNSAFE) permission set, you need extra permissions in the database. This can be achieved by setting the TRUSTWORTHY bit in the database (ALTER DATABASE[DevDB]SET TRUSTWORTHY ON); however, this is not a preferred option as it can cause other undesired side effects. Note that if your assembly does not require resources outside of the database (for example, writing to a file), you do not need to assign an EXTERNAL_ACCESS permission set to the assembly in order to execute the SQL CLR in the database. You only need to assign an EXTERNAL_ACCESS permission set to the assembly when accessing resources outside of the database server.

If your assembly will need access to resources outside of the database, use the following method as the preferred alternative to setting the TRUSTWORTHY bit in the database as explained above.

  1. Create a .NET strong name key file by using the sn.exe tool.
    C:\> SET SN_TOOL="C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\sn.exe"
    
    C:\> SET KEY_PATH="C:\Programming\c#\SQLCLRIntegrationExample\keys"
    
    C:\> %SN_TOOL% -k %KEY_PATH%\extSQLKey.snk
    
    Copyright (c) Microsoft Corporation. All rights reserved.
    
    C:\> dir %KEY_PATH%
     Volume in drive C has no label. Volume Serial Number is DC7C-B8D3 Directory of C:\Programming\c#\SQLCLRIntegrationExample\keys 03/26/2013 12:29 AM <DIR> . 03/26/2013 12:29 AM <DIR> .. 03/26/2013 12:29 AM 596 extSQLKey.snk 1 File(s) 596 bytes 2 Dir(s) 51,610,288,128 bytes free
  2. In the master database, create a master key (if one does not already exist).
    USE [Master]
    Go
    
    CREATE MASTER KEY
    ENCRYPTION BY PASSWORD = 'some_secure_password';
    
    Command(s) completed successfully.
  3. Still in master, create an asymmetric key.
    CREATE ASYMMETRIC KEY extSQLKey
    FROM FILE = 'C:\Programming\c#\SQLCLRIntegrationExample\keys\extSQLKey.snk';
    
    Command(s) completed successfully.
  4. Also in the master database, create a login from the asymmetric key.
    CREATE LOGIN extSQLLogin
    FROM ASYMMETRIC KEY extSQLKey;
    
    Command(s) completed successfully.
  5. Give the login just created EXTERNAL ACCESS ASSEMBLY permission.
    GRANT EXTERNAL ACCESS ASSEMBLY to extSQLLogin;
    
    Command(s) completed successfully.
  6. Build your assembly like before but this time sign it with your strong name key.
    cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319
    
    SET SRC_PATH=C:\Programming\c#\SQLCLRIntegrationExample\src
    SET DLL_PATH=C:\Programming\c#\SQLCLRIntegrationExample\assemblies
    SET KEY_PATH=C:\Programming\c#\SQLCLRIntegrationExample\keys
    
    csc /target:library /keyfile:%KEY_PATH%\extSQLKey.snk /out:%DLL_PATH%\StoredProcedures.dll %SRC_PATH%\StoredProcedures.cs
    
    Microsoft (R) Visual C# Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5 Copyright (C) Microsoft Corporation. All rights reserved.
    
    csc /target:library /keyfile:%KEY_PATH%\extSQLKey.snk /out:%DLL_PATH%\Math.dll %SRC_PATH%\Math.cs
    
    Microsoft (R) Visual C# Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5 Copyright (C) Microsoft Corporation. All rights reserved.
    
    DIR %DLL_PATH%
     Volume in drive C has no label. Volume Serial Number is DC7C-B8D3 Directory of C:\Programming\c#\SQLCLRIntegrationExample\assemblies 03/26/2013 12:13 AM <DIR> . 03/26/2013 12:13 AM <DIR> .. 03/26/2013 01:00 AM 3,584 Math.dll 03/26/2013 01:00 AM 4,096 StoredProcedures.dll 2 File(s) 7,680 bytes 2 Dir(s) 51,609,612,288 bytes free
  7. The assembly is now ready to be deployed. The assembly is signed with a strong name key, and the strong name key has an asymmetric key created from it and there is a login created from that symmetric key with the necessary permission set.

 

Create Assemblies in SQL Server

With the assemblies built, the next step is to create the assembly in a SQL Server database along with the external procedure and/or function wrappers to run the assembly.

MathAsm

Use [DevDB]
Go

CREATE ASSEMBLY MathAsm FROM 'C:\Programming\c#\SQLCLRIntegrationExample\assemblies\Math.dll'
    WITH PERMISSION_SET = EXTERNAL_ACCESS;
Go

CREATE FUNCTION Factorial(@x FLOAT)
    RETURNS FLOAT
    EXTERNAL NAME MathAsm.Math.Factorial;
Go

Command(s) completed successfully.

StoredProceduresAsm

Use [DevDB]
Go

CREATE ASSEMBLY StoredProceduresAsm FROM 'C:\Programming\c#\SQLCLRIntegrationExample\assemblies\StoredProcedures.dll'
    WITH PERMISSION_SET = EXTERNAL_ACCESS;
Go

CREATE PROCEDURE GetVersion AS EXTERNAL NAME StoredProceduresAsm.StoredProcedures.GetVersion;
Go

CREATE FUNCTION addTax(@originalAmount FLOAT)
    RETURNS FLOAT
    EXTERNAL NAME StoredProceduresAsm.StoredProcedures.addTax;
Go

Command(s) completed successfully.

Note that the external reference for creating the procedure and wrapper functions is in the form:

[EXTERNAL NAME] assembly_name.class_name.method_name

Run Example Assemblies in SQL Server

With the assemblies and procedures / functions wrappers created in SQL Server, run the following T-SQL to execute the assemblies.

SELECT [DevDB].[dbo].[Factorial](5) AS "Factorial"
Go

Factorial ----------------- 120

EXEC GetVersion
Go

(No column name) ----------------------------- Microsoft SQL Server 2012 - 11.0.2100.60 (X64) Feb 10 2012 19:39:15 Copyright (c) Microsoft Corporation Business Intelligence Edition (64-bit) on Windows NT 6.2 (Build 9200: ) (Hypervisor)

SELECT [DevDB].[dbo].[addTax](10.00) AS "Original + Tax"
Go

Original + Tax ----------------------------- 10.86

Drop Assemblies from SQL Server

The following T-SQL can be used to drop the previously created objects in the example Class.

MathAsm

Use [DevDB]
Go

DROP FUNCTION [Factorial];
Go

DROP ASSEMBLY [MathAsm];
Go

Command(s) completed successfully.

StoredProceduresAsm

Use [DevDB]
Go

DROP PROCEDURE [GetVersion];
Go

DROP FUNCTION [addTax];
Go

DROP ASSEMBLY [StoredProceduresAsm];
Go

Command(s) completed successfully.

About the Author

Jeffrey Hunter is an Oracle Certified Professional, Java Development Certified Professional, Author, and an Oracle ACE. Jeff currently works as a Senior Database Administrator for The DBA Zone, Inc. located in Pittsburgh, Pennsylvania. His work includes advanced performance tuning, Java and PL/SQL programming, developing high availability solutions, capacity planning, database security, and physical / logical database design in a UNIX / Linux server environment. Jeff’s other interests include mathematical encryption theory, tutoring advanced mathematics, programming language processors (compilers and interpreters) in Java and C, LDAP, writing web-based database administration tools, and of course Linux. He has been a Sr. Database Administrator and Software Engineer for over 20 years and maintains his own website site at: http://www.iDevelopment.info. Jeff graduated from Stanislaus State University in Turlock, California, with a Bachelor’s degree in Computer Science and Mathematics.

from:http://www.idevelopment.info/data/SQLServer/DBA_tips/Programming/PROG_20.shtml

Configure SQL Server Express to allow remote tcp/ip connections on port 1433

The following article explains how to allow SQL Server Express to accept remote connections over TCP/IP for port 1433. By default, when SQL Server Express is installed it gerates a random port to listen on. In addition, SQL Server Express only listens for connection on localhost. Using the SQL Server Configuration Manager, you will need to tell SQL Server Express to use port 1433.

 

To allow SQL Server Express to accept remote connections, please follow these steps:

1) Log into your server through Remote Desktop Connection (instructions for connecting to your server through RDC can be found here).

2) Click Start, Programs, Microsoft SQL Server 2005/2008/2012 and select SQL Server Configuration Manager.

 

3) Select SQL Server Network Configuration

 

4) Double click on Protocols for SQLEXPRESS

 

5) Right click TCP/IP and select Properties

6) Scroll down to IPAll make sure TCP Dynamic Ports is blank and that TCP Port is set to 1433.

7) Click OK

8) Make sure that port: 1433 is enable on your VDS firewall (instructions for enabling firewall ports can be found here).

9) Mixed mode authentication must also be enabled for remote connections (instructions for enabling firewall ports can be found here).

10) Make sure that the SQL Browser is enabled and running.

from:http://support.webecs.com/kb/a868/how-do-i-configure-sql-server-express-to-allow-remote-tcp-ip-connections-on-port-1433.aspx

Refer:http://blog.citrix24.com/configure-sql-express-to-accept-remote-connections/