Happy 15th Birthday .NET!

Happy-Birthday-Microsoft-DotNet

Today marks the 15th anniversary since .NET debuted to the world. On February 13th, 2002, the first version of .NET was released as part of Visual Studio.NET. It seems just like yesterday when Microsoft was building its “Next Generation Windows Services” and unleashed a new level of productivity with Visual Studio.NET.

Since the beginning, the .NET platform has allowed developers to quickly build and deploy robust applications, starting with Windows desktop and web server applications in 2002. You got an entire managed framework for building distributed Windows applications, ASP.NET was introduced as the next generation Active Server Pages for web-based development, and a new language, C# (pronounced “see sharp” :-)) came to be.

Over the years, .NET and it’s ecosystem has grown and expanded to meet the needs of all kinds of developers and platforms. As the technology landscape has changed, so has .NET. You can build anything with .NET including cross-platform web apps, cloud services, mobile device apps, games and so much more. We have a vibrant open-source community where you can participate in the direction of .NET.

Xamarin.Forms (Android): Workaround For Splash Screen With Logo

What is the quickest way to add a splash screen to your Android project in Xamarin?

  1. Create a new folder under the Android project folder "Resources" with the name "Values".
  2. In that folder add a new "Styles.xml" file. Add -> New Item, then XML File. Make sure after creating this file to have the property "Build Action" set to the default value: "AndroidResource". In this file we will create a new theme "Theme.Splash" that set the background of our Splash with our logo.
  3. Edit the file to be as follows:
    <?xml version="1.0" encoding="utf-8" ?>
    <resources>
      <style name="Theme.Splash" parent="android:Theme">
        <item name="android:windowBackground">@drawable/myLogo</item>
        <item name="android:windowNoTitle">true</item>
      </style>
    </resources>
  4. Add a Splash Activity to the Android Project using Add -> New Item, then Activity. Let's name it SplashActivity.
  5. Change the attributes of the activity to set the theme attribute to "@styles/Theme.Splash", MainLauncher attribute to "True", and NoHistory also to "True". The Theme attribute is responsible for the style of the activity, the MainLauncher is responsible for making this activity the first activity to show and NoHistory is responsible for preventing navigation back to this activity. The activity attributes should look like the following:
    [Activity(Theme = "@style/Theme.Splash", 
              MainLauncher = true, 
              NoHistory = true)]
  6. Add the following code to the "OnCreate" method in Splash activity immediately after the comments // Create your application here:
    // Simulate a long loading process on app
    System.Threading.Thread.Sleep(10000);
    StartActivity(typeof(MainActivity));

    The first line simulates a long-loading process.
    The second line Start our MainActivity where our application will run main tasks after the Splash is shown.

  7. Just before running the application, we need to ensure that the MainLancher attribute of the MainActivity is set to false:
    [Activity(Label = "HandyApp.Droid", Icon = "@drawable/icon", 
              MainLauncher = false, 
              ConfigurationChanges = ConfigChanges.ScreenSize | 
                                     ConfigChanges.Orientation)]
  8. And let's run the application.

Do you want to logo in the center of your screen?

  1. In Styles.xml, remove the entire line where the "windowBackground" attribute and value are. Instead insert the following line specifying that the background is of White color:
    <item name="android:colorBackground">@android:color/white</item> 
  2. In the Resources folder, create a new folder "layout". Here we will add our layout for the SplashActivity.
  3. In the layout folder, add a new Android Layout: Add->New Item...->Android Layout. let's call it "SplashLayout.xaml".
  4. Edit the source of SplashLayout to match the following markup:
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:minHeight="25px"
        android:minWidth="25px"
        android:gravity="center"
        android:background="#6d6763">
        <ImageView
            android:src="@drawable/myLogo"
            android:layout_height="fill_parent"
            android:layout_width="wrap_content"
            android:layout_gravity="center"
            android:id="@+id/imageView1" />
    </LinearLayout>
    Here we have an ImageView in the center with source (src) of your logo in the drawable folder.
  5. In SplashActivity.cs, edit the "OnCreate" method to match the following code:
    [Activity(Theme = "@style/Theme.Splash", 
              MainLauncher = true, NoHistory = true)]
    public class SplashActivity : Activity {
        protected override void OnCreate(Bundle savedInstanceState) {
            base.OnCreate(savedInstanceState);
    
            SetContentView(Resource.Layout.SplashLayout);
            System.Threading.ThreadPool
                            .QueueUserWorkItem(o => LoadActivity());
        }
    }
    In this code, we set the content view of the SplashActivity to our SplashLayout.xaml and then we queue the MainActivity in the ThreadPool object using the LoadActivity method that we will write in the next step.
  6. Add a new method to the SplashActivity class called "LoadActivity":
    private void LoadActivity()     {
        // Simulate a long pause
        System.Threading.Thread.Sleep(5000);
        RunOnUiThread(() => StartActivity(typeof(MainActivity)));
    }  
    Note how we shifted the sleep period to this method.
  7. Run the application

