Wednesday, 31 October 2018

Xamarin - Cross Platform Mobile Development

Xamarin - Cross Platform Mobile Development

Xamarin is one of the most popular cross-platform frameworks at the moment. Xamarin development allows you to develop Android, iOS, OS X, and Windows applications using Visual Studio and C#.

It allows you to share code between your Android and iOS app and compile it into native code. It also provides the advantages of native UI, native performance, and access to specific device features.

Xamarin-Supported IDE

Visual Studio is Microsoft’s modern, sophisticated IDE with many features for creating mobile, desktop, and web applications. It supports the development of mobile with .NET (Android, iOS, tvOS, watchOS), Mac desktop apps, .NET Core applications, ASP.NET Core Web applications, and Cross-platform Unity games.

It includes a rich editor, debugging, native platform integration with iOS, Mac, and Android, and integrated source control to name just a few of its many features.

Visual Studio for Mac replaced Xamarin Studio (Xamarin Studio 6.3 is the final release) and offers all the features of Xamarin Studio, plus cloud and web development, and contains improvements for cross-platform mobile development.

Xamarin-vs- Native App

Multi-Platform:

    Xamarin delivers multi-platform mobile apps and target all major platforms like iOS, Android and Windows. There are no discrepancies in functionality between platforms. Beyond that some of the most popular frameworks that are used to create cross-platform mobile apps are PhoneGap, Ionic, Titanium, etc. Whereas Native application doesn’t support all platforms.

    Here winner is Xamarin because it targets all major platforms.

Mobile Apps Development Time:

    Xamarin or Native, which one takes less time while developing mobile apps – it completely depends on how much technologies are required at time of development. Using Xamarin, entrepreneurs can skip the extra development time for each platform. This is also excellent for testing and saving development cost.

    Again winner is Xamarin apps are accessible for wider audiences at lower cost as compared to Native apps.


Performance of an Application:

    If we talk about performance, then Native applications are leading. Some of common challenges of Xamarin/Hybrid apps are: screen transitions are not smooth, buttons are not responding well as compared to native buttons and reaction time is higher.

    In the landscape of performance, Native apps have already won.

Specific Framework/Tool:

    Sometimes, operating systems require specific framework in order to access existing framework such as TouchID, push notification, Bluetooth connections, motion data, GPS data. If Xamarin developers need any one of above framework when creating an application must build a bridge between app and framework – the result will additional cost. In that case, you need to develop Native application.



Conclusion is totally depends on your requirements. 

Saturday, 29 September 2018

CI/CD with Visual Studio Online

We are going to automate our build and deployment process with Visual Studio Team Service for micro-services which are developed in Azure Service Fabric Framework.

We cover the following steps for CI/CD with Visual Studio Online,
  • Generate build and published artifacts with each checked-in
  • Release artifacts while new build available with Pre-deployment approvals

Create a build definition

Logged-in to the Visual Studio Team Service and go to the Build and Release tab, then clicking on the New button from the page which showing several templates for generating build. we select Azure Service Fabric Application template from available options




After clicking on Apply button, Visual Studio Team Service automatically generate tasks which require to build Service Fabric Application.




But VSTS wants some inputs from us for Agent queue field, we select Hosted VS2017 option to build our Service Fabric Application.





From Triggers tab, we enable continuous integration option.

Now we are good to go for generating build which trigger based on each checked-ins. We save our build definition and queue build. 

Our build failed due to following error,

Error : The OutputPath property is not set for project 'Authentication.Business.csproj'. Please check to make sure that you have specified a valid combination of Configuration and Platform for this project. Configuration='Release' Platform='x64'. You may be seeing this message because you are trying to build a project without a solution file, and have specified a non-default Configuration or Platform that doesn't exist for this project

Some of our projects in Service Fabric Application are configured with Any CPU option, and in VSTS set the Platform target variable to x64 which breaking our build.

Going back to build definition edit tab, and setting up variable of BuildPlatform to blank so that VSTS automatically identify the appropriate Platform for Service Fabric Application.



Clicking on Save & queue build,

This time our build succeeded and build artifacts are generated in drop folder in Visual Studio Team Service Server.

