A Blog about web development and Life

Tuesday, September 8, 2020

Automate Build & Deploy React production build with gitlab-ci to Linux base server (AWS)

Right now as everyone wanting to automate literaly everything, this post will show you how you can automate the react build and deployment. I am using create-react-app getting started with react and assuming you have a similar setup.




    Setup .gitlab-yml file for gitlab auto deploy

    Here's the whole .gitlab-yml file that you can copy directly to root of your project.

    Breaking each line:
    image: node:10
     
    cache:
      paths:
        - node_modules/
    

    This line define the node version that should be used by the docker instance of shared gitlab-runner and the path defines to cache the node_modules dir.

    before_script:
      - apt-get update -qq && apt install -y openssh-client openssh-server
      - mkdir -p ~/.ssh     
      - echo -e "$SSH_PRIVATE_KEY" > ~/deploy.pem     
      - chmod 400 ~/deploy.pem     
      - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'
    

    The code in `before_script` runs before the actual execution. This is to install and setup pre-requisits for deployment like openssh. Also, as I am using AWS ec2 instance to host the project, I have a .pem file to logging in to server via ssh, which is stored in gitlab variables as  SSH_PRIVATE_KEY and accessed by $SSH_PRIVATE_KEY in yml file. So, I'm adding the public-key to the a file and updating permission of the file as per AWS guidelines.

    deploy_production:
      only:
        refs:
          - master
      stage: deploy
      environment: 
        name: production
      script:
        - npm install
        - REACT_APP_SERVER=production CI=true npm run build
        - scp -i ~/deploy.pem -r build/* $USER_NAME@$SERVER_IP:/var/www/html/provider
    'deploy_production' & 'deploy_staging' blocks are almost similar except 'deploy_production' have all the setup for production build and master branch of react whereas 'deploy_staging' have setup for staging build and staging branch. You can define any other branch you want in `refs`
    Gitlab ci/cd has 3 stages: test, build & deploy, I have merged the build and deploy part in the deploy stage but you can implement it seperatly.
    The script block, runs the essential script to make the project live. Here, for production, I set the environment variable `CI` to true; that'll consider any warning pops-up while building as error, so make sure there is no warning (or error ofcourse) else you can set that to false as I did for staging.
    Atlast, you need to define the dir path where you want to upload/copy the build
    We are using scp command to sync the build folder to our server. Basically, It uploads the build folder to our server.

    You can easily setup the variables mentioned in code (i.e. SSH_PRIVATE_KEY, USER_NAME, SERVER_IP) from your project's CI/CD settings. Visit this link for reference.

    Note: While setting up environment variables, if you want to use it for protected branches only (i.e master/production) remember to select that option.

    After setting up the variables, just push or merge to the branch you've specified in yml file and check the CI/CD Pipeline. It will assign the job to the shared gitlab-runner (Also, you can setup your own gitlab-runner on your server and you can use your own docker image too) and execute these commands.

    So, That's it, your react app deployed. Reach me out incase you catch any issue while setting up.
    Read More

    Monday, November 25, 2019

    Headless Browsing and UI testing Automation : A nightmare

    Do you ever need to use the web using your code instead of a web browser? That's what we call Headless Browsing. The prime application for headless browsing is Automate the UI testing flow. Some other applications I can think of is keeping track of some rates of particular items from some sites on daily basis, visiting some website for views (If you are using google products you might not want to use this as google have set strict policy for this), parsing data from other sites.




    So, the main purpose of headless browser 


    • Test automation in modern web applications.
    • Taking screenshots of web pages.
    • Running automated tests for JavaScript libraries.
    • Scraping web sites for data.
    • Automating interaction of web pages.

    How you can achieve this with node.js?

    Nightmare, don't get scared it's just a name of a node package. So, you to just need to install nightmare in your project like this,

    npm install nightmare

    Let's just write a script for logging in into StackOverflow and get your reputation.


    const Nightmare = require('nightmare');
    let userData = {
    user: "your.email@address",
    pass: "yourpassword"
    }
    const nightmare = Nightmare({ show: false });
    const LOGIN_PAGE = 'https://stackoverflow.com/users/login';
    nightmare
    .goto(LOGIN_PAGE)
    .wait('#login-form')
    .type('#email', userData.user)
    .type('#password', userData.pass)
    .click('#submit-button')
    .wait('a.my-profile')
    .evaluate(() => {
    let el = document.querySelector('.js-header-rep');
    return el ? el.innerHTML : 'null';
    })
    .end()
    .then(progressText => {
    console.log('reputation :', progressText)
    })
    .catch(function (error) {
    console.error('err', error);
    });


    When I initialized the nightmare on the 6th line, I passed the show option as false, which means I want to perform this whole action in the background. If you want to display the scenario on the screen then you should pass true.

    If your login credentials are valid then this script will show your reputation in console, you can store it somewhere if you want.

    This is just a simple script to visit a site. you can do much more as mentioned above.
    If you want to run this script daily like visiting your blog daily, you can set cronjob on server.

    Have sweet dreams!!
    Happy Coding.

    Read More

    Friday, July 19, 2019

    Custom application logic for Loopback models

    This post is the continuation of the previous one
    What if you want to customize your REST API or add different methods for it?When building an application, you’ll generally need to implement custom logic to process data and perform other operations before responding to client requests.
    In Loopback there are 3 ways to do this:
    1. Adding logic to models
    2. Defining boot scripts
    3. Defining middleware
    For this post I'm explaining about the first one, Adding logic to models. There are 3 types to add custom application logic to model.
    • Remote Method
    • Remote Hook
    • Operation Hook

    Remote Method :

    A remote-method is nothing but nodejs function mapped to REST endpoints. You can create remote-method by cli or typing by yourself (click here to know how). 
    In the previous post, I used memory db. For this one, I'm going to use MongoDB as datasource. You need to install loopback-connector-mongodb to connect to MongoDB.
    npm install loopback-connector-mongodb --save
    
    Then you need to add datasource :
    lb datasource
    Enter the datasource name and select MongoDB connector from the list. Then, configure the MongoDB database configuration.
    After adding datasource, create a model as described in the previous post (select the freshly created datasource).
    Now, for creating remote-method, run this command :
    lb remote-method
    Select the model, in which you want the remote-method, enter the name of remote-method, enter endpoints (you can set multiple endpoints for the same remote-method) to be mapped to this remote-method, select method type (get, post, put, delete) and set arguments to be passed with the appropriate type.

    ? Select the model: library
    ? Enter the remote method name: test
    ? Is Static? Yes
    ? Description for method: 
    
    Let's configure where to expose your new method in the public REST API.
    You can provide multiple HTTP endpoints, enter an empty path when you are done.
    ? Enter the path of this endpoint: /test
    ? HTTP verb: post
    
    Let's add another endpoint, enter an empty name when done.
    ? Enter the path of this endpoint: 
    
    Describe the input ("accepts") arguments of your remote method.
    You can define multiple input arguments.
    Enter an empty name when you've defined all input arguments.
    ? What is the name of this argument? name
    ? Select argument's type: string
    ? Is this argument required? Yes
    ? Please describe the argument: 
    ? Where to get the value from? (auto)
    

    /**
    *
    * @param {string} name
    * @param {Function(Error)} callback
    */

    library.test = function (name, callback) {
    // TODO
    callback(null);
    };


    At last, there is a sample code given in cli, copy that and paste it into your model.js. You can write your logic instead of // TODO. If you are returning anything in response, you have to set return type in the model.json. If you are returning an Object set type "object" and if there is no root in an object or other type set root to "true". 

    "returns": {
    "type": "object",
    "root": true
    },

    To return response use callback(). callback accepts two arguments, first as error and second as success. If there is some logical error you just use this callback(error), otherwise callback(null,success).
    This remote-method is now listed in loopback explorer.

    Remote Hook :

    Basically, hooks in loopback used to do something before the method executes or after the method executes. Sometimes you got some parameters with a blank value, then you have to set the default value for them, so you can use before hook. Just like that, sometimes you have to process something after the method is done executing, so you use after hook.
    This runs before the remote method :

    modelName.beforeRemote( methodName, function( ctx, next) {
    //...
    next();
    });

    This runs after the remote method :

    modelName.afterRemote( methodName, async function( ctx) {
    //...
    return;
    });

    Remote hooks are provided with a Context ctx object that contains transport-specific data (for HTTP: req and res). The ctx object also has a set of consistent APIs across transports.
    The context object passed to afterRemoteError() hooks has an additional property ctx.error set to the Error reported by the remote method.

    Operation Hook :

    Operation hooks are not tied to a particular method, but rather are triggered from all methods that execute a particular high-level create, read, update, or delete operation. These are all methods of PersistedModel that application models inherit.

    So, basically, if you want to check the data passed in the built-in create operation, use before create-hook. Similarly, after the create operation, on the basis of the response you need to add some logs or want to perform some action using after create-hook.
    These are the operation hooks supported in loopback :
    access, before save, after save, before delete, after delete, loaded, persist
    Here is how you use these hooks. I am using only after save and before save here, for example, you can use any of above you need. This is after save method,


    Library.observe('after save', function (ctx, next) {
    ctx.instance //the request data
    ctx.Model.modelName //name of the model
    next();
    })

    Here's before save,

    Transaction.observe('before save', async function (ctx, next) {
    ctx.instance //the request data
    ctx.Model.modelName //name of the model
    next();
    })


    Here's the link for the official documentation:
    https://loopback.io/doc/en/lb3/Adding-logic-to-models.html



    Happy Coding
    Read More

    Loopback by Strongloop : Getting started

    Loopback is developed by Strongloop and maintained by IBM. The LoopBack framework is a set of Node.js modules that you can use independently or together to quickly build REST APIs. Heart of Loopback is its models. The application interacts to data-source through models.
    The following diagram illustrates, How loopback works :

    Benefits of using Loopback over Express

    • Loopback has a steep learning curve, on other side Express have a very little learning curve. 
    • Loopback has built-in Database integration, whilst you need npm package in Express.
    • Loopback has built-in models and authentication, API explorer, built-in ORM/ODM with the juggle and various driver and ACL. On the other side, Express needs separate npm package for all this.
    Node.Js is widely used for quickly wrapping up projects with REST APIs. You have to choose the framework that best suits you and the project.

    Installation :

    Prerequisite :

    After making sure that you have Node.js installed, run this command :
    npm install -g loopback-cli
    This installs loopback's CLI globally on your system.

    Getting Started :

    Loopback uses CLI to create an application. Run this command to create a loopback application:
    lb
    This will prompt you for several questions about the application, answer it carefully.
    Write your application name, here I'm going to make a Hello World app.
    What's the name of your application?
     HelloWorld
    Enter the directory of your project :
    Enter name of the directory to contain the project: (HelloWorld)
    Select the loopback version. Currently, the Active version of loopback is 4, but I'm using 3.x LTS. 
    Which version of LoopBack would you like to use? (Use arrow keys)  3.x (Active Long Term Support)
    Here, you have to choose which type of application you want to make?
    • api-server: It will have a built-in User model with user authentication. Perfect for REST APIs.
    • empty-server: It will have only loopback configured, without any built-in model or datasources.
    • hello-world: A sample app to showcase the application logic with a single model.
    • notes: A sample project for Notes, having a connection of memory database.
    What kind of application do you have in mind? (Use arrow keys)
     api-server (A LoopBack API server with local User auth) 
      empty-server (An empty LoopBack API, without any configured models or datasources) 
      hello-world (A project containing a controller, including a single vanilla Message and a single remote method) 
      notes (A project containing a basic working example, including a memory database)
    This will create a directory filled with all the node.js module required by loopback and configured loopback dir structure. To run the application, get inside the project dir and run this command :
    node .
    This will host the application on port 3000 of localhost. go to http://localhost:3000/explorer. It will display the Message API through the loopback explorer. Play with it.

    Now, if you want to create a separate REST API, you need to create a model. Run this command to create a model :
    lb model
    This will also prompt you with some model related questions: 
     Enter the model name: library
    
    Currently, we haven't defined a datasource. The default option is memory db. 
    Select the datasource to attach library to: (Use arrow keys)
    ❯ db (memory) 
      (no datasource) 
    
    Select model's base class (Use arrow keys)
      Model 
    ❯ PersistedModel 
      ACL 
      AccessToken 
      Application 
      Change 
      Checkpoint 
    (Move up and down to reveal more choices)
    One of the powerful advantages of LoopBack is that it automatically generates a REST API for your model. The generator will ask whether you want to expose this REST API. 
    Expose library via the REST API? Yes
    Loopback let you decide that How do you want to use your model, through server only or through Loopback Client API (common). Here we're using server-side only, so select server and hit enter. 
    Common model or server only? 
      common 
    ❯ server 
    Every loopback model has properties. That's like fields of database table. Add as much property you want to see in the table. After you finish adding just hit enter with blank and the model is generated for you. 
    Let's add some library properties now.
    
    Enter an empty property name when done.
    ? Property name: name
    ? Property type: (Use arrow keys)
    ❯ string 
      number 
      boolean 
      object 
      array 
      date 
      buffer
    ? Required? (y/N)  y
    ? Default value[leave blank for none]: 
    It'll create library.json (contains model configurations) and library.js (contains model application logic)file inside /server/models/.
    You can simply perform the REST API calls with loopback API explorer.

    What if you want to customize your REST API or add different methods for it? 
    checkout the answer here.
    Read More

    Wednesday, April 3, 2019

    Points to keep in mind while developing Email Templates

    I have come to know that in frontend development Email Template designing is a kind of headache for those who don't know how to code the HTML perfectly. There are many things to keep in mind if you're designing an Email template, from the basic difference between a static webpage and an email template or how will email service providers render your template.

    So, here are the points you must keep in mind:

    1. Use Table instead of div

    Most of the email clients are not supporting the div structure on top of the body, the render engine mishandles your style. Instead of that, you must use the table tag, which should be the first element in the body.  So, dived your classic div structured into rows and columns for the email. For the best-case scenario, use one column UI.

    2. Use inline-css

    Outlook, Gmail and Yahoo remove your HTML & head tag to resolve the conflict between their own tags. So, if you are using external css or internal css then it will be excluded, to overcome this you must specify inline-css or style in tags.

    3. Do not use float and position 

    Most of the email clients neglect the float and position styles. Instead of using float/position use margin/padding inside the table's td tag.

    4. Keep everything within 600px wide

    This will help you make a similar UI for mobile and desktops and free your users from horizontal scrolling.

    5. Avoid using border/outline

    Some of the email clients like Outlook does not support the border/outline.

    6. Do not use border-radius

    Border-radius property works fine with Gmail or Yahoo but it'll not work at all in Outlook. (Outlook kind of a jerk in email template designing).

    7. Avoid images or use alter the text

    Most of the email clients blocks images by default. You can use alter text with images. If you are using alter text then be sure you add the size for the image so that email clients do not override the space.

    8. Use inbuilt fonts

    Use HTML inbuilt fonts like Arial, Verdana, Georgia, Sans Serif and Times New Roman because not every email clients have the custom font-family.

    9. Avoid animations and javascript

    Sometimes the animations or javascript cannot load properly or blocked by email clients. Use GIFs instead of animations.

    10. Keep CSS, simple

    Avoid compound style declarations (i.e.: “font:#000 12px Arial, Helvetica, sans-serif;”), shorthand code (i.e.: #000 instead of #000000), CSS layout properties (i.e.: slot, position, clear, visibility, etc.), complex selectors (i.e.: descendant, child or sibling selectors, and pseudo-elements)

    11. Avoid body attributes

    You may encounter email clients that don't pay attention to body attributes, which means all your hard work is for naught. Instead of that apply the attribute or style to the leading table.

    12. Use Absolute Image Paths

    Do not use a relative path for images/gifs, the better option is to use URL.

    13. make mobile-friendly

    To make your email template mobile-friendly, use media queries to make it look pretty. Also, use twice a large size images so the image can be equally crispy as mobile/desktop.

    14. Conditional targeting

    If you need to make use of elements that we know is not supported by Outlook, make use of conditional targeting and VML to show or hide elements.

    15. Annoying paragraph tags

    You will notice that Outlook will give much space for the p tags and vice versa for Yahoo. That's because they use different email renderer and it will give paragraphs default margins.

    So, That's all for now. If you find an important point or stuck somewhere just reach me in the comment section.

    Edit: Recently I was surfing around the web and find out this https://mjml.io/. If you want you can use this instead of taking care of these points.
    Read More

    Thursday, January 24, 2019

    FizzBuzz Problem

    Hello guys, today I'm discussing about a well-known interview question, asked for logic measurement of a backend developer in many IT company.
    fun fact: This is discussed in Stackoverflow's Annual Survey 2019.


    Fizz Buzz Problem 

    Problem statement: Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”

    PS: I'm using javascript to solve this problem

    Solution:

    This is really simple, but tricky question if you don't pay attention.
    Happy Codding.

    Read More

    Monday, September 17, 2018

    Webpages with Github hosting

    Website for you and your projects.
    Hosted directly from your GitHub repository. Just edit, push, and your changes are live.
    GitHub now can host your static projects to their servers, and that's for free. You just have to enable the GitHub pages for your repositories. You can forward GitHub's default URL to your custom domain/sub-domain. Let's see how we can do that.
    Login to your GitHub account. create a new repository with name "(your GitHub username).github.io". This is your base GitHub page. add a sample index.html file to master branch and after commit, open a new tab on your browser and type: (your GitHub username).github.io 
    Bingo!! you just hosted your first page on GitHub. (If it does not reflect the changes wait for some time, GitHub might be taking some time to publish it)
    GitHub gives the option to use it's prebuilt theme to the pages. If you don't want to create a custom static site then go to settings of the repository. Scroll down to Github Pages, click on choose theme, then select an appropriate theme and edit necessary text. 
    Now, if you want to host your another static project, create a repository, add files to it and go to settings, scroll down to GitHub Pages, and on the source select 'master branch'. Open new tab on browser and type : (your GitHub username).github.io/repository-name
    If you own a domain and want to forward this github page site to your own domain/sub-domain, just open the (your GitHub username).github.io repository and add a CNAME file. Then write your domain/subdomain name.
    Go to your domain registrar and add a CNAME entry for the domain/subdomain and add repository name in the value field. If you're using a subdomain, you have to first add a subdomain in DNS settings. Generally domain registrar takes 24 hours time to add CNAME to their system. You can see your project hosted on your domain after that. PS: for other projects, you have to just add '/repository-name' after your domain.
    This is so much helpful for the Front-end developer to showcase their skills.
    Read More

    Live Game Streaming on YouTube

    Hello Guys, Today I gonna talk about how to stream your mobile gameplay to YouTube Gaming. Nowadays, PUBG (PlayerUnknown's BattleGround) is the most trending mobile game. Many Pro players upload/stream their gameplay to YouTube and earn money through monetization.
    Ok. Let's start. First of all Download YouTube Gaming App.
    After download, open the app and create/choose your google account for your YouTube channel. If you're a new user then you have to wait for 24 hours until you stream your gameplay (YouTube need to activate your account).
    Now Just click on the first icon(streaming icon) on the top left corner and this screen will appear:
    Click Next and select Stream if you want to live stream your gameplay or Record if you want to save the video to your phone and upload it later. Select the video format you want to upload/stream.

    Click next, you'll see a tips screen, read it and click next.

    Now, Select the game you want to stream or record. Add the stream info, i.e. stream name and stream description. Then click next.

    If you're streaming the gameplay, you'll see the share link screen to social media. Select if you want to share it to any social media platform and click next.

    Now, you'll see your game running on your device with a small video bar and a panel with buttons like mute voice, turn off video and start streaming. When you're ready to click on stream button and you're live. There is a settings button that will help you to change the size of the little round screen of your video.

    PS: You need a very fast internet connection for the live streaming game.
    Happy Playing PUBG.
    This blog is written on blogger-editor
    Read More

    Tuesday, September 4, 2018

    Dynamic Form and Grid with C# in WPF

    Ever wanted to generate the form & grid dynamically and add data from some data source? Here's to help you.

    Create a WPF project in Visual Studio. Add a UserControl and name it mainUserControl.xaml
    Now add a stackpanel just like this :
    <UserControl x:Class="TestApp.mainUserControl"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
                 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
                 xmlns:local="clr-namespace:SaiData.TestApp"
                 mc:Ignorable="d" 
                 >
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="5*"/>
                <ColumnDefinition Width="43*"/>
            </Grid.ColumnDefinitions>
            <StackPanel Name="panel1" Margin="18.971,24,24,0" Grid.Column="1">
    
            </StackPanel>
        </Grid>
    </UserControl>
    
    Now, go to mainUserControl.cs file :
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    
    namespace TestApp
    {
        /// <summary>
        /// Interaction logic for mainUserControl.xaml
        /// </summary>
        public partial class mainUserControl : UserControl
        {
          public mainUserControl(){
            InitializeComponent();
            
            TextBlock tb = new TextBlock();
            tb.Text = "Username :";
            tb.Width = 100;
            tb.HorizontalAlignment = HorizontalAlignment.Left;
            panel1.Children.Add(tb);
            TextBox username = new TextBox();
            username.Width = 100;
            username.HorizontalAlignment = HorizontalAlignment.Left;
            panel1.Children.Add(username);
    
            TextBlock tb1 = new TextBlock();
            tb1.Text = "Full Name :";
            tb1.Width = 100;
            tb1.HorizontalAlignment = HorizontalAlignment.Left;
            panel1.Children.Add(tb1);
            TextBox fullname = new TextBox();
            fullname.Width = 100;
            fullname.HorizontalAlignment = HorizontalAlignment.Left;
            panel1.Children.Add(fullname);
            
            ComboBox cb = new ComboBox();
            cb.Width = 150;
            cb.HorizontalAlignment = HorizontalAlignment.Left;
            cb.Margin = new Thickness(0, 5, 0, 0);
            CustomerData[] customer_list = gd.getCustomerRecord();
            cb.Items.Add("Select Gender");
            cb.Items.Add("Male");
            cb.Items.Add("Female");
            cb.Items.Add("Other");
            cb.SelectedIndex = 0;
            panel1.Children.Add(cb);
            
            TextBlock tb2 = new TextBlock();
            tb2.Text = "Full Name :";
            tb2.Width = 100;
            tb2.HorizontalAlignment = HorizontalAlignment.Left;
            panel1.Children.Add(tb2);
            TextBox password = new TextBox();
            password.Width = 100;
            password.HorizontalAlignment = HorizontalAlignment.Left;
            panel1.Children.Add(password);
            
            Button submit = new Button();
            submit.Name = "submit_user";
            submit.Width = 100;
            submit.HorizontalAlignment = HorizontalAlignment.Left;
            submit.Content = "Save user Data";
            submit.Margin = new Thickness(0, 5, 0, 0);
            submit.Click += (s, e) =>
            {
                //here you can define action for submitting form.
                MessageBox.Show("username = " + username.Text);
            };
            panel1.Children.Add(submit);
          }
        }
    }
    
    This will create a form dynamically on your UserControl. Now to add dynamic grid with Edit/Delete buttons add this code to your existing UserControl or make a new UserControl :
    DataGrid dg = new DataGrid();
    dg.HorizontalAlignment = HorizontalAlignment.Left;     
    dg.VerticalAlignment = VerticalAlignment.Top;
    dg.AutoGenerateColumns = true;            
    //the function getData used to get the data from data-source, you can manipulate it. 
    getData gd = new getData(); // getData holds getUserRecord() to get the data 
    UserData[] data = gd.getUserRecord();       
    dg.ItemsSource = data;
    FrameworkElementFactory sp = new FrameworkElementFactory(typeof(StackPanel)); 
    sp.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);     
    FrameworkElementFactory delete = new FrameworkElementFactory(typeof(Button)); 
    delete.AddHandler(Button.ClickEvent, new RoutedEventHandler((s, e) => { 
    MessageBox.Show(data[dg.SelectedIndex].id); })); 
    delete.SetValue(ContentControl.ContentProperty, "Delete");
    FrameworkElementFactory edit = new
    FrameworkElementFactory(typeof(System.Windows.Controls.Button)); 
    edit.AddHandler(Button.ClickEvent, new RoutedEventHandler((s, e) => {
    MessageBox.Show("edited click!"); }));
    edit.SetValue(ContentControl.ContentProperty, "Edit");
    edit.SetValue(FrameworkElement.MarginProperty, new Thickness(5, 0, 0, 0));
    sp.AppendChild(delete);        
    sp.AppendChild(edit);
    DataGridTemplateColumn dataGridTemplateColumn = new DataGridTemplateColumn()
    {                
    Header = "new...",    
    CellTemplate = new DataTemplate { VisualTree = sp }     
    };
    dg.Columns.Add(dataGridTemplateColumn);  
    panel1.Children.Add(dg);
    
    That's it. You Just made a dynamically generated grid and form.

    PS: The new code panel is added using the http://blogger-editor.xyz
    Read More

    Saturday, July 28, 2018

    Electron app with AngularJs and MySQL Database


    Hello folks, 
    Do you know about Electron API (a GitHub repository, helping a web developer to make standalone cross-platform app)? The electron can make any web app to Desktop Application in all three major OS (i.e. Windows, Mac, Linux). Okay, enough intro about Electron, let's move on Problem...
    So, if you are an Angular Developer and you want to make a Desktop app having a database in MySQL, you came to right place! 
    The Directory structure should look like this :
    AngularElectronMySQL ->
         -Electron
         -WebApp (Angular app)
         -Setup
    So, First Initialize your Angular project using angular-cli (you can use also build it simply). Here, I am assuming that you completed your Angular Project and Built it. Just one more thing add a data-service for getting data from MySQL. Subscribe to the MySQL server (for our case: http://localhost:1024). After that, you need to copy the files from the built project to electron folder. I used npm like this : 
    Now, for Electron create a main.js file inside the Electron folder. Write down this code : 
    Now, for connecting with MySQL, we need to create a Node.JS mini-server. create a mysql.js file inside Electron folder.
    That's it!! Run your Electron App. The first time it will prompt you for the database credential and store it in a file.
    Here's the list of required npm dependencies to install : 
    For Node: http, mysql, electron-prompt
    For Copy.js : fs-extra, delete
    Read More

    Thursday, June 14, 2018

    Arrange Marriage = Online Shopping

    Hey guys, how are you all? Yeah, I know came after a while but came with a witty post you might like. Enjoy.

    So, I thought everyone done online shopping once in their lifespan. Right??  If No, you already did arrange marriage and that is kind of same!!

    Let see through the scenario, step by step. I'm writing arrange marriage as AM for short!


    Step 1: open your account

    While shopping you have to sign up for the account for the respective site.
    Same in AM, you have to prepare your self to do the process. So basically you either goto any marriage bureau or go through any matrimonial advertisement or by actually sign up on online websites for matchmaking!! Kind of same right?? 藍

    Anyways moving to next step...

    Step 2: search and filter items

    Assume that you want to buy a mobile phone!
    So, you search for mobile and add some filters like budget, manufacturer, RAM/ROM, Camera etc.
    Well, you kinda do same in AM, you make up your mind for a particular life partner with some genetic nature or looks or profession etc. Yes, that's a filter!! 

    Moving on...

    Step 3: choose from best according to you

    Ok, now you filtered all the requirements of yours and the results came out.
    Now you'll compare the minimal results and choose best and click on Add to Cart! (Plus point is you can remove the item from the cart)
    No, you don't have this type of button or feature if you selected one stay with it in AM, choose carefully!!

    Step 4: Buy now

    After adding to cart you have bought the item.
    You've already fixed your life partner this step is just like ensuring it - engagement!!

    Step 5: Payment options 

    Now select the payment option appropriately.
    And in AM, both the family decides how they want to actually Arrange the Marriage i.e. by showing off how much their savings is!!!

    Step 6: Item Delivered!

    Ok after payment successful, the item will be delivered to you in some days...
    Same after the engagement your life partner will be yours for the rest of your life after the final day -Marriage day!! *TnC

    * TnC: Return or Replacement can be done as a form of Divorce in AM but no refund applicable 

    Well, now do you wonder what I think about Love Marriage?
    Ummm... It is also kind of online shopping but with some conditions.. if both families agreed that it's on Bumper offer or on Sale!! And if not agree then you're buying it because you can't live with it, whether its experience or not! 

    Well, if you ask me what's better than I would like to say I like to do online shopping but if there is SALE than that's would be great!!

    Okay, I rest my case! Now it's your turn to tell me what you think by commenting below!!



    Sponsor: This blog is co-sponsored by The YTDOWNLOAD team!! Go check out this awesome website for downloading youtube videos in few clicks!
    Stay Happy. Stay Blessed.
    Read More

    Search This Blog