Create And Delete HDInsight Cluster


Brief:

In cloud computing, we have API available from service providers like Azure/AWS which allows us to create and resource (VM,DB,etc.) at run time and delete when the job is done. It is very helpful to save the cost. Using below procedure you can create and delete the Azure HDInsight Cluster automatically through application (Console application) and terminate the instance when the processing is done. Here we are using non interactive Authentication method for sign in.

Need:

As we know, we can create Azure HDInsight cluster through Azure Portal manually. But if we have a requirement where we need to create HDInsight cluster and after finishing the work we need to delete it (to save the cost). Rather than doing this manually we can create an application which can be schedule in scheduler to run daily and it will do required the operations (Create HDInsight Cluster, Delete Cluster) automatically.

How It Works:

    Requirements-
  •    Need a Microsoft Azure Subscription.
  •    Install NuGet package given below,
    1. Install-Package Microsoft.Rest.ClientRuntime.Azure.Authentication -Pre
    2. Install-Package Microsoft.Azure.Management.ResourceManager -Pre
    3.  Install-Package Microsoft.Azure.Management.HDInsight

To manage the HDInsight cluster (Create and Delete) you can use following class.



public class HdinsightClusterManager

    {

        // The client for managing HDInsight

        public HDInsightManagementClient _hdiManagementClient;

        private ClusterCreateParameters Parameters { get; set; }



        public HdinsightClusterManager(string SubscriptionId, string TenantId, string ClientId, string clientSecret)

        {

            Parameters = new ClusterCreateParameters();

            // Authenticate and get a token

            var authToken = Authenticate(TenantId, ClientId, SubscriptionId, clientSecret);



            // Get an HDInsight management client

            _hdiManagementClient = new HDInsightManagementClient(authToken);

        }



        public void InitClusterCreateParameters(int NewClusterNumWorkerNodes, string NewClusterUsername, string NewClusterPassword,

            string NewClusterLocation, string ExistingStorageName, string ExistingStorageKey, string ExistingBlobContainer,

            string NewClusterType, string rdpPassword, string rdpUsername, string _HeadNodeSize, string _WorkerNodeSize)

        {

            Parameters = new ClusterCreateParameters();

            Parameters.ClusterSizeInNodes = NewClusterNumWorkerNodes;

            Parameters.UserName = NewClusterUsername;

            Parameters.Password = NewClusterPassword;

            Parameters.Location = NewClusterLocation;

            Parameters.DefaultStorageAccountName = ExistingStorageName;

            Parameters.DefaultStorageAccountKey = ExistingStorageKey;

            Parameters.DefaultStorageContainer = ExistingBlobContainer;

            Parameters.ClusterType = NewClusterType;

            Parameters.RdpPassword = rdpPassword;

            Parameters.RdpUsername = rdpUsername;

            Parameters.RdpAccessExpiry = DateTime.Now.AddDays(10);

            Parameters.HeadNodeSize = _HeadNodeSize;

            Parameters.WorkerNodeSize = _WorkerNodeSize;

        }



        public bool CreateCluster(string existingResourceGroupName, string newClusterName)

        {

            System.Console.WriteLine("Creating a cluster.  The process takes 10 to 20 minutes [" + DateTime.Now.ToShortTimeString() + "] ...");

           

            Parameters.OSType = OSType.Windows;

            // Create the cluster

            _hdiManagementClient.Clusters.Create(existingResourceGroupName, newClusterName, Parameters);

            System.Console.WriteLine("The cluster has been created [" + DateTime.Now.ToShortTimeString() + "].");

           

            return true;

        }



        public OperationResource DeleteCluster(string existingResourceGroupName, string clusterName)

        {

            System.Console.WriteLine("Deleting a cluster.  The process takes 10 to 20 minutes[" + DateTime.Now.ToShortTimeString() + "] ...");

            

            var result = _hdiManagementClient.Clusters.Delete(existingResourceGroupName, clusterName);

            System.Console.WriteLine("The cluster has been deleted [" + DateTime.Now.ToShortTimeString() + "].");

           

            return result;

        }



        /// <summary>

        /// Authenticate to an Azure subscription and retrieve an authentication token

        /// </summary>

        /// <param name="tenantId">The AAD tenant ID</param>

        /// <param name="clientId">The AAD client ID</param>

        /// <param name="subscriptionId">The Azure subscription ID</param>

        /// <param name="clientSecret">Get this from Application created in Active Directory</param>

        /// <returns></returns>

        static private TokenCloudCredentials Authenticate(string tenantId, string clientId, string subscriptionId, string clientSecret)

        {



            var authContext = new AuthenticationContext("https://login.windows.net/" + tenantId);

            var credential = new ClientCredential(clientId, clientSecret);

            var tokenAuthResult = authContext.AcquireToken("https://management.azure.com/", credential);

            return new TokenCloudCredentials(subscriptionId, tokenAuthResult.AccessToken);

        }



        /// <summary>

        /// Authenticate to an Azure subscription and retrieve an authentication token by interactive method

        /// </summary>

        /// <param name="TenantId">The AAD tenant ID</param>

        /// <param name="ClientId">The AAD client ID</param>

        /// <param name="SubscriptionId">The Azure subscription ID</param>

        /// <returns></returns>

        static private TokenCloudCredentials Authenticate(string TenantId, string ClientId, string SubscriptionId)

        {

            var authContext = new AuthenticationContext("https://login.microsoftonline.com/" + TenantId);

            var tokenAuthResult = authContext.AcquireToken("https://management.core.windows.net/",

                ClientId,

                new Uri("urn:ietf:wg:oauth:2.0:oob"),

                PromptBehavior.RefreshSession,

                UserIdentifier.AnyUser);

            return new TokenCloudCredentials(SubscriptionId, tokenAuthResult.AccessToken);

        }



        /// <summary>

        /// Marks your subscription as one that can use HDInsight, if it has not already been marked as such.

        /// </summary>

        /// <remarks>This is essentially a one-time action; if you have already done something with HDInsight

        /// on your subscription, then this isn't needed at all and will do nothing.</remarks>

        /// <param name="authToken">An authentication token for your Azure subscription</param>

        static private void EnableHDInsight(TokenCloudCredentials authToken)

        {

            // Create a client for the Resource manager and set the subscription ID

            var resourceManagementClient = new ResourceManagementClient(authToken);

            //resourceManagementClient.SubscriptionId = SubscriptionId;

            // Register the HDInsight provider

            var rpResult = resourceManagementClient.Providers.Register("Microsoft.HDInsight");

        }

    }

