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();
                    }
                }
            }
        }
    }