Sunday, September 4, 2016

Cordova add local notifications with default sound



1. add plugin Local-Notification
cordova plugin add https://github.com/katzer/cordova-plugin-local-notifications

2. To test a sample, In onDeviceReady, add below. This will show the notification after about a minute after you launch your app. You can close the app or minimize it (ie; go launch another app or go to home page)


        var date = new Date();
        date = new Date(date.getTime() + 1 * 60000) // add a minute from now

        cordova.plugins.notification.local.schedule({
            id: 1,
            title: "My Notification Title",
            message: "My Notification Body",
            at: date,
            sound: "res://platform_default"
        });

Android emulator add ringtone and notification sounds

The default android emulator do not come with any sounds, like ringtones or notification sounds. You can check this by going to the settings --> Sound option and see whats set for ringtone or notifications. By default, this will be set as None.

To add sounds locate mp3 file(s) you want to use and put it into a folder, for example create a  folder sounds and copy the file(s) there. you can download some from www.freesound.org if needed

Run the AVD (Android Virtual Device) manager and click edit on the AVD name you want to use. Make sure SD card option is selected and a size is provided.  About 100MB will be more than enough. Click OK to and close.

Now fire up the emulator ( by clicking start in AVD manager) and once its running, come to the command prompt. Assuming you have android tools in your path (ex: "C:\Program Files (x86)\Android\android-sdk\platform-tools\") , issue below command
adb devices

If all is well, it should show the emulator device details we are connecting to.
for example

C:\>"C:\Program Files (x86)\Android\android-sdk\platform-tools\adb.exe" devices
List of devices attached
emulator-5554   device

Make a note of the below folders

SD-Card
/mnt/sdcard/alarms
/mnt/sdcard/notifications
/mnt/sdcard/ringtones

Form commands like below to copy the mp3 files to your emulator where sounds is the folder where you have stored your local copy of mp3 files to be copied

C:\Users\myname\Downloads>adb push sounds /mnt/sdcard/ringtones
push: sounds/ding.mp3 -> /mnt/sdcard/ringtones/ding.mp3
1 file pushed. 0 files skipped.
584 KB/s (24912 bytes in 0.041s)

C:\Users\myname\Downloads>adb push sounds /mnt/sdcard/notifications
push: sounds/ding.mp3 -> /mnt/sdcard/notifications/ding.mp3
1 file pushed. 0 files skipped.
619 KB/s (24912 bytes in 0.039s)

Now restart your emulator, and the sounds should show up in setting. You can select the appropriate sounds now!

You may even skip the SD card and directly copy to the system folders (I haven't tested this)
Android OS System
/system/media/audio/alarms
/system/media/audio/notifications
/system/media/audio/ringtones

Wednesday, August 10, 2016

Visual studio message - Your license has gone stale and must be updated

Running Visual Studio 2015 on Windows 2012 R2, and suddenly a popup came saying "Your license has gone stale and must be updated"

Clicking the update licence gave an error download of licence failed. Sign out and sign in also did not work. The only other option was to exit visual studio, and that's not very helpful at all.

After numerous google searches, figured that the issue is about UAC. To solve, I followed the below steps

1. Go to Control Panel
2. Search UAC
3. Click on Action Center, Change User Account Control Settings
4. Make a note of the current slider setting
5. Turn the slider all the way to the bottom (ie; Never notify option) and click OK
6. Go back to visual studio and check the update license, and voila, the licence updated
7. Revert UAC original setting by going back to UAC and apply the original value (Step 4)

Sunday, May 29, 2016

Scania Truck Driving Simulator Brake and Accelerator switched in controller pedal

I got the Ferrari 458 Italia Racing Wheel for XBox360 and PC and hooked it up to my PC to play Scania Truck Driving Simulator

This may work for any steering wheel controller for this game

However, after starting the game, I found that the accelerator and brake are swapped. ie; Press the brake in the pedals and the truck go forward. Press the accelerator in the pedals and the truck will break and stop.. and press it further, it will go reverse!

To make it work, I had to make the following changes.


  1. Run the game and create a profile
  2. Start any game (example freeform driving) and then press escape to find options
  3. Make sure Keyboard + controller is selected and in the controller selection, click and press your Brake and Accelerator to register under Acceleration Axis and Brake Axis. The both should register as Joystick Z axis.  Also you can notice that see that they work opposite
  4. Now quit the game 
  5. In windows go to the following location :- C:\Users\\Documents\SCANIA Truck Driving Simulator\profile\44696E. Note that 44696E may not be the profile you see.. if you have only one profile in the game, there is only one folder here. 
  6. Inside this folder you can see file controls.sii
  7. This is a text file, so open this file in your favorite text editor, example notepad
  8. Locate the following lines in the file
    • config_lines[124]: "mix aforward `normalize(sel(c_jcombined, -j_throttle?0, (-j_throttle?1 * -0.5 + 0.5)), c_throt_dz)`"
    • config_lines[125]: "mix abackward `normalize(sel(c_jcombined, j_brake?0, (j_brake?1 * -0.5 + 0.5)), c_brake_dz)`"
  9. Change -j_throttle to j_throttle and j_brake to -j_brake
    • config_lines[124]: "mix aforward `normalize(sel(c_jcombined, j_throttle?0, (j_throttle?1 * -0.5 + 0.5)), c_throt_dz)`"
    • config_lines[125]: "mix abackward `normalize(sel(c_jcombined, -j_brake?0, (j_brake?1 * -0.5 + 0.5)), c_brake_dz)`"
  10. Save the file
  11. Run the game again, and now the throttle and brake should be working as it should be!

Tuesday, April 19, 2016

Windows 8, 8.1, 10 File explorer crashes after some time or clicking on the desktop

Please try below as solution:

Control Panel ==> Appearance and Personalization ==> file explorer options ==> click 'Clear' button next to Clear File Explorer history


if you are in explorer, you can copuy paste below in the address bar
Control Panel\Appearance and Personalization\File Explorer Options


IIS Unable to start debugging on the web server

---------------------------
Microsoft Visual Studio
---------------------------
Unable to start debugging on the web server. Could not start ASP.NET debugging. More information may be available by starting the project without debugging.

Click Help for more information.
---------------------------
OK   Help  
---------------------------


Solution: Please check to make sure the app pool you are debugging against is running. If its stopped, visual studio will give this error message

Monday, March 7, 2016

C# use proxy with HttpClient request


Posting a JSON string to server using a proxy


var httpClientHandler = new HttpClientHandler
{
    Proxy = new WebProxy("http://localhost:8888", false),
    UseProxy = true
};
using (var client = new HttpClient(httpClientHandler))
{
    string apiUrl = "http://yourserver.com/postpage";
    StringContent content = new System.Net.Http.StringContent("{dataelem:value}", Encoding.UTF8, "application/json");
    HttpResponseMessage response = client.PostAsync(apiUrl, content).Result;
}


Thursday, March 3, 2016

Execute arbitrary c# code at runtime, like a script

Here, we are compiling the c# code at runtime, and executing the result directly from in memory. The class is instantiated, and the method is called dynamically. The result, in this case a string is read back after the code executes

using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;

        public string RunCodeSnippet(string sCSharpCodeSnippet)
        {
            string sCSharpSource =
            @"using System;
              namespace com.mycomp
              {
                  public class MyClass
                  {
                     public string RunCSharpScript()
                     {
                        return(" + sCSharpCodeSnippet + @");
                     }
                  }
              }";

            Dictionary<string, string> csProviderOptions = new Dictionary<string, string> { { "CompilerVersion", "v3.5" } };
            CSharpCodeProvider csProvider = new CSharpCodeProvider(csProviderOptions);

            CompilerParameters csCompilerParams = new CompilerParameters { GenerateInMemory = true, GenerateExecutable = false };

            CompilerResults csCompresults = csProvider.CompileAssemblyFromSource(csCompilerParams, sCSharpSource);


            if (csCompresults.Errors.HasErrors)
            {
                throw new Exception("Compile Error! - " + csCompresults.Errors[0] + Environment.NewLine + sCSharpSource);
            }

            object o = csCompresults.CompiledAssembly.CreateInstance("com.mycomp.MyClass");
            MethodInfo mi = o.GetType().GetMethod("RunCSharpScript");
            var dataout = mi.Invoke(o, null);
            return (string)dataout;
        }

Sample Usage:
            try
            {
                string sResult = RunCodeSnippet("\"The time now is : \" + DateTime.Now.ToString()");
            }
            catch (Exception ex)
            {
                sError = ex.Message;
            }

Tuesday, February 16, 2016

C# formatting JSON as rtf document (can be useful to display on Richtext controls or exporting rtf files)

C# code that converts JSON string to RTF


sInJSON = sInJSON.Replace("\\", "\\\\").Replace("{", "\\{").Replace("}", "\\}").Replace(Environment.NewLine, "\\line" + Environment.NewLine);
string sRTFOut = @"{\rtf1\ansi\deff0
{\colortbl;\red0\green0\blue0;\red255\green140\blue0;\red255\green0\blue0;\red0\green128\blue0;\red0\green0\blue255;\red255\green0\blue255;\red0\green0\blue128;\red0\green128\blue128}" +
    Regex.Replace(
        sInJSON,
        @"(¤(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\¤])*¤(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)".Replace('¤', '"'),
        match =>
        {
            var cls = "\\cf2";
            if (Regex.IsMatch(match.Value, @"^¤".Replace('¤', '"')))
            {
                if (Regex.IsMatch(match.Value, ":$"))
                {
                    cls = "\\cf3";
                }
                else {
                    cls = "\\cf4";
                }
            }
            else if (Regex.IsMatch(match.Value, "true|false"))
            {
                cls = "\\cf5";
            }
            else if (Regex.IsMatch(match.Value, "null"))
            {
                cls = "\\cf6";
            }
            return cls + match + "\\cf1";
        })
+ "}";


Please review the RTF code outputted down below.

Points to Note: The RTF file always start with {\rtf1\ansi\deff0
After this, you can declare your color palatte as: {\colortbl;\red0\green0\blue0;\red255\green140\blue0;\red255\green0\blue0;\red0\green128\blue0;\red0\green0\blue255;\red255\green0\blue255;\red0\green0\blue128;\red0\green128\blue128}
and each of these can be later referred to as \cf1, \cf2 etc
Please also note that chars \, { and } are considered special characters. If you have it in your text, please override with \. For example, } should be changed as \} to display }

