Wednesday 30 October 2013

Using Geo Location in browser

GeoLocation

Using geoLocation with esri maps.
Solution works on
  1. Internet explorer 10
  2. FireFox
  3. Opera
  4. Chrome
  5. Windows Phone (nokia in office)
  6. Android (Samsung)
  7. IOS (Iphone 4)
Solution does not work
  1. Safari

Now lets get to the code:

This is way how we can detect whether the geolocation is supported in your browser. Obviously you will want to add some different code instead of displaying your result into console.

 if (!navigator.geolocation) {              
    console.log("geolocation is not supported by this browser.");
}

Method that actually gets the location is as follows

 function getLocation() {
    console.log("Supports location, getting current location");
    navigator.geolocation.getCurrentPosition(showPosition, errorCallBack);
 }
This method has 2 callbacks. First method that displays position, and second that handles all errors.

function showPosition
 function showPosition(position) {
     console.log("Latitude: " + position.coords.latitude);
     console.log("Longitude: " + position.coords.longitude);
 }
note: position does not get filled rightaway but its callback.

function errorCallBack
 function errorCallBack() {
                // deal with errors
            }


Here I am including my testing code with esri maps.

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
        <link rel="stylesheet" type="text/css" href="http://js.arcgis.com/3.7/js/esri/css/esri.css">
        <script src="//js.arcgis.com/3.7/"></script>
    </head>
    <body>

        <div id="locationInfo">
            <a style="float:right;" class="Button" href="#" onclick="getLocation()">
                <i class="icon-map-marker"></i>
                <span class="i-name">Use my location</span>
            </a>
        </div>
        <div style="clear: both;"></div>
        <div style="width: 400px;height: 400px;">
            <div id="map" class="map">

            </div>
        </div>

        <script>
            var map;
            var defaultZoomLevel = 12;
            require([
                  "esri/map",
                  "dojo/domReady!"
                ], function (
                  Map, LocateButton
                ) {
            
                    map = new Map("map", {
                        center: [-2.58791, 51.454513],
                        zoom: defaultZoomLevel,
                        basemap: "streets"
                    });
                });
            
            
                if (!navigator.geolocation) {              
                    console.log("Geolocation is not supported by this browser.");
                    RemoveLocation();
                }
            
            function getLocation() {
               console.log("Supports location, getting current location");
               navigator.geolocation.getCurrentPosition(showPosition, errorCallBack);
            }
            
            function showPosition(position) {
                console.log("Latitude: " + position.coords.latitude);
                console.log("Longitude: " + position.coords.longitude);
            
                CenterMap(position.coords.latitude, position.coords.longitude);
            }
            
            function CenterMap(lat, long) {
                var CenPoint = new esri.geometry.Point({ "x": long, "y": lat, " spatialReference": { " wkid": 4326} });
            
                var pointer = esri.geometry.geographicToWebMercator(CenPoint);
            
                map.centerAndZoom(pointer, defaultZoomLevel);
            }
            
            function errorCallBack() {
                // deal with errors
            }
            
            function RemoveLocation() {
                document.getElementById("locationInfo").innerHTML = "";
            }
            
        </script>
    </body>
</html>
 
More reading: diveintohtml5 (this is thanks to Peter Bridger)

Tuesday 29 October 2013

SQLMETAL

You might be surprised but this tool is still about, but most people had forgotten its around.

Its great tool for generating fast data access code.


SqlMetal.exe (Code Generation Tool)

.NET Framework 4. 
The SqlMetal command-line tool generates code and mapping for the LINQ to SQL component of the .NET Framework. By applying options that appear later in this topic, you can instruct SqlMetal to perform several different actions that include the following:
  • From a database, generate source code and mapping attributes or a mapping file.
  • From a database, generate an intermediate database markup language (.dbml) file for customization.
  • From a .dbml file, generate code and mapping attributes or a mapping file.
The SQLMetal file is included in the Windows SDK that is installed with Visual Studio. By default, the file is located at drive:\Program Files\Microsoft SDKs\Windows\vn.nn\bin. If you do not install Visual Studio, you can also get the SQLMetal file by downloading theWindows SDK.



Note Note
Developers who use Visual Studio can also use the Object Relational Designer to generate entity classes. The command-line approach scales well for large databases. Because SqlMetal is a command-line tool, you can use it in a build process. Object Relational Designer (O/R Designer)
Object Relational Designer (O/R Designer)
sqlmetal [options] [<input file>]

