Sunday 24 November 2013

TFS Something went wrong and we can't sign you in right now.


Issue -Error message (from tfs.visualstudio.com):

 Something went wrong and we can't sign you in right now. Please try again later.

Cause:

Your solution has been previously binded, but when you rebind, its to your old configuration. You will need to check out again.

Solution 1:


Make sure you back up all your changes.


  1. Remove binding to your solution.
  2. Bind again
  3. Deal with merges


Solution 2 (Could be safer as you coping over data, and still have unchanged original changes):



  1. Check our to different location
  2. Copy over your changes
  3. Deal with merges


Tuesday 19 November 2013

Using MVC 4 bundles & missing scripts

I have been working on page which is using MVC 4 and I thought that I will use build in feature that come out of box with System.Web.Optimization. Bundles make live easier as we can register our scripts in code and get nice minified file with all in one. There fore there is not so many trips from client to server to get one script one, next script etc.

From design we have to include many scripts such as:

<script src="/Scripts/jquery.min.js"></script>
<script src="/Scripts/bootstrap.min.js"></script>
<script src="/Scripts/jquery.isotope.min.js"></script>
<script src="/Scripts/jquery.prettyPhoto.js"></script>
<script src="/Scripts/easing.js"></script>
<script src="/Scripts/jquery.lazyload.js"></script>
<script src="/Scripts/jquery.ui.totop.js"></script>
<script src="/Scripts/selectnav.js"></script>
<script src="/Scripts/ender.js"></script>
<script src="/Scripts/responsiveslides.min.js"></script>
<script src="/Scripts/custom.js"></script>

Next conversion is to razor:
    @Scripts.Render("~/Scripts/jquery.min.js")
    @Scripts.Render("~/Scripts/bootstrap.min.js")
    @Scripts.Render("~/Scripts/jquery.isotope.min.js")
    @Scripts.Render("~/Scripts/jquery.prettyPhoto.js")
    @Scripts.Render("~/Scripts/easing.js")
    @Scripts.Render("~/Scripts/jquery.lazyload.js")
    @Scripts.Render("~/Scripts/jquery.ui.totop.js")
    @Scripts.Render("~/Scripts/selectnav.js")
    @Scripts.Render("~/Scripts/ender.js")
    @Scripts.Render("~/Scripts/responsiveslides.min.js")
    @Scripts.Render("~/Scripts/custom.js")
Bundles are different:

        @Scripts.Render("~/bundles/site")

code in app_start / bundle config

 var scriptBundle = new ScriptBundle("~/bundles/site")
        "~/Scripts/jquery.min.js",
        "~/Scripts/bootstrap.min.js",
        "~/Scripts/jquery.isotope.min.js",
        "~/Scripts/jquery.prettyPhoto.js",
        "~/Scripts/easing.js",
        "~/Scripts/jquery.lazyload.js",
        "~/Scripts/jquery.ui.totop.js",
        "~/Scripts/selectnav.js",
        "~/Scripts/ender.js",
        "~/Scripts/responsiveslides.min.js",
        "~/Scripts/custom.js");
 bundles.Add(scriptBundle);
This will include all files in no specific order. Also will exclude all allready minified files.
And result will look like:
<script src="/Scripts/jquery.prettyPhoto.js"></script>
<script src="/Scripts/easing.js"></script>
<script src="/Scripts/jquery.lazyload.js"></script>
<script src="/Scripts/jquery.ui.totop.js"></script>
<script src="/Scripts/selectnav.js"></script>
<script src="/Scripts/ender.js"></script>
<script src="/Scripts/custom.js"></script>

I my case I do want to include minified files and order of scripts is important to me, as all depend on each other with specific order.

Final solution is:

bundles.IgnoreList.Clear();
Clears ignore list which contain definition for minified scripts.

bundles.FileSetOrderList.Clear();
Clears file set order list, will be displayed as they are registered.

 BundleTable.EnableOptimizations = true;
Force minification of the files registered.

        bundles.FileSetOrderList.Clear();
        bundles.IgnoreList.Clear();
            
            var scriptBundle = new ScriptBundle("~/bundles/site")
                   .Include("~/Scripts/jquery.min.js")
                   .Include("~/Scripts/bootstrap.min.js")
                   .Include("~/Scripts/jquery.isotope.min.js")
                   .Include("~/Scripts/jquery.prettyPhoto.js")
                   .Include("~/Scripts/easing.js")
                   .Include("~/Scripts/jquery.lazyload.js")
                   .Include("~/Scripts/jquery.ui.totop.js")
                   .Include("~/Scripts/selectnav.js")
                   .Include("~/Scripts/ender.js")
                   .Include("~/Scripts/responsiveslides.min.js")
                   .Include("~/Scripts/custom.js");
            bundles.Add(scriptBundle);
            BundleTable.EnableOptimizations = true;





