C# and multicultural IsDate() and ToDate()

C# does not provide IsDate() function. Sometimes in your developer environment region settings are different from the live environment. In my case, I don’t know what region settings there are in my company servers.

For this reason, I created a function to check is a string is a date in a culture and to convert a string to a date.

/// 
/// Determines whether the specified text is date.
/// 
/// The text.
/// 
/// true if the specified text is date; 
/// otherwise, false.
/// 
public static bool IsDate(this string text)
{
    if (!string.IsNullOrEmpty(text))
    {
        DateTime result = DateTime.MinValue;
        foreach (CultureInfo cultureInfo in 
                 CultureInfo.GetCultures(CultureTypes.AllCultures))
        {
            try
            {
                if (DateTime.TryParse(text, cultureInfo, 
                                      DateTimeStyles.None, 
                                      out result))
                    return true;
            }
            catch (Exception ex) { }
        }
    }

    return false;
}

/// 
/// To the date.
/// 
/// The text.
/// System.Nullable<DateTime>.
public static DateTime? ToDate(this string text)
{
    if (!string.IsNullOrEmpty(text))
    {
        DateTime result = DateTime.MinValue;
        foreach (CultureInfo cultureInfo in 
                 CultureInfo.GetCultures(CultureTypes.AllCultures))
        {
            try
            {
                if (DateTime.TryParse(text, cultureInfo, 
                                      DateTimeStyles.None, 
                                      out result))
                    return result;
            }
            catch (Exception ex) { }
        }
    }

    return null;
}

Happy coding!

Show/Hide Hidden Files on macOS

Show/Hide Hidden Files the Long Way

The long way to show hidden Mac OS X files is as follows:

  • Open Terminal found in Finder > Applications > Utilities
  • In Terminal, paste the following:

    defaults write com.apple.finder AppleShowAllFiles YES
    
  • Press return
  • Restart your Mac

This will show all hidden files. To hide them again, follow the same steps but replace the Terminal command with:

defaults write com.apple.finder AppleShowAllFiles NO

It’s not the longest set of instructions or the biggest command to commit to memory but if you’re doing this a lot, it’s worth spending a few minutes now to save yourself a lot more time in the future.

Device name in Xamarin

Using Device Information Plugin for Xamarin and Windows, you have access to same information for a device:

  • GenerateAppId: used to generate a unique Id for your app.
  • Id: this is the device specific Id
  • Device Model: get the model of the device
  • Version: get the version of the Operating System

If you want the device name, it's not in this list. Then for that we can create our functions.

IDevice interface

First of all we have to create an interface, I call it IDevice.

using System;
namespace myApp.Interfaces
{
    public interface IDevice
    {
        string DeviceName();
    }
}

The GetDeviceName() method returns the name of the device. You will need to implement this method in iOS and Android.

iOS dependency

Then in iOS project, I add a new dependence like:

using System;
using myApp.iOS;
using myApp.Interfaces;

[assembly: Xamarin.Forms.Dependency(typeof(Device_iOS))]
namespace myApp.iOS
{
    public class Device_iOS: IDevice
    {
        public string GetDeviceName() {
            return UIKit.UIDevice.CurrentDevice.Name;
        }
    }
}

To get the name of the device in iOS, you use the UIDevice class in the UIKit Framework.

Android

For Android, I add the following code to the project:

using System;
using Android.Bluetooth;
using myApp.Droid;
using myApp.Interfaces;
using Xamarin.Forms;

[assembly: Dependency(typeof(Device_Droid))]
namespace myApp.Droid.Dependencies
{
    public class Device_Droid : IDevice
    {
        /// 
        /// Get device the name.
        /// 
        /// The name.
        public string DeviceName()
        {
			BluetoothAdapter myDevice = 
                BluetoothAdapter.DefaultAdapter;
			return myDevice.Name;
        }
    }
}

Getting the device name is a little tricky in Android, which has no public API for that purpose. You can get it from the BluetoothAdapter class; however, to use the BluetoothAdapter class, you need to add the Bluetooth permission in the Android project.

Android Bluetooth

Call dependency

After that I have to add in my main project a call to the dependency.

