Friday 16 November 2012

Getting the Longitude and Latitude from a particular address or postcode with Google Maps Api v3.

Google API v3 supports unlimited calls, and doesn’t need the complexity of creating keys like the version 2, Bing maps or Yahoo maps.

I have created a small, but useful function to get the Latitude and Longitude of a particular address or postcode. It looks pretty simple, but this is a nice start if you want to build something big with the Google API.

In this example I target the Buckingham Palace, in London (UK).

<html>
<head>
    <script type='text/javascript' src='http://maps.google.com/maps/api/js?sensor=false'></script>
    <script type="text/javascript">
        //########################################
        function GetLongitudeAndLatitude(_sAddress) {
            var mygc = new google.maps.Geocoder();
            mygc.geocode({ 'address': _sAddress }, function (results, status) {
                alert("latitude : " + results[0].geometry.location.lat());
                alert("longitude : " + results[0].geometry.location.lng());
            });
        }
        //########################################
    </script>
</head>
<body onload="GetLongitudeAndLatitude('SW1A 1AA');">
</body>
</html>

Thursday 15 November 2012

HMTL 5, CSS3 and JavaScript for Windows 8 – Box element

The box element is one of the most awaited elements in HTML5. It is going to facilitate the task of creating boxes in our web site. At this point we are going to start forgetting border-… with divs or tables and concentrate in a really good implementation called box.

I am going to list all the elements compatible with almost all browsers and add some examples:

  1. display:box : To define an element as a flexbox we set the display to box.
    .flexbox {
    display: -moz-box;
    display: -webkit-box;
    display: box;
    }

  2. box-orient: Lay out the children of a div element horizontally.
    .rule {
    -moz-box-orient: vertical;
    -webkit-box-orient: vertical;
    box-orient: vertical;
    }

  3. box-ordinal-group: Specify the display order of the child element of a box, We can reorder elements as we like, using box-ordinal-group.
    .box
    {
    display:-moz-box; /* Firefox */
    display:-webkit-box; /* Safari and Chrome */
    display:box;
    border:1px solid black;
    }
    .ord1
    {
    margin:5px;
    -moz-box-ordinal-group:1; /* Firefox */
    -webkit-box-ordinal-group:1; /* Safari and Chrome */
    box-ordinal-group:1;
    }
    .ord2
    {
    margin:5px;
    -moz-box-ordinal-group:2; /* Firefox */
    -webkit-box-ordinal-group:2; /* Safari and Chrome */
    box-ordinal-group:2;
    } 

  4. box-flex: Define two flexible p elements. If the parent box has a total width of 300px, #p1 will have a width of 100px, and #p2 will have a width of 200px. Box-flex allow the content to expand to fill the available space.
    div
    {
    display:-moz-box; /* Firefox */
    display:-webkit-box; /* Safari and Chrome */
    display:box;
    width:300px;
    border:1px solid black;
    }
    #p1
    {
    -moz-box-flex:3.0; /* Firefox */
    -webkit-box-flex:3.0; /* Safari and Chrome */
    box-flex:3.0;
    border:1px solid red;
    }
    #p2
    {
    -moz-box-flex:1.0; /* Firefox */
    -webkit-box-flex:1.0; /* Safari and Chrome */
    box-flex:1.0;
    border:1px solid blue;
    }

  5. box-align: Center the child elements of a div box by using the box-align and box-pack properties together.
    div
    {
    width:350px;
    height:100px;
    border:1px solid black;
    /* Firefox */
    display:-moz-box;
    -moz-box-orient:horizontal;
    -moz-box-pack:center;
    -moz-box-align:center;
    /* Safari and Chrome */
    display:-webkit-box;
    -webkit-box-orient:horizontal;
    -webkit-box-pack:center;
    -webkit-box-align:center;
    /* W3C */
    display:box;
    box-orient:horizontal;
    box-pack:center;
    box-align:center;
    } 

  6. box-direction: This reverses the order of elements. We can use normal, reverse and inherit.
    #main {
    -moz-box-direction: reverse;
    -webkit-box-direction: reverse;
    box-direction: reverse;
    }

  7. box-pack: Box-pack controls alignment in the direction set by orient. it centers the child elements of a div box by using the box-align and box-pack properties together.
    div
    {
    width:350px;
    height:100px;
    border:1px solid black;
    /* Firefox */
    display:-moz-box;
    -moz-box-orient:horizontal;
    -moz-box-pack:center;
    -moz-box-align:center;
    /* Safari and Chrome */
    display:-webkit-box;
    -webkit-box-orient:horizontal;
    -webkit-box-pack:center;
    -webkit-box-align:center;
    /* W3C */
    display:box;
    box-orient:horizontal;
    box-pack:center;
    box-align:center;
    } 