To get the required parameter you can follow the below methods,
  • SubscriptionId and TenantId – Log in to Azure Portal, if you click on the Help icon in the upper right and then choose 'Show Diagnostics' you can find the SubscriptionId and tenantid in the diagnostic JSON.
  • ClientId and clientSecret – To get the ClientId and clientSecret follow the procedure given here and also give the appropriate permission to Azure Resource Group where we will be creating HDInsight Cluster. After initializing HDInsightManagementClient class object you can use CreateCluster and DeleteCluster Methods to Create and Delete the HDInsight Cluster. You can refer to link for remaining parameters. Creation and Deletion of cluster will take around 20 to 30 minutes.

Boston Byte Time Tracker Application 2.0


Brief:


The Time Tracker application (or Timer, as we all in Boston Byte call it) is one of the many user interfaces for the internally used Time Tracker System. This application runs on the employee's desktop and supports Windows Operating System (OS), Macintosh OS X, Ubuntu OS and it's other variants. The employee can select any assigned project tasks. He/she can then start or stop the timer for various tasks for which he/she has been working. The time records are updated on the centralized server accordingly. Along with many additional server side modules, the whole system makes it much easier to track the project status in real-time.

Need :

Timer 1.0 had been developed using the .Net Framework since the inception of our organization and has been continuously evolving ever since. During the early years, almost all desktops were running Windows OS and thus the Timer 1.0 was developed for Windows OS only. But gradually over time, our expertise would span various technologies and environments for which our developers would choose the OS which best suited their development needs. Thus making it impossible to run the Timer 1.0 application on these new operating systems.

Timer 1.0 had a major performance drawback due to the fact that to maintain the consistency of the time records, both the client & server had to be in sync continuously. Polling mechanism had been implemented to achieve the same. Well, as it turns out, with the gradual increase in the number of employees the polling mechanism had taken a toll on the server as well as the internal network bandwidth. So we had to find an alternate solution to address the issue.