Now our next step is deploying latest artifacts to the Service Fabric environment which is hosted in Azure.


Create a release definition
Go to Release tab, and clicking on + Icon and select Create release definition option which landed us on this page,

We select Azure Service Fabric Deployment template which create deploy service fabric application task,

We need to tell VSTS about info of the Azure cluster infrastructure by setting up the connection so, that VSTS can deploy latest available artifacts to our azure service fabric cluster.


Clicking on Manage button which shown near Cluster Connections option which redirect us to Service Endpoint tab from Setting in VSTS.
Select Service Fabric option from dropdown.


There are three ways to connect Service Fabric,
  1. Certificate Based
  2. Azure Active Directory credential
  3. Others
Here we going to the Certificate Based approach to connect with our service fabric cluster which is hosted on Azure infrastructure.




·         Connection name: Name of your cluster connection name (Ex. - Azure-SF-Connection)
·         Cluster Endpoint: Micro service cluster endpoint format will be tcp://{your-cluster-name}.{azure-region-name}.cloudapp.azure.com:19000 (Ex. - tcp://microcluster.eastus.cloudapp.azure.com:19000)
·         Server Certificate Thumbprint: Server Certificate Thumbprint which used to secure Cluster in Azure (Ex. - 6B5F7C79B7E64FF1WDF87BEC9E8D32C7A5QQ9819)
·         Client Certificate: Server Certificate in Base64 String (Ex - base64 string format)
·         Password: If your Server Certificate have Password which need to be add our here. (Ex - XYZ)

We can obtain base64 string of Client Certificate using below PowerShell script,
[System.Convert]::ToBase64String([System.IO.File]::ReadAllBytes("C:\certificate.pfx"))

From script it's convert Client Certificate named "certificate.pfx" which is on C: drive into the base64 string.



Coming back to the Release definition task and dropdown showing the values of cluster connection and we set that connection & rest of the options which shown in red marks to the azure service fabric task.



And our Release pipeline is,



After checked-in in the branch, VSTS will pick up the latest source and build artifact and based on latest artifact will deploy in Service Fabric Application on Azure. 




Friday, 31 August 2018

Microsoft Azure Search Service


Microsoft Azure search provides powerful, scalable and stable search experience over data in web and mobile applications.

It provides an easy way to scale up and scale down based on user traffic/workload over the application. As per Microsoft SLA – it is highly available infrastructure with 99.95% uptime. There are some of the key features like auto-complete, auto-correct, geo-search and facet navigation filters.

There are two ways to configure search index from data source either though azure portal or Azure Search SDK.

The SDK provides client libraries that enable us to manage search indexes, data sources, indexers and execute queries. All the search API are available over HTTP with JSON response.

Azure Search Configuration Steps:

We would configure azure search service using Azure portal, the first login to the portal and create new search service with resource group, location, and pricing tier. Now we would follow the below steps with sample screen for further:

1.    Import Data- Choose Data source

Click on top bar – Import Data for data source section




Azure search would provide below data source as an input:

The pull model retrieves data from external data sources. It's supported through indexers that streamline and automate aspects of data ingestion, such as connecting to, reading, and serializing data. Indexers are available for Azure Cosmos DB, Azure SQL Database, Azure Blob Storage, and SQL Server hosted in an Azure VM. You can configure an indexer for on-demand or scheduled data refresh.



2. Create Index 

Here during index creation need to select Fields that defines the searchable data in your index. A Fields collection includes required and optional fields, named and typed, with index attributes that determine how the field can be used.



Attribute Description
searchable   Full-text searchable, subject to lexical analysis such as word-breaking during indexing. 
filterableReferenced in $filter queries. Filterable fields of type Edm.String or Collection(Edm.String) do not undergo word-breaking, so comparisons are for exact matches only. For example, if you set such a field f to "good day", $filter=f eq 'test' will find no matches, but $filter=f eq 'good day' will.
sortableBy default the system sorts results by score, but you can configure sort based on fields in the documents. Fields of type Collection(Edm.String) cannot be sortable.
facetableTypically used in a presentation of search results that includes a hit count by category (for example, restaurant in a specific city). This option cannot be used with fields of type Edm.GeographyPoint
keyUnique identifier for documents within the index. 
retrievableDetermines whether the field can be returned in a search result.

