Render in MVC a link with image and text

Hi guys, I want in MVC to render a text with an image as an ActionLink. For creating a simple anchor tag, we use Html.ActionLink() helper which generates anchor tag for us.

If you want to create something a bit more complicated, you must create you own component. For this reason, I created the following code. It allows you to create an anchor with an image and a text.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace PSC.MVC.Helpers
{
    public static class CustomHtmlHelpers
    {
        /// 
        /// Enum ImageAndText
        /// 
        public enum ImageAndText
        {
            /// 
            /// Image on the left, text on the right
            /// 
            ImageOnTheLeft,

            /// 
            /// Text on the left, image on the right
            /// 
            ImageOnTheRight
        }

        /// 
        /// Images the action link.
        /// 
        /// The HTML helper.
        /// The link text.
        /// The action.
        /// The controller.
        /// The route values.
        /// The HTML attributes.
        /// The image source.
        /// The alternate text.
        /// The text style.
        /// The image style.
        /// The image position.
        /// IHtmlString.
        public static IHtmlString ImageActionLink(
               this HtmlHelper htmlHelper, string linkText, string action, 
               string controller, object routeValues, object htmlAttributes, 
               string imageSrc, string alternateText = "", 
               string textStyle = "", string imageStyle = "", 
               ImageAndText imagePosition = ImageAndText.ImageOnTheLeft)
        {
            var urlHelper = new UrlHelper(
                    htmlHelper.ViewContext.RequestContext);

            // create the image
            var img = new TagBuilder("img");
            img.Attributes.Add("src", 
                    VirtualPathUtility.ToAbsolute(imageSrc));
            if (!string.IsNullOrEmpty(alternateText))
                img.Attributes.Add("alt", alternateText.Trim());
            if (!string.IsNullOrEmpty(imageStyle))
                img.Attributes.Add("style", imageStyle);

            // create a render for the image and the text
            string render = "";
            if (imagePosition == ImageAndText.ImageOnTheLeft)
                render = img.ToString(TagRenderMode.SelfClosing) + linkText;
            else
                render = linkText + img.ToString(TagRenderMode.SelfClosing);

            // create the anchor with image and text
            var anchor = new TagBuilder("a") {
                InnerHtml = render
            };
            if (!string.IsNullOrEmpty(textStyle))
                anchor.AddCssClass(textStyle);

            // add reference to the anchor
            anchor.Attributes["href"] = urlHelper.Action(action, 
                                                         controller, 
                                                         routeValues);
            anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes));

            return MvcHtmlString.Create(anchor.ToString());
        }
    }
}

In your MVC code you have to add:

@using PSC.MVC.Helpers;

and then you can call your component:
@Html.ImageActionLink("Your text", "Index", "Home", null, null, 
                      "~/Content/images/img.png", "Logo", "navbar-brand", 
                      "width: 40px;")

A Simple Speedtest Application for Xamarin

In my previous post I described how to check your connection in a C# project. I should have the same function in a PCL project for Xamarin. Based on my project, I created this function:
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace PSC.Xamarin.Connection
{
	/// 
	/// Speed test.
	/// 
	public class SpeedTest
	{
		public double SecondsForOneMb { get; set; } = 0;
		public double KbSeconds { get; set; } = 0;

		/// 
		/// Starts the test to download a file from an url.
		/// Read SecondsForOneMb and KbSeconds for the result
		/// 
		public async Task StartTest()
		{
			string url = 
            "http://puresourcecode.com/file.axd?file=/SpeedTest/1024kb.txt";
			HttpClient client = new HttpClient();

			// get current tickcount 
			double starttime = Environment.TickCount;

			// download file from the specified URL, 
			// and save it to C:\speedtest.txt
			// in your project change the path of the following line
			var httpResponse = await client.GetAsync(url);
			byte[] dataBuffer = 
                   await httpResponse.Content.ReadAsByteArrayAsync();

			// get current tickcount
			double endtime = Environment.TickCount;

			// how many seconds did it take?
			// we are calculating this by subtracting starttime from
			// endtime and dividing by 1000 (since the tickcount is in 
			// miliseconds 1000 ms = 1 sec)
			SecondsForOneMb = Math.Floor(endtime - starttime) / 1000;

			// calculate download rate in kb per sec.
			// this is done by dividing 1024 by the number of seconds it
			// took to download the file (1024 bytes = 1 kilobyte)
			KbSeconds = Math.Round(1024 / SecondsForOneMb);
		}
	}
}

Happy coding!

A Simple Speedtest Application

