Tuesday, 1 December 2020

Batch Scripting | Batch Programming | Batch File | Batch Tutorial | Scripting Made Easy | Working with Batch Scripting

Batch Scripting | Batch Programming | Batch File | Batch Tutorial | Scripting Made Easy | Working with Batch Scripting

Prerequisites

- Computer programming knowledge.
- Windows command line commands basics.

What is Windows Command Prompt | Command Line | Command Shell | cmd | cmd.exe | Command Line Interpreter?

Command prompt is an executable windows application which is available on most of the operating systems. It supports a list of windows commands. Command line interface helps in performing windows operations like creating/deleting/renaming/copying/moving folders or files, open files or applications etc.

What is a batch file?

A batch file or a batch script or batch job is a file which contains the list or collection of commands which will execute sequentially from top to bottom in command window. In windows operating system a batch file stored with an extension *.bat.

Batch scripting advantages

- Run multiple processes at a time
- Perform repetitive tasks
- Back up files
- Easy to manage large processes
- Saves time by running collection of commands
- Can call one batch from another batch
- Supports the user inputs as an arguments
- Publishing applications
- Supports all the windows command line commands
- Can work with git commands (git installation required)

In this tutorial you will be introduced with the basic batch scripting commands.

Batch file commands


ECHO

@ECHO [ON/OFF] - sets the command-line settings. ON - Displays the executing commands on command window, OFF - won't displays the  commands on window.
ECHO [Text] - Print text to the screen)
ECHO. - Print an empty line to the screen
ECHO - Displays the current setting of the command-line

PAUSE

Stops the commands execution and wait for any key press.

REM

Adds comment in script file.
Example:
REM comment details will goes here

EXIT

Terminates execution and closes the command window.

Variables

Variable can be initialized with SET command.

Syntax: SET [/A] [variable-name]=value
/A - If the value needs to be numeric 

String variable: 
SET employeeName="Srinubabu Ravilla"
ECHO %employeeName%

The above script will print the "Srinubabu Ravilla" on screen. Variable can be accessed by surrounding with the %% as shown above.

String concatination: 
SET employeeFirstName=Srinubabu
SET employeeLastName=Ravilla
ECHO %employeeFirstName%+%employeeLastName%

The above script will print the "Srinubabu Ravilla" on screen by combining both first name and last name variables.

Numeric variables: 
SET /A employeeFixedPay=500000
SET /A employeeVariablePay=100000
ECHO Employee total salary: %employeeFixedPay% + %employeeVariablePay%

The above script prints the "Employee total salary:600000 " on screen.

Prompt user for input:
SET /p userInput=Enter employee name: 
ECHO User input: "%userInput%"

The above script prints the user entered input on screen.

Escape sequence

Most special characters can be escaped using the caret (^) below are the list of characters that can be escaped.
Batch Scripting | Batch Programming | Batch File | Batch Tutorial | Scripting Made Easy | Working with Batch Scripting
Example: 
ECHO Mobile number format ^<Country-Code^>^<10-digit-numeric-value^>

The above script will print "Mobile number format <Country-Code><10-digit-numeric-value>"

Directories

Get the current batch script execution directory:
An environment variable CD stores the current command directory
ECHO Current directory: %CD%

Windows commands can be utilize in the batch scripting. Below are the few examples.

Change from one directory to another:
cd /d c: 
 
Navigate to another directory by directory path:
SET folderPath=C:\Users - Manual path
CD %folderPath%  - With path from variable
 
Create a new folder:
md "NewFolder1234" - Create folder in current directory
md "c:\Users\sravilla\test123" - Create new folder in by path
md %directoryVariable% - Create directory from variable/user input 
 
Open Folder:
%SystemRoot%\explorer.exe %FolderPath%
%SystemRoot%\explorer.exe "C:\Users"

Start