To view the most current option list, type sqlmetal /? at a command prompt from the installed location.
Connection Options
Option
Description
/server: <name>
Specifies database server name.
/database: <name>
Specifies database catalog on server.
/user: <name>
Specifies logon user id. Default value: Use Windows authentication.
/password:<password>
Specifies logon password. Default value: Use Windows authentication.
/conn: <connection string>
Specifies database connection string. Cannot be used with /server/database/user, or /password options.
Do not include the file name in the connection string. Instead, add the file name to the command line as the input file. For example, the following line specifies "c:\northwnd.mdf" as the input file: sqlmetal /code:"c:\northwind.cs" /language:csharp "c:\northwnd.mdf".
/timeout: <seconds>
Specifies time-out value when SqlMetal accesses the database. Default value: 0 (that is, no time limit).
Extraction options
Option
Description
/views
Extracts database views.
/functions
Extracts database functions.
/sprocs
Extracts stored procedures.
Output options
Option
Description
/dbml [:file]
Sends output as .dbml. Cannot be used with /map option.
/code [:file]
Sends output as source code. Cannot be used with /dbml option.
/map [:file]
Generates an XML mapping file instead of attributes. Cannot be used with /dbml option.
Miscellaneous
Option
Description
/language: <language>
Specifies source code language.
Valid <language>: vb, csharp.
Default value: Derived from extension on code file name.
/namespace: <name>
Specifies namespace of the generated code. Default value: no namespace.
/context: <type>
Specifies name of data context class. Default value: Derived from database name.
/entitybase: <type>
Specifies the base class of the entity classes in the generated code. Default value: Entities have no base class.
/pluralize
Automatically pluralizes or singularizes class and member names.
This option is available only in the U.S. English version.
/serialization: <option>
Generates serializable classes.
Valid <option>: None, Unidirectional. Default value: None.
For more information, see Serialization [LINQ to SQL].
Input File
Option
Description
<input file>
Specifies a SQL Server Express .mdf file, a SQL Server Compact 3.5 .sdf file, or a .dbml intermediate file.

SqlMetal functionality actually involves two steps:
  • Extracting the metadata of the database into a .dbml file.
  • Generating a code output file.
    By using the appropriate command-line options, you can produce Visual Basic or C# source code, or you can produce an XML mapping file.
To extract the metadata from an .mdf file, you must specify the name of the .mdf file after all other options.
If no /server is specified, localhost/sqlexpress is assumed.
Microsoft SQL Server 2005 throws an exception if one or more of the following conditions are true:
  • SqlMetal tries to extract a stored procedure that calls itself.
  • The nesting level of a stored procedure, function, or view exceeds 32.
    SqlMetal catches this exception and reports it as a warning.
To specify an input file name, add the name to the command line as the input file. Including the file name in the connection string (using the /conn option) is not supported.

Generate a .dbml file that includes extracted SQL metadata:
sqlmetal /server:myserver /database:northwind /dbml:mymeta.dbml
Generate a .dbml file that includes extracted SQL metadata from an .mdf file by using SQL Server Express:
sqlmetal /dbml:mymeta.dbml mydbfile.mdf
Generate a .dbml file that includes extracted SQL metadata from SQL Server Express:
sqlmetal /server:.\sqlexpress /dbml:mymeta.dbml /database:northwind
Generate source code from a .dbml metadata file:
sqlmetal /namespace:nwind /code:nwind.cs /language:csharp mymetal.dbml
Generate source code from SQL metadata directly:
sqlmetal /server:myserver /database:northwind /namespace:nwind /code:nwind.cs /language:csharp


Wednesday 23 October 2013

Could not load file or assembly 'Microsoft.Data.Tools.Components' or one of its dependencies.

Error

Build 
MSBuild 
Db\Database.sqlproj 
_SetupSqlBuildInputs 
SqlModelResolutionTask 
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\SSDT\Microsoft.Data.Tools.Schema.SqlTasks.targets(395, 5): error MSB4018: The "SqlModelResolutionTask" task failed unexpectedly.
System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Data.Tools.Components, Version=11.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
File name: 'Microsoft.Data.Tools.Components, Version=11.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
   at Microsoft.Data.Tools.Schema.Sql.Extensibility.ToolingShim.DoDacFxCompatibilityTest()
   at Microsoft.Data.Tools.Schema.Tasks.Sql.DataTask.Execute()
   at Microsoft.Data.Tools.Schema.Tasks.Sql.SqlModelResolutionTask.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__20.MoveNext()

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

Project Db\Database.sqlproj failed. 
Project CMS.sln failed. 

Solution

  1. download latest version of your ssdt http://msdn.microsoft.com/en-us/data/tools.aspx or http://msdn.microsoft.com/en-us/data/hh297027
  1. if you installing it on server download offline version(iso)
  2. inside you will be able to find file {ISO}\SSDT\X86\SSDTBUILDUTILITIES.MSI
  3. Execute this installation and problem is solved.

Thursday 3 October 2013

Executing scripts / files using powershell

Note: PS refers to PowerShell

Powershell has 2 main ways I have tested how to execute scripts.
  1.        Start-Process
  2.        Invoke-Command