Wednesday 13 November 2013

Cannot create/shadow copy 'Autofac.Integration.Mvc' when that file already exists.


Exception


=== Pre-bind state information ===
LOG: User = Domain\Cpo
LOG: DisplayName = Autofac.Integration.Mvc
 (Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: Autofac.Integration.Mvc | Domain ID: 11
WRN: A partial bind occurs when only part of the assembly display name is provided.
WRN: This might result in the binder loading an incorrect assembly.
WRN: It is recommended to provide a fully specified textual identity for the assembly,
WRN: that consists of the simple name, version, culture, and public key token.
WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue.
LOG: Appbase = file:///D:/WebUI/
LOG: Initial PrivatePath = D:\WebUI\bin
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: D:\WebUI\web.config
LOG: Using host configuration file: C:\Users\Cpo\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Users/Cpo/AppData/Local/Temp/Temporary ASP.NET Files/root/5c8bbc72/8da9d219/Autofac.Integration.Mvc.DLL.
LOG: Attempting download of new URL file:///C:/Users/Cpo/AppData/Local/Temp/Temporary ASP.NET Files/root/5c8bbc72/8da9d219/Autofac.Integration.Mvc/Autofac.Integration.Mvc.DLL.
LOG: Attempting download of new URL file:///D:/WebUI/bin/Autofac.Integration.Mvc.DLL.
LOG: Using application configuration file: D:\WebUI\web.config
LOG: Using host configuration file: C:\Users\Cpo\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Post-policy reference: Autofac.Integration.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=17863af14b0044da
ERR: Failed to complete setup of assembly (hr = 0x800700b7). Probing terminated.

Fix 1


Clean your solution and restart your application.

Fix 2

The .Net Framework has a feature called Shadow Copy. Shadow copy is enabled on every appdomain created by ASP.NET by default. By default assemblies loaded will be copied to a shadow copy cache directory, and will be used from that location. Why does ASP.Net do this? So the original file is not locked and can be modified. An interesting error I have ran into intermittently when running ASP.Net apps with the debugger is ‘Cannot create/shadow copy when that file already exists‘ I’m still not sure why this happens only on occasion, as I can often clean my solution, then reload a web app and it will work fine then. But if you are getting it frequently enough for it to affect your work, you can add the following to your app’s web.config or the master .Net web.config:
<system.web>
   <hostingEnvironment shadowCopyBinAssemblies="false" />
</system.web>

Note: this fix is copied from: http://ranafaisal.wordpress.com/2008/03/25/cannot-createshadow-copy-when-that-file-already-exists/


Tuesday 12 November 2013

Windows 7 and NodeJs


Install NodeJs on Windows

http://nodejs.org/download/

Write your scripts:

var http = require('http');
var s = http.createServer(function(req,res){
res.writeHead(200, {'content-type':'text/plain'});
res.write("Hello");
setTimeout(function(){
res.end(" world\r\n");
},2000);
});
s.listen(8000);


Refer to nodejs.org for more information

Friday 8 November 2013

Mock return value only once

Processing records using mock and NUnit


 public List ProcessRecords(IRecordsReader conf)
        {
            var pageHitsResults = new List();
            if (conf != null && conf.HasRecords)
                while (conf.Read())
                {
                    pageHitsResults.Add(
                        new PageHitsResults { Date = conf.GetDateTime("Date"), Hits = conf.GetInt("Hits"), TotalHits = conf.GetInt("TotalHits") });
                } return pageHitsResults;
        }
        [Test]
        public void ProcessRecordsTests()
        {
            var isqlHelperMock = new Mock();
            var iRecordsReaderMock = new Mock();
            iRecordsReaderMock.Setup(x => x.HasRecords).Returns(true);
            int i = 1;
            iRecordsReaderMock.Setup(x => x.Read()).Returns(() => { return i++ == 1; }); var dateTime = DateTime.Now; iRecordsReaderMock.Setup(x => x.GetDateTime("Date")).Returns(dateTime); iRecordsReaderMock.Setup(x => x.GetInt("Hits")).Returns(55); iRecordsReaderMock.Setup(x => x.GetInt("TotalHits")).Returns(123); var pageHitsLogic = new PageHitsLogic(isqlHelperMock.Object); var actual = pageHitsLogic.ProcessRecords(iRecordsReaderMock.Object); Assert.AreEqual(1, actual.Count); Assert.AreEqual(dateTime, actual.First().Date); Assert.AreEqual(55, actual.First().Hits); Assert.AreEqual(123, actual.First().TotalHits);
        }
        [Test]
        public void ProcessRecordsTestsTest()
        {
            var isqlHelperMock = new Mock(); var iRecordsReaderMock = new Mock(); iRecordsReaderMock.Setup(x => x.HasRecords).Returns(true); int i = 1; iRecordsReaderMock.Setup(x => x.Read()).Returns().Returns(() => i++ == 1); var dateTime = DateTime.Now; iRecordsReaderMock.Setup(x => x.GetDateTime("Date")).Returns(dateTime); iRecordsReaderMock.Setup(x => x.GetInt("Hits")).Returns(55); iRecordsReaderMock.Setup(x => x.GetInt("TotalHits")).Returns(123); var pageHitsLogic = new PageHitsLogic(isqlHelperMock.Object); i++;
            // if used here the defalut value of I is 2 and the function for reading does did not yet execued 
            var actual = pageHitsLogic.ProcessRecords(iRecordsReaderMock.Object);
            Assert.AreEqual(1, actual.Count);
            Assert.AreEqual(dateTime, actual.First().Date);
            Assert.AreEqual(55, actual.First().Hits);
            Assert.AreEqual(123, actual.First().TotalHits);
        }

Console Command - Copy files with permisions

I needed to copy all files with all permission. I could not remember command.


xcopy Source TargetDirectory /O /X /E /H /K

Umbraco truncate vs Regex


Comparison of regex removal of html tags and using memory stream for the same impression.

Compiled regex is faster.



  class Program
    {
        static void Main(string[] args)
        {

            int repeats = 1;
            
            
            Regex regex = new Regex(@"<(.|\n)*?>",RegexOptions.Compiled);
            


            var htmlStr = @"
<div id='lipsum'>
<p>
</p><ul>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
<li>Vestibulum tincidunt eros ac velit scelerisque pharetra.</li>
</ul>
<p></p>
<p>
</p><ul>
<li>Aenean pellentesque mauris et massa eleifend tristique.</li>
<li>In rutrum magna at arcu molestie porta.</li>
<li>Pellentesque rutrum nibh non est auctor varius.</li>
</ul>
<p></p>
<p>
</p><ul>
<li>Vestibulum elementum ante blandit risus cursus convallis.</li>
<li>In id magna lacinia, luctus sapien in, tempor elit.</li>
</ul>
<p></p>
<p>
</p><ul>
<li>Integer tempus tellus nec purus ultrices, quis facilisis magna adipiscing.</li>
<li>Cras convallis sapien vel augue ultrices pulvinar.</li>
<li>Sed pretium eros vel tellus feugiat, ut congue erat pellentesque.</li>
<li>Vestibulum convallis tortor congue sapien condimentum, sit amet vestibulum nisl tristique.</li>
<li>Cras non lacus sagittis, auctor massa eget, pulvinar elit.</li>
<li>Morbi eu augue tincidunt, luctus lacus vestibulum, varius elit.</li>
</ul>
<p></p>
<p>
</p><ul>
<li>Cras at dui sed justo convallis mattis.</li>
<li>Curabitur molestie mi nec dui interdum aliquet.</li>
<li>Maecenas malesuada magna non aliquam sollicitudin.</li>
<li>Maecenas porta erat quis turpis dictum faucibus.</li>
<li>Duis dignissim elit a ultrices tristique.</li>
</ul>
<p></p></div>";

            //var timer1 = new Stopwatch();
            //Console.WriteLine("Not compiled");
            //timer1.Start();

            //for (int i = 0; i < repeats; i++)
            //{
            //     Do.StripHtmlFromString(htmlStr);
            //}
            //timer1.Stop();

            var timer1 = new Stopwatch();
            Console.WriteLine("Inhouse");
            timer1.Start();

            for (int i = 0; i < repeats; i++)
            {
                Do.DisplaySearchSummary(htmlStr, 150, regex);
            }
            timer1.Stop();

            Console.WriteLine("Inhouse: " + timer1.ElapsedTicks);

            var timer2 = new Stopwatch();
            Console.WriteLine("umbraco");
            timer2.Start();

            for (int i = 0; i < repeats; i++)
            {
                Do.Truncate(htmlStr, 150, true, false);
            }
            timer2.Stop();

            Console.WriteLine("Umbraco: " + timer2.ElapsedTicks);


            Console.ReadKey();
            Console.ReadKey();
        }
    }

    public class Do
    {
        

        /// <summary>
        /// Strips the HTML from string.
        /// </summary>
        /// <param name="htmlString">The HTML string.</param>
        /// <returns>
        /// String without html tags.
        /// </returns>
        public static string StripHtmlFromString(string htmlString, Regex regex)
        {
            if (string.IsNullOrEmpty(htmlString)) return htmlString;
            
            return regex.Replace(htmlString,string.Empty);
        }


        public static string DisplaySearchSummary(string descriptionText, int requiredLength, Regex regex, string ending = "...")
        {
            descriptionText = StripHtmlFromString(descriptionText, regex);

            if (!string.IsNullOrEmpty(descriptionText) && descriptionText.Length >= requiredLength)
            {
                // Get the required requiredLength of the string
                var requiredtext = descriptionText.Substring(0, requiredLength - 1);

                // Select the last occurence of a whitespace character to break the string correctly
                var ouputtext = string.Concat(requiredtext.Substring(0, requiredtext.LastIndexOf(' ')), ending);

                return ouputtext;
            }

            return descriptionText;
        }
      
        
        public static string Truncate(string html, int length, bool addElipsis, bool treatTagsAsContent)
        {
            using (var outputms = new MemoryStream())
            {
                using (var outputtw = new StreamWriter(outputms))
                {
                    using (var ms = new MemoryStream())
                    {
                        using (var tw = new StreamWriter(ms))
                        {
                            tw.Write(html);
                            tw.Flush();
                            ms.Position = 0;
                            var tagStack = new Stack<string>();
                            using (TextReader tr = new StreamReader(ms))
                            {
                                bool IsInsideElement = false;
                                bool lengthReached = false;
                                int ic = 0;
                                int currentLength = 0, currentTextLength = 0;
                                string currentTag = string.Empty;
                                string tagContents = string.Empty;
                                bool insideTagSpaceEncountered = false;
                                bool isTagClose = false;
                                while ((ic = tr.Read()) != -1)
                                {
                                    bool write = true;

                                    if (ic == (int)'<')
                                    {
                                        if (!lengthReached)
                                        {
                                            IsInsideElement = true;
                                        }
                                        insideTagSpaceEncountered = false;
                                        currentTag = string.Empty;
                                        tagContents = string.Empty;
                                        isTagClose = false;
                                        if (tr.Peek() == (int)'/')
                                        {
                                            isTagClose = true;
                                        }
                                    }
                                    else if (ic == (int)'>')
                                    {
                                        //if (IsInsideElement)
                                        //{
                                        IsInsideElement = false;
                                        //if (write)
                                        //{
                                        //  outputtw.Write('>');
                                        //}
                                        currentTextLength++;
                                        if (isTagClose && tagStack.Count > 0)
                                        {
                                            string thisTag = tagStack.Pop();
                                            outputtw.Write("</" + thisTag + ">");
                                        }
                                        if (!isTagClose && currentTag.Length > 0)
                                        {
                                            if (!lengthReached)
                                            {
                                                tagStack.Push(currentTag);
                                                outputtw.Write("<" + currentTag);
                                                if (tr.Peek() != (int)' ')
                                                {
                                                    if (!string.IsNullOrEmpty(tagContents))
                                                    {
                                                        if (tagContents.EndsWith("/"))
                                                        {
                                                            //short close
                                                            tagStack.Pop();
                                                        }
                                                        outputtw.Write(tagContents);
                                                    }
                                                    outputtw.Write(">");
                                                }
                                            }
                                        }
                                        //}
                                        continue;
                                    }
                                    else
                                    {
                                        if (IsInsideElement)
                                        {
                                            if (ic == (int)' ')
                                            {
                                                if (!insideTagSpaceEncountered)
                                                {
                                                    insideTagSpaceEncountered = true;
                                                    //if (!isTagClose)
                                                    //{
                                                    // tagStack.Push(currentTag);
                                                    //}
                                                }
                                            }
                                            if (!insideTagSpaceEncountered)
                                            {
                                                currentTag += (char)ic;
                                            }
                                        }
                                    }
                                    if (IsInsideElement || insideTagSpaceEncountered)
                                    {
                                        write = false;
                                        if (insideTagSpaceEncountered)
                                        {
                                            tagContents += (char)ic;
                                        }
                                    }
                                    if (!IsInsideElement || treatTagsAsContent)
                                    {
                                        currentTextLength++;
                                    }
                                    currentLength++;
                                    if (currentTextLength <= length || (lengthReached && IsInsideElement))
                                    {
                                        if (write)
                                        {
                                            outputtw.Write((char)ic);
                                        }
                                    }
                                    if (!lengthReached && currentTextLength >= length)
                                    {
                                        //reached truncate point
                                        if (addElipsis)
                                        {
                                            outputtw.Write("&hellip;");
                                        }
                                        lengthReached = true;
                                    }

                                }

                            }
                        }
                    }
                    outputtw.Flush();
                    outputms.Position = 0;
                    using (TextReader outputtr = new StreamReader(outputms))
                    {
                        return outputtr.ReadToEnd().Replace("  ", " ").Trim();
                    }
                }
            }
        }
    }

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

<#  #>

Wednesday 25 September 2013

PowerShell creating database and associating login

I have been working on droping new database as part of my continuous deployment implementation.
For this I have needed to create couple powerhsell scripts.

Here is one example (prototype how it works)

Note: it needs tidy up.







$Instance   = ".\SQLEXPRESS"
$LoginName  = "Login name"
$Password   = "loginPassword"
$DBName     = "Database"

#Get the server object
$srv = New-Object ("Microsoft.SqlServer.Management.SMO.Server") $instance

        $varDBUser = "Usern"
        $varDBPassword = "password"
        $srv.ConnectionContext.LoginSecure = $false
        $srv.ConnectionContext.Login = $varDBUser
        $srv.ConnectionContext.Password = $varDBPassword

#Get the login object if it exists
$Login = $srv.Logins.Item($LoginName)

IF (!($Login))  #check to see if login already exists
{
   Write-Host " login does not exists, creating"

 #it doesn't, so instantiate a new login object
    $Login = New-Object ("Microsoft.SqlServer.Management.SMO.Login") ($Server, $LoginName)

    #make it a SQL Login
    $Login.LoginType = [Microsoft.SqlServer.Management.Smo.LoginType]::SqlLogin

    #Create it on the server with the specified password
    $Login.Create($Password)



}

#Get the database object
$DB = $srv.Databases[$DBName]
 
#Get the user object if it exists
$User = $DB.Users[$LoginName]

if (!($User)) # check to see if the user is already in the database
{
    #it doesn't, so add it
    $User = New-Object ("Microsoft.SqlServer.Management.SMO.User") ($DB, $LoginName)
    $User.Login = $LoginName
    $User.Create()
}

Monday 23 September 2013

Running referenced powershell scripts from teamcity build.

I have been tasked  with creating automation for build process using PowerShell and TeamCity.

I have had multiple functions that I wanted to call in multiple steps, but the one issue had problem with was error:

[15:50:43][Step 7/8] .\ExecuteScripts.ps1 : The term '.\ExecuteScripts.ps1' is not recognized
[15:50:43][Step 7/8] as the name of a cmdlet, function, script file, or operable program. Check the
[15:50:43][Step 7/8] spelling of the name, or if a path was included, verify that the path is
[15:50:43][Step 7/8] correct and try again.
[15:50:43][Step 7/8] At \Path\RunUmbracoInstallation.ps1:5 char:1
[15:50:43][Step 7/8] + .\ExecuteScripts.ps1


This is so helpfull that I had to find way around it.
I have created basic file (test.ps1 - first version) that I have been able to execute from team build process.

After this step have been executing correctly though TeamCity.
I have set up permissions on powershell for user account under which teamcity agent run to FullControl.






File: test.ps1 - first version


 param(
        [Parameter(Mandatory=$True)] [string] $arg1,
        [Parameter(Mandatory=$True)] [string] $arg2
    )

function PowerShellTest{
  
    Write-Host -fore Magenta "Executing function powershell test with arguments:"
    Write-host -fore Cyan "arg1:$arg1  arg2:$arg2"
}

  
PowerShellTest


File: test.ps1 - final version

 param(
        [Parameter(Mandatory=$True)] [string] $arg1,
        [Parameter(Mandatory=$True)] [string] $arg2
    )


 &lt;# ========== Loading required files ============ #&gt;
$commons =Join-Path (Get-ScriptDirectory)"test2.ps1"
.$commons;

&lt;# ========== Loading required files ============ #&gt;

function PowerShellTest{
  

    Write-Host -fore Magenta "Executing function powershell test with arguments:"
    Write-host -fore Cyan "arg1:$arg1  arg2:$arg2"

    PowerShellTest2 -arg1 $arg1 -arg2 $arg2
}


function Get-ScriptDirectory
{
    $Invocation = (Get-Variable MyInvocation -Scope 1).Value
    Split-Path $Invocation.MyCommand.Path
}

  
PowerShellTest


File: test2.ps1



function PowerShellTest2{  

 param(
        [Parameter(Mandatory=$True)] [string] $arg1,
        [Parameter(Mandatory=$True)] [string] $arg2
    )

    Write-Host -fore Magenta "Executing function powershell test2:"
    Write-host -fore Cyan "arg1:$arg1  arg2:$arg2"
}



Now build configuration



Note:
  1. that script arguments do not have staring - before and value is in quotes.
  2. Powershell run mode: is defined as to what version of my PS and x64 is as my server version


After running agent again I do get results as:



 Execute PS Test script (Powershell)
[18:14:36][Step 8/8] Starting: Path\powershell.exe -NoProfile -NonInteractive -ExecutionPolicy ByPass -File PathToWorkDirectory\test.ps1 arg1="Test1" arg2="2Test2"
[18:14:36][Step 8/8] in directory: PathToWorkDirectory\
[18:14:37][Step 8/8] Executing function powershell test with arguments:
[18:14:37][Step 8/8] arg1:arg1=Test1 arg2:arg2=2Test2
[18:14:37][Step 8/8] Executing function powershell test2:
[18:14:37][Step 8/8] arg1:arg1=Test1 arg2:arg2=2Test2
[18:14:37][Step 8/8] Process exited with code 0


I have managed to do this thanks to this blog article.
http://leftlobed.wordpress.com/2008/06/04/getting-the-current-script-directory-in-powershell/

Thursday 19 September 2013

PowerShell - Usefull commands


Update help definition  from online.

You need to run this command under administrator rights.

PS C:\Windows\system32> Update-Help
(I have read, that it gets updated almost every week)


PowerShell can run with wildcards : *

PS C:\Windows\system32> help *service*


Name                              Category  Module                    Synopsis                                                                                                               
----                              --------  ------                    --------                                                                                                               
Get-Service                       Cmdlet    Microsoft.PowerShell.M... Gets the services on a local or remote computer.                                                                       
New-Service                       Cmdlet    Microsoft.PowerShell.M... Creates a new Windows service.                                                                                         
New-WebServiceProxy               Cmdlet    Microsoft.PowerShell.M... Creates a Web service proxy object that lets you use and manage the Web service in Windows PowerShell.                 
Restart-Service                   Cmdlet    Microsoft.PowerShell.M... Stops and then starts one or more services.                                                                            
Resume-Service                    Cmdlet    Microsoft.PowerShell.M... Resumes one or more suspended (paused) services.                                                                       
Set-Service                       Cmdlet    Microsoft.PowerShell.M... Starts, stops, and suspends a service, and changes its properties.                                                     
Start-Service                     Cmdlet    Microsoft.PowerShell.M... Starts one or more stopped services.                                                                                   
Stop-Service                      Cmdlet    Microsoft.PowerShell.M... Stops one or more running services.                                                                                    
Suspend-Service                   Cmdlet    Microsoft.PowerShell.M... Suspends (pauses) one or more running services.         


Get full help information about command including examples


PS C:\Windows\system32> help Get-Service -full

What version of PowerShell do I have Installed

  1. $PSVersionTable
  2. $host.version

Get gui for command

PS C:\Windows\system32> Show-Command Start-Process

Get members of commands:

This command shows all information what all I can get get.

PS D:\Scripts> get-service | get-member

PowerShell function parameters
If you are using parameters use param definition in function instead in bracets of the function name:

function WebConfig-SetAppConfigValueForKey{
    param(
         [Parameter(Mandatory=$true)]
         [xml]$doc,
         [Parameter(Mandatory=$true)]
         [string]$key,
         [Parameter(Mandatory=$true)]
         [string]$value
    )


Executing script path

If you are executing script you will be able to get path of the script which gets executed.

function Test(){
    $scriptpath = $MyInvocation.MyCommand.Path
    write-host $scriptpath
}

Test

If you execute the script without file you will get null