How to develop/configure Facebook (OAuth) based authentication for Google Firebase using React

The post assumes that you have basic knowledge on Firebase and you do have a Project created and available for POC in Firebase.  It also uses a 3rd party NPM package “react-facebook-login” to take care of invoking facebook OAuth api’s :

  1. Enable Facebook authentication in FireBaseauth1 Copy the App ID and App Secret from Facebook and copy over the OAuth redirect URI (as we need to update it in the Facebook developer site)
    auth2Click on “Add Domain” and key in your dns/domain for the React site (If you are using localhost, you don’t need to include the port number)auth3
  2. Configure Facebook settings
    1. Login to Facebook developer portal select/create a new app (if you don’t have one setup yet)
    2. Click on “Add product” and choose “Set Up” in Facebook Login
    3. fb1Choose “WWW/Web”
    4. In Site URL provide your site’s url.  In case of localhost, include the port number as well (http://localhost:3000/).  (Note: This will update the platform website url, which can be modified using the Settings->Basic on the left site menu bar.)  Click Save and Continue
    5. The other tabs are just help text on setting up of the authentication mechanism using JS.
    6. Go to Facebook Login->Settings and provide the OAuth redirect URI (which was copied while setting up of the FireBase facebook authentication).fb2
  3. Creating React Application
    Step 1 and Step 2 are just the basic steps required to enable Facebook to pass on the auth_token to Firebase and ensure a seamless auth experience.  Now let’s move on to the coding part:

    1. Go to Fire Base Authentication settings and click on “Web Setup“.  Copy the content to be used for replacing the configuration in the code :firebasesettings
    2. Use “create-react-app” to create a new react application.  I have named mine as “firebasefacebookauth
    3. Use “create-react-app” to create a new react application.  I have named mine as “firebasefacebookauth
    4. Run npm install react-facebook-login --save
    5. Run npm install firebase --save
    6. Create a new React class Component (I am naming it as fbauth.js)
    7. Paste the below code into fbauth.js
      import React from 'react'
      import firebase from 'firebase';
      import FacebookLogin from 'react-facebook-login';
      export class FBAuth extends React.Component{
              this.state = {userSignedIn: false, fbReAuthenticate: true };
              var config = {
                  apiKey: "<FIREBASE_API_KEY>",
                  authDomain: "FIREBASE_AUTH_DOMAIN_URL",
                  databaseURL: "FIREBASE_REALTIME_DATABASE_URL",
                  projectId: "FIREBASE_PROJECTID",
                  storageBucket: "FIREBASE_STORAGEBUCKET_ID",
                  messagingSenderId: "FIREBASE_MESSAGINGSENDERID"
          //This will be the CAllBACK that would get invoked after authentication from Facebook
          responseFacebook = (response) => {
              //Validate if it has a valid accessToken
              if (response.accessToken)
                  // Build Firebase credential with the Facebook access token.
                  var credential = firebase.auth.FacebookAuthProvider.credential(response.accessToken);
                     // Sign in with credential from the Google generated based on the Facebook Auth Token.
                     firebase.auth().signInWithCredential(credential).then((user) => {
                          if (user) {
                              // User has successfully signed in.
                             // alert('user logged in successfully - 1'); 
                              this.setState ({userSignedIn: true});
                            } else {
                              // No user is signed in.
                              alert('user didnt sign in');
                     .catch(function(error) {
                          // Handle Errors here.
                          var errorCode = error.code;
                          var errorMessage = error.message;
                          // The email of the user's account used.
                          var email =;
                          // The firebase.auth.AuthCredential type that was used.
                          var credential = error.credential;
                          alert(errorCode + ' ' + errorMessage);
          //To handle the SignOut functionality
              firebase.auth().signOut().then(() =>
                 // alert('user successfully signed out')
                  this.setState({userSignedIn: false});
              ).catch((error) => {
                  alert('error during signout - ' + error.code + ' ' + error.message);
              let status ;
              // alert(this.state.userSignedIn);
               if (this.state.userSignedIn)
                   status = 'user signed in'
                  status = '';
              return (
                          callback={(e) => this.responseFacebook(e) } 
                          reAuthenticate = {this.state.fbReAuthenticate}
                      <button onClick = { (e) => this.SignOutFromFireBase(e) } > Sign Out </button>
                          {status }         

      Change Firebase configuration and Facebook App Id

      1. Replace the Firebase configuration in LIne 12 through Line 18 with configuration copied from Step A.
      2. Replace FACEBOOK_APPID in line 87 with your application id.
    8. Run npm start You should get the below output :output

Continue reading

1,203 total views, no views today

Create ASP.NET Core WebSite with Angular (4.0 Version).

This post is just a reference point (collation of links to other great posts), to help folks who are new to the arena, looking for ways to develop a  Single Page Application (SPA) using ASP.NET Core Web Application with Angular (4.0) as the front end development framework.

These SPA templates use the JavaScript Services functionality to embed NodeJS within ASP.NET Core on the server, and compile the JavaScript applications server-side as part of the .NET build process.

The below are the list of options that one can leverage for creating a new ASP.NET Core based SPA application :

Option 1

If you are looking for a ready-to-develop SPA with all bells and whistles put together, then try the below template from Mark PiesZak.  It has all the required packages pre-configured and supports SEO optimization and by far the best template available for development with ASP.NET CORE + ANGULALR 4.0.  (If any one has a better template/link, please do share just so I can update the post accordingly)

Just download the code from git and follow the instructions on the site to get started!

Continue reading

983 total views, 2 views today

Setup/Configure NodeJS, MongoDB, Mongoose with Visual Studio Code

The intent of the article is to provide a step-by-step instruction to write a “Hello World” application using NodeJS, MongoDB, Mongoose in “Visual Studio Code” editor.  The article also assumes that you are aware of the concepts behind using a MEAN stack for developing JavaScript based web application and their advantages etc.,

Step 1 (Install Node):

Download and Install NodeJS from this link

Step 2 (Install Mongo DB):

Download and Install Mongo DB from this link (make sure that you follow the instructions on the page to setup the Windows service and test it, before proceeding further).

Step 3 (Setup development environment):

  1. Fire up “Visual Studio Code” and use the “Open Folder” option to point to “any” folder where you plan to create/store the project specific files (to be created as part of the “hello world” application).
  2. Use the “File-> New File” option (or the “New File” in the Explorer window) to create a new file and name it as “main.js“.
  3. Launch the “Integrated Terminal” window from “View->Integrated Terminal”.
  4. Type “npm init” (as provided in the below image and keep pressing “enter” for all questions prompted to assign the default values, which can be overridden by providing a custom value, if preferred). integratedterminal
  5. When completed it will create the “package.json” file along with all the default settings.
  6. Open up the “package.json” and add the dependencies for mongodb and mongoose (as highlighted below) and save the file:packagejson
  7. In the “Integrated Terminal” type “npm install” and hit enterdependencyinstall
  8. After the dependencies are installed by npm, you should see the “node_modules” folder on the explorer window (which contains all the dependent npm modules required for mongodb and mongoose to run in nodejs ecosystem):nodemodules

Continue reading

2,974 total views, 1 views today

“Everythingis fine, but we had a small problem getting your license…” – SharePoint Add In Error.


The above error occurs typically when you try to install an add-in from the SharePoint Store using the O365 Global administrator account.


  1. GoTo Office 365 Admin Portal.
  2. Under Users, Select “Active Users” and Add a user
  3. Make sure that you choose “SharePoint Administrator” as the role for the new user
  4. Now try to login to the site using the new user and add the app from the SharePoint Store.

The above had worked for me when I tried to add the Napa developer tool to the Dev site.


1,290 total views, no views today

Use CodeDoM to load code from file and compile it at Runtime in

Public Sub LoadCodeFromFileAndExecute() 
        Dim objCodeCompiler As System.CodeDom.Compiler.CodeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("VisualBasic")

        Dim objCompilerParameters As New System.CodeDom.Compiler.CompilerParameters
  ''The below one is a custom dll that I require for processing the logic (and have provided as an example, just so you can refer such custom ones as required)
  ''Again, the Nlog is used for logging and the configuration for Nlog is loaded from the web.config, when the application initializes itself.
        objCompilerParameters.GenerateInMemory = True

        ' Get the source code and compile it from the file system (assuming that your code itself is residing in the bin folder from where the application is being executed)
        Dim strCode As String = String.Empty
        Using sw As StreamReader = New StreamReader("D:\\DynamicCode\\bin\\GetLogDetailsFromDictionary.vb")
            strCode = sw.ReadToEnd()
        End Using

  ''Try to compile the code 
        Dim objCompileResults As System.CodeDom.Compiler.CompilerResults = objCodeCompiler.CompileAssemblyFromSource(objCompilerParameters, strCode)

        ' Check for compiler errors.  In my case I am just exiting the Sub
        If objCompileResults.Errors.HasErrors Then
            Exit Sub
        End If

        ' Get a reference to the NEW assembly emitted by CodeDom as part of the compilation performed in the earlier statement
        Dim objAssembly As System.Reflection.Assembly = objCompileResults.CompiledAssembly

        ' Create an instance of the DynamicCode class referenced in the source code.
        Dim objTheClass As Object = objAssembly.CreateInstance("HelloWorld")

  ''Verify if the CreateInstance was able to generate a new instance successfully
        If objTheClass Is Nothing Then
            Exit Sub
        End If

  ''Invoke the Method 
        Dim objResult As Object = objTheClass.GetType.InvokeMember("SayHello", _
                    BindingFlags.InvokeMethod, Nothing, objTheClass, Nothing)

    Catch ex As Exception

    End Try
End Sub

1,630 total views, 1 views today

Entity Framework – Performance Optimization Tips

The below are some tips towards optimizing the performance of applications that use Entity Framework.

  1. To disable AutoDetectChanges, when not needed ( /
  2. Even though the DBContext object is a lightweight one, its the number of entities that affects the performance.  For instance, after you are done creating a new DbContext, if you perform repeated .Add(..) and .SaveChanges(), at one point you will see a downgrade in performance and if investigated, it will point to the number of Entities that incrementally got included resulting in degrading the performance of the DBContext object.  A solution is to dispose the DBContext and create new objects for a set of operations (for instance every 1000 objects), however from a “Data Integrity / Atomicity” (ACID) perspective, every DbContext will use its own connection and multiple connections will require MSDTC, which at times can be a trouble to live with in the long run.  So, in such cases, we could resort to the option of using a single Connection and TransactionScope as outlined in the MSDN link. (
  3. As a rule of thumb, while retrieving data from the database, retrieve only those fields are required.  This is not just for including a where condition aimed at filtering the records, but also the fields that are required.
  4. Use Take & Skip in EF to query data based on “pages” (
  5. Avoid calling SaveChanges() for every transaction, but instead try to call the SaveChanges() for every 500 iterations and dispose the old dbcontext and generate a new one.  This approach eliminates the need to perform the change detection for each record (when saved individually) and as well removes network latency involved in persisting the changes to the data base.  However, regeneration of the context object would essentially mean a SQLConnection is assigned to the db context, which would result in MSDTC (as there are multiple connections involved – one per context).
  6. Use SQLBulkCopy if it involves inserting multiple records (thousands of rows)
  7. If you do not want to disable the AutoDetectChanges, another option is to detach the entities that are already committed through the SaveChanges() operation.  This would reduce the number of entities being accumulated in the dbContext as we progress through the loop/iterations and help eliminate the lag that gets induced when the entities count in the db context crosses a threshold (which could vary depending on how relational the entities are).

1,462 total views, 2 views today

Azure Quick Starts Code Samples, provided by Microsoft.

If you are looking for a good source of code examples towards getting started with Azure, then I would recommend to use something that’s available right off the Visual Studio IDE.

When you try to create a new project, under cloud select “Quick Starts” to view the grand list of Azure offerings and pick your type of project to automatically create a sample application along with the necessary plumbing logic to consume the particular service:



817 total views, no views today

Orchard Setup errors on MY SQL.

When I tried to setup Orchard CMS using MY SQL 5.7 as the back end, was haunted by the below errors relating to Indexes:

1)create index `IDX_AutoroutePartRecord_DisplayAlias` on `Orchard_Autoroute_AutoroutePartRecord` (DisplayAlias)

2)create index `IDX_RecipeStepResultRecord_ExecutionId_StepName` on `Orchard_Recipes_RecipeStepResultRecord` (ExecutionId, StepName)

3)create index `IDX_MediaPartRecord_FolderPath` on `Orchard_MediaLibrary_MediaPartRecord` (FolderPath) "

To solve the errors, had to change the script as below :  (since per MY SQL, BLOBS and TEXT columns can be indexed, but a prefix length must be given

1) create index `IDX_AutoroutePartRecord_DisplayAlias` on `Orchard_Autoroute_AutoroutePartRecord` (DisplayAlias(10))

2) create index `IDX_RecipeStepResultRecord_ExecutionId_StepName` on `Orchard_Recipes_RecipeStepResultRecord` (ExecutionId(10), StepName(10))

3)create index `IDX_MediaPartRecord_FolderPath` on `Orchard_MediaLibrary_MediaPartRecord` (FolderPath(10))


1,126 total views, no views today

Using LocalDB in ASP.NET MVC Application with EntityFramework 6

At times we resort to the use of LocalDB, which in definition is a light weight version of the SQL Server Express, which loads itself on demand (i.e., whenever the application tries to read data using SQLConnection or through EntityFramework etc.,).  The db itself can be created by right clicking on the App_Data folder and selecting Add->SQL Server database option from Visual Studio Solution Explorer.  Once created the .mdf file resides in the App_Data folder and can be accessed via the Server Explorer (which acts as the conduit) to perform mundane db operations such as create/alter table, open query window etc.,

When we employ EF as the ORM to access data, it doesnt work as straight forward as it does with SQL Server based backend options.  One common error that you may see is the below error (as given in the screenshot):

Continue reading

1,654 total views, no views today