3. Customization Target Index

 Configuration database schedule for record synchronization.


4. Data Source Synchronization

5. Search Explore as an Output – Search APIs

 Here is the sample of suggestion search 

Here in left side you can see the facetable output using Azure search  APIs.

Key benefits:

  1. Enrich and extract insights through cognitive skills
  2. Get your search indices up and running quickly
  3. Easily scale up and down
  4. Connect search results to business goals with great control over search ranking
  5. Take advantage of Microsoft’s deep knowledge of natural language processing
  6.  Easily add geospatial search to your app

  

Service Limitation: every service has some of the limitation based on the resource which
We opt to create service indexes.

For more service quotas limitation please refer below URL.

Monday, 30 July 2018

Microsoft Azure Media Service – Encoding & Indexing Process using C#.Net – Part 2


As per continue thread on encoding and indexing process via Azure media service, in this part I would share technical implementation pf those steps via source code.

We need to Install the Azure SDK for an additional set of templates and tools which help you access even more cloud resources and services to improve your Azure development experience directly from Visual Studio. Also you can install library using NuGet packages.

Below are the some of namespace which I have import for this implementation:

using Microsoft.WindowsAzure.MediaServices.Client;
using Microsoft.WindowsAzure.MediaServices.Client.ContentKeyAuthorization;
using Microsoft.WindowsAzure.MediaServices.Client.DynamicEncryption;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;

As mentioned above - we are using Azure storage and media service class library, first of all we wold create instance of storage account’s container blob client to pull the Media files.  

CloudQueueClient AzureQueueClient;
CloudQueue AzureCloudQueue;
CloudQueueMessage AzureQueueMessage;

public ProcessorService()
      {
            var tokenCredentials = new AzureAdTokenCredentials(AppConfiguration.AADTenantDomain,
                new AzureAdClientSymmetricKey(AppConfiguration.ClientId, AppConfiguration.ClientSecret),
                AzureEnvironments.AzureCloudEnvironment);
            var tokenProvider = new AzureAdTokenProvider(tokenCredentials);
            context = new CloudMediaContext(new Uri(AppConfiguration.RESTAPIEndpoint), tokenProvider);

            sourceStorageAccount = new CloudStorageAccount(new StorageCredentials(AppConfiguration.SourceStorageAccountName, AppConfiguration.SourceStorageAccountKey), true);
            amsStorageAccount = new CloudStorageAccount(new StorageCredentials(AppConfiguration.AMSStorageAccountName, AppConfiguration.AMSStorageAccountKey), true);
            issuer = AppConfiguration.Issuer;
            Audience = AppConfiguration.Audience;

            AzureQueueClient = sourceStorageAccount.CreateCloudQueueClient();
        }

Get the respective blob file :

CloudBlockBlob blob = (CloudBlockBlob)sourceFile;
Copy blob file to Azure media service storage container file.

var amsFile = amsAssetContainer.GetBlockBlobReference(strFilename);

            if (!amsFile.Exists())
            {
                amsFile.StartCopyAsync(new Uri(sourceFile.Uri.AbsoluteUri + signature));
                 while (true)
                {
                    amsFile.FetchAttributes();
                    if (amsFile.CopyState.Status != CopyStatus.Pending)
                    {
                        break;
                    }
                    //It's still not completed. So wait for some time.
                    System.Threading.Thread.Sleep(1000);
                }
            }

After copy of blob file need to initiate encoding process job

