How to use filters within controllers in AngularJs (mini-challenge 12)

filters within controllers

Filters within controllers (mini-challenges 12)

AngularJs Mini-Challenges is a growing collection of “Challenges” about the most quirky parts of the AngularJs framework. It encourage you to find and fix common mistakes and subtle bugs, as well as performance issues and bad practices, that non-expert AngularJs programmers may encounter on their endeavours into the depths of the framework.

AngularJs Mini-Challenges does not aim to teach you AngularJs. Former knowledge of the Framework is strongly recommended in order to understand the topics covered in this Challenges. In order to learn the basics of the Framework, please head over to this excellent book:

 

book

Book Tip

ng-book – The Complete Book on AngularJS
Ready to master AngularJS? What if you could master the entire framework – with solid foundations – in less time without beating your head against a wall?


Amazon

 

The Challenge:

How would you use filters within controllers like “filter” in JavaScript? And how to create a custom filter?
For example in the html you can use filter’s filter to do a search in a list of elements:

 <tr ng-repeat="friend in friends | filter:searchText">

<table id="searchTextResults">
<tr>
<th>Name</th>
<th>Phone</th>
</tr>

<tr ng-repeat="friend in friends | filter:searchText">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
</tr>
</table>

 
 

Solution:

In AngularJs you can inject the $filter service within the controller, and use it with the following syntax for “filter”:

$filter('filter')(array, expression, comparator, anyPropertyKey)

 

function myController($scope, $filter)
{
   $scope.result = $filter('filter')($scope.arrayOfObjects, $scope.searchCriteria);
}

You can also use other AngularJs filters Build-in like:

 $scope.formatedDate = $filter('date')($scope.date, "yyyy-MM-dd");
 $scope.result = $filter('lowercase')($scope.name);

You can find here a list of build-in AngularJs filters:
https://docs.angularjs.org/api/ng/filter

 
 
Filter Example with pipe in the HTML:

 
 
Filter example within the controller using Javascript:

 
 

How to create custom filters in AngularJs

AngulrJs have a build-in method to register custom filters, using the same approach you can use when you register a controller, a service and factories. See following example:

var myApp = angular.module('myApp', []);
app.filter('myFilter', function() {
  return function(input, option1, option2) {
    var output;
    // Logic to make your filter works.
    return output;
  }
});

 
for more reference about how to create a custom filter you can refer to https://scotch.io/tutorials/building-custom-angularjs-filters
 

Angular 2 seed for Visual Studio 2015

Angular 2 seed for Visual Studio 2015

This Angular 2 seed for Visual Studio 2015 targets Angular version 2.1.0 released on Oct 12, 2016. This project is based on official Angular2 Seed project. It relies on TypeScript and SystemJS.

angular 2 seed

Instructions:

-1 Clone or fork the repocitory.
https://github.com/jomendez/AngularJs-2-Visual-Studio-2015
-2 Make sure you have node installed, this code require node v5.x.x or higher and npm v3.x.x or higher, to check what version you are using run node -v and npm -v, in your cmd console.
-3 Open a cmd console, and go to your project root file location and run npm install to install dependencies

npm behind a corporate proxy

If you are trying to setup the seed behind a proxy, you migth encounter issues of connection refuced, etc. You can use the following command:
With password:

npm config set proxy=http://<username>:<pass>@proxyhost:<port>
npm config set https-proxy=http://<uname>:<pass>@proxyhost:<port>

or without password:

npm config set proxy=http://proxyhost:<port>
npm config set https-proxy=http://proxyhost:<port>

 

Fixing errors when using resharper

If you don’t have installed resharper in your computer please ignore this section, if you have it intalling, resharper migth cause cause some sintax error validation.

Error:
“Typescript Feature 1.5. Current language level is 1.4”.

Solution:
Resharper setting. From the menu bar in VS2015 -> Resharper -> Options -> Code Editing -> TypeScript -> Inspections -> Typescript language level, change to 1.5

Error:
Symbol ‘component can not be properly resolved, probably its located in an inaccessible module’

Solution:
You can disabled resharper’s typescript inspection for now.
Resharper > Options > Code Inspection > Settings
Find ‘File masks’ (bottom right) and add *.ts

 

Browser support

The Angular 2 seed runs on all major browsers including Internet Explorer 11+, Edge, Firefox, Chrome, Opera and Safari.

License

The Angular 2 seed is released under the MIT license.

Styling External Links in your site with CSS