HMTL 5, CSS3 and JavaScript for Windows 8 – text-transform

This property will be used with CSS3. The text-transform property controls the capitalization of text.

Value Description
none No capitalization. The text renders as it is. This is default
capitalize Transforms the first character of each word to uppercase
uppercase Transforms all characters to uppercase
lowercase Transforms all characters to lowercase
inherit Specifies that the value of the text-transform property should be inherited from the parent element

Example:

   1:  <!DOCTYPE html>
   2:  <html>
   3:  <head>
   4:  <style>
   5:  p.uppercase {text-transform:uppercase;}
   6:  p.lowercase {text-transform:lowercase;}
   7:  p.capitalize {text-transform:capitalize;}
   8:  </style>
   9:  </head>
  10:   
  11:  <body>
  12:  <p class="uppercase">This is some text.</p>
  13:  <p class="lowercase">This is some text.</p>
  14:  <p class="capitalize">This is some text.</p>
  15:  </body>
  16:  </html>
  17:   

HMTL 5, CSS3 and JavaScript for Windows 8 – Media Types

One of the key features we are going to be using in Windows 8 it is Media Types.

Media Types allows you to set different types of screens of devices. It is really useful to create full accessibility to your site, so for example, if the person which is going to read the site can’t see properly, we can use the tag braille next to @media, in that way, if this person has a special device capable of translating sites into braille, it will work.

Other useful case will be having to deal with mobile devices or especial screens, then we can use handheld or screen and (min-width:480px)

Some other properties can be used for different media types. For example, the "font-size" property can be used for both screen and print media, but perhaps with different values. A document usually needs a larger font-size on a screen than on paper, and sans-serif fonts are easier to read on the screen, while serif fonts are easier to read on paper.

Media Types

Media Type Description
all Used for all media type devices
aural Used for speech and sound synthesizers
braille Used for braille tactile feedback devices
embossed Used for paged braille printers
handheld Used for small or handheld devices
print Used for printers
projection Used for projected presentations, like slides
screen Used for computer screens
tty Used for media using a fixed-pitch character grid, like teletypes and terminals
tv Used for television-type devices

Example:
This example displays screen,print and custom screens for a mobile device:

<html>
<head>
<style>
@media screen
   {
   p.test {font-family:verdana,sans-serif;font-size:14px;}
   }
@media print
   {
   p.test {font-family:times,serif;font-size:10px;}
   }
@media screen,print
   {
   p.test {font-weight:bold;}
   }
@media screen and (min-width:200px) and (max-width:480px)
   {
      #navar{
       float: none;
       width: 200px;
      }
   }
@media screen and (min-width:480px)
   {
      #navar{
       float: left
       width: 500px;
      }
   }
</style>
</head>

<body>
....
</body>
</html>

Wednesday 14 November 2012

HMTL 5, CSS3 and JavaScript for Windows 8 – sessionStorage vs localStorage

HTML5 has introduced a new paradigm in the save state or save objects world for HTML5. Unfortunately this is not available for all the browsers yet, but it is available for the whole Windows 8 platform, including apps.

There are two types of Web Storage so far, and these are the localStorage, and the sessionStorage. The main difference is that the localStorage persists over different tabs or windows, and even if we close the browser, accordingly with the domain security policy and user choices about quota limit. The antagonist is the sessionStorage object which follows this rule:

When a new HTMLDocument is created, the user agent must check to see if the document's top-level browsing context has allocated a session storage area for that document's origin. If it has not, a new storage area for that document's origin must be created.

Each Document object must have a separate object for its Window's sessionStorage attribute.