C# IL Viewer for Visual Studio Code using Roslyn side project

For the past couple of weeks I've been working on an IL (Intermediate Language) Viewer for Visual Studio Code. As someone that develops on a Mac, I spend a lot of time doing C# in VS Code or JetBrains' Rider editor - however neither of them have the ability to view the IL generated (I know JetBrains are working on this for Rider) so I set out to fix this problem as a side project.

As someone that's never written a Visual Studio Code extension before it was a bit of an abmitious first extension, but enjoyable none the less.

Today I released the first version of the IL Viewer (0.0.1) to the Visual Studio Code Marketplace so it's available to download and try via the link below:

Download IL Viewer for Visual Studio Code

Download C# IL Viewer for Visual Studio Code or install it directly within Visual Studio Code by launching Quick Open (CMD+P for Mac or CTRL+P for Windows) and pasting in the follow command and press enter.

ext install vscodeilviewer

The source code is all up on GitHub so feel free to take a look, but be warned - it's a little messy right now as it was hacked together to get it working.

il_viewer_animated

For more information you can visit this link.

Global Resources problem in Xamarin projects

Today I spent a lot of time to understand why my style doesn’t work.

<Application xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
             x:Class="myProject.App">
    <Application.Resources>
        <ResourceDictionary>
            <Style x:Key="WarmGreyLine" TargetType="BoxView">
                <Setter Property="HeightRequest" Value="1" />
                <Setter Property="HorizontalOptions" Value="Fill" />
                <Setter Property="Color" Value="#EEE9E5" />
                <Setter Property="Margin" Value="0,10,0,10" />
            </Style>
        </ResourceDictionary>
    </Application.Resources>
</Application>

I followed a video about it on Xamarin University. Everything was the same. They say you can copy your style from a ContentPage.Resources and page in the Application.Resources section

    <ContentPage.Resources>
        <ResourceDictionary>
            <Style x:Key="WarmGreyLine" TargetType="BoxView">
                <Setter Property="HeightRequest" Value="1" />
                <Setter Property="HorizontalOptions" Value="Fill" />
                <Setter Property="Color" Value="#EEE9E5" />
                <Setter Property="Margin" Value="0,10,0,10" />
            </Style>
        </ResourceDictionary>
    </ContentPage.Resources>

The XAML is correct but if you execute the code you receive an error like:

Inner Exception: Position 38:14. StaticResource not found for key WarmGreyLine Message: Exception has been thrown by the target of an invocation.

The Solution

The is a little thing in the video they forgot to say!

In the App.xaml.cs you have to call InitializeComponent();

namespace myInventories
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();
        }
    }
} 

Happy coding!

Announcing Microsoft ASP.NET WebHooks V1

WebHooks provide a simple pub/sub model for wiring together Web APIs and services with your code. A WebHook can be used to get notified when a file has changed in Dropbox, a code change has been committed to GitHub, a payment has been initiated in PayPal, a card has been created in Trello, and much more — the possibilities are endless! When subscribing, you provide a callback URI where you want to be notified. When an event occurs, an HTTP POST request is sent to your callback URI with information about what happened so that your Web app can act accordingly. WebHooks happen without polling and with no need to hold open a network connection while waiting for notifications.

Receiving WebHooks

Dealing with WebHooks depends on who the sender is. Sometimes there are additional steps registering a WebHook verifying that the subscriber is really listening. Often the security model varies quite a bit. Some WebHooks provide a push-to-pull model where the HTTP POST request only contains a reference to the event information which is then to be retrieved independently.

The purpose of Microsoft ASP.NET WebHooks is to make it both simpler and more consistent to wire up your API without spending a lot of time figuring out how to handle any WebHook variant:

WebHoks-Receiving

A WebHook handler is where you process the incoming WebHook. Here is a sample handler illustrating the basic model. No registration is necessary – it will automatically get picked up and called:

public class MyHandler : WebHookHandler
{
    // The ExecuteAsync method is where to process the WebHook data regardless of receiver
    public override Task ExecuteAsync(string receiver, WebHookHandlerContext context)
    {
        // Get the event type          
        string action = context.Actions.First();
 
        // Extract the WebHook data as JSON or any other type as you wish
        JObject data = context.GetDataOrDefault();
 
        return Task.FromResult(true);
    }
}

Finally, we want to ensure that we only receive HTTP requests from the intended party. Most WebHook providers use a shared secret which is created as part of subscribing for events. The receiver uses this shared secret to validate that the request comes from the intended party. It can be provided by setting an application setting in the Web.config file, or better yet, configured through the Azure portal or even retrieved from Azure Key Vault.

For more information about receiving WebHooks and lots of samples, please see these resources:

More detail on Microsoft Blog.

How do I extract text that lies between two strings?