Are you looking for an easy way to style and denote external links in your web site or blog, it is always good for the user to know when they are going to navigate away from your page, enriching the user experience. Perhaps most of the sites out there achieve this by placing code on the Back End. Here I going to share with you what I found on this topic, and how to do it just using CSS.

Clicking on external links, navigating away..

denote external links

We are going to use CSS selector to apply styles to all the “a” (anchors) except for internal links. This is translated into code like this:

a[href*="//"]:not([href*="mywebsite.com"]) {
    /* css code here  */
}

 

Notice that we combined the selector with some regular expression, the * mean select all elements, for a full list of selectors, you can visit:
http://www.w3schools.com/cssref/css_selectors.asp

Now, you can combine this selector with the ::after of the <a> element to include for example an icon that might looks like the externals links on Wikipedia.
(from http://www.w3schools.com/)
after browser suport

Although Wikipedia doesn’t use this approach, they use a class instead to insert the icon at the end of the external links, this should be done manually. With the method exposed here all the externals links will be styled automatically when the page loads.
external links wikipedia

 

book

Book Tip

CSS Mastery
Fully updated to the latest CSS modules, make the journey to CSS mastery as simple and painless as possible. This book dives into advanced aspects of CSS-based design, such as responsive design, modular CSS, and CSS typography. Through a series of easy-to-follow tutorials, you will learn practical CSS techniques you can immediately start using in your daily work.
Amazon

 

Here is a working example of how all the external links are decorated with the Wikipedia’s external link icon

a[href*="//"]:not([href*="example.com"]):after {
    margin-left: 3px;
    content: url(data:image/svg+xml,%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%20standalone%3D%22no%22%3F%3E%3Csvg%20xmlns%3D%22
http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2212%22%20height%3D%2212%22%3E%3Cpath%20fill%3D%22%23fff%22%20stroke%3D%22%2306c%22%20d%3D%22M1.5
%204.518h5.982V10.5H1.5z%22%2F%3E%3Cpath%20d%3D%22M5.765%201H11v5.39L9.427%207.937l-1.31-1.31L5.393%209.35l-2.69-2.688%202.81-2.808L4.2%202.544z%22
%20fill%3D%22%2306f%22%2F%3E%3Cpath%20d%3D%22M9.995%202.004l.022%204.885L8.2%205.07%205.32%207.95%204.09%206.723l2.882-2.88-1.85-1.852z%22%20fill%3D
%22%23fff%22%2F%3E%3C%2Fsvg%3E)
    }

Also you can denotate all the links that navigate away from your page even internal links that get open in another tab or windows:

:not compatibility

One last thing to keep in mind when you use this approach is the browser compatibility with the :not css selector, for example Internet Explorer starting supporting it from version 9:
(from http://www.w3schools.com)
not css selector browser compatibility

Ultimately, for the no compatible browsers you can detect the browser version with JavaScript or Jquery and then select all the external links and apply the style using JavaScript code:
Jquery Example:

$(function() {
  $('a').each(function(i, e) {
    if ($(e).attr("href") && ($(e).attr("href").indexOf("http://") > -1 || $(e).attr("href").indexOf("https://") > -1)) {
      $(e).css({
        "background-image": "linear-gradient(transparent,transparent),url(data:image/svg+xml,%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%20standalone%3D%22no%22%3F%3E%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2212%22%20height%3D%2212%22%3E%3Cpath%20fill%3D%22%23fff%22%20stroke%3D%22%2306c%22%20d%3D%22M1.5%204.518h5.982V10.5H1.5z%22%2F%3E%3Cpath%20d%3D%22M5.765%201H11v5.39L9.427%207.937l-1.31-1.31L5.393%209.35l-2.69-2.688%202.81-2.808L4.2%202.544z%22%20fill%3D%22%2306f%22%2F%3E%3Cpath%20d%3D%22M9.995%202.004l.022%204.885L8.2%205.07%205.32%207.95%204.09%206.723l2.882-2.88-1.85-1.852z%22%20fill%3D%22%23fff%22%2F%3E%3C%2Fsvg%3E)",
        "background-repeat": "no-repeat",
        "padding-right": "13px"
      });
    }
  });
});

 

Working example:

Market yourself Put your name out there

Market yourself

It is very important to put your name out there (using several resources like a blog, github, stackoverflow, etc)  in order to market your self, specially when you moved to the U.S and you haven’t work for a company here, even if you did, still very important to communicate to your potential employers that you love what you do and you dedicate time of your free time to keep improving your skills by for example contributing to github open source project, or answering questions on stackoverflow, etc. Create you own blog is another way to market yourself, among other benefits you’ll learn to deal with criticism, you might get feedback from new people, You’ll have the opportunity of practice your written English and become a better writer, you will help other people, etc.


 

Get your own resources

get your own resources market yourself

Github.com

You can either create your own projects (maybe univercity projects) or contribute to someone else’s project, the idea is to collaborate and share. Here is an excellent guide to how to contribute to github projects http://kbroman.org/github_tutorial/pages/fork.html

 

stackoverflow.com

Stackoverflow has become an essential tool for developers with millions of answer to different issues/situation for a day to day of a developer, has become a tool of knowledge where you can find your answer already or ask a question there’s going to be somebody ready to answer your question. You can become one of this person that uses your knowledge to help others sharing what you learn product of your experience. Also when you register in stackoverflow  you can create a profile where employers can find you and send you job offers.

 

Your own blog

Blogging is another tool to market yourself. There is a lot of resources to create your own blog, the two more popular services are www.blogger.com and https://wordpress.com/ you can create and host you blog for free with this two services, if you want more flexibility in the functionalities you can add to your blog or more control on the look and feel, I’ll suggest you, to buy a hosting, I use wordpress with godaddy for this blog, also I’ll suggest you to buy your own domain, for example yourname.com or yourname.me. If you still not convinced I’ll recommend this article: http://www.thomashanning.com/10-reasons-you-should-blog-as-a-developer/

 

book

Book Tip

Soft Skills: The software developer’s life manual
Soft Skills: The software developer’s life manual is a unique guide, offering techniques and practices for a more satisfying life as a professional software developer


Amazon

 

 

Connect with people near you

It is very important that you connect with other folks, doing this you might be opening doors to future jobs opportunities, you can use Linkedin to find other developers and managers near you, also you can use the meetups as a resource to meet people. I hardly recommend that before you apply to a job, research about it, look for the managers of the group you are applying, try to connect with them, you can use Tweeter, Linkedin, etc. You can ask for advises, make thoughtful tweets, ask them about the position they have open, etc. When you connect with them before you get the interview this might play in your favor.

 

 

Your resume

Your resume is your more important marketing tool, the content of your resume it’s provably the first thing hiring managers are going to learn about you, and it might open or close you the door to an interview, that’s why it is very important to create a very pleasurable first impression. There are few rules of what a recruiter or hiring manager will spect from your resume:

https://www.livecareer.com/resume-examples/it/software-engineer (online tool to create your resume)

http://www.techrepublic.com/blog/10-things/10-tips-for-writing-a-job-winning-developer-resume/

http://www.businessinsider.com/how-to-write-a-developer-resume-that-will-get-you-hired-2014-11?op=1

 

 

Prepare yourself for interviews

The interview is the next step in your journey to land in a job as software developer or related field, it is very important that you prepare yourself. Here are few websites where you can find useful information about interviews specifically within the software development field. Also in the book I suggested above there are several tips for interviews. Here you can find some useful links.

http://www.infusivesolutions.com/blog/bid/97934/10-Job-Interview-Tips-for-Software-Developers

https://www.coursera.org/learn/cs-tech-interview

https://www.youtube.com/watch?v=E88P7tQhMvI

http://www.programmerinterview.com/index.php/job-advice/how-to-prepare-for-a-software-engineering-interview/

 

Learn, Prepare yourself (Guide for U.S Immigrants)


 

Getting started:

This is one of the few careers that is highly pay and you don’t need a licence though, but you need to prove that you know and are able learn and perform the job with high standards. That’s the biggest advantage of the software developer career or related fields you don’t need a degree certificate, a diploma or a license to be able to work on this field, your knowledge and your experience should be sufficient to be able to find a job. I’m not saying that trying to get a degree is bad, if you want to go to the university and get your degree that’s fine, but it is not mandatory when you are looking for a job as a software developer.
If you still thinking that it is not worth the effort to trying to re-orientate or continue your career as a software developer or related field in the USA, I encourage you to do a quick search on salaries on the internet, this might not be 100% accurate but at least will give you an idea of how much you could worth, you can check this site for salary research:

http://www.indeed.com/salary/Estimator.html
https://www.glassdoor.com/Salaries/index.htm
https://www.roberthalf.com/workplace-research/salary-guides

These are few from the many websites in internet that might help you to investigate what is an average salary for a Software developer or related field.

 

Your English is a must:

learn English

You might be wondering why this guide is written in english, it is because even though the target audience of this material are immigrants, the first step to a successful career in this country is to learn english, if it is not your first language of course.
If you were born in USA, or any English speaking country, or have an excellent domain of the English language, then, you can skip this section. If not this is very important for you, first thing you should do, before you even think of apply for a job, is perfectionate your english or start learning it if you are in cero. Not only because you most likely will be interacting with others at your company in english, but also because a great number of good resources to learn and also the tools you might be interacting with, are going to be in english.

Here are some resources you can use to learn or perfectionate your english:
You can go to college to take ESOL (English for Speakers of Other Languages) class.
If you are starting learning and you want to learn by yourself I recommend you Rosetta Stone
If you are more advanced, then I highly recommend Open English (www.openenglish.com)
www.engvid.com (free and muy bueno)

 

Productivity and inspiration

Productiviti And Inspiration

Productivity: If you are starting you career as a software developer or related field here in the USA or are planning to continue your career here, whichever is your case, you need to be productive and get the most of the time you have available. I don’t know why but I found out that living in this country it is like going hight speed on the expressway, and the time just flies. Being productive means that you are highly effective in a relatively short period of time. One of the most important things in this career is to be prepared and possess as much knowledge as possible in your field, remember, you’ll probably have to compete with very talented people for job opportunities. I strongly believe that the main thing you need to do to improve your productivity is define your goals and plan your actions to achieve those goals.
One technique I use to be focus and improve my performance when I studying or developing software is the pomodoro technique, click here to learn more. In general you can visit this blog post with advices of how to be productive, however this post is more focused to loud open spaces offices, but I guess you’ll extract the idea.
Also if you use chrome you can install this extension to pomodoro your time:
https://chrome.google.com/webstore/detail/pomodoro-timer/hfgjlgjnpkpmnpojkkpfkogapiclopop?utm_source=chrome-app-launcher-info-dialog

Inspiration: sometimes you’ll feel like you don’t want to do anything, that’s normal. It is very important for your productivity to overcome that stage. Look for things that inspires me, had helped me to keep focus and get back on track, for example I found very interesting the Ted Talks, these are some of my favorites:






Inspiration from books:

I consider books a key source of knowledge, as a matter of fact I think it is the main source of knowledge. For me I prefer to listen an audio book (of course, when it is not code examples involved, etc.), I use to drive almost one hour to work, I like to drive while listen an audiobook, also at the gym, when I’m working out. For me it is a bit hard to allocate time to read a paperback book. Also audible offers a monthly subscription of $14.95 a month. Receive 1 credit each month, with that credit you can purchase any audiobook you want (I have this subscription myself).

Click here to subscribe to Audible
These are some of my favorites audiobooks for inspiration:


 

Learn, learn and learn

learn Learn Learn

This is perhaps the most important thing a software developer needs to do to start/maintain and built a successful career. These are some resources to free to learn or sharpen your development skills:
https://www.codecademy.com/
https://www.hackerrank.com/
https://mva.microsoft.com/
https://www.coursera.org/

Some paid services to learn:
https://www.pluralsight.com/
https://www.lynda.com/
https://teamtreehouse.com/
https://www.udemy.com/

Certifications:
There are many opinions on certifications, some managers would like candidates with certification some don’t, In my opinion, possessing a certification doesn’t guarantee that you are going to obtain the job, however it might make the difference between two candidates with the same experience and skill sets, I see certifications as milestones for when I want to learn something new or improve my knowledges in certain technology, When I studying for a certification I like to study to learn deeply first and after that I start thinking on the exam, just my opinion. I totally recommend and encourage you to do certifications, it is a way to study for an end objective (the exam) it is always good to have a little bit of pressure and a deadline, to avoid procrastination.

These are some of the certification, you should research in your field for the certification that suit you:

Scrum:
https://www.scrumalliance.org/certifications/practitioners/certified-scrummaster-csm

Microsoft technologies (Web, Mobile, Desktop, DB, Application lifecycle, etc):
https://www.microsoft.com/en-us/learning/certification-overview.aspx

Java:
http://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=458&get_params=p_track_id:JSE7PROG

PHP
http://www.zend.com/en/services/certification

Books:

These are some of my favorites books (click on the images below):

Here click the link to obtain a complete list of
Microsoft Exam references

Some of my favorites technical books (some of them are free):

Javascript:
https://github.com/getify/You-Dont-Know-JS
http://speakingjs.com/es5/index.html

AngularJs:
https://www.ng-book.com/

Asp.Net

C#

I highly encourage you to do some research and find the best books in your field of expertise, you might be surprised of the many books offered for free. For more books, please contact me via tweeter @joMendezdev

Notes:
There are few programs that you might be eligible for, for example the WIOA program (Workforce Innovation and Opportunity Act) Where they can pay for your trainings and courses for your development
http://sitefinity.floridajobs.org/frequently-asked-questions-directory/wia-program-faq
Read the FAQs to get more information.

 

Follow the leaders, learn from them

Follow the Leader

The leaders can help you to stay on top of relevant news and trends and keep up to date in technology. Here is a list of the most relevant Front-End leaders. https://twitter.com/frontendrescue/lists/cool-people/members
Note: I encourage you to find the leaders on your field, follow them, learn from them, and with hard work you can become a leader.


 

Find the best resources (keep current)

find the best resources

In this career it is always important to be current, and be on top of the new frameworks, design patterns, good practices, etc. You should find you own resources in your field, for example daily news, magazines, blog post, etc.
One thing I do is that I subscribe to RSS feeds of the blogs that I’m interested on, here is an example of how you can do it on Outlook (animated gif):

add rss outlook guide

Here are few examples of some of the resources I use to keep current, in my case I look for resources related to .Nec/C#/Javascript/AngularJs etc.:
https://hackernoon.com/
https://medium.com/tag/javascript
http://blog.cwa.me.uk/
https://css-tricks.com/
https://www.smashingmagazine.com/

You’ll need to research and find your resources in your field.

 

Attend conferences

attend conference

Attending conferences is fun, you can meet other developers, in the meetups usually somebody give a speech about certain topic of interest, You can use meetup.com to find groups related to your interests:
https://www.meetup.com/find/?metaCategory=tech
I’m part of the DotNetMiami group, also, MiamiJs, among others. I hope I see you around in one of this groups one of this days.

Also there are some annual events like:

http://technightattheballpark.com/ which take place around august
The tech night at the ballpark it is more for meetup and networking, a lot of recruiters and companies go there to try to find talented tech prospective, and after that, enjoy the baseball game.

http://www.fladotnet.com/codecamp/ (this is awesome, you can’t miss this one)
Description taken from the website:
What is Code Camp? South Florida Code Camp is a FREE one day GEEK FEST held on Saturday February 18, 2017. This is the 13th year for South Florida Code Camp. The event will have speakers from the local community and beyond. Speakers will be presenting some of the most requested topics like Machine Learning, DotNet Core, Windows 10, Mobile Development, ASP.NET, Javascript, JQuery, Visual Studio 2015, MVC Framework, Sharepoint, SQL Server 2016, Xamarin, cross platform development and Azure. Code Camp is community driven by a group of dedicated volunteers and speakers. Breakfast and lunch is included!

 

CSS Tooltip, without JavaScript or Jquery

In this article I’m going to explore how to Create css tooltip, without using JavaScript or JQuery plugins.

css tooltip

Tooltips

Tooltips are great artifact to complement/enrich the user experience providing hint and more information to the user. There are a lots of JavaScript plugins that provides this functionality, but if you don’t feel like adding that weight to your site, adding more files and more JavaScript code, we can take care of it just using plain CSS.
As an alternative we can use the HTML title attribute to effectively accomplish the same solution, but you can’t style the tooltip to your liking.
Sometimes I prefer to use CSS alternatives to common JavaScript interactions when I’m developing specially when I’m developing prototypes. There are some projects where downloading a plugin or creating a new file for a few lines of code seems like overkill.

Here is a working example:

Hover over this

 

Creating a Css Tooltip

To create our tooltip just using css, we are going to take advantage of the ::before and ::after selector, we are going to use the ::before for the tooltip body and the ::after for the littler arrow. We are going to set the Tooltip content with data-tooltip parameter of the html element.

 <span class="tooltip-toggle" data-tooltip="Sample text for your tooltip!">
     Hover over this
 </span>

 

book

Book Tip

CSS Mastery
Fully updated to the latest CSS modules, make the journey to CSS mastery as simple and painless as possible. This book dives into advanced aspects of CSS-based design, such as responsive design, modular CSS, and CSS typography.

Amazon

 

 

Definition and Usage.

::after selector inserts something after the content of each selected element(s).
You can use the content property to specify the content to insert. This property can be combined with the attr() attribute to get the text from an html atribute.
::before selector inserts something before the content.
Example:

.tooltip-toggle::before {
  position: absolute;
  top: -80px;
  left: -80px;
  background-color: green;
  border-radius: 5px;
  color: #fff;
  content: attr(data-tooltip);
  padding: 1rem;
  text-transform: none;
  -webkit-transition: all 0.5s ease;
  transition: all 0.5s ease;
  width: 160px;

.tooltip-toggle::after {
  position: absolute;
  top: -12px;
  left: 9px;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 5px solid green;
  content: " ";
  font-size: 0;
  line-height: 0;
  margin-left: -5px;
  width: 0;
}
}

With the :hover we can show/hide the tooltip as a transition:

.tooltip-toggle:hover::before,
.tooltip-toggle:hover::after {
  opacity: 1;
  -webkit-transition: all 0.75s ease;
  transition: all 0.75s ease;
}

.tooltip-toggle::before,
.tooltip-toggle::after {
  color: #efefef;
  font-family: monospace;
  font-size: 16px;
  opacity: 0;
  pointer-events: none;
  text-align: center;
}

Here is the full code example of the css tooltip:

Interview Question

You can also use this article as reference to create css interview questions for a seasoned front-end developer, to validate the deep experience on using, formating the ::before and ::after elements.

Prevent angular executing controller twice (Mini-Challenge 11)

Prevent angular executing controller twice (Mini-Challenge 11)

Prevent angular executing controller twice

AngularJs Mini-Challenges is a growing collection of “Challenges” about the most quirky parts of the AngularJs framework. It encourage you to find and fix common mistakes and subtle bugs, as well as performance issues and bad practices, that non-expert AngularJs programmers may encounter on their endeavours into the depths of the framework.

AngularJs Mini-Challenges does not aim to teach you AngularJs. Former knowledge of the Framework is strongly recommended in order to understand the topics covered in this Challenges. In order to learn the basics of the Framework, please head over to this excellent book:

 

book

Book Tip

ng-book – The Complete Book on AngularJS
Ready to master AngularJS? What if you could master the entire framework – with solid foundations – in less time without beating your head against a wall?


Amazon

 

 

The Challenge:

We have an Angularjs application. For this challenge we are going to show only the fragment of code necessary to solve the challenge. Below we have the controller, the view and the router. when you navigate to the #/dashboard page you noticed that the controller is executed twice by placing a breakpoint in your browser console. This makes the analyticsServices.save() method to execute twice duplicating the data in your database. What you would do to prevent angular executing controller twice?

This is the controller

function MyController($scope, userServices, analyticsServices) {

    userServices.get({ id: $scope.currentUserId },
        function(user) {
            analyticsServices.save(user);
        });
}

This is a fragment of the code in the view:

<!-- dashboard.html -->
<div ng-controller="MyController">

<!-- html content -->

</div>

This is the of the router

 .when('/dashboard', {
            templateUrl: '/app/dashboard/dashboard.html',
            controller: 'MyController',
            controllerAs: 'ctr',
            title: 'Dashboard'
});


Solution:

Having the controller defined in the controller property in the router and also defined in the ng-controller in the view, this digested the controller twice. Removing the ng-controller directive from the HTML view can resolve the issue. Alternatively, you can remove the controller: property from the routing directive.


Hope this was helpful, please feel free to leave your comments, share other scenarios, or improve this solution! :)

How to avoid js files cache script bundle with razor

It happened to me, that I was working on an ASP.NET MVC Razor with AngularJs application, and every time that the team make a change in the AngularJs files and deploy to Production, the users start complaining about unresolved issues in the application. Those issues were because of the browser cache the JavaScript files in the client side. So in this article, I’ll try to find an optimal solution to this problem, meaning that the javascript bundle should avoid cache when a new version of the application is deployed to production.
bundle cache

Avoiding browser cache:

We have to consider that one of the most popular techniques to avoid browsers cache with javascript files is to add a variable at the end of the file name, like this: src=”/app/app.js?nocache=12365434576″.

  <script type="text/javascript" src="/app/app.js?nocache=12365434576"></script>

Now this resolve the issue partially since 12365434576 it’s going to be a random number that always going to avoid the cache, and we don’t want that, we want to avoid cache only when a new version is deployed, for a better performance. So what we need to do is, instead of set the nocache var to a random number we are going to user the version of the application, like this:


Bundle Code:

We had a code like this to compose the bundle in App_Start/BoundleConfig.cs

 private static void AddAppBundles(BundleCollection bundles)
        {
            var path = "admin";
            var scriptBundle = new ScriptBundle("~/js/app");
            var FullPath = HttpContext.Current.Server.MapPath(string.Format("~/{0}", path));
            if (Directory.Exists(FullPath))
            {
                scriptBundle.Include(
                    // Order matters
                    string.Format("~/{0}/app.module.js", path),
                    string.Format("~/{0}/app.core.module.js", path)
                    )

                    .IncludeDirectory(string.Format("~/{0}", path), "*.module.js", true)
                    .IncludeDirectory(string.Format("~/{0}", path), "*.js", true);
            }
            bundles.Add(scriptBundle);
        }

With the code above we can include all the javascript files found in “path” variable in our _Layout.cshtml page, with this code:

@Scripts.Render("~/js/app")

The code is going to render something like this:

  <script type="text/javascript" src="/app/app.js"></script>
<script type="text/javascript" src="/app/config.js"></script>
<script type="text/javascript" src="/app/dashboard/dashboard.module.js"></script>
<script type="text/javascript" src="/app/layout/layout.module.js"></script>
<script type="text/javascript" src="/app/blocks/apiendpoint.config.js"></script>
<script type="text/javascript" src="/app/blocks/apiendpoint.provider.js"></script>

The question here is how we can render something like this src=”/app/app.js?nocache=1.28.16145.10″, when we render the bundle in razor.
We are going to use @Scripts.RenderFormat.

Solution:

@{  
    string version = typeof(yourProjectNamespace.WebApiApplication).Assembly.GetName().Version.ToString();
}
    <!--app scripts.-->
    @Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}?nocache="+ version +"\"></script>", "~/js/app")

