Open url using Selenium Chromedriver c#

This is a simple example to show how to navigate to url using selenium chromedriver

Install selenium webdriver using Nuget Package

PM> Install-Package Selenium.WebDriver.ChromeDriver -Version 80.0.3987.10600

Below code performs a navigation to google.com

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Support.UI;
using System.Collections.ObjectModel;
using System.Threading;
using System.Configuration;


namespace OpenURL
{
    class Program
    {
        static void Main(string[] args)
        {
            IWebDriver driver = null;
            try
            {

                //driver = new ChromeDriver(@"c:\temp\");//load chromedriver from desired folder.
                driver = new ChromeDriver(AppDomain.CurrentDomain.BaseDirectory);//load chromedriver from bin folder as nuget package deploys chrome driver .exe and other dlls into bin
                driver.Url = "https://www.google.com";//Set the url you would like to navigate
                driver.Manage().Window.Maximize();
                driver.Navigate();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception" + e.ToString());
            }

            finally
            {
                Thread.Sleep(2000);
                driver.Quit();
                Console.ReadLine();
            }
        }
    }
}

Use bin or desired folder to load chrome driver

 driver = new ChromeDriver(AppDomain.CurrentDomain.BaseDirectory);
//this helps loading chromedriver from bin folder
driver = new ChromeDriver(@"c:\temp\");
//this helps to load chromdriver.exe from temp folder.

Calculation in SharePoint Designer – Workflow

There are two ways to perform a calculation.

  1. By creating a calculated column for the library and use excel formulas
  2. Using SharePoint designer workflow.

This will help you to perform any calculations using workflow.

Select “Do calculation” from “Action”

you can perform basic mathematical operations like addition, multiplication, division, etc., and store into workflow variable.

Then the workflow variable can be updated into a library column

Sort Array object python

This code will help to sort any custom list object in ascending or descending order

accuracy=[
        {
            "Alg": "DecisionTree",
            "val": 90
        },
        {
            "Alg": "GradientBoosting",
            "val": 60
        },
        {
            "Alg": "LinearRegression",
            "val": 95
        },
        {
            "Alg": "LogisticRegression",
            "val": 96
        }
    ]

ascending=sorted(accuracy, key = lambda i: float(i['val']))
print(ascending)
desc=sorted(accuracy, key = lambda i: float(i['val']),reverse=True)
print(desc)
Output

[{'Alg': 'GradientBoosting', 'val': 60}, {'Alg': 'DecisionTree', 'val': 90}, {'Alg': 'LinearRegression', 'val': 95}, {'Alg': 'LogisticRegression', 'val': 96}]
[{'Alg': 'LogisticRegression', 'val': 96}, {'Alg': 'LinearRegression', 'val': 95}, {'Alg': 'DecisionTree', 'val': 90}, {'Alg': 'GradientBoosting', 'val': 60}]

Create simple application using Microsoft LUIS (1/2)

This article will help developers to create a simple AI application using Microsot LUIS. In the below example, we will be able to create one simple conversation with Microsoft LUIS. (Ex: who are you? ) and LUIS will understand command provided.

People may use various way to find out about one. So we are going to put all those sentences as intents  (Ex: Who are you? , what are you? , who. etc.,) 


go to https://www.luis.ai/


Click on Create new app

For an example i have given as “hello world”.


Once the app has been created, we need to create intents. There are lot of prebuilt intents available from microsoft that can be used. (Example  Music related, Fitness related, places, travel, etc.,)

the intent name is “Who”


this is where we start populating intent sentences for “Who“, i have given four sentences just for an article purpose.


once intents are populated, it is important to click on “Train”. this will be automatically added to the training data. If the train button shows red, then some new intents are not yet added to the model , so it is important the “Train” button shows green

 


once the data has been trained, you can perform  a small testing by providing various commands and monitor the top scoring intent. it should match the intent you have created.

 


Once the testing is done, proceed to publish tab and push it to production. It generates an URL which contains the key and the subscription id for the app.
This url will be used in the application

o

Continue to the next article to see the implementation of LUIS in .net

Read Excel file using Python

This article shows how to import data from Excel using Python.

Step 1: install pandas

open Ananconda Command Prompt

Step 2: install pandas

\> pip install pandas

Read excel file

import pandas as pd
dataset1=pd.read_excel("C:/folderpath/filname.xlsx",sheet_name="sheetname")
dataset1.head()
print(dataset1.get("columnname"))

Read data from CSV File

import pandas as pd
dataset1=pd.read_csv("C:/foldername/filename.csv",encoding='ISO-8859-1')
dataset1.head()
print(dataset1.get("columnname"))

Access javascript variable from GeckoFx

This article helps developers to retrieve javascript variables from any webpage.
Two things are covered in the below code.

  • Injecting javascript into any webpage
  • Accessing javascript variable from the webpage.

Step 1: Navigating to the webpage (“https://gcatch.in/wp-content/uploads/2018/03/GecoFx.html”)


GeckoWebBrowser browser_gecko= new GeckoWebBrowser();
browser_gecko.Navigate("https://gcatch.in/wp-content/uploads/2018/03/GecoFx.html");
browser_gecko.DocumentCompleted += browser_DocumentCompleted_gecko;


private void browser_DocumentCompleted_gecko(object sender, GeckoDocumentCompletedEventArgs e)
{

            string jCode = " function variable() {return geckovariable;}"; // geckovariable is the variable name that exists in the webpage.
            GeckoElement script = browser_gecko.Document.CreateElement("script");
            script.TextContent = jCode;
            GeckoNode res = browser_gecko.Document.Head.AppendChild(script);

            string outString = "";
            AutoJSContext context = new AutoJSContext(browser_gecko.Window);
            JsVal result = context.EvaluateScript("variable()", browser_gecko.Window.DomWindow);
}

GeckoFx in WPF

Webbrowser component for WPF application. Default web browser component may have some limitation in terms of rendering webkits, html5.

GecoFx will help to render html5, etc.,
Below is a sample , how integrate GecoFx into your WPF Application

Install GecoFx from Nuget
PM> Install-Package GeckoFX -Version 1.0.5

Below are some of the functionalities frequency used with GeckoFx

  1. How to Invoke a script from GecoFx Control
    if user needs to execute a certain javascript function found in html page , you can use the below code to trigger the function.

    
    GeckoWebBrowser browser_gecko= new GeckoWebBrowser();
    browser_gecko.Navigate("https://gcatch.in/wp-content/uploads/2018/03/GecoFx.html");
    browser_gecko.DocumentCompleted += browser_DocumentCompleted_gecko;

     


    https://gcatch.in/wp-content/uploads/2018/03/GecoFx.html , you can check the page source and check javascript code for reference. below code will execute the function geckofunctioncheck

    
    private void browser_DocumentCompleted_gecko(object sender, GeckoDocumentCompletedEventArgs e)
    {
    AutoJSContext context = new AutoJSContext(browser_3w.Window); 
    context.EvaluateScript("geckofunctioncheck()"); 
    }
    


 
Namespaces



using Gecko;
using Gecko.Events;

Sharepoint Item level security – Workflow

Sharepoint has a feature to set item level security either manually or through workflow. In some case we might need to dynamic. (Ex: When we restrict people to view only their region data, we can either create different views per region or create a workflow to set the security level based on their region ) . But if its a sensitive data, creating a view doesnt make sense. Somehow we can pull up the data even by creating our own view). This article shows you how to set item level security using SharePoint workflow

1. Select impersonation step, it creates an unique step 

2. Now if you click on “Action”, you will notice some new list actions. Add list permission, Inherit list permission, …

with this actions, you can modify current item’s permission or any other list’s item permission.

List Templates in webOS

List widget has many properties, among which there are
listTemplate [optional]
itemTemplate [required]
emptyTemplate [optional]

listTemplate
In listTemplate file (optional; defines HTML template for list’s container; if omitted, list items are added to scene with no container):

<div style="background-color: #1e1e1e;color:#FFFFFF;height:55px;">
MyList
</div>
<div>
	#{listElements}
</div>

If ListTemplate is been defined, then you need to mention where those items should be populated. where #{listElements} refers to the list items. if #{listElements} not mentioned, then it wont populate the items.

itemTemplate
defines HTML template for list items

<div class="palm-row">
<div id="storyText" class="listText truncating-text">#{data}</div>
</div>

in ListExample-assistant.js

ListExampleAssistant.prototype.setup = function() {
	this.controller.setupWidget("listId",
	  this.attributes = {
	      itemTemplate: "ListExample/myRowTemplate",
	      listTemplate: "ListExample/myListTemplate",
	      swipeToDelete: true,
	  },
	  this.model = {
	      listTitle: "List Title",
	      items : [
	          {data: "Item 1"},
	          {data: "Item 2"},
	          {data: "Item 3"},
	          {data: "Item 4"},
	          {data: "Item 5"},
	      ]
	  }
	);
};
listTemplate 

<div style="background-color: #1e1e1e;color:#FFFFFF;height:55px;">
MyList 
</div>
<div>
#{listElements} 
</div>

itemTemplate

<div class="palm-row" x-mojo-tap-highlight="momentary"> 
<div style="float:left">#{data}</div>
</div> 
listTemplate 

</div> <div class="palm-group">
<div class="palm-group-title">
My List 
</div>
<div class="palm-list">
#{-listElements} 
</div>
</div>

Where palm-group / palm-group-title and palm-list are inbuilt classes

 itemTemplate

<div class="palm-row" x-mojo-tap-highlight="momentary"> 
<div style="float:left">#{data}</div>
</div> 
in scene assistant: 
if listTemplate not mentioned, then the listeitems will be populated
directly into the scene.

		ListExampleAssistant.prototype.setup = function() {
	this.controller.setupWidget("listId",
	  this.attributes = {
	      itemTemplate: "ListExample/myRowTemplate",
	      swipeToDelete: true,
	  },
	  this.model = {
	      listTitle: "List Title",
	      items : [
	          {data: "Item 1"},
	          {data: "Item 2"},
	          {data: "Item 3"},
	          {data: "Item 4"},
	          {data: "Item 5"},
	      ]
	  }
	); 	
};

		

itemTemplate

<div class="palm-row" x-mojo-tap-highlight="momentary"> 
<div style="float:left">#{data}</div>
</div>	

Database to list in WebOS

This tutorial shows how to insert record into SQL Storage(HTML5) and Populate the rows in List widget.

Refer to List Widget

Step1 : Create Basic Scene “DatabaseList”

in DatabaseList-Scene.html

<div>Database Tutorial</div>

<div id="textField"></div>
<div id="button-1"></div>
<div id="listId" class="listClass"></div>

Step2 : Create one html file for List Widget
in myRowTemplate.html

<div class="palm-row">
<div style="float: left;">#{data}</div>
&nbsp;

</div>

Step 3: DatabaseList-assistant.js Creating a new table named”ofive_table” with two columns ID – Autoincrement Column Title – Text column

DatabaseListAssistant.prototype.setup = function() {
var name = "MainDB";  // required
var version = "1";  // required

var db = openDatabase(name, version);

if (!db) {
  Mojo.Log.error("Could not open database");
} else {

  db.transaction(
  	function (transaction)
  	{
	    transaction.executeSql("CREATE TABLE IF NOT EXISTS Ofive_Table(id integer primary key autoincrement, Title TEXT)",[],
    		function(transaction, results)
    	       {Mojo.Log.info("Successfully created table")},
               function(transaction, error)
               {Mojo.Log.error("Could not create table: ")});
  });
}
this.controller.setupWidget('button-1',{},{buttonLabel: 'Insert'});
this.controller.setupWidget('textField',{},{original : 'initial value'});
Mojo.Event.listen(this.controller.get('button-1'),Mojo.Event.tap, this.InsertRow)
var attributes = {
             itemTemplate: 'DatabaseList/myRowTemplate',
             swipeToDelete: true,
         }
this.controller.setupWidget('listId', attributes);  
};

Step 4: Include the following function which performs

Reference for Queries
– Inserting a new record into the Table (ofive_Table)
– Retrieve all records from the table and Populate into the List widget

DatabaseListAssistant.prototype.InsertRow=function(event){
var db = openDatabase("MainDB", "1"); // this is all that is required to open an existing DB

db.transaction( function (transaction) {
  transaction.executeSql("INSERT INTO Ofive_Table(Title) VALUES (?)",  [$('textField').innerText],
      function(transaction, results) {    // success handler
      Mojo.Log.info("Successfully inserted record");
      },
      function(transaction, error) {      // error handler
       Mojo.Log.error("Could not insert record: " + error.message);
      }
  );
  transaction.executeSql("SELECT * FROM Ofive_Table",  [],
                         function(transaction, results) {    // success handler
			  var Ar1=[]
                          for(i=0;i<results.rows.length;i++)
			  {
			  Ar1.push({data: results.rows.item(i).Title})
			  }
			 $("listId").mojo.noticeUpdatedItems(0, Ar1);
                         },
                         function(transaction, error) {      // error handler
                           Mojo.Log.error("Could not insert record: " + error.message);
                         }
  );
})	

}

Output