My initial prolem was to extract from a SQL string generated by MySql, all fields. I had a string like

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: }>,
<{CreatedDate: }>,
<{CreatedBy: }>,
<{UpdatedDate: }>,
<{UpdatedBy: }>,
<{IsDeleted: }>);


With a bit of RegEx I can extract all fields with the following function:

public IEnumerable<string> GetSubStrings(string input, string start, 
                                         string end) {
    Regex r = new Regex(Regex.Escape(start) + "(.*?)" + Regex.Escape(end));
    MatchCollection matches = r.Matches(input);
    foreach (Match match in matches)
        yield return match.Groups[1].Value;
}


Then if you want to have in a single line this query and generate the list of fields to have a list of parameters for a MySqlCommand for example, you can use the following function:

string strSQL = yoursql.Replace(Environment.NewLine, "")
                       .Replace("\r", " ");
string strParameters = "";

List<string> prm = GetSubStrings(strSQL, "<{", ": }>").ToList();
foreach(string s in prm) {
    string tmp = s.Replace("?", "");
    strParameters += Environment.NewLine + 
        $"cmd.Parameters.Add(\"?{tmp}\", MySqlDbType.VarChar)" +
        $".Value = record.{tmp}"; ;
}
this.textBoxParams.Text = strParameters;

strSQL = strSQL.Replace("`inventoryapp`.", "");
strSQL = strSQL.Replace("<{", "?").Replace(": }>", "");

Happy coding!

It’s a Good Day to Be a C# Developer

great_time_csharp_header

Recently at Connect(), Microsoft made a slew of new announcements. First, the public availability of Visual Studio 2017 Release Candidate. This just isn't a new version of the signature developer tool, it also includes the latest bits for C# 7.0. Second, Google announced they were joining the .NET Foundation. This means that Google, technically a competitor of Microsoft, wants to be actively involved in the evolution of .NET (and indirectly C#). Third, the first public release of Visual Studio for Mac. As a native environment, Visual Studio for Mac will provide the same world class tooling support for Xamarin applications, using C# and F#.

We could go on, but there is a common thread that runs between many of these announcements. As a developer, choosing C# as a part of your technology stack is an excellent decision! But what if you are not a C# developer already? How does C# compare to other popular languages such as JavaScript, Java, Python, etc?

Migrate SQLite to MySQL

I’m developing a huge app made with Xamarin Forms in my company. A problem was to create all tables in the device with SQLite to the main database MySql.

SQLLite-To-MySql-1

I found a way to create all tables quickly with a tool called SQLite to MySQL.

SQLite-to-MySQL is a powerful and reliable tool to convert SQLite databases to MySQL, MariaDB or Percona format. The program has high performance due to direct connection to source and destination databases (it does not use ODBC or any other middleware software). Command line support allows to script, automate and schedule the conversion process.

SQLLite-To-MySql-2

SQLLite-To-MySql-3

Features

  • All versions of Linux/Unix and Windows MySQL servers are supported
  • Option to customize resulting table structure
  • Convert indexes and relationships between tables
  • Stores conversion settings into profile
  • Option to filter data using SELECT-queries
  • Option to merge SQLite data into an existing MySQL database
  • Option to synchronize MySQL database with SQLite data
  • Support for multibyte character sets
  • Option to export SQLite database into MySQL script file
  • Verified compatibility with MariaDB and Percona
  • Option to customize MySQL storage engine and MySQL charset
  • Special approach for Virtual Server users
  • Command line support
  • Easy-to-use wizard-style interface
  • Full install/uninstall support
  • Unlimited 24/7 support service
  • 1-year subscription for updates
    SQLLite-To-MySql-7

Click here to download and try it.

Xamarin Forms and Google Mobile Ads for iOS: update

In my previous post I explaind how to add on your application advertising. In those days Xamarin has removed from the Component Store the component called Google Mobile Ads for iOS.

Now you have to install another component called Firebase AdMob for iOS.

Firebase_admob_ios

After installed this component you can see in your Output window a similar info without see an advert in your app:

2016-11-18 11:28:14.853 WordBankEasy.iOS[11103:2250070] <Google> You must set the rootViewController property of <GADBannerView: 0x1034702c0; frame = (-10 0; 320 50); clipsToBounds = YES; layer = <CALayer: 0x174e39d40>> before loading a request.

To fix this issue you have to find before the right UIViewController. For that you can use the following code:

    UIViewController viewController = null;
    foreach (UIWindow rootView in UIApplication.SharedApplication.Windows) {
        if (rootView != null) {
            viewController = rootView.RootViewController;
        }
    }

    adView = new BannerView(size: AdSizeCons.Banner,
                            origin: new CGPoint(-10, 0))
    {
        AdUnitID = AdmobID,
        RootViewController = viewController
    };

Happy coding!

Xamarin Forms Components

Hello guys!

From today on Nuget there are 4 new components for Xamarin Forms created by me.

Happy coding!

Advertsing

125X125_06


Subscribe to our mailing list

* indicates required


TagCloud

MonthList

CommentList