The purpose of this code is the detect how slow is your connection downloading a file from a site. First of all, you have to create a file with a known size: for that you can use fsutil in the prompt (see another post in this blog for info).

When yo do put your file in a webserver (or you can use my url), we can create the code to check the connection speed.

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;

namespace SpeedTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "A simple speed test connection for your app";

            // the URL to download a file from
            Uri URL = new Uri(
            "http://puresourcecode.com/file.axd?file=/SpeedTest/1024kb.txt"
            );
            WebClient wc = new WebClient();

            Console.WriteLine("Simple speedtest");
            Console.WriteLine("----------------");
            Console.WriteLine("Will test your download rate. " + 
                              "Press any key to begin.");
            Console.ReadKey();

            Console.WriteLine("\nDownloading file: 1024kb.txt...");
            Console.WriteLine("From http://puresourcecode.com");
            Console.WriteLine("Note: This file will automatically " + 
                              "be deleted after the test.");

            // get current tickcount 
            double starttime = Environment.TickCount;

            // download file from the specified URL, 
            // and save it to C:\speedtest.txt
            // in your project change the path of the following line
            wc.DownloadFile(URL, @"C:\speedtest.txt");

            // get current tickcount
            double endtime = Environment.TickCount;

            // how many seconds did it take?
            // we are calculating this by subtracting starttime from
            // endtime and dividing by 1000 (since the tickcount is in 
            // miliseconds 1000 ms = 1 sec)
            double secs = Math.Floor(endtime - starttime) / 1000;

            // calculate download rate in kb per sec.
            // this is done by dividing 1024 by the number of seconds it
            // took to download the file (1024 bytes = 1 kilobyte)
            double kbsec = Math.Round(1024 / secs);

            Console.WriteLine("\nCompleted. Statistics:\n");

            Console.WriteLine("1mb download: \t{0} secs", secs);
            Console.WriteLine("Download rate: \t{0} kb/sec", kbsec);

            Console.WriteLine("\nPress any key to exit...");
            Console.Read();
            Console.WriteLine("Deleting file...");
            try
            {
                // delete downloaded file
                System.IO.File.Delete(@"C:\speedtest.txt");
                Console.WriteLine("Done.");
            }
            catch
            {
                Console.WriteLine("Couldn't delete download file.");
                Console.WriteLine("To delete the file yourself.");
                Console.ReadKey();
            }
        }

    }
}

Happy coding!

Howto: Generate many files of a particular size in Windows

I shoud find a simple way to generate a file of exact size. Finally I found this command in the Prompt of Windows (Windows10 in my case but it presents in the previous version of Windows)

fsutil

The syntax for using for this purpose fsutil is:

fsutil file createnew filename filesize

I used a simple loop to create files of a particular size using fsutil. Running from a command prompt:

For creating a file of 1 Mb you can type

fsutil file createnew C:\Users\e.rossini\1024kb.txt 1048276

Happy coding!

Xamarin forms, UWP Windows 10 App, TitleBar and Status bar customization

Customize the title bar of your Universal App for Windows 10 is quite easy, but you need to write different code for PC and Mobile. The class that allows you to customize the title bar:

  • when running on a PC is called TitleBar
  • when running on a Mobile is called StatusBar

Before to call the API you first need to check if it exists (true if you are running on that platform):

//PC customization
if (ApiInformation.IsTypePresent(
                   "Windows.UI.ViewManagement.ApplicationView"))
{
    var titleBar = ApplicationView.GetForCurrentView().TitleBar;
    if (titleBar != null)
    {
        titleBar.ButtonBackgroundColor = Colors.DarkBlue;
        titleBar.ButtonForegroundColor = Colors.White;
        titleBar.BackgroundColor = Colors.Blue;
        titleBar.ForegroundColor = Colors.White;
    }
 }

//Mobile customization
if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
{

    var statusBar = StatusBar.GetForCurrentView();
    if (statusBar != null)
    {
        statusBar.BackgroundOpacity = 1;
        statusBar.BackgroundColor = Colors.DarkBlue;
        statusBar.ForegroundColor = Colors.White;
    }
}

You could receive an error

StatusBar doesn't exist in context

You resolve it to add in the reference for UWP project Windows Mobile Extensions for the UWP and Windows Desktop Extensions for the UWP.

Extensions

Happy coding!

Add Calabash to your Xamarin project

Why add Calabash to your project? Because without it you can't test your application with Xamarin Test Cloud.

Scenario