Start command can be used to start the program
START C:\Users - Opens the directory
start notepad.exe - Opens notepad
START https://dotnetcookie.blogspot.com/ - Opens the URL in default browser
START mailto:srinubabu.ravilla@gmail.com - Creates a new email in mail application

Loops

Unlike other programming languages batch scripting supports only for loop. The definition of a loop is,  statements execution repeats until specified condition is satisfied.

Basic Syntax:
FOR %%variable_name IN list DO commands

list - List of any elements, separated by either spaces, comma's or semicolons.
command - Can be any internal or external command, batch file, list of commands.
%%variable_name - Variable declaration in loops is specified with %%variable_name instead of %variable_name%.

Looping through numbers
FOR %%x IN (1 2 3 4 5 6 3 2 1) DO Echo %%x

The above script prints all the numbers from starting to ending.

Looping through range of values 
Batch scripting supports numeric range looping. 

Syntax: FOR /L %%variable_name IN (LowerLimit, Increment, UpperLimit) Do some_code

/L - Specifies the loop  suppose to iterate through the range of values.
LowerLimit - The minimum numeric start value  
Increment - Numeric increment which adds to LowerLimit in each iteration 
UpperLimit - The maximum value in a range to limit with 

FOR /L %%Number_Variable IN (0, 2, 15) DO ECHO %%Number_Variable

The above script prints the range of values between 0 and 15 with the increment of 2 in each iteration.
Output: 0,2,4,6,8,10,12,14

Loop through files
Batch script supports looping through the files in current directory. File lookup (*.*) specified in the below command can support the wild card search like (*.jpg). 

for /r %%file_path in (*.*) do echo %%file_path  

Looping through directories/folders
Batch script supports looping through the directories (Includes sub directories) in current directory. Directory lookup ("*") specified in the below command can support the wild card search like (*.jpg). 

for %f in (.\*) do @echo %f                - Files in current directory
for /D %s in (.\*) do @echo %s         - Subdirs in current directory
for /R %f in (.\*) do @echo %f         - Files in current and all subdirectories
for /R /D %s in (.\*) do @echo %s    - subdirs in current and all subdirectories

So, this is all about the batch scripting. Please start with the basic commands and practice in you machine to get familiar understanding and effective learning.

Friday, 27 November 2020

CSS Basic Selectors - Learn CSS | Html with CSS Tutorials | Tricks | Front-end Development

CSS selectors are useful in front end development. In this tutorial I am going to show you what are the CSS basic selectors.

Below are the four basic selectors which we use on daily web development


1. Universal Selector

2. Type Selector

3. Class Selector

4. ID Selector


1. Universal Selector

The universal selector matches all elements of any type in HTML document. Consider the below scenario in where we have div, span and paragraph for which I want to set a a green font colour for all of them.

CSS

*{

     font-color:green;

 }

<div>div content</div>

<span>span content</span>

<p>paragraph content</p>

User Interface

div content
span content

paragraph content

2. Type Selector

Type selector matches all the HTML elements by the given HTML element name. This selector travels throughout the HTML document and find out the elements which are matched with the given element name and apply the styles on them. Cosider below where we have to set a light green background colour for all the paragraphs.

CSS

p{

background-color: lightgreen;

}

<span>Paragraph 1</p>

<p>dotnetcookie.blogspot.com contains the regular updates on C#.NET for the followers</p>

<span>Paragraph 2</p>

<p>dotnetcookie.blogspot.com contains the regular updates on UI Technologies for the followers</p>

<span>Paragraph 3</span>

<p>dotnetcookie.blogspot.com contains the regular updates on SQL Server for the followers</p>

User Interface


Paragraph 1

dotnetcookie.blogspot.com contains the regular updates on C#.NET for the followers

Paragraph 2

dotnetcookie.blogspot.com contains the regular updates on UI Technologies for the followers

Paragraph 3

dotnetcookie.blogspot.com contains the regular updates on SQL Server for the followers

3. Class Selector

The class selector matches all the HTML elements by their class attribute value. If any HTML element class attribute value is matches with the given class name selector then the changes will apply to them. Consider the below scenario in which we want to apply a light green colour background to the success message and light  yellow colour message to info message.

CSS

.success {

background-color: lightgreen;

}

.info {

background-color: #f4ff54;

}

<div class="success">Congratulations! Your are successfully completed CSS basic selectors blog post</div>

<div class="info">You need to go through the other tutorials to become an expert in CSS</div>

User Interface

Congratulations! Your are successfully completed CSS basic selectors blog post

You need to go through the other tutorials to become an expert in CSS

4. ID Selector

The ID selector applies the styles to the elements based on the value of their id attribute. The HTML elements should be identified by the unique ids. Lets take two containers , apply the background colour for the div container which id value is equal to "warningMessage".

CSS

#warningMessage{

background-color: lightgreen;

}

<div id="warningMessage">HTML does not allow the duplicate id values.</div>

<div>Please go through the other tutorials on this blog to become an expert in CSS</div>

User Interface

HTML does not allow the duplicate id values.
Please go through the other tutorials to become an expert in CSS

Above are the basic selectors which we use regularly in our web development.

Thursday, 26 November 2020

C# - Truncate characters from string by keeping right side string with the specific length

 

Challenge

Consider a scenario where you are uploading a file in a website and prcoess the file by appending the date at the end of the file name and saves in a location and then saving the uploaded file name in the database. Post uploading the file you are displaying all the submitted files in a grid like below.

Uploaded filename: Developer_Profile.xlsx
Saved filename appended with date: Developer_Profile_11242020.xlsx
https://dotnetcookie.blogspot.com/
Consider the column length for the filename is 150. If the uploaded file name length is more than 150 and there is no length validation before inserting into database then database will throw the exception. So we need to add a validation before uploading. Assume that the client doesn't want to restrict the upload if the file name length is more than 150 characters. Instead client comes with the below requirement.

- If the file length is greater than 150
- Truncate filename to 150 characters, but keep the right side portion which is date part along with extension.

Example: Uploaded file with file name length more than 150
Filename: Developer_Profile_ dummy text of the printing and typesetting industrya Lorem Ipsum has been the industry's standard dummy text ever sinceweb page editors now use Lorestandard_11242020.xlsx

Keep the date part and remove/trim the additional characters highlighted above.

Truncated filename with 150: Developer_Profile_ dummy text of the printing and typesetting industrya Lorem Ipsum has been the industry's standard dummy text ever sinceweb page edit_11242020.xlsx

Below is the extesion method which will truncate the file name and the respective unit testcacses. Follow the code comments which is self explanatory.

Extension method to truncate string

        /// <summary>
        /// If input length is greater than the truncate length value
        /// Trims the input with length truncate length value.
        /// Keeps the right side of the input value
        /// </summary>
        /// <param name="value">Input value</param>
        /// <param name="truncateLength">Truncates input if the input length is greater than this</param>
        /// <param name="rightLengthToKeep">The right side string length which needs to take while truncating</param>
        /// <returns></returns>
        public static string TruncateRight(this string value, int truncateLength, int rightLengthToKeep)
        {
            var errorMessage = "Negative values are not allowed";

            // Handle empty, null and white spaces 
            if (string.IsNullOrWhiteSpace(value))
            {
                return value;
            }

            // Handle negative values
            if (truncateLength < 0)
            {
                throw new ArgumentOutOfRangeException("truncateLength", truncateLength, errorMessage);
            }

            // Handle negative values
            if (rightLengthToKeep < 0)
            {
                throw new ArgumentOutOfRangeException("rightLengthToKeep", rightLengthToKeep, errorMessage);
            }

            if (rightLengthToKeep > truncateLength)
            {
                errorMessage = $"rightLengthToKeep value ({rightLengthToKeep}) shoud be less than or equal to truncateLength ({truncateLength})";
                throw new ArgumentOutOfRangeException(errorMessage);
            }

            if (value.Length <= truncateLength)
            {
                return value;
            }

            // To skip middle range we need to take the left side end rage and right side start rage.
            int leftStringEndIndex = truncateLength - rightLengthToKeep;
            int rightStringStartIndex = value.Length - rightLengthToKeep;

            var finalResult = "";

            // Get left side value
            for (int i = 0; i < leftStringEndIndex; i++)
            {
                finalResult = finalResult + value[i];
            }

            // Get right side value
            for (int i = rightStringStartIndex; i < value.Length; i++)
            {
                finalResult = finalResult + value[i];
            }

            return finalResult;
        }

Unit tests

        [Fact]
        public void SkipRightThenTrimTest()
        {
            // Test filename: FileNameToTestWithTruncateLogicTruncateMe_11242020_ErroFile.csv
            // Total string length is 63

            // Null check
            string testString = null;
            Assert.Equal(null, testString.TruncateRight(40, 22));

            // Empty check
            testString = ""; 
            Assert.Equal("", testString.TruncateRight(40, 22));

            // Whitespace check
            testString = "  ";
            Assert.Equal("  ", testString.TruncateRight(40, 22));

            // Negative value check 
            testString = "FileNameToTestWithTruncateLogicTruncateMe_11242020_ErroFile.csv";
            Assert.Throws<ArgumentOutOfRangeException>(() => testString.TruncateRight(-22, 40));
            Assert.Throws<ArgumentOutOfRangeException>(() => testString.TruncateRight(22, -40));
            
            // Invalid range check
            Assert.Throws<ArgumentOutOfRangeException>(() => testString.TruncateRight(22, 40));

            // Truncate filename if it more than 22 chars and take right 22 characters
            Assert.Equal("_11242020_ErroFile.csv", testString.TruncateRight(22, 22)); 
           
            // Truncate filename if it is more than 40 chars and keep right 22 characters and left 18 chars
            Assert.Equal("FileNameToTestWith_11242020_ErroFile.csv", testString.TruncateRight(40, 22));
            
            // Take filename directly if the fielname lenth and truncate value length is equal
            Assert.Equal(testString, testString.TruncateRight(63, 22));
            
            // Take filename directly if the truncate value length is greater than the filename length
            Assert.Equal(testString, testString.TruncateRight(70, 22));
        }
    }

Tuesday, 22 September 2020

C# LINQ - Partitioning the List Collection Into Chunks

















Partitioning is the key part while working with the large collections in programming. LINQ helps in dividing the huge collection into chunks. 

Below code snippet takes the list and the chunk size and yields the chunks from the collection.

public static IEnumerable<List<T>> Partition<T>(List<T> source, Int32 size)
{
    for (int i = 0; i < Math.Ceiling(source.Count / (Double)size); i++)
        yield return new List<T>(source.Skip(size * i).Take(size));
}

Test Results:





JavaScript - window.location.origin is not working in Internet Explorer


window.location.origin does not work on Internet Explorer. 

Follow the below code which will set the window.location.origin value by concatenating the portions of the URL. 

 if (!window.location.origin)
    window.location.origin = window.location.protocol + '//' + window.location.hostname + (window.location.port ? (':' + window.location.port) : ''); 
}

window.location properties

window.location.protocol         - Return the protocol of the current URL
window.location.hostname      - Returns the domain name of the web host
window.location.port                  - Number of the internet host port (of the current page)

Saturday, 29 August 2020

JavaScript - How to Download All Pictures from Instagram Profile on Single Click


1. Open Instagram profile you want to download images from in Chrome browser.

2. Open Chrome Console (Press F12).

3. Enter the below script in console window then all appearing images in the Instagram profile current screen will be opened into a new tab.


document.querySelectorAll("div.v1Nh3.kIKUG._bz0w a").forEach(function (item) { window.open(item.querySelector("img")["src"]) });