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{
          constructor(props)
          {
              super(props);
      
              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"
              };
              firebase.initializeApp(config);
          }
      
          //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)
              {            
                  console.log(response);
                  console.log(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 = error.email;
                          // The firebase.auth.AuthCredential type that was used.
                          var credential = error.credential;
                          alert(errorCode + ' ' + errorMessage);
                 });
              }
           
          }
      
          //To handle the SignOut functionality
          SignOutFromFireBase(e)
          {
              firebase.auth().signOut().then(() =>
              {
                 // alert('user successfully signed out')
                  this.setState({userSignedIn: false});
              }
              ).catch((error) => {
                  alert('error during signout - ' + error.code + ' ' + error.message);
              });
          }
      
      
          render()
          {
      
              let status ;
              // alert(this.state.userSignedIn);
               if (this.state.userSignedIn)
                   status = 'user signed in'
               else
                  status = '';
              return (
                  <div> 
                      <FacebookLogin
                          appId="FACEBOOK_APPID_GOES_HERE"
                          autoLoad={false} 
                          fields="name,email,picture"
                          callback={(e) => this.responseFacebook(e) } 
                          cssClass="my-facebook-button-class"
                          icon="fa-facebook"
                          reAuthenticate = {this.state.fbReAuthenticate}
                      />
                      <button onClick = { (e) => this.SignOutFromFireBase(e) } > Sign Out </button>
                      <p/>
                          {status }         
                      <div> 
      
                      </div>
                  </div>
              )
          }
      }

      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

293 total views, 2 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)

https://github.com/MarkPieszak/aspnetcore-angular2-universal

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

Continue reading

283 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

969 total views, 9 views today

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

SharePointAppError

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

Solution

  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.

 

695 total views, 2 views today

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

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

        Dim objCompilerParameters As New System.CodeDom.Compiler.CompilerParameters
        objCompilerParameters.ReferencedAssemblies.Add("System.dll")
  
  ''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)
        objCompilerParameters.ReferencedAssemblies.Add("D:\\DynamicCode\\bin\\CustomCommon.dll")            
  
  ''Again, the Nlog is used for logging and the configuration for Nlog is loaded from the web.config, when the application initializes itself.
        objCompilerParameters.ReferencedAssemblies.Add("D:\\DynamicCode\\bin\\Nlog.dll")
  
        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

        Throw
    End Try
End Sub

813 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 (https://msdn.microsoft.com/en-us/data/jj556205.aspx / https://blog.oneunicorn.com/2012/03/12/secrets-of-detectchanges-part-3-switching-off-automatic-detectchanges/)
  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. (https://msdn.microsoft.com/en-us/data/dn456843.aspx#existing).
  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” (http://stackoverflow.com/questions/3870091/entity-framework-linq-to-sql-skip-take)
  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) http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx
  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).

823 total views, 1 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:

AzureGettingStarted

 

441 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 http://dev.mysql.com/doc/refman/5.0/en/create-index.html)

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))

 

717 total views, 1 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,062 total views, 1 views today

SharePoint Online Root Site – Customize or not to Customize it.

Some time back, when I was fairly new to Office 365 & SharePoint Online, for the sake of learning I had provisioned a demo site and playing around with it.  At that time, I didn’t know the importance of the SharePoint Online root site and started noticing that my SharePoint instance had started to act weird.  Upon further investigation found that the root/default site is not an isolated site after all, and that its existence is very important to the overall health of all other sites provisioned in that tenant.

The below are some facts as to why its better to leave the root site “untouched” and leave it in its own pristine condition:

  1. Do not ever delete the Root site :  If you ever are required to delete the site or had accidentally deleted it, all other SharePoint sites in that tenant will cease to work.  This is because of the fact that the “default/root” site is used for some kind of authentication mechanism (before allowing users to sign-in to other sites) and that is very important for it to be available at all times.
  2. Missing Site Settings in the Default/Root Site:  In the root site,  if you navigate to “Site Settings” you would notice that some of the most common links would have gone missing such as Themes, Composed Looks, Save as Site Template, Delete Site etc.,  Even though you are the “Global Adminstrator” / “Site Collection Administrator / Owner”, it would still not be available and this is due to the fact that “Custom Scripts” are not enable in Root site”.
  3. Custom Scripts Not Enabled in Root site: By design Microsoft has turned off the option to run “Custom Scripts” in the default site, for the sake of preventing users from adding scripts in their My Sites, which could have ill effects on the overall health of the tenant.  It should also be noted that “My Sites” are dependent on the root site and use the settings as applied on the root site for enforcing it onto itself as well.
  4. Cannot create a Default/Root site using PowerShell : Microsoft has disabled provisioning root sites in SharePoint Online using Powershell and it can only be created through the “SharePoint Admin Center”.
  5. At times, when you try to re-provision a root/default site (which you have deleted for some reason), even after you select the “Permanently delete the site collection from the recycle bin and continue“, it might still throw an error saying that the “A site with that name already exists”.  In such instances, you simply have to wait for 1 or 2 hours for it to complete its pending activities.

Taking into consideration the above effects, its advisable to create new sites and perform customizations on them, rather to work directly on the root site.  Not sure as to why Microsoft documentation doesn’t warn about its effects, but from all practical purpose, its better if we plan the site hierarchy by including a “\sites” or “\teams” in the URL (which gets added when provisioning new sites in the admin center).

1,613 total views, 1 views today