I created my app for iOS and I want to test it on Xamarin Cloud. First thing I have to install to create a UITest easily is Xamarin Test Recorder. When I opened this application, I was confuse because nobody explain what kind of app I can choose. Basically if you have a iOS project, before use Xamarin Test Recorder, you must create an .ipa and it means you have to create an archive and publish it.

After createing a UITest project you can sent it with Export function directly to TestCloud. The problem I discovered is

Errors and Failures:
1) SetUp Error : RecorderTest.NewTest
   SetUp : System.Exception : Unable to contact test backend running in app. A common cause is that the app is not properly linked with Calabash. Please verify that it includes the Calabash component.
  at Xamarin.UITest.iOS.iOSAppLauncher.EnsureCalabashRunning (ICalabashConnection connection) <0x7507b30 + 0x0005f> in <filename unknown>:0 
  at Xamarin.UITest.iOS.iOSAppLauncher.LaunchApp (IiOSAppConfiguration appConfiguration, Xamarin.UITest.Shared.Http.HttpClient httpClient, Xamarin.UITest.TestCloud.TestCloudiOSAppConfiguration testCloudAppConfiguration, Xamarin.UITest.Shared.Http.HttpClient testCloudWsClient, Xamarin.UITest.Shared.Http.HttpClient xtcServicesClient, Boolean testCloudUseDeviceAgent) <0x6cbb340 + 0x0019b> in <filename unknown>:0 
  at Xamarin.UITest.iOS.iOSApp..ctor (IiOSAppConfiguration appConfiguration, IExecutor executor) <0x6b39778 + 0x00b03> in <filename unknown>:0 
  at Xamarin.UITest.iOS.iOSApp..ctor (IiOSAppConfiguration appConfiguration) <0x6b39738 + 0x0001f> in <filename unknown>:0 
  at Xamarin.UITest.Configuration.iOSAppConfigurator.StartApp (AppDataMode appDataMode) <0x6b38e18 + 0x00063> in <filename unknown>:0 
  at RecorderTest.SetUp () <0x6b37f70 + 0x0004f> in <filename unknown>:0 
  at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
  at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) <0x31e7110 + 0x00093> in <filename unknown>:0 

Why this? Because I didn't install Calabash.

Add Calabash for iOS

First al all, open your Terminal with admin privileges. Then execute this script:

gem install calabash-cucumber gem install calabash-android gem install xamarin-test-cloud

Now in your system there are the basic for Calabash.

Now you can install a Calabash sandbox. Do not use sudo to install the Calabash Sandbox. Execute this script

curl -sSL https://raw.githubusercontent.com/calabash/install/master/install-osx.sh | bash

Now in the directory of your iOS project execute this script:

calabash-ios download

And finally you can generate a feature folder. The features folder is a special folder where Cucumber expects the test code to reside. Calabash can create this folder and provide some boilerplate code to get us started.

The last step is to execute in your iOS project the following command in the Terminal

calabash-ios gen

Now you create a new .ipa and do a new test. This time it will work!

Happy coding!

WebAssembly is now ready for browsers to use

WebAssembly, a portable code format that could make for a faster web, has moved to minimum viable product (MVP) status, with browser vendors now able to switch WebAssembly on by default.

webassembly-screenshot

A recent bulletin from Mozilla Senior Staff Engineer Luke Wagner said representatives of the four major browsers agreed that the design and binary format were complete to the extent that no further design work was doable without implementation experience and significant usage. Browsers represented included Google Chrome, Microsoft Edge, Mozilla Firefox, and WebKit, which is Apple's browser engine for Safari, according to the bulletin posted on a World Wide Web Consortium mailing list.

WebAssembly is a highly touted effort that not only is set to run web apps in the browser at near-native speeds but also allow for other languages to be used for browser programming beyond JavaScript. The effort has drawn praise from JavaScript founder Brendan Eich, who recently expressed concern that the four browser vendors might end up disunifying over the project, thus jeopardizing it. But Wagner said proponents for all four browsers have been active and participate in the WebAssembly Community Group.

For developers, WebAssembly provides fast load times for large codes and predictable, near-native runtime performance, Wagner said. "This enables developers to bring functionality and experiences to the web that might have otherwise been gated on JavaScript." Since WebAssembly can be used as a library from JavaScript, JavaScript developers can utilize WebAssembly's performance through libraries and frameworks.

WebAssembly could possibly use other languages, such as Python, in the browser, depends on the language's ecosystem, Wagner said. "One requirement for supporting a language is that WebAssembly provides the necessary features to run that language efficiently. For many languages, this requires adding garbage collection [memory management] features to WebAssembly, which is on the road map but will take at least a year or two." The other challenge of supporting a language is porting over language libraries and frameworks to run in a browser and use web APIs.