var platform = DependencyService.Get<IDevice> ();
string name = platform.GetDeviceName();

Happy coding!

Microsoft says iOS and Android support doesn’t mean Windows Phone is dead

Is-Windows-Phone-dead

In an interview with Business Insider, Microsoft’s Joe Belfiore spoke briefly about Microsoft’s recent announcements made at Build such as the Windows 10 Fall Creators Update but also took the time to comfort those worried about the small presence of Windows phones at the event and Microsoft’s growing focus on iOS and Android devices.

“We’re going to continue to support Windows phone,” Belfiore said before adding that, “Windows is a platform that drives the experience on a whole range of devices. We live in a highly diverse world.”

With the significantly higher number of users on iOS and Android compared to Windows 10 Mobile, it’s understandable that Microsoft would want to offer their services and products to those using those ecosystems. This often frustrates Windows phone users though as it can appear that Microsoft favors offering support for other companies’ mobile devices over their own. And for the most part, recently anyway, this has been fairly true.

It’s been a while since Microsoft released their own Windows phone device (they’ve been relying on other companies to manufacture phones) but the Windows 10 Mobile operating system continues to get updates (though admittedly not as big as the Windows 10 updates) as do many Windows phone apps. There’s also a growing number of rumors and statements that suggest that Microsoft could be planning a “Surface Phone” which could radically redefine what a smartphone looks like and is used for.

The Essential Meta Tags for Social Media

These days, almost every website encourages visitors to share its pages on social media. We’ve all seen the ubiquitous Facebook and Twitter icons, among others, just begging to be clicked. This comes as no surprise as sharing via social media, the internet incarnation of word-of-mouth, is one of the most effective ways for businesses and individuals to gain awareness.

When users choose to share these links, it is tasked to the web developer to make sure that the associated web pages are properly prepared, which is what we’ll look at now. Facebook and Twitter are, by far, the most popular social media platforms, so let’s focus on those two.

Sharing on Facebook and Twitter

Facebook offers developers various options on how a shared web page appears in its timeline depending on the website’s content. Unless otherwise specified, every website defaults to the type called, appropriately, “website”, which is the example we’ll use.

Let’s say someone has shared the home page of a fictional travel company – Facebook displays it like this:

facebook-card

Twitter, as well, has multiple ways to format shared web pages that appear in its feed, but we’ll look at the one that’s quite similar to the above example from Facebook, which Twitter calls the “Summary Card with Large Image”:

twitter-card

As we can see, each features multiple attributes of the shared Web page:

  • a prominent image and title
  • a description
  • the domain name

Proprietary <meta> Tags

How do we specify these attributes? With <meta> tags. When a link is shared, both Facebook and Twitter scrape the associated web page and read its <meta> tags to display the appropriate information.

Facebook uses <meta> tags leveraging the Open Graph protocol, a classification system for Web pages that extends beyond those <meta> tags already defined in HTML5. A complete list of <meta> tags available can be found at the Open Graph Web site. There are so many from which to choose that it can be somewhat intimidating, but only four are actually required:

<meta property="og:title" 
      content="European Travel Destinations">
<meta property="og:description" 
      content="Offering tour packages for individuals or groups.">
<meta property="og:image" 
      content="http://euro-travel-example.com/thumbnail.jpg">
<meta property="og:url" 
      content="http://euro-travel-example.com/index.htm">

Twitter has its own <meta> tags that are similar to the Open Graph protocol, but uses the “twitter” prefix instead of “og”. As with Facebook, only a few are required. The type of display format we’re requesting from Twitter is also specified:

<meta name="twitter:title" 
      content="European Travel Destinations ">
<meta name="twitter:description" 
      content=" Offering tour packages for individuals or groups.">
<meta name="twitter:image" content=" 
      http://euro-travel-example.com/thumbnail.jpg">
<meta name="twitter:card" 
      content="summary_large_image">

Reconciling <meta> Tags

There’s no harm with having multiple tags that appear redundant. Too much information never hurt anyone except by adding a few extra bytes to the HTML file.

But for our purposes, and for the sake of brevity, we can leverage the fact that Twitter allows us to substitute Open Graph <<meta> tags for its own. In the end, except for the necessity of specifying a display format, none of the custom Twitter <meta> tags are needed. This gives us the following, which could be considered the bare minimum of tags necessary to make a web page amenable for sharing on social media:

<meta property="og:title" 
      content="European Travel Destinations">
<meta property="og:description" 
      content="Offering tour packages for individuals or groups.">
<meta property="og:image" 
      content="http://euro-travel-example.com/thumbnail.jpg">
<meta property="og:url" 
      content="http://euro-travel-example.com/index.htm">
<meta name="twitter:card" 
      content="summary_large_image">

Reconciling the guidelines for the image is simple: follow Facebook's recommendation of a minimum dimension of 1200x630 pixels and an aspect ratio of 1.91:1, but adhere to Twitter's file size requirement of less than 1MB.

Validating <meta> Tags

If there are any doubts about the legitimacy of paring down to these five tags, we can use the helpful Facebook Sharing Debugger and Twitter Card Validator. Both these tools will scrape any Web page hosted on a public server for relevant <meta> tags and display how it would look when shared. It will also list any errors and provide suggestions. So how did we do with our particular example? Twitter seems fine with things, but Facebook, on the other hand, lists one item as a warning:

facebook-warning

Social Media Analytics

What Facebook is indicating is that if you’re going to use their analytics tool, which they call Domain Insights, you must provide the unique ID number associated with your account. The <meta> tag would then look something like this:

<meta property="fb:app_id" content="your_app_id" />

Twitter has something similar that they call Twitter Card Analytics. To get the most out of this tool, Twitter recommends using the following <meta> tag that contains the Twitter username that you want associated with the shared Web page:

<meta name="twitter:site" content="@website-username">

Keep in mind, though, that if you have no particular interest in using these analytic tools, then omitting the above two <meta> tags has no effect on how a shared Web page appears on a Facebook timeline or Twitter feed.

What else?

Facebook documentation recommends one additional <meta> tag, though it’s not required. A <meta> tag that denotes the name of the Web site in which the shared page resides:

<meta property="og:site_name" content="European Travel, Inc.">

Twitter suggests one other <meta> tag as well that is recommended, but not required:

<meta name="twitter:image:alt" content="Alt text for image">

This provides an alternative image description for those who are visually impaired.

Final Markup

That should do it. To reiterate, when you look at documentation from Facebook and Twitter for sharing Web pages, there are many other <meta> tags available that can be used to specify different types of content. But, in general, the following will suffice:

<!--  Essential META Tags -->
<meta property="og:title" 
      content="European Travel Destinations">
<meta property="og:description" 
      content="Offering tour packages for individuals or groups.">
<meta property="og:image" 
      content="http://euro-travel-example.com/thumbnail.jpg">
<meta property="og:url" 
      content="http://euro-travel-example.com/index.htm">
<meta name="twitter:card" 
      content="summary_large_image">

<!--  Non-Essential, But Recommended -->
<meta property="og:site_name" 
      content="European Travel, Inc.">
<meta name="twitter:image:alt" 
      content="Alt text for image">

<!--  Non-Essential, But Required for Analytics -->
<meta property="fb:app_id" content="your_app_id" />
<meta name="twitter:site" content="@website-username">

Happy coding!

How to capitalize the first letter in a cell in Excel

If you’d like to capitalize all letters in a cell, it’s easy – just use the following formula (assuming cell A1 has the text you want to capitalize).

=PROPER(A1)

But what if you just want to capitalize the first word in the cell “A1”? For example, you have the following  text in a cell “A1” and you’d like to capitalize just the first letter:

How to have the First Letter of a sentence Capitalize

To capitalize “How” in cell “A1”, use one of the following formula:

=REPLACE(A1,1,1,UPPER(LEFT(A1,1)))

or

=CONCATENATE(UPPER(LEFT(A1,1)),RIGHT(A1,LEN(A1)-1))

The result:

How to have the first letter of a sentence capitalize

Not working for you?

Remember to replace A1 with the cell that contains the string of words you want to parse out.

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!

Advertsing

125X125_06

Planet Xamarin

Planet Xamarin

Calendar

<<  June 2017  >>
MonTueWedThuFriSatSun
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789

View posts in large calendar

Month List