For a new project, my client required to output date strings in a format that included the two letter suffix added to the day number, like in British date (“January 1st 2018” as opposed to “January 1 2018”). The solution makes use of the custom formatting capabilities in the framework whereby it is possible to implement the IFormatProvider and ICustomFormatter interfaces to provide custom string formatting for use with methods that support formatting such as String.Format() or Console.WriteLine(). I decided to extend the existing DateTime format provision in the framework…
Category: C#
Xamarin Forms: TranslateY (or other properties) for platform
Sometimes you need to change a value for a specific platform and this value is a Double, for example. I spent a couple of minutes to find a working code. <Label> <Label.TranslationY> <OnPlatform x:TypeArguments=”x:Double” Android=”-10″ /> </Label.TranslationY> </Label> Happy coding!
Enable and control iOS 11 Large Titles in Xamarin.Forms
Apple introduced with iOS 11 a new UI in particular for larger titles: if you open your email, you see at the top a large title. That sit in the Navigation Bar and can be scrolled away when more space is needed. We can enable large titles with a renderer. For this example, I only created a new project and added the following renderer in the iOS project under Renderers folder. You can easily add to all your solution the following renderer in your iOS project: using System; using YourProject.iOS.Renderers;…
UriBuilder in Xamarin Forms
In Xamarin Forms there is a native function called UriBuilder: it allow you to create a well-formed url. In my implementation, all parameters are in a Dictionary called parameters. Using Linq, I put in builder.Query only the parameters with a value. UriBuilder builder = new UriBuilder(yourUrl); Dictionary<string, string> parameters = new Dictionary<string, string>(); parameters.Add(“reference”, Reference); parameters.Add(“param1”, Param1); builder.Query = string.Join(“&”, parameters.Where(p => !string.IsNullOrWhiteSpace(p.Value)) .Select(p => string.Format(“{0}={1}”, Uri.EscapeDataString(p.Key), Uri.EscapeDataString(p.Value)))); return builder.ToString(); Happy coding!
Binding FormattedString for Xamarin Forms
Xamarin Forms doesn’t have a Label with a Bindable FormattedString. For example, if you want a bindable bold word in the middle of a sentence in a Label, it’s very hard to design it with common control. For that, I create my own component for that. LabelRenderer.cs using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; using System.Runtime.CompilerServices; using Xamarin.Forms; namespace PSC.Controls { public class Label : Xamarin.Forms.Label { protected override void OnBindingContextChanged() { base.OnBindingContextChanged(); UpdateFormattedTextBindingContext(); } protected override void OnPropertyChanged( [CallerMemberName] string propertyName = null) { base.OnPropertyChanged(propertyName); if (propertyName ==…
Xamarin Forms Repeater View
A ListView is a kind of repeater but isn’t always what I want. It’s surprising something like this isn’t included in the framework but making your own is fairly simple. namespace PSC.Controls { /// <summary> /// Repeater view. /// </summary> public class RepeaterView : StackLayout { /// <summary> /// The item template property. /// </summary> public static readonly BindableProperty ItemTemplateProperty = BindableProperty.Create( “ItemTemplate”, typeof(DataTemplate), typeof(RepeaterView), null, propertyChanged: (bindable, value, newValue) => Populate(bindable)); /// <summary> /// The items source property. /// </summary> public static readonly BindableProperty ItemsSourceProperty = BindableProperty.Create( “ItemsSource”, typeof(IEnumerable),…
Xamarin, Android and starting a service at device boot
In my previous post called Xamarin: how to Start an Application at Device Boot in Android, I explained how you can change your Android Xamarin’s project to launch your app at the device boot. It is a good start but my problem was a bit more complex. I want to create a background service to track the geolocation of a device. I googled a lot to find a solution without a great success. Then I started to implement my code with some tests. Finally, I found a good way and…
Xamarin: how to Start an Application at Device Bootup in Android
This tutorial will explain to stat an application while the Android device boot-up. For this, we need to listen to the BOOT_COMPLETED action and react to it. BOOT_COMPLETED is a Broadcast Action that is broadcast once, after the system has finished booting. You can listen to this action by creating a BroadcastReceiver that then starts your launch Activity when it receives an intent with the BOOT_COMPLETED action. Add this permission to your manifest In your Android.Manifest you must add thi permission: <uses-permission android:name=”android.permission.RECEIVE_BOOT_COMPLETED” /> Then open this file and…
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…
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 { ///…
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…
How do I extract text that lies between two strings?
My initial problem was to extract from a SQL string generated by MySql, all fields. I had a string like 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 INSERT INTO `inventoryapp`.`inventory_keys` (`Id`, `PropertyId`, `AppointmentId`, `SectionType`, `KeysDescription`, `FobsWorking`, `EntryCodes`, `AlarmCodes`, `Notes`, `Version`, `CreatedDate`, `CreatedBy`, `UpdatedDate`, `UpdatedBy`, `IsDeleted`) VALUES (<{Id: }>, <{PropertyId: }>, <{AppointmentId: }>, <{SectionType: }>, <{KeysDescription: }>, <{FobsWorking: }>, <{EntryCodes: }>, <{AlarmCodes: }>, <{Notes: }>, <{Version:…
How to update the data in listview in Xamarin.Forms?
First you add a new class as a ViewModel like: public class RoomViewModel : BaseViewModel { [here following code] } If you don’t have BaseViewModel try to download from nuget Refractored.MvvmHelpers. Then in your class define an observable collection like public ObservableCollection<RoomRecommandation> _roomSuggestionList = new ObservableCollection<RoomRecommandation>(); public ObservableCollection<RoomRecommandation> Recommendations { get { return _roomSuggestionList; } } In your ContentPage add a listview like: <ListView ItemsSource="{Binding Recommendations}"> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <Grid Padding="10" RowSpacing="10" ColumnSpacing="10"> <Grid.RowDefinitions> <RowDefinition Height="" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <controls:CircleImage…
Xamarin Forms MasterDetail Page Navigation Recipe
In this recipe I will show you how to add a hamburger menu to your Xamarin Forms application using the MasterDetailPage class. The Xamarin.Forms MasterDetail Page consists of one page for the master and one or more pages for the detail. When used for the main navigation, as in this recipe, we will have a single master page and 4 detail pages. The code for this recipe comes from the Xamarin Forms CRM sample. I have simplified and streamlined the code, and a full Xamarin Studio solution is included at…
Remove multiple line in the same file with C#
Read the file, remove the multiple line (but it saves one of them) in memory and put the contents back to the file (overwriting) and create a backup file with the original file. using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace DelMultiLine { class Program { static void Main(string[] args) { if (args.Count() == 0 || args.Count() > 2) { Console.WriteLine(“\nDelMultiLine (by Enrico Rossini – puresourcecode.com)”); Console.WriteLine(“———————————————————————–“); Console.WriteLine(“Remove duplicate line in a file\n”); Console.WriteLine(“Usage:”); Console.WriteLine(” delmultiline <Filename> <resultFilename>\n”); Console.WriteLine(“filename: define a full path for the file you want…
Dijkstra’s Algorithm in C# with Generics
I recently needed to to implement a shortest-path algorithm (to identify preferred domain controllers using site link costs) and I found Dijkstra’s Algorithm Path class using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DijkstraAlgorithm { public class Path<T> { public T Source { get; set; } public T Destination { get; set; } /// <summary> /// Cost of using this path from Source to Destination /// </summary> /// /// Lower costs are preferable to higher costs /// </remarks> public int Cost { get; set; } } }…
DistinctBy in Linq (Find Distinct object by Property)
public class Size { public string Name { get; set; } public int Height { get; set; } public int Width { get; set; } } Consider that we have Size Class for advertisement which is having Heigth, Width and Name as property in it. Now Requirement is I have to find out the all product with distinct Name values. Size[] adv = { new Size { Name = “Leaderboard”, Height = 90, Width = 728 }, new Size { Name = “Large Rectangle”, Height = 280, Width = 336…
C# and HTML5: drag and Drop elements
HTML5 API includes Drag and Drop (DnD) native functionality. The event listener methods for all the drag and drop events accept Event object which has a readonly attribute called dataTransfer. The event.dataTransfer returns DataTransfer object associated with the event This is the list of events fired during the different stages: Event Description dragstart Fires when the user starts dragging of the object. dragenter Fired when the mouse is first moved over the target element while a drag is occuring. A listener for this event should indicate whether a drop is…
C# MVC: HttpContextBase from HttpContext.Current
It’s easy by using the HttpContextWrapper HttpContextBase basecontext = (new HttpContextWrapper(HttpContext.Current)); Happy coding!
How to check if IsNumeric?
If you need to check if something is a number, in C# doesn’t exist a function for that. That I’ve created the following code. public bool IsNumeric(object Expression) { if (Expression == null || Expression is DateTime) return false; if (Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean) return true; try { if (Expression is string) Double.Parse(Expression as string); else Double.Parse(Expression.ToString()); return true; } catch { } // just dismiss errors…
Customize Json result in Web API
If you work with Visual Studio 2015 and WebAPI, this short post is for you! We have to make our Web API project easy to debug so, I’m going to remove the XML formatter. I’m doing that because I’m in a test project and I’d like to see the response in the browser. The easily way to force the response to Json for all Web API requests is to remove the XML. Obviously you shouldn’t do it in production. Global.asax var formatters = GlobalConfiguration.Configuration.Formatters; formatters.Remove(formatters.XmlFormatter); Now we can start change…
Creating a URL shortener using ASP.NET WepAPI and MVC: error handling
In the two previous post I discussed about the first step to creare this application and the implementation of the business logic. Now we can implement the error handling. We have two custom exception classes: ShorturlConflictException (when a segment already exists) and ShorturlNotFoundException (when a segment isn’t found in the database). There is also a third type: an unexpected exception, for example when there is no database connection. Normally, the user will see these errors. We have to build a mechanism where these exceptions are caught and a nice error…
Creating a URL shortener using ASP.NET WepAPI and MVC: implementing the business layer
In my previsious post I discussed the first implementation of this application. In this post I’m explained how to implement the business layer. First of all you make sure the Business project references the Data, Entities and Exceptions projects. In the Exceptions project you add two new classes: ShorturlConflictException using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PSC.Shorturl.Web.Exceptions { public class ShorturlConflictException : Exception { } } ShorturlNotFoundException using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PSC.Shorturl.Web.Exceptions { public class ShorturlNotFoundException : Exception {…
Creating a URL shortener using ASP.NET WepAPI and MVC
In this tutorial, I use several techniques and tools. I use Microsoft Visual Studio 2015 and the latest version of all components. ASP.NET MVC: Microsoft’s modern web application framework. As the name says, it pushes you to use the MVC (model view controller) software design principle. ASP.NET Web API: Web API and MVC are used together in many applications. With MVC, the HTML of the web pages are rendered on the server, and with Web API you can, like the name says, create an API. Web API also uses the…
Throw vs Throw e
Some people asked me the different between those two following code: Code 1 try { … } catch (Exception ex) { throw ex; } Code 2 try { … } catch (Exception ex) { throw; } I don’t think there is ever a good reason to write catch (Exception e) { throw e; }. This loses the original stacktrace. When you use throw; the original stacktrace is preserved. This is good because it means that the cause of the error is easier to find.