Figer's Technology Consulting |

Microsoft Azure mobile services Node.js - Insert record into another table with-in an insert/update call

From Azure portal go into the Insert or update script and add this


function update(item, user, request) {
    request.execute({ success: insertAuditEntry });

    function insertAuditEntry() {
        var auditTable = tables.getTable('audit');
        var audit = {
            record: 'checkins',
            recordId: item.id,
            timestamp: new Date(),
            values: 'Add value here'
        };
        auditTable.insert(audit, {
            success: function() {
                // Write to the response now that all data operations are complete
                request.respond();
            }
        });
    }
}

Simple Javascript to stop the double tap action of zooming on Mobile



var time_stamp= Date.now();

window.addEventListener("touchstart",function(event_){

if (event_.timeStamp-time_stamp<300){ //300ms delay

    time_stamp= Date.now();

    event_.preventDefault();

    return false;

}

    else{ 

        time_stamp= Date.now();

    }

});

Installing free SSL cert on Azure website


No need to re-invent the wheel so I'm just linking to Troy Hunt's article which walks you through the entire process.

1.) Make sure your site is atleast a basic website instance (free and shared don't work, shared really should)

2.) on StartSSL make sure you are using your main browser and that it's a desktop browser when you first sign-up, you need to be able to save the SSL cert the company installs on your browser for further authentication, failing to do so will probably lock you out of your account.

http://www.troyhunt.com/2013/09/the-complete-guide-to-loading-free-ssl.html

Azure Mobile Services Async in .NET Web Forms applications



It's easy to code in Javascript or Java and catch the successful asyncinsert, but in web forms the proper code wasn't obvious nor easily found online. Here is my solution to add a record to my Azure Mobile Service on web forms button click. The key is the line in bold.


        protected void btnAdd_Click(object sender, EventArgs e)

        {

            RegisterAsyncTask(new PageAsyncTask(() => SaveRecord()));

        }


        public async Task SaveRecord()

        {

            //Get Domain name from username (which is email address)

            String[] strUsername = User.Identity.Name.Split('@');

            String strUserDomain = strUsername[1];


            try

                var sunshineTable = client.GetTable<sunshine>();


                var SunshineRecord = new sunshine

                {

                    firstname = this.txtFirstName.Text,

                    lastname = this.txtLastName.Text,

                    email = this.txtEmail.Text,

                    userdomain = strUserDomain

                };


                await sunshineTable.InsertAsync(SunshineRecord);

                String strID = SunshineRecord.Id;


                //Sunshine Record Saved Successfully, now lets save group NPI records

                    var npirecords = client.GetTable<npirecords>();

                    var npirecord = new npirecords();

                    NPIDatatable dtNPIrecords = (NPIDatatable)Session["NPIGroupRecords"];

                    foreach (DataRow row in dtNPIrecords.lNPIDatatable.Rows) // Loop over the rows.

                    {


                        //coveredrecipienttype = this.ddlCoveredRecipientType.SelectedValue,

                        npirecord.firstname = row["First Name"].ToString();

                        npirecord.lastname = row["Last Name"].ToString();

                        npirecord.npi = row["NPI"].ToString();

                        npirecord.credentials = row["Credentials"].ToString();

                        npirecord.gender = row["Gender"].ToString();

                        npirecord.address = row["Address"].ToString();

                        npirecord.city = row["City"].ToString();

                        npirecord.state = row["State"].ToString();

                        npirecord.zip = row["Zip"].ToString();

                        npirecord.country = row["Country"].ToString();

                        npirecord.licensenumber = row["License Number"].ToString();

                        npirecord.licensestate = row["License State"].ToString();

                        npirecord.taxonomycode = row["Taxonomy Code"].ToString();

                        npirecord.sunshinerecordid = strID;

                        await npirecords.InsertAsync(npirecord);

                    };

             }

            catch (Exception ex)

            {

    

            }

        }

Simple Login Page Background Image using CSS