This is an example of the result rendered:

  <script type="text/javascript" src="/app/app.js?nocache=1.28.16145.10"></script>
<script type="text/javascript" src="/app/config.js?nocache=1.28.16145.10"></script>
<script type="text/javascript" src="/app/dashboard/dashboard.module.js?nocache=1.28.16145.10"></script>
<script type="text/javascript" src="/app/layout/layout.module.js?nocache=1.28.16145.10"></script>
<script type="text/javascript" src="/app/blocks/apiendpoint.config.js?nocache=1.28.16145.10"></script>
<script type="text/javascript" src="/app/blocks/apiendpoint.provider.js?nocache=1.28.16145.10"></script>

Hope this was helpful. :)

State Management in ASP.Net

In this article I’ll try to cover the different techniques session state management in ASP.Net applications. With this we are going to be able to determine the best approach for our solution when we manage the session states in ASP.Net applications.
session state management

These are the session state management options in Asp.net

  • Off
  • StateServer
  • InProc
  • SQLServer
  • Cookies
  • Query String
  • Custom

Fot Off|StateServer|InProc|SQLServer, we will need to specify the session state tag in the web.config. This is a template code:

<sessionState mode="Off|StateServer|InProc|SQLServer"
              cookieless="true|false"
              timeout="number of minutes"
              stateConnectionString="tcpip=server:port"
              sqlConnectionString="sql connection string"
              stateNetworkTimeout="number of seconds"/>