Start-Process

       After research, and using in example i have found it is ill-suited to run commands with arguments, unless you construct everything in one command and then execute. You can get only one set of results and you need to add additional logic in order to pass messages to parent window.

Example:

$ScriptPath = "D:\Scripts\script.ps1"
$WebSiteName = 'MyWebSite'
$PathToDirectory ="D:\site"


#Definition of AllArguments (keep in mind the quotes) 
$AllArgument = '-ExecutionPolicy Unrestricted -file "' + $ScriptPath + '" 
-IsRunAsAdmin -args ' + "$WebSiteName, $PathToDirectory" 

$AdminProcess = Start-Process "$PsHome\PowerShell.exe" -WindowStyle Maximized  -Verb RunAs -ArgumentList $AllArgument -PassThru 
      
# Access the process by ID and wait for its end
Wait-Process $AdminProcess.Id 

Invoke-Command

       Is used mosty of running command as part of a script where there is no need for user interaction. All output is directed into one window unless specified otherwise.
Example
$ScriptPath = "D:\Scripts\script.ps1"
$WebSiteName = 'MyWebSite'
$PathToDirectory ="D:\site\"

Executing option script 1

$script = [scriptblock]::create( @"
param(`$PathToDirectory,`$WebSiteName,`$Debug=`$False)
&{ $(Get-Content $ScriptPath -delimiter ([char]0)) } @PSBoundParameters
"@ )

Invoke-Command -Script $script -Args $PathToDirectory,$WebSiteName, $false

Executing option script 2

icm { 
    param($PathToDirectory,$WebSiteName,$Debug=$False)
    D:\Scripts\script.ps1 @PSBoundParameters
} -ArgumentList $PathToDirectory,$WebSiteName, $false
NOTE: icm is same as Invoke-Command

Executing option script 3

Invoke-Command { 
    param($PathToDirectory,$WebSiteName,$Debug=$False)
    &$ScriptPath @PSBoundParameters
} -ArgumentList $PathToDirectory,$WebSiteName, $false 

Wednesday 2 October 2013

Umbraco Links


 Slowly I am getting loads of articles about Umbraco

Here are some I have found usefull


Publishing events using V4 code base in V6 
http://our.umbraco.org/forum/developers/api-questions/38101-V6-ContentService-Publish-Event


MVC

 Custom routing
http://shazwazza.com/category/Umbraco


MVC Umbraco testing
http://dipunm.wordpress.com/2013/06/16/creating-testable-controllers-in-umbraco/


Code UI Automation
http://watin.org/

Restart IIS Site using powershell script with credentials

I need to reset iis site using team city build.
I have decided to use PowerShell as I have been using it for everything else to do with the build.

When I have attempted to run this under my normal credentials, it did not work and I got error:

 System.InvalidOperationException: Process should have elevated status to access IIS configuration data.
    at Microsoft.IIs.PowerShell.Provider.ConfigurationPr
 ovider.Start(ProviderInfo providerInfo)
    at System.Management.Automation.SessionStateInternal
 .NewProvider(ProviderInfo provider)
    at System.Management.Automation.SessionStateInternal
 .AddProvider(Type implementingType, String name,
 String helpFileName, PSSnapInInfo psSnapIn,
 PSModuleInfo module)



Not to be beaten, I have proceeded on trip how to run this with elevated permissions.






Code:

# ============================== #
#     Definition of variables    #
# ============================== #
$UserName = "Domain\UserName"  
$UserPassword = 'password'
$computer = 'ServerName'
$WebSiteName = 'Site-Build'

# ============================== #
#   Generic setup                                              #
# ============================== #
$SecurePassword = ConvertTo-SecureString -AsPlainText -Force -String $UserPassword
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $UserName , $SecurePassword

# ========================== #
#   Option 1                                            #
# ========================== #
$a = {
  function foo([string]$WebSiteName){

    Write-Host "Restarting website $WebSiteName"
    Import-Module WebAdministration
    Stop-WebSite $WebSiteName
    Start-Sleep -Milliseconds 5000
    Start-WebSite $WebSiteName
    return "$WebSiteName"
  }
 
  foo($args)
}
$rv = Invoke-Command -Credential $Credential -ComputerName $computer -ScriptBlock  $a -ArgumentList $WebSiteName
Write-Host $rv1

# ========================== #
#   Option 2 - preffered by me                #
# ========================== #
Start-Sleep -Milliseconds 15000

function foo([string] $WebSiteName){
   
    Write-Host "Restarting website $WebSiteName"
    Import-Module WebAdministration
    Stop-WebSite $WebSiteName
    Start-Sleep -Milliseconds 5000
    Start-WebSite $WebSiteName

    return "$WebSiteName"
}


$rv1 = Invoke-Command -Credential $Credential -ComputerName $computer -ScriptBlock ${function:foo} -ArgumentList $WebSiteName
Write-Host $rv1

<#  #>