public IAsset EncodeToAdaptiveBitrateMP4Set(IAsset asset)
        {
            // Declare a new job.
            var job = context.Jobs.Create(string.Format("Media Encoder Standard processing of {0}", asset.Name));

            var processor = GetLatestMediaProcessorByName("Media Encoder Standard");

            // In this case "Adaptive Streaming" preset is used.
            var task = job.Tasks.AddNew(string.Format("Media Encoder Standard processing of {0}", asset.Name),
                processor,
                "Adaptive Streaming",
                TaskOptions.None);

            task.Priority = 100;
            task.InputAssets.Add(asset);
            task.OutputAssets.AddNew(string.Format("{0} - Media Encoder Standard encoded", asset.Name),
                AssetCreationOptions.None);

            job.StateChanged += new EventHandler<JobStateChangedEventArgs>(JobStateChanged);
            job.Submit();
            job.GetExecutionProgressTask(CancellationToken.None).Wait();

            return job.OutputMediaAssets[0];
        }

After continue monitor of job state – finally we would need to publish URL

  private string GetStreamingOriginLocator(IAsset asset)
        {

             var assetFile = asset.AssetFiles.Where(f => f.Name.ToLower().
                                        EndsWith(".ism")).
                                        FirstOrDefault();

            IAccessPolicy policy = context.AccessPolicies.Create("Streaming policy",
                TimeSpan.FromDays(1825),
                AccessPermissions.Read);

            // Create a locator to the streaming content on an origin.
            ILocator originLocator = context.Locators.CreateLocator(LocatorType.OnDemandOrigin, asset,
                policy,
                DateTime.UtcNow.AddMinutes(-5));

            // Create a URL to the manifest file.
            return originLocator.Path + assetFile.Name;
        }

You would get streaming locator which would be used in Media play for streaming  content.

In the same manner – After Encoding you should initiate the Indexing process job like below

public IAsset RunIndexingJob(IAsset asset)
        {
            // Declare a new job.
            IJob job = context.Jobs.Create(string.Format("Media Indexing processing of {0}", asset.Name));

            // grab an instance of Azure Media Indexer and run a job
            IMediaProcessor indexer = GetLatestMediaProcessorByName("Azure Media Indexer");

            string title = asset.Name;
            title = System.Text.RegularExpressions.Regex.Replace(title, @"[^\w\.@-]", " ");
            string configuration = "<?xml version=\"1.0\" encoding=\"utf-8\"?><configuration version=\"2.0\"><input><metadata key=\"title\" value=\"@title\" /><metadata key=\"description\" value=\"\" /></input><settings></settings><features><feature name=\"ASR\"><settings><add key=\"Language\" value=\"English\"/><add key=\"CaptionFormats\" value=\"ttml; sami; webvtt\"/><add key=\"GenerateAIB\" value =\"true\" /><add key=\"GenerateKeywords\" value =\"true\" /></settings></feature></features></configuration>";
            configuration = configuration.Replace("@title", title);
            ITask task = job.Tasks.AddNew(string.Format("Media Indexing processing of {0}", asset.Name),
                indexer,
                configuration,
                TaskOptions.None);

            task.Priority = 100;

            // Specify the input asset to be encoded.
            task.InputAssets.Add(asset);
            task.OutputAssets.AddNew(string.Format("{0} - Media Indexed file", asset.Name), AssetCreationOptions.None);

            job.StateChanged += new EventHandler<JobStateChangedEventArgs>(JobStateChanged);
            job.Submit();
            job.GetExecutionProgressTask(CancellationToken.None).Wait();

            return job.OutputMediaAssets[0];
        }

After completion of indexing process – you would able to download files.

static void DownloadAsset(IAsset asset, string outputDirectory)
        {
            try
            {
                foreach (IAssetFile file in asset.AssetFiles)
                {
                    file.Download(Path.Combine(outputDirectory, file.Name));
                }
            }
            catch (Exception ex)
            {
                 throw ex;
            }
         }


An indexing job can generate the following outputs:

  1.  Closed caption files in the following formats: SAMI, TTML, and WebVTT.
  2.  Keyword file (XML). 
  3.  Audio indexing blob file (AIB) for use with SQL server.







So above are the process of encoding and indexing of media file using C#.NET, if you would have any queries and please comment below, for more in-depth information kindly follow Microsoft MSDN site. - https://docs.microsoft.com/en-us/azure/media-services/



Thank you!


Xamarin - Cross Platform Mobile Development

Xamarin - Cross Platform Mobile Development Xamarin is one of the most popular cross-platform frameworks at the moment. Xamarin devel...