Off Mode

Off mode, which disables session state.


StateServer Session State mode

StateServer Session State mode, which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. StateServer session runs as a Windows service and would help to minimize database traffic.
Example:

<configuration>
  <system.web>
    <sessionState mode="StateServer"
      stateConnectionString="tcpip=SampleStateServer:42424"
      cookieless="false"
      timeout="20"/>
  </system.web>
</configuration>

InProc Session State

InProc Session State, this mode stores session state with the ASP.NET worker process (in memory on the Web server). It is not valid in a web farm configuration.
Example

<configuration>
   <system.web>
      <sessionState mode="InProc"
                    cookieless="true"
                    timeout="20"/>
      </sessionState>
   </system.web>
</configuration>

SqlServer Session State

SqlServer Session State. stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. Although, It does support a web farm configuration, you should not use this if you want to minimize database traffic.
Example:

<configuration>
  <system.web>
    <sessionState mode="SQLServer"
      sqlConnectionString="Integrated Security=SSPI;data 
        source=SampleSqlServer;" />
  </system.web>
</configuration>

Cookie State mode

Cookie State mode. Cookies are stored on the client, so the application would not be able to keep the state if they switched to a different device or a different browser. Also the user needs to have the cookies enabled in their browser


Query String

Query String It can be used for passing limited state information across request boundaries, this solution would not be able to keep the state if they switched to a different device. This solution will work even if the user have disabled the cookies in the browser.