An error occurs with MobileCenter for Xamarin iOS

I added Microsoft Mobile Center to my project after creating the app there. On MobileCenter documentation you can know the Install Identifier for your application (MobileCenter documentation is here).

System.Guid installId = MobileCenter.InstallId;

This function is working fine if you have Android or iOS 10. With iOS less than 10 an error occurs:

Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).

and the StackTrace is similar to

at System.Guid+GuidResult.SetFailure (System.Guid+ParseFailureKind failure, System.String failureMessageID, System.Object failureMessageFormatArgument, System.String failureArgumentName, System.Exception innerException) [0x00030] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.4.0.123/src/mono/mcs/class/referencesource/mscorlib/system/guid.cs:198 \n at System.Guid+GuidResult.SetFailure (System.Guid+ParseFailureKind failure, System.String failureMessageID) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.4.0.123/src/mono/mcs/class/referencesource/mscorlib/system/guid.cs:184 \n at System.Guid.TryParseGuidWithDashes (System.String guidString, System.Guid+GuidResult& result) [0x0008f] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.4.0.123/src/mono/mcs/class/referencesource/mscorlib/system/guid.cs:695 \n at System.Guid.TryParseGuid (System.String g, System.Guid+GuidStyles flags, System.Guid+GuidResult& result) [0x00115] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.4.0.123/src/mono/mcs/class/referencesource/mscorlib/system/guid.cs:443 \n at System.Guid.Parse (System.String input) [0x00021] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.4.0.123/src/mono/mcs/class/referencesource/mscorlib/system/guid.cs:262 \n at Microsoft.Azure.Mobile.MobileCenter.get_InstallId () [0x0000a] in :0 \n at myInventories.Helpers.LogHelpers.SendMessageToAzure (System.String EventName, System.String PageName, System.String BaseClass, myInventories.Logs.ActionType Action, System.String MoreInfo, System.Collections.Generic.Dictionary`2[TKey,TValue] DictionaryInfo) [0x00008] in /Users/enricorossini/Projects/myInventories/myInventories/myInventories/Helpers/LogHelpers.cs:72

To avoid this error you have to check the OS version.

Implementation

In your solution you have to add in all projects Device Information Plugin (for NuGet Xam.Plugin.DeviceInfo). Then you check easily the OS version with

// check the OS version to avoid error on MobileCenter
string MobileId = "";
var osInfo = CrossDeviceInfo.Current;
if ((osInfo.Platform == Plugin.DeviceInfo.Abstractions.Platform.iOS) && 
    (osInfo.VersionNumber.Major < 10)) 
{
    MobileId = "Unknown";
}
else {
    MobileId = MobileCenter.InstallId.ToString();
}

Happy coding!

This is iPhone 8

iPhone8-Introduction

The hardware that allows the iPhone 8's rumored facial recognition capability could consist of a "revolutionary" new camera system for its front-facing camera.

iPhone8-Camera

iPhone8-OLED

iPhone8-Security

iPhone8-Colors

The report follows related rumors of Apple augmenting or ditching its Touch ID fingerprint scanner in favor of iris or facial recognition technology, fueled by its acquisition of Israeli facial recognition startup RealFace. Samsung's Galaxy Note 7 -- yep, that Galaxy Note 7 -- was among the first phones to come equipped with an iris scanner.

99.6 percent of new smartphones run Android or iOS

google-pixel-phone-shootout

The latest smartphone figures from Gartner are out, and they paint an extremely familiar picture. Between them, Android and iOS accounted for 99.6 percent of all smartphone sales in the fourth quarter of 2016. This duopoly has been the norm for a while now (in the second quarter of 2015 this figure was 96.8 percent), but it’s always impressive — and slightly terrifying — to see how Google and Apple continue to wring the last decimal point drops of market share from global smartphone users.

Of the 432 million smartphones sold in the last quarter, 352 million ran Android (81.7 percent) and 77 million ran iOS (17.9 percent), but what happened to the other players? Well, in the same quarter, Windows Phone managed to round up 0.3 percent of the market, while BlackBerry was reduced to a rounding error. The once-great firm sold just over 200,000 units, amounting to 0.0 percent market share.

Screen_Shot_2017_02_16_at_10.48.25_AM

Advertsing

125X125_06

Calendar

<<  April 2017  >>
MonTueWedThuFriSatSun
272829303112
3456789
10111213141516
17181920212223
24252627282930
1234567

View posts in large calendar

Month List