<script>
$('body').css('background-image', 'url(../images/glassbackground.png)');
$('body').css('background-repeat', 'no-repeat');
$('body').css('background-size', '100% 200%');
$('body').css('background-origin', 'content-box');
</script>

ADB over wifi



These easy commands from Terminal on a Mac

To find the IP address of the device: run ./adb shell and then netcfg.


1.) adb tcpip 5555

2.) adb connect 192.168.1.102:5555


Disconnect USB and proceed with wireless debugging.


To switch back to USB when done

3.) adb -s 192.168.1.102:5555 usb 

Google Glass Hello World GDK app in Eclipse



Pre-requisites: Eclipse IDE, Android SDK, Google Glass

You need to run the application directly on the Glass device, there is no emulator (make sure you enable debugging on Glass)


In this tutorial, we will learn how to write a simple “Hello,World!” program for Google Glass using the GDK.


Step 1: Create Android project for Glass


Create a new Android application project called HelloGlass with package name com.app.glass and choose the Target platform as Glass Development Kit Preview for Android 4.4


Step 2: Creating cards


As per the Glass design patterns, developers can either create static cards or Live cards. In this case I will choose to create a static card since I would only be displaying a message to the user. The Card class creates well-formed cards given a set of properties.


A Card has the following properties:


1. Main body text

2. Left-aligned footer

3. One or more images that are displayed as a mosaic on the background of the card or on the left side of the card.


Step 3: Voice Invocation model


Voice commands play an important role in user interaction with Glass allowing hands-free and quick actions. Any Glass application that you develop needs to be invoked using a voice command. Developers can also add their own voice commands. However, please make sure you read the voice command checklist before you proceed.


Step 4: Putting it all together


Let’s start by creating our Hello,World application. Create a new Activity class called HelloWorldActivity and add the following code!


HelloWorldActivity.java


package com.app.glass;


import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import com.google.android.glass.app.Card;


public class HelloWorldActivity extends Activity {


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);


Card myCard = new Card(this);

myCard.setText("Hello, World!");

myCard.setFootnote("First Glassware for Glass");

View cardView = myCard.getView();

// Display the card we just created

setContentView(cardView);

}


}

Next, we need to create a Service class that will recognize the voice command.


HelloGlass.java


package com.app.glass;


import android.app.Service;

import android.content.Intent;

import android.os.IBinder;


public class HelloGlass extends Service {


@Override

public IBinder onBind(Intent intent) {

// TODO Auto-generated method stub

return null;

}


public int onStartCommand(Intent intent, int flags, int startId) {


Intent i = new Intent(this, HelloWorldActivity.class);

i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(i);

return START_STICKY;

}


}

In order to launch the Glassware from the “ok,glass” menu we need to add the following service in the AndroidManifest.xml file!


AndroidManifest.xml

<!--?xml version="1.0" encoding="utf-8"?-->

package="com.app.glass"

android:versionCode="1"

android:versionName="1.0" &gt;


&lt;uses-sdk

android:minSdkVersion="8"

android:targetSdkVersion="19" /&gt;


<!-- Don't use themes -->

&lt;application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name" &gt;

&lt;activity

android:name="com.app.glass.HelloWorldActivity"

android:label="@string/app_name"

android:enabled="true"&gt;


&lt;service

android:name="com.app.glass.HelloGlass"

android:enabled="true"

android:exported="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name" &gt;


<!-- Voice command found in res/xml/voice_trigger_start -->

&lt;meta-data

android:name="com.google.android.glass.VoiceTrigger"

android:resource="@xml/voice_trigger_start" /&gt;


res/xml/voice_trigger_start.xml


<!--?xml version="1.0" encoding="utf-8"?-->

<!-- The string used to start the application from the "Okay, Glass" menu -->


res/values/strings.xml


<!--?xml version="1.0" encoding="utf-8"?-->


HelloGlass

Settings

hello glass

Save Money! Schedule backups on free SQL Server Express