How It Works:

Timer 2.0 was on the meeting board and we had to address the above mentioned issues along with some other changes. To make it platform independent, we decided to go with JAVA particularly JAVAFX. To address the polling issue, we decided to keep the whole system event driven with the help of MQTT. The Last Will & Testament (LWT) feature of MQTT was the prime reason for us to go with MQTT. If any Timer application crashes or is disconnected from the network then the MQTT broker relays the LWT message to application server and the server updates the time records accordingly. Another reason to go with MQTT is that it has it's own implementation of socket level keep-alive ping so we don't need to worry about polling the server explicitly. The result of this implementation is that Timer 2.0 application consumes 2 bytes per 30 seconds i.e. around 0.07 bytes per second whereas Timer 1.0 used to consume around 40,000 bytes per second. Along with that, the server CPU load has decreased drastically. The Timer application will continue to evolve with technologies which would better suit our future needs.

Avoiding File Inclusion - Remote File Include (RFI)/ Local File Include (LFI)


Brief:
 
File Inclusion is one of the common vulnerabilities in web applications. It happens because of 'include' functionality. In this, malicious files are forced to be included in system from remote location or locally. Most of the times, proper validations are not abide on inputs to the system which leads to adding malicious scripts, executable files entering into the system. This vulnerability can lead to maliciously executing unwanted files on the server or reveal sensitive files data to attackers, etc.
There are two types of File Inclusion Vulnerability
  1. Remote File Include (RFI)
  2. Local File Include (LFI)
 
How It Works:
 
We were working on a PHP project which needed a strict security measures. To handle both the file intrusion attacks, we have added a separate PHP file to state which files need to included and which not. Along with this, we also have verified the 3rd Party Libraries to understand if any file inclusion is happening there. 3rd Party Libraries are more prone to file inclusion so we have handled it separately.
You can refer below code that we have added for avoiding File Inclusion Attacks:

$link = $_SERVER['PHP_SELF'];
$link_array = explode('/', $link);
$page = end($link_array);
switch ($page) {
    case "terms_conditions":
        include($page . ".php");
        break;
    case "contact_us":
        include($page . ".php");
        break;
    case "privacy":
        include($page . ".php");
        break;
    default:
        include_once './header.php';
        include_once './banner.php';
        include_once './home.php';
        include_once './footer.php';
}

You can see, only terms_conditions, contact_us, privacy pages to be included and by default header, banner, home and footer pages are supposed to be added. Apart from these files, nothing is going to be included.

PayUMoney Integration

Brief :

Now a day as me are moving more towards digitization, new models, concepts, softwares are making their way into the market.  If we talk specifically about websites that operate more into E-commerce and B2C there are few basic things that are necessary for the website to sustain.
Such as customer engagement, customers have become smart and demanding they need softwares/websites which will give them the maximum satisfaction(in terms of time been spend of the website), user friendly flow and the main thing Payment methods.

Its a thumb rule if you want to sell anything online you need to have a payment gateway integrated to your website and that is where PayUMoney comes in.
PayUMoney is an e-commerce application service provider that authorizes credit card payments for e-businesses & online retailers.

Need :


We needed PayUMoney payment gateway to be integrated in one of our project as we were operating into B2C (Business to Customer) model where we wanted the customer to buy our product online and make the payments.

How it works :

You can integrate PayUMoney payment gateway by following the below steps :
There are few requisites that you need before implementing PayUMoney
1. Merchant Id
2. Merchant Key
3. Salt Key.
Note : All the above mentioned key's are different for Test & Live account.

Phase 1. Pre-Phase of Integration(Test) :

1. In this phase first you need to create your own PayUMoney Merchant account with a valid email address.
2. To create the test merchant account visit  https://test.payumoney.com/
3. Follow the instructions to fill all the required details.
4. As we are creating a test account, fill all required business details and use this details for PAN no. ABCDE1234F and DOB – 01/04/1990 .
5. Add your bank detail, note you can add whatever bank name and details use this IFSC – ALLA0212632 in place of IFSC.(No Bank verification in case of test accounts)
6. Once all these steps are completed your test account is live, in case if its not yet live then contact the support team for further assistance.
7. Now once above steps are complete you can get your salt key, go to Manage Account ⇒ My Account ⇒ Merchant -Key Salt copy your key and paste in your code.
8. Once all these steps are done completely you are good to go.
9. You then need to integrate the code given below.