Custom mode

Custom mode, which enables you to specify a custom storage provider.
Example:

<configuration>
  <connectionStrings>
    <add name="OdbcSessionServices" 
      connectionString="DSN=SessionState;" />
  </connectionStrings>

  <system.web>
    <sessionState 
      mode="Custom"
      customProvider="OdbcSessionProvider">
      <providers>
        <add name="OdbcSessionProvider"
          type="Samples.AspNet.Session.OdbcSessionStateStore"
          connectionStringName="OdbcSessionServices" 
          writeExceptionsToEventLog="false" />
      </providers>
    </sessionState>
  </system.web>
</configuration>

These are the options we have in Asp.net to manage the session state in an application. Hope this was helpful.

ASP.NET MVC Routers common questions

I’m doing this article as a self remainder of how to declare routers in ASP.NET MVC I will try to answer the most common questions about ASP.NET MVC Routers that I was able to find on internet. Hopefully this might help you as well. Routers

When you create a MVC application with Visual Studio, and you go to the RouteConfig.cs file this is the default code generate by the template:

 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", 
                                action = "Index", 
                                id = UrlParameter.Optional },
                constraints: new {id = @"\d+"}
            );

Most common questions about routers:

“Why do we use route.IgnoreRoute?”
This will tells the routing engine to ignore any requests that match the provided pattern “{resource}.axd/{*pathInfo}”. In this case to ignore any requests to axd resources.