Example RTF code output:

{\rtf1\ansi\deff0
{\colortbl;\red0\green0\blue0;\red255\green140\blue0;\red255\green0\blue0;\red0\green128\blue0;\red0\green0\blue255;\red255\green0\blue255;\red0\green0\blue128;\red0\green128\blue128}\{\line
    \cf3"firstName":\cf1 \cf4"John"\cf1,\line
    \cf3"lastName":\cf1 \cf4"Smith"\cf1,\line
    \cf3"isAlive":\cf1 \cf5true\cf1,\line
    \cf3"age":\cf1 \cf225\cf1,\line
    \cf3"address":\cf1\line
    \{\line
        \cf3"streetAddress":\cf1 \cf4"21 2nd Street"\cf1,\line
        \cf3"city":\cf1 \cf4"New York"\cf1,\line
        \cf3"state":\cf1 \cf4"NY"\cf1,\line
        \cf3"postalCode":\cf1 \cf4"10021-3100"\cf1\line
    \},\line
    \cf3"phoneNumbers":\cf1\line
    [\line
        \{\line
            \cf3"type":\cf1 \cf4"home"\cf1,\line
            \cf3"number":\cf1 \cf4"212 555-1234"\cf1\line
        \},\line
        \{\line
            \cf3"type":\cf1 \cf4"office"\cf1,\line
            \cf3"number":\cf1 \cf4"646 555-4567"\cf1\line
        \}\line
    ],\line
    \cf3"children":\cf1\line
    [\line
    ],\line
    \cf3"spouse":\cf1 \cf6null\cf1\line
\}\line
}