sessionStorage object will not persist if we close the tab (top-level browsing context) as it does not exists if we surf via another tab or window. As summary, as soon as we are in our tab the session storage allows us to save a large amount of key/value pairs and lots of text, something impossible to do via cookie. This is what my implementation is trying to do with browsers that do not implement this special object. If you have doubts, you can directly test the demo link, and come back whenever you want.

To create applications which requiere to remember past data localStorage is our object. For other purposes we can use sessionStorage which at the end of the day is like Session in ASP.NET.

Tuesday 13 November 2012

HMTL 5, CSS3 and JavaScript for Windows 8 – Calling a Web Service with AJAX

There are different ways to call a web service in JavaScript, but the best ones are done with AJAX. I have decided to add the same call but with different formats, so you can’t get lost and choose your favourite.

url: Web service address
type: Protocol, you can choose between GET and POST
timeout: Who long it is your application waiting for the web service.
dataType: Type of data, it could be text , json etc.
contentType: The content type you want, ie: "application/json; charset=utf-8",
cache: Read example below…
datafilter: Read example below…
Accepts:
Read example below…

METHOD 1

     $.ajax({
         url: '/sdsd/sdsd',
         type: 'GET',
         timeout: 1000,
         dataType: 'text'
     }).done(function (responsetext) {
         //do something
     }).fail(function () {
         //do something
     });



METHOD 2

     $.ajax({
         url: '/sdsd/sdsd',
         type: 'GET',
         timeout: 1000,
         dataType: 'text',
         success: function (responsetext) {
             //do something
         },
         error: function (e) {
             //do something
         }
     });




If you don’t specify an error handling jQuery will keep running.



To work with JSON so you can pass data across, JavaScript provides JSON.stringify and JSON.parse.



If you want to send JSON data , you can use something like this (Thanks Bobby):

 function InfoByDate(sDate, eDate) {
        var divToBeWorkedOn = "#AjaxPlaceHolder";
        var webMethod = "http://MyWebService/Web.asmx/GetInfoByDates";
        var parameters = "{'sDate':'" + sDate + "','eDate':'" + eDate + "'}";
        $.ajax({
            type: "POST",
            url: webMethod,
            data: parameters,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                $(divToBeWorkedOn).html(msg.d);
            },
            error: function (e) {
                $(divToBeWorkedOn).html("Unavailable");
            }
        });
    }



The onreadystatechange event is key in AJAX. This is the only way to monitor what is going on. We have three core properties. Please check the values and the example.



onreadystatechange
Stores a function (or the name of a function) to be called automatically each time the readyState property changes

readyState
Holds the status of the XMLHttpRequest. Changes from 0 to 4:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

status
200: "OK"
404: Page not found

<html>
<head>
<script>
    function loadXMLDoc() {
        var xmlhttp;
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", "ajax_info.txt", true);
        xmlhttp.send();
    }
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
I recently show this question in a what it could be a Microsoft exam, and I think it will be quite useful to try to understand ajax calls, it is based on the accepts and datafilter parameter:

You are developing a web application that retrieves data from a web service. The data being retrieved is a custom binary datatype named bint. The data can also be represented in XML. Two existing methods named parseXml() and parseBint() are defined on the page. The application must:
· Retrieve and parse data from the web service by using binary format if possible
· Retrieve and parse the data from the web service by using XML when binary format is not possible



You need to develop the application to meet the requirements. What should you do? (To answer, drag the appropriate code segment to the correct location. Each code segment may be used once, more than once, or not at all. You may need to drag the split bar between panes or scroll to view content.)

          var request = $.ajax({
            uri:'/',
            accepts: 'application/bint, text/xml',
            datafilter: function(data,type){
                if(request.getResponseHeader("Content-Type")=="application/bint")
                   return parseBint(data);
                else
                   return parseXml();
                 },            
            success: function (data) {
              start(data);
            }
        });


Another interesting example is the way you can display on-line stock rates in real time. One of the features we should use to get a time stamp in the header is cache set to false. This will force requested pages not to be cached by the browser. I attach an example:

var stockRate;
function getResults(){
$.ajax({
            async: false,
            cache:false,
            type: "POST",
            url: "stockrates.asmx/rates"
            data: {'stockname':stockName},
            dataType: "json",
            success: function (msg) {
               stockRate=result;
        });
        ShowRate();
}

HMTL 5, CSS3 and JavaScript for Windows 8 – User Input Validation

HTML 5 Supports new validation fields and new input types. This new features are going to make the life really easy for us if we know what we have and what we can use.

The <input> tag supports in the type attribute, the following values:

button
checkbox
color
date
datetime
datetime-local
email
file
hidden
image
month
number
password
radio
range
reset
search
submit
tel
text
time
url
week

There are some tips you should know:

    • If one of the types is not supported by the browser, the field will be displayed anyway, but not in the correct format.
    • Use the form event to validate instead the input event.
    • HTML likes to emphasize the name and id attributes. id for CSS and name when the form is submitted.

We also have the required attribute. This attribute is completely new and allow us to validate client-side. A good validation will include server-side validation as well, so don’t forget to do that.

ie:  <input type="text" name="username" required="required" />

We can set maximum and minimum values with our input control. To do that we will be using the max attribute and the min attribute.

ie: <input type="text" name="price" type=”number” required="required" min=”5” max=”100” />

There is an excellent attribute it is going to help us formatting numbers or any character, very useful for phone numbers by the way. The attribute is called pattern.

The pattern attribute specifies a regular expression against which the control's value, or, when the multiple attribute applies and is set, the control's values, are to be checked.

If specified, the attribute's value must match the JavaScript Pattern production. [ECMA262]

If an input element has a pattern attribute specified, and the attribute's value, when compiled as a JavaScript regular expression with the global, ignoreCase, and multiline flags disabled (see ECMA262 Edition 5, sections 15.10.7.2 through 15.10.7.4), compiles successfully, then the resulting regular expression is the element's compiled pattern regular expression. If the element has no such attribute, or if the value doesn't compile successfully, then the element has no compiled pattern regular expression. [ECMA262]

Constraint validation: If the element's value is not the empty string, and either the element's multiple attribute is not specified or it does not apply to the input element given its type attribute's current state, and the element has a compiled pattern regular expression but that regular expression does not match the entirety of the element's value, then the element is suffering from a pattern mismatch.

Constraint validation: If the element's value is not the empty string, and the element's multiple attribute is specified and applies to the input element, and the element has a compiled pattern regular expression but that regular expression does not match the entirety of each of the element's values, then the element is suffering from a pattern mismatch.

The compiled pattern regular expression, when matched against a string, must have its start anchored to the start of the string and its end anchored to the end of the string.

Note:
This implies that the regular expression language used for this attribute is the same as that used in JavaScript, except that the pattern attribute is matched against the entire value, not just any subset (somewhat as if it implied a ^(?: at the start of the pattern and a )$ at the end).

When an input element has a pattern attribute specified, authors should include a title attribute to give a description of the pattern. User agents may use the contents of this attribute, if it is present, when informing the user that the pattern is not matched, or at any other suitable time, such as in a tooltip or read out by assistive technology when the control gains focus.

ie: <label> Part number: <input pattern="[0-9][A-Z]{3}" name="part" title="A part number is a digit followed by three uppercase letters."/> </label>

It will produce the following:

A part number is a digit followed by three uppercase letters.
You cannot submit this form when the field is incorrect.

How to create a nice border validation?
The best practice for validation logic is to add a red border when the validation has not been done properly. In CSS 3 you can add the valid/invalid into the input element.

For validation you could have the following:
input {
  border: solid 1px;
}
input:invalid{
   border-color: #f00;
}
input:valid{
  border-color: #0f0;
}

Monday 12 November 2012

HMTL 5, CSS3 and JavaScript for Windows 8 – Little JavaScript tips

In this post I am going to add these small things I always forget when I work with JavaScript and are quite useful:

  1. How do you put a message in the browser’s status bar?: windows.status(“hello world”);
  2. What do you use to comment in JavaScript?: // and /* */
  3. What is the correct way to write a JavaScript array?: var txt = new Array (“Hello”,”World”, “how”);
  4. How do you write something with JavaScript?: document.write(“Hello World”);
  5. How does a “while” loop start?: while(i<=10);
  6. What is the purpose of DOM (Document Object Model)?: The DOM represents the structure of a web page. You use it to add dynamic functionality to the page.
  7. DOM core methods to create new objects for a document:
      • document.createElement(tagname)
      • document.createTextNode(string)
      • document.createAttribute(name,value)
      • document.createDocumentFragment
  8. How do you round a number to the nearest integer?: Math.round(7.25);
  9. How do you find the Maximum number between two numbers?: Math.max(x,y);
  10. How to pass a JavaScript reference into a website: <script type=”text/javascript” src=”alertme.js”></script>
  11. Internet Explorer 6,7 and 8 do not support addEventListener() and removeEventListener(). Use similar attachEvent() and detachEvent() functions instead.
    Some events in the HTML DOM ‘bubble’ meaning that if the event occurs on an element (and it is or isn’t handled), the event will then also fire on the element’s parent node and then on its grandparent node and so on until the event reaches an element where it may not bubble any further or it reaches the root node. Both addEventListener and removeEventListener have an optional third Boolean parameter indicating whether or not this is the case.
  12. How do you find clients browser name?: navigator.appName
  13. How do you open a new window in JavaScript?:mywindow=window.open(“http://www.google.com”);
  14. How do you split a large string in two lines in Javascript?:
    document.write(“hello my name is \
    prince”);
  15. Microsoft implementation of JavaScript is called JScript.
  16. <noscript> tag Alerts the users that your page uses JavaScript, and so the user should enable JavaScript in the browser in order to display your page correctly.
  17. Having the following code what does this code returns….(this is a nice exercise):

<script>
var a=””
var b=0;
var c=false;
document.write(a==c);//true
document.write(a===c);//false
document.write(b==c);//true
document.write(b===c);//false
</script>



</script>

HMTL 5, CSS3 and JavaScript for Windows 8 - IMG

This is a nice question I remembered for one of my Microsoft exams, I have just wanted to blog it:

Which is mandatory attribute in this line?

<img src=”lalala.png” alt"=”this is lalala” height=”100” width=”100”>

Answer… src!

Enjoy your day…

HMTL 5, CSS3 and JavaScript for Windows 8 – The magic of the <SECTION> and <ARTICLE> tags in HTML 5.

<Section>:
There is a new kid on the block in HTML5, and that is called <Section>. The <Section> tag has been introduced to make the life easier to the web developers. It is basically a notation, but a really useful and powerful one, especially if it is combined withe the <Article> tag.

The <Section> tag defines sections in a document. Such as chapters, headers, footers, or any other sections of the document. One of the best things about the <Section> Tag, it is the fact it supports all the Globals Attributes in HTML and of course the Event Attributes.

So this:
<section>
  <h6>WWF's Panda symbol</h6>
  <p>The Panda has become the symbol of WWF. The well-known panda logo of WWF originated from a panda named Chi Chi that was transferred from the Beijing Zoo to the London Zoo in the same year of the establishment of WWF.</p>
</section>

It will generate:

WWF's Panda symbol

The Panda has become the symbol of WWF. The well-known panda logo of WWF originated from a panda named Chi Chi that was transferred from the Beijing Zoo to the London Zoo in the same year of the establishment of WWF.

<Article>:
The <Article> tag is much more independent than the section one,self-contained content. An article normally comes embedded into a section.

An article should make sense on its own and it should be possible to distribute it independently from the rest of the site.

Potential sources for the <article> element:

  • Forum post
  • Blog post
  • News story
  • Comment

So this:
<article>
  <h1>Internet Explorer 9</h1>
  <p>Windows Internet Explorer 9 (abbreviated as IE9) was released to
  the  public on March 14, 2011 at 21:00 PDT.....</p>
</article>

It will generate:

Internet Explorer 9

Windows Internet Explorer 9 (abbreviated as IE9) was released to the public on March 14, 2011 at 21:00 PDT.....

HMTL 5, CSS3 and JavaScript for Windows 8 – [href] attribute.

A good question and easy to answer in the href attribute in HTML 5. Well just to let you know, it keeps doing the same thing than HTML 4, always with its sister <a>.

The [href] attribute is the most important part of linking one online resource to another.

HMTL 5, CSS3 and JavaScript for Windows 8 – What is an Ordered List?

An ordered list starts with the <ol> tag. Each list item starts with the <li> tag. The list items are marked with numbers.

In the HTML 5 paradigm, only the following attributes are supported:

 

Attribute

Vale

Description

compact compact Not supported
reversed reversed Specifies that the list order should be descending (9,8,7...)
start number Specifies the start value of an ordered list
type

1
A
a
I
i

Specifies the kind of marker to use in the list.

An example like this:
<ol>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>
<ol start="50">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

Will produce the following:

  1. Coffee
  2. Tea
  3. Milk
  1. Coffee
  2. Tea
  3. Milk

HMTL 5, CSS3 and JavaScript for Windows 8 – Heading Tags in a HTML 5 Document.

Html 5 is keeping the old fashion HTML heading tags, but this time they are going to be used extensible. Remember larger the number, smaller the header.

<H1> Hello World </H1>:

Hello World

<H2> Hello World </H2>:

Hello World

<H3> Hello World </H3>:

Hello World

<H4> Hello World </H4>:

Hello World

<H5> Hello World </H5>:

Hello World

<H6> Hello World </H6>:

Hello World

HMTL 5, CSS3 and JavaScript for Windows 8 – An unofficial collaboration of Web browser manufacturers and interested parties

WHATWG has become a large community where vendors and users have become key in the project. The Web Hypertext Application Technology Working Group (WHATWG) is a community of people interested in evolving HTML and related technologies. The WHATWG was founded by individuals from Apple, the Mozilla Foundation and Opera Software in 2004.

Since then, the editor of the WHATWG specifications, Ian Hickson, has moved to Google. Chris Wilson of Microsoft was invited but did not join, citing the lack of a patent policy to ensure all specifications can be implemented on a royalty-free basis.

The DOCTYPE declaration for this new standard is:
<!DOCTYPE html>

Thursday 2 August 2012

Deploying a Timer Job in a Single Farms and Multiple Farms

What apparently could look a piece of cake, deploy a timer job, some times could become a nightmare.

On single farms Timer Jobs are controlled by the SPTimerv4 service which establish all the Timer Jobs on the START. That means, if you deploy a timer job and activate it it will not work until you re start this service

If you are working in a single farm with only one server you should have a mayor problem, but I recommend you to follow these instructions before activating the feature, this is the best installation you can perform:

  1. Create a wsp package in Visual Studio.
  2. Copy the wsp package in the server you want to deploy the Timer Job (for instance c:)
  3. Go to the server were you want to deploy the solution and go to Start->SharePoint 2010 Management Shell
  4. Type Add-SPSolution
  5. It will ask for the identity, just type c:\nameofsolution.wsp
  6. Now let’s go to install it.
  7. Type Install-SPSolution –GACDeployment
  8. it will ask for the identity: just type nameofsolution.wsp
  9. Now type net stop sptimerv4
  10. Now type net start sptimerv4
  11. Now type iisreset
  12. Go to Site Collection Administration->Site Collection Features
  13. Activate the feature.

To Uninstalling the service

  1. Deactivate the feature by going to Site Collection Administration->Site Collection Features
  2. Uninstall-SPSolution -Identity nameofsolution.wsp –allwebapplications
  3. Remove-SPSolution –force
  4. then Type the identity: nameofsolution.wsp
  5. Now type net stop sptimerv4
  6. Now type net start sptimerv4
  7. Now type iisreset

On Multiple farms it is a different issue. For the start you need to synchronize all the clocks so the whole farm can run the Timer Job properly. Only the application pool owners from the particular server where site collection lives will be able to activate the feature. The other way, will be doing it with Enable-SPFeature via Powershell or use the famous stsadm.

Now, having a farm like this:

image

The first thing we will do is going to the Server 3 (Apps). This server is the one which contains all the services, and we will do the following:

  1. Copy the wsp package in the server you want to deploy the Timer Job (for instance c:)
  2. Go to the server were you want to deploy the solution and go to Start->SharePoint 2010 Management Shell
  3. Type Add-SPSolution
  4. It will ask for the identity, just type c:\nameofsolution.wsp
  5. Now let’s go to install it.
  6. Type Install-SPSolution –GACDeployment
  7. it will ask for the identity: just type nameofsolution.wsp
  8. Now type net stop sptimerv4
  9. Now type net start sptimerv4
  10. (optional) Now type iisreset

Now, for every single server, a apart of of Server 4, do the following:

  1. Go to the server were you want to deploy the solution and go to Start->SharePoint 2010 Management Shell
  2. install-spsolution nameofsolution.wsp -GACDeployment –force
  3. Now type net stop sptimerv4
  4. Now type net start sptimerv4
  5. (optional) Now type iisreset

Go to Site Collection Administration->Site Collection Features and try to activate the feature. If you get an Access Denied, will be because you are in the wrong server, and your app pool identity doesn’t have access to it. I recommend you going to any other server to do it or just type the following from Powershell:

type Enable-SPFeature , and then type the name of the feature.

To remove the Timer Job, I suggest you to disable the feature first and then do the following:

  1. Uninstall-SPSolution -Identity nameofsolution.wsp –allwebapplications
  2. Remove-SPSolution –force
  3. then Type the identity: nameofsolution.wsp
  4. Now type net stop sptimerv4
  5. Now type net start sptimerv4
  6. (Optional) Now type iisreset

 

Conclusion: Timer Jobs are natural services for Sharepoint and become a really useful tool when you want to perform really complex operations. It is all controlled by Sharepoint so you don’t need to worry about, but only remember, theses steps so you don’t spend more time deploying it than developing.

Tuesday 17 July 2012

On Infopath 2010 "Unable to connect to the SharePoint site."

This is the scenario, you are going to Infopath 2010, you go to File->Sharepoint List and when it ask to enter the location of a Sharepoint list, you enter your site and gives you this error: "Unable to connect to the SharePoint site."

The problem is simple, your web application needs a Root site. This is common when you create a site with the wizard so you get http://xxx/sites/mynewsite. What we can it is to create a site for http://xxx/.

How?
  1. Go to Central Administration.
  2. Site Collections->Create site collections.
  3. Select web application where you want to create site collection from the drop down.
  4. Give a desiredtitle/description and select “/” from the URL drop down. Front slash stands for a top level site. You will not see it listed in the drop down if you have already created a top level site collection because you can only create one top level site collection per web application.
  5. Try Infopath 2010 now!

Tuesday 19 June 2012

"The Module DLL 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\isapi\owssvr.dll' could not be loaded due to a configuration problem.The current configuration only supports loading images built for a x86 processor architecture. The data field contains the error number."

This is an interesting problem I spotted the other day when someone messed around with my lovely dev server.

The solution is really simple it is a matter of changing the application pool to x64... how?

go to Start->type InetMgr.exe -> Expand your server ->Application Pools -> Select the application pool you think it could be wrong->Advance Settings... -> Under general, change "Enable 32-Bit Applications" to False. Click ok!

Thursday 31 May 2012

Configuring an Alternate Access Mapping (AAM) in SharePoint 2010 to expose a web application to the Internet.

I know many people have been in trouble trying to do what it looks a simple exercise, expose a web application to the outside world.

I have to admit we will need few requirements to do this, and they are not easy to get:

  • A DNS address: A URL will be pointing your server, in this case we are going to use a random one: http://svm15031.vps.tagadab.com
  • An Installation of Sharepoint 2010 Enterprise or Foundation.
  • II7
  • Windows Server 2008
  • a web application already created.

Let’s go to follow a simple step by step scenario so we know what we are doing.

Step 1
Go to Start->Microsoft SharePoint 2010 Products->SharePoint 2010 Central Administration

Step 2
Go to Central Administration->Application Management->Manage Web applications.image

Step 3
Click on web applications and select your “80” website, and on the top left click extend. In this way we are going to extend our site to port 81, so the users are comming from the outside world will use this port. Click on “Extend” and fill the following fields:

  1. Port: 81
  2. Host Header: svm15031.vps.tagadab.com
  3. Zone: Select Internet

image

Step 4
To check the bindings go to Server Manager->Roles->Web Server (IIS)->Internet Information Server.
Click on the site we are dealing, in this case will be called . On the right side click on bindings and be sure you receive something similar.
image

Step 5
We are going to change the authentication of the extended site now. Go to Central Administration->Application Management->Manage Web applications select the “80” Web application and click on Authentication Providers. You will receive this dialog, click on Internet.
image

Step 6
On IIS Authentication Settings un tick Integrated Windows authentication and tick Basic authentication (password is sent in clear text).
image

Step 7
Everything is done now…but we have to be sure that our application can be seen in port 81 from the outside world, so let’s go to create a rule in the firewall to do that. Go to Server Manager->Configuration->Windows Firewall with…->Inbound Rules-> Right click –> New Rule. Select Port and click Next. On specific local ports type 81 and click on Next –>Allow connection –> Next –> Domain, Public and private tick it! –>Next –>Type teh name of the rule and finish. Do the same with Outbound Rules.
image

Step 8
In my web application I created a site collection with a site called “hello”, this is how I will call it from Internet:
http://svm15031.vps.tagadab.com:81/sites/hello/SitePages/Home.aspx . It will prompt for user and password!

And this will be the result:
image

Enjoy!

Thursday 3 May 2012

"Administration service is stopped. Start the Microsoft SharePoint Foundation Administration 2010 service in order for the operation to continue." On Sharepoint 2010

This is one of this messages you don't expect, specially when you are trying to restore a backup at 4:00AM in the morning after seeing that the whole farm needs to be rebuilt. The last thing you need at 4:00AM is more problems, just because in four hours the company will start running.

To prevent that I have placed this little post, I hope it will will help.



So why is the "Administration service is stopped. Start the Microsoft SharePoint Foundation Administration 2010 service in order for the operation to continue." is popping up?. Well there is Windows Service called WSSADMIN.exe is used by SharePoint to perform backup/restore operations.



As you probably guessing the service has not been started, so just go to Services in Windows, and find a service called "SharePoint 2010 Administration".

Click on start and voila!

Friday 6 January 2012

Adding a Custom Content Type to a document library with Powershell in Sharepoint 2010

Sometimes you will want to add your own Content Types (custom content types) to your list or document libraries (a list basically…). You can do it with the web interface, it is pretty easy, but what about if you need to perform this for 30,000 sites… you don’t want to spend the rest of the year clicking everywhere.

I have created a function , AddContentTypeToDocumentLibraryRemovingOtherContentType, which allows you to Add a Content Type (“DMSDocument”) and remove the default one (“Documents”). Be aware I will remove “Documents” from my list and add the content type from the site. Whart I am doing here is replacing the default “Document” content type with sophisticated Document content type I developed before called “DMSDocument”

You only need to pass:

  1. Name of the site URL
  2. Name of the Document Library
  3. Name of the Content Type to be added
  4. Name of the Content Type you want to remove from your Document Library.
 $_CurrentURL =  "http://sp_server"
 $_DocumentLibraryName = "Document Centre"
 $_ContentTypeToBeRemoved = "Document"
 $_ContentTypeToBeAdded = "DMSDocument"
 
 Function AddContentTypeToDocumentLibraryRemovingOtherContentType($_sCurrentURL,$_sDocumentLibraryName,$_sContentTypeToBeRemoved, $_sContentTypeToBeAdded)
 { 
 		## Getting the website...
  		$SPWeb = Get-SPWeb -Identity $_sCurrentURL		
		
		## Getting the Document Library (list) and enable Content Types
		$List = $SPWeb.Lists[$_sDocumentLibraryName]
		$List.ContentTypesEnabled = $true
		$List.update()
		
		## Getting the content types to be removed
		## NOTE: This particular one, "Document" lives in our list,
		##       so we remove it from there
		$DocumentCT = $List.ContentTypes[$_sContentTypeToBeRemoved]		
		## This Content type lives in the site, so we get it from there
    	         $CustomCT = $SPWeb.ContentTypes[$_sContentTypeToBeAdded]
    	         $List.ContentTypes.Delete($DocumentCT.Id)
		$List.ContentTypes.Add($CustomCT) 		
		$List.update()	
		
		## Disposing SPWEB object to avoid memory leaks.
		$SPWeb.Dispose()
}
AddContentTypeToDocumentLibraryRemovingOtherContentType $_CurrentURL $_DocumentLibraryName $_ContentTypeToBeRemoved $_ContentTypeToBeAdded

Conclusion: Powershell will bring you a high rate of productivity, but don’t forget to dispose the objects, otherwise you could cause memory leaks in your farm.