“Why the parameters in {} ?”
The {} indicates that the delimited string is a variable, it can anything. In the ignore route this is used so that any .axd requests are matched.

Why map MapRoute has First parameter “Default”
The first parameter is the route name. This can be used when referring to routes by name. It can be null
E.g.

routes.MapRoute(
  "Default", //Default Route
  "{controller}/{action}/{id}", // URL with parameters
   new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
);

routes.MapRoute(
  "Feedback", // Custom Route name
  "Feedback",
   new { controller = "Home", action = "Feedback" }
);

//Then you can call it like this:
@Html.RouteLink("Feedback");

What is the Second Parameter-“{controller}/{action}/{id}” for?
This is the pattern that is matched. In this case it is setting up the default route which is a url formed by the controller name, action name and an optional id. The url http://yoursite.com/Foo/Bar would call the Bar method on the Foo controller. Changing the url to http://mysite.com/Foo/Bar/1 would pass a parameter with the identifier id and value 1.

What is the third parameter?
The third parameter supplies defaults. In the case of the default route the default controller name is Home and the default action is Index. The outcome of this is that a request to http://yoursite.com would call the Index method on the Home controller. The id part of the route is specified as being optional with UrlParameter.Optional.

What is the fourth parameter?
The fourth parameter is for constraints, you can use regular expressions, in this example in particular this expression “\d+” match strings that are sequences of one or more digits (0-9).