Displayed as RTF:

{
   "firstName":"John",
  
"lastName":"Smith",
  
"isAlive":true,
  
"age":,
  
"address":
   {
      
"streetAddress":"21 2nd Street",
      
"city":"New York",
      
"state":"NY",
      
"postalCode":"10021-3100"
   },
  
"phoneNumbers":
   [
       {
          
"type":"home",
          
"number":"212 555-1234"
       },
       {
          
"type":"office",
          
"number":"646 555-4567"
       }
   ],
  
"children":
   [
   ],
 

You can also use this method to save/export to RTF files using your winform or ASP.Net web application

Microsoft OneDrive for Business stops sync with error the server you are trying to access is using an authentication protocol not supported

After a local windows password change, OneDrive for business stopped working with error
- the server you are trying to access is using an authentication protocol not supported

This error also kept pooping up during random times (guessing onedrive was trying to do a Sync)

Turns out the cached password is not updated in the Windows credential manager.

To Solve
Go to:
  1. Control Panel
  2. User Accounts
  3. Credential Manager
  4. Windows Credentials
  5. Look for the credential thats named like Microsoft* and on expanding the username matching the one you use to login
  6. Delete this credential. If in doubt, you can delete all of them and no harm is done as windows will ask for the credentials again as needed
  7. Now, go to onedrive.com, and login as usual. Once on the One Drive page, click Sync
  8. this should open your local OneDrive for buiness app and it should start normally at this time

I encountered this problem with Office 2016 on Windows 10, and this might be a problem for other versions of Office as well

Thursday, February 11, 2016

asp.net save GridView as HTML text


GridView1 is the gridview you want to save as HTML code

System.Web.UI.HtmlTextWriter htmlwriter = new System.Web.UI.HtmlTextWriter(new StringWriter());
GridView1.RenderControl(htmlwriter);
string htmlString = htmlwriter.ToString();


Change font styles on a asp.net GridView

While defining the asp.net GridView, you can set the below font related properties to adjust as you need


    Font-Bold="True|False"
    Font-Italic="True|False"
    Font-Names="string"
    Font-Overline="True|False"
    Font-Size="string|Smaller|Larger|XX-Small|X-Small|Small|Medium|Large|X-Large|XX-Large"
    Font-Strikeout="True|False"
    Font-Underline="True|False"

Below is an example

:GridView 
 ID="GridView1" 
 runat="server" 
 Font-Names="Times New Roman" 
 Font-Size="Medium">
</asp:GridView>

Wednesday, February 10, 2016

C# Cancel / abort an async method call/function with a web call as an example


Make the web method call.

string result = await MakeWebCall();

public async Task<string> MakeWebCall()
{
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://www.mysite.com");
    req.Method = WebRequestMethods.Http.Get;
    string result = null;

    try
    {
        using (WebResponse resp = await req.GetResponseAsync((ctGetResponse = new CancellationTokenSource()).Token))
        {
            StreamReader reader = new StreamReader(resp.GetResponseStream());
            result = await reader.ReadToEndAsync();
        }
    }
    catch (Exception ex)
    {
        return (ex.ToString());
    }
    return result;
}

Register the cancellationtoken

public static class Extensions
{
    public static async Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request, CancellationToken ct)
    {
        using (ct.Register((state) => ((HttpWebRequest)state).Abort(), request, false))
        {
            try
            {
                var response = await request.GetResponseAsync();
                return (HttpWebResponse)response;
            }
            catch (WebException ex)
            {
                // WebException is thrown when request.Abort() is called,
                if (ct.IsCancellationRequested)
                    // the WebException will be available as Exception.InnerException
                    throw new OperationCanceledException(ex.Message, ex, ct);
                // Abort not caled, throw the original Exception
                throw;
            }
        }
    }
}