<?php
// Merchant key here as provided by PayUMoney.
$MERCHANT_KEY = "hDkYGPQe";

// Merchant Salt as provided by PayUMoney.

$SALT = "yIEkykqEH3";

// End point - change to https://secure.payu.in for LIVE mode
$PAYU_BASE_URL = "https://test.payu.in";

$action = '';

$posted = array();
if(!empty($_POST)) {
  foreach($_POST as $key => $value) {  
    $posted[$key] = $value;
  
  }
}

$formError = 0;

if(empty($posted['txnid'])) {
  // Generate random transaction id
  $txnid = substr(hash('sha256', mt_rand() . microtime()), 0, 20);
} else {
  $txnid = $posted['txnid'];
}
$hash = '';
// Hash Sequence
$hashSequence = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10";
if(empty($posted['hash']) && sizeof($posted) > 0) {
  if(
          empty($posted['key'])
          || empty($posted['txnid'])
          || empty($posted['amount'])
          || empty($posted['firstname'])
          || empty($posted['email'])
          || empty($posted['phone'])
          || empty($posted['productinfo'])
          || empty($posted['surl'])
          || empty($posted['furl'])
          || empty($posted['service_provider'])
  ) {
    $formError = 1;
  } else {
    $hashVarsSeq = explode('|', $hashSequence);
    $hash_string = '';  
    foreach($hashVarsSeq as $hash_var) {
      $hash_string .= isset($posted[$hash_var]) ? $posted[$hash_var] : '';
      $hash_string .= '|';
    }
    $hash_string .= $SALT;
    $hash = strtolower(hash('sha512', $hash_string));
    $action = $PAYU_BASE_URL . '/_payment';
  }
} elseif(!empty($posted['hash'])) {
  $hash = $posted['hash'];
  $action = $PAYU_BASE_URL . '/_payment';
}
?>


HTML Code:

<html>
  <head>
  <script>
    var hash = '<?php echo $hash ?>';
    function submitPayuForm() {
      if(hash == '') {
        return;
      }
      var payuForm = document.forms.payuForm;
      payuForm.submit();
    }
  </script>
  </head>
  <body onload="submitPayuForm()">
    <h2>PayU Form</h2>
    <br/>
    <?php if($formError) { ?>
  
      <span style="color:red">Please fill all mandatory fields.</span>
      <br/>
      <br/>
    <?php } ?>
    <form action="<?php echo $action; ?>" method="post" name="payuForm">
      <input type="hidden" name="key" value="<?php echo $MERCHANT_KEY ?>" />
      <input type="hidden" name="hash" value="<?php echo $hash ?>"/>
      <input type="hidden" name="txnid" value="<?php echo $txnid ?>" />
      <table>
        <tr>
          <td><b>Mandatory Parameters</b></td>
        </tr>
        <tr>
          <td>Amount: </td>
          <td><input name="amount" value="<?php echo (empty($posted['amount'])) ? '' : $posted['amount'] ?>" /></td>
          <td>First Name: </td>
          <td><input name="firstname" id="firstname" value="<?php echo (empty($posted['firstname'])) ? '' : $posted['firstname']; ?>" /></td>
        </tr>
        <tr>
          <td>Email: </td>
          <td><input name="email" id="email" value="<?php echo (empty($posted['email'])) ? '' : $posted['email']; ?>" /></td>
          <td>Phone: </td>
          <td><input name="phone" value="<?php echo (empty($posted['phone'])) ? '' : $posted['phone']; ?>" /></td>
        </tr>
        <tr>
          <td>Product Info: </td>
          <td colspan="3"><textarea name="productinfo"><?php echo (empty($posted['productinfo'])) ? '' : $posted['productinfo'] ?></textarea></td>
        </tr>
        <tr>
          <td>Success URI: </td>
          <td colspan="3"><input name="surl" value="<?php echo (empty($posted['surl'])) ? '' : $posted['surl'] ?>" size="64" /></td>
        </tr>
        <tr>
          <td>Failure URI: </td>
          <td colspan="3"><input name="furl" value="<?php echo (empty($posted['furl'])) ? '' : $posted['furl'] ?>" size="64" /></td>
        </tr>

        <tr>
          <td colspan="3"><input type="hidden" name="service_provider" value="payu_paisa" size="64" /></td>
        </tr>

        <tr>
          <td><b>Optional Parameters</b></td>
        </tr>
        <tr>
          <td>Last Name: </td>
          <td><input name="lastname" id="lastname" value="<?php echo (empty($posted['lastname'])) ? '' : $posted['lastname']; ?>" /></td>
          <td>Cancel URI: </td>
          <td><input name="curl" value="" /></td>
        </tr>
        <tr>
          <td>Address1: </td>
          <td><input name="address1" value="<?php echo (empty($posted['address1'])) ? '' : $posted['address1']; ?>" /></td>
          <td>Address2: </td>
          <td><input name="address2" value="<?php echo (empty($posted['address2'])) ? '' : $posted['address2']; ?>" /></td>
        </tr>
        <tr>
          <td>City: </td>
          <td><input name="city" value="<?php echo (empty($posted['city'])) ? '' : $posted['city']; ?>" /></td>
          <td>State: </td>
          <td><input name="state" value="<?php echo (empty($posted['state'])) ? '' : $posted['state']; ?>" /></td>
        </tr>
        <tr>
          <td>Country: </td>
          <td><input name="country" value="<?php echo (empty($posted['country'])) ? '' : $posted['country']; ?>" /></td>
          <td>Zipcode: </td>
          <td><input name="zipcode" value="<?php echo (empty($posted['zipcode'])) ? '' : $posted['zipcode']; ?>" /></td>
        </tr>
        <tr>
          <td>UDF1: </td>
          <td><input name="udf1" value="<?php echo (empty($posted['udf1'])) ? '' : $posted['udf1']; ?>" /></td>
          <td>UDF2: </td>
          <td><input name="udf2" value="<?php echo (empty($posted['udf2'])) ? '' : $posted['udf2']; ?>" /></td>
        </tr>
        <tr>
          <td>UDF3: </td>
          <td><input name="udf3" value="<?php echo (empty($posted['udf3'])) ? '' : $posted['udf3']; ?>" /></td>
          <td>UDF4: </td>
          <td><input name="udf4" value="<?php echo (empty($posted['udf4'])) ? '' : $posted['udf4']; ?>" /></td>
        </tr>
        <tr>
          <td>UDF5: </td>
          <td><input name="udf5" value="<?php echo (empty($posted['udf5'])) ? '' : $posted['udf5']; ?>" /></td>
          <td>PG: </td>
          <td><input name="pg" value="<?php echo (empty($posted['pg'])) ? '' : $posted['pg']; ?>" /></td>
        </tr>
        <tr>
          <?php if(!$hash) { ?>
            <td colspan="4"><input type="submit" value="Submit" /></td>
          <?php } ?>
        </tr>
      </table>
    </form>
  </body>
</html>


Note : The above code will work for both Test & Live integration provided you make changes according in the below section of the code.

// Merchant key here as provided by PayUMoney
$MERCHANT_KEY = "hDkYGPQe";

// Merchant Salt as provided by PayUMoney
$SALT = "yIEkykqEH3";

// End point - change to https://secure.payu.in for LIVE mode
$PAYU_BASE_URL = "https://test.payu.in"; (For testing purposes)


10. Also once you have implemented the test feature, you can only test it by entering the below mentioned Card details for your payment to be successful.

Test Card Number: 5123456789012346
Test CVV: 123
Test Expiry: May 2017

Phase -2 (Live Integration):

1. In order to integrate PayUMoney on to your live website, you will first have to create your Merchant account(this time with your actual credentials)
2. Follow all the desired steps and documentation needed.
3. PayUMoney asks for a set of documents which the Merchant is suppose to submit online as well as offline in order to generate his Salt key.
4. Once all the above steps are completed successfully PayUMoney generates your Merchant Key & Salt Key.
5. You just need to replace the key details in the PayUMoney Index.php code and also change the End point to https://secure.payu.in for LIVE mode.\

Boston Byte Grabs a Spot in Clutch’s List of Top Software Developers in Massachusetts

Boston Byte is a collective of highly-skilled and highly-professional developers dedicated to solving your technological ...