How to create a custom Routers Constraint?
For this example we are going to create a Guid constraing, we have to create a class that inherit from IRouteConstraint and implement it:
routers implement interface
This is the code:

public class GuidConstraint : IRouteConstraint {

public bool Match(HttpContextBase httpContext, Route route, string parameterName, 
                  RouteValueDictionary values, RouteDirection routeDirection)
{
    if (values.ContainsKey(parameterName))
    {
        string stringValue = values[parameterName] as string;
        if (!string.IsNullOrEmpty(stringValue))
        {
            Guid guidValue;
            return Guid.TryParse(stringValue, out guidValue) && (guidValue != Guid.Empty);
        }
    }
    return false;
}}

You can use it in the route like this:

routes.MapRoute("doubleGuid", "{controller}/{action}/{guid1}", 
                 new { controller = "YourController", action = "YourAction" }, 
                 new { guid1 = new GuidConstraint() });

Why we use new?
The new keyword is creating/instanciating an object using the object initializer syntax that was introduced in version 3 of the .Net framework.

Difference between “MapHttpRoute” and “MapRoute”?
ultimately both operate on the same underlying ASP.NET route table, the difference is that MapRoute is used for when the application is hosted in ASP.NET. MapHttpRoute is used for Web Apis for when hosting outside of ASP.NET, Web API wouldn’t have to rely on System.Web.
Web API is not sitting on top of MVC, Web Forms, or, for that matter ASP.NET at all. It can be hosted within web context (ASP.NET) but can also be self hosted in a Console app, WPF, etc.

The major advantage of using routing is that it creates a convention for your Urls. If you created a new controller called Account and action methods called Index and Review then the methods would be available at /Account and Account/Review respectively.

Other resources:
http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/creating-a-route-constraint-cs
https://msdn.microsoft.com/en-us/library/cc668201.aspx?f=255&MSPPError=-2147217396