When we're bootstrapping our startups we try to save money and we lean towards SQL Server Express (lacks SQL agent to schedule backups) because it's free until the idea is proven / funded and it justifies the enterprise edition. We of course still need to make sure our data is securely backed up be it onsite with a client or as an Amazon EC2 instance spun up in the cloud.


Here is how we solved this problem.

-------------------------------------------------


Add the exact line below and save it as SQLBackup.bat


"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.exe" -S localhost -i "D:\SQLBackup\SQLBackup.sql" &gt;&gt; log.txt


Add all the SQL below and save it as SQLBackup.sql (update server folder location D:\SQLBackup\ and database name SEA2014 as needed, this will create a backup for each day of the week by name and overwrite if the file exists so you'll get the last 7 days of backups). Make sure the folder location has security permission to be accessed, test running the .bat from the command prompt to test.


DECLARE @dest nvarchar(255)

SET @dest = N'D:\SQLBackup\SEA2014_' + CAST(DATEPART(weekday, GETDATE()) AS nvarchar(1)) + '.bak'

BACKUP DATABASE [SEA2014] TO DISK = @dest WITH NOFORMAT, NOINIT, NAME = N'SEA2014-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10

GO


DECLARE @dest nvarchar(255)

SET @dest = N'D:\SQLBackup\SEA2014_' + CAST(DATEPART(weekday, GETDATE()) AS nvarchar(1)) + '.bak'

declare @backupSetId as int

select @backupSetId = position from msdb..backupset where database_name=N'SEA2014' and backup_set_id=(select max(backup_set_id) from msdb..backupset where database_name=N'SEA2014' )

if @backupSetId is null begin raiserror(N'Verify failed. Backup information for database ''SEA2014'' not found.', 16, 1) end

RESTORE VERIFYONLY FROM DISK = @dest WITH FILE = @backupSetId, NOUNLOAD, NOREWIND

GO


Finally in Windows Task Scheduler call the .bat file on a weekly basis.

Code Google Glass using C# in Xamarin Studio

1.) Install Xamarin Studio 

 2.) Follow this YouTube Video to configure Xamarin Studio with Google Glass: http://www.youtube.com/watch?v=NyjB4QoX9fM 

 3.) In Xamarin Studio, click "Tools" -> "Open Android SDK Manager", make sure "API Level 19" is selected, then click "Install XX Packages" where XX equals the number of packages that will be installed. 

 4.) Update MainActivity.cs voice trigger lines to this:
[IntentFilter (new String[]{ "com.google.android.glass.action.VOICE_TRIGGER" })]
[MetaData ("com.google.android.glass.VoiceTrigger", Resource = "@xml/voicetriggerstart")]

5.) rename voicetrigger.xml under XML folder to VoiceTriggerStart.xml

6.) Modify app to your liking. 

 7.)Sideload the .APK to onto Glass: https://www.youtube.com/watch?v=TYJQhebDvRE

Poor Man's Single Sign-On between two systems

1.) Pass a new querystring variable we'll call "values" from one system to the other.


2.) This "Values" parameter will be symmetrically encrypted from one system and decrypted on the receiving system using 3DES with a common secret key. See my article on how I'm already doing this: http://www.figers.com/Blog/2014/02/28/symetrical-3des-encryption-in-java-and-decryption-in-vb-net/


3.) "values" will contain the UserID, other values you need and a randomly generated number in the form of today's date attached to 10 digit randomly generated number, it would look like 040320141234567890.


4.) When the system receiving the request decrypts "values" it checks the randomly generated number to see if it's been used before, if it has, it rejects the entire request. If it hasn't been used before it processes the sign-on request and adding the random number to the table for later verification.


5.) Since the URL can never be re-used we aren't concerned with browser history or sniffing over the wire at say a coffee shop.


5.) Each time the first system displays the link to jump to the second system or the link is clicked it generates a new random number in the link.


6.) Because the number is encrypted an attacker would need to know the secret key to even be able to guess a number to try (i.e. unless 3DES is cracked this is not possible).


Now we have secure Single Sign-On from one system to another.