Define the token globally

private CancellationTokenSource ctGetResponse;

call cancellation as required. In this example, its called when a link is clicked on the winform

private void linkLabelCancel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
            ctGetResponse.Cancel();
}

Format a timespan object in c# for display


new timespan initialized to 0
and then read as minutes:seconds:milliseconds (precision 2 digits)

TimeSpan ts = new TimeSpan(0, 0, 0); 
string tsString = ts.ToString("mm':'ss':'ff"); 

Read or Send an eTag header with a HTTP web request


This will add a eTag value to the header

string sEtag = "11234244";
System.Net.HttpWebRequest req1 = (HttpWebRequest)WebRequest.Create("https://mysite.com");
req1.Headers.Add("ETag", (new System.Net.Http.Headers.EntityTagHeaderValue("\"" + sEtag + "\"")).Tag);


And we can read it back easily from the response object (resp is WebResponse)

sEtag = resp.Headers.Get("ETag");

How to return value of the identity column after an insert in SQL server


Table MyTable with Id as an IDENTITY column (auto insert records)

CREATE TABLE [dbo].[MyTable] (
[Id] int IDENTITY(1, 1) NOT NULL,
[Component] varchar(50));

A Sample procedure that inserts a record and returns the id of the record inserted

CREATE PROCEDURE [dbo].[InsertRetId] 
@Component [VARCHAR](50),
@Id int output
AS
BEGIN

INSERT INTO [dbo].[MyTable]
           ([Component]
     VALUES
           (@Component);

select @Id = Scope_Identity();

END

Turn on Windows 11 Fast Boot

If windows starting is slow, to enable windows 11 fast startup/boot,  Press Windows + R, type powercfg.cpl, and hit Enter.  This will direct...