Sunday, 2 August 2020

create and Install the Windows service in C#

How to create a Windows service in C#?

 
Let's create a Windows Service in C# using Visual Studio. 
 
Step 1
 
Open Visual Studio, go to File > New and select Project. Now select a new project from the Dialog box and select “Window Service” and click on the OK button.
 
windows service
 
Step 2
 
Go to Visual C# -> ”Windows Desktop” -> ”Windows Service” and give an appropriate name and then click OK
 
windows service 
 
Once you click the OK button the below screen will appear, which is your service
 
windows service 
 
Step 3
 
Right-click on the blank area and select “Add Installer”
 

How to Add an Installer to a Windows Service

 
Before you can run a Windows Service, you need to install the Installer, which registers it with the Service Control Manager.
 
windows service 
 
After Adding Installer, ProjectInstaller will add in your project and ProjectInstakker.cs file will be open. Don’t forget to save everything (by pressing ctrl + shift + s key)
 
windows service 
 
Solution Explore looks like this:
 
windows service 
 
Step 4
 
Right-click on the blank area and select “View Code”
 
windows service
 
Step 5
 
Its has Constructor which contains InitializeComponent method:
 
The InitializeComponent method contains the logic which creates and initializes the user interface objects dragged on the forming surface and provided the Property Grid of Form Designer.
 
Very important: Don't ever try to call any method before the call of InitializeComponent method.
 
windows service 
 
Step 6
 
Select InitializeComponent method and press F12 key to go definition
 
windows service 
 
Step 7
 
Now add the below line:
 
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
 
You also can add description and display service name (optionally).
  1. this.serviceInstaller1.Description = "My First Service demo";  
  2. this.serviceInstaller1.DisplayName = "MyFirstService.Demo";  
windows service
 
Step 8
 
In this step, we will implement a timer, and code to call the service at a given time. We will create a text file and write the current time in the text file using the service. 
 
windows service 
 
Service1.cs class 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Diagnostics;  
  6. using System.IO;  
  7. using System.Linq;  
  8. using System.ServiceProcess;  
  9. using System.Text;  
  10. using System.Threading.Tasks;  
  11. using System.Timers;  
  12. namespace MyFirstService {  
  13.     public partial class Service1: ServiceBase {  
  14.         Timer timer = new Timer(); // name space(using System.Timers;)  
  15.         public Service1() {  
  16.             InitializeComponent();  
  17.         }  
  18.         protected override void OnStart(string[] args) {  
  19.             WriteToFile("Service is started at " + DateTime.Now);  
  20.             timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);  
  21.             timer.Interval = 5000; //number in milisecinds  
  22.             timer.Enabled = true;  
  23.         }  
  24.         protected override void OnStop() {  
  25.             WriteToFile("Service is stopped at " + DateTime.Now);  
  26.         }  
  27.         private void OnElapsedTime(object source, ElapsedEventArgs e) {  
  28.             WriteToFile("Service is recall at " + DateTime.Now);  
  29.         }  
  30.         public void WriteToFile(string Message) {  
  31.             string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";  
  32.             if (!Directory.Exists(path)) {  
  33.                 Directory.CreateDirectory(path);  
  34.             }  
  35.             string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/''_') + ".txt";  
  36.             if (!File.Exists(filepath)) {  
  37.                 // Create a file to write to.   
  38.                 using(StreamWriter sw = File.CreateText(filepath)) {  
  39.                     sw.WriteLine(Message);  
  40.                 }  
  41.             } else {  
  42.                 using(StreamWriter sw = File.AppendText(filepath)) {  
  43.                     sw.WriteLine(Message);  
  44.                 }  
  45.             }  
  46.         }  
  47.     }  
  48. }  
Code explanation - the above code will call service every 5 seconds and create a folder if none exists and write our message.
 
Step 9. Rebuild your application.
 
Right-click on your project or solution and select Rebuild.
 
windows service 
 
Step 10
 
Search “Command Prompt” and run as administrator
 
windows service 
 
Step 11
 
Fire the below command in the command prompt and press ENTER.
 
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319 
 
windows service 
 
Step 12
 
Now Go to your project source folder > bin > Debug and copy the full path of your Windows Service exe file.
 
windows service
 
windows service
 

Installing a Windows Service

 
Open the command prompt and fire the below command and press ENTER.
 
Syntax
 
InstallUtil.exe + Your copied path + \your service name + .exe
 
Our path
 
InstallUtil.exe C:\Users\Faisal-Pathan\source\repos\MyFirstService\MyFirstService\bin\Debug\MyFirstService.exe
 
windows service 
 

Check the status of a Windows Service

 
Open services by following the below steps:
  1. Press Window key + R.
  2. Type services.msc
  3. Find your Service.
windows service
 
windows service
 
You may notice that the Windows service is running. 
 
windows service
 

Check Windows Service Output 

 
The service will create a text file with the following text in it. 
 
windows service 
 
The log folder will be created in your bin folder.
 

Uninstalling a Windows Service

 
If you want to uninstall your service, fire the below command.
  1. Syntax InstallUtil.exe -u + Your copied path + \your service name + .exe
  2. Our path InstallUtil.exe -u C:\Users\Faisal-Pathan\source\repos\MyFirstService\MyFirstService\bin\Debug\MyFirstService.exe

Wednesday, 29 July 2020

View hosted site on other machines in Same Network

Create a website in IIS

 
Open run (windows key + R) and type inetmgr and press enter
 
image1
 
image2
 
IIS Manager opens.
 
Then right click on Sites and click on Add Website. The Add website dialog opens.
 
image3
  • Fill in required details and select folder where compiled code is located. Eg: C:\Nigel\Publish
  • Select required port , default is 80. I will be using 7500.
  • Do not enter host name details if you are testing or using on LAN. 
Then click ok. A website gets created and it will show under Sites.
 
image4
 
Now right click on website name then Manage website and then click browse.
 
image5
 
The link should be in the form on http://localhost:7500/  if you used port 7500 and selected http.
 

Locate your IP Address

 
Now open command prompt. Type cmd in run.
 
image6
 
Type ipconfig and press enter. Now locate your PC's IP address on the LAN.
 
image7
 
Now in your website link replace localhost with 192.168.0.24 (IP address) so your URL will be - http://192.168.0.24:7500/
Try it in your browser to make sure it works.
 

Change Firewall Rules

 
In Cortana search type firewall then click on Windows firewall with advanced security.
 
image8 
 
The firewall window opens.
 
image9
  
Click on Inbound rules on the left. Then click new Rule in the right side menu.
  
image10
 
The New inbound rule wizard will open. What type of rule would you like to create? Select Port and click Next.
 
image11
 
In Does this rule apply to TCP or UDP? Select TCP. Then enter port number (7500) in specific local ports textbox. Then click Next >.
 
image12
 
Then the Action form opens. Select Allow the connection and click Next .
 
image13
 
Then the profile form opens. In the When does this rule apply? - Select required ones , if not sure then select all. Click Next.
 
image14
  
Give this Firewall rule a Name and Description, so you know for what purpose you created this. Then click finish.
 
image15
 
Now if you share the link we created earlier with someone else on your LAN it should open your website.
 
Link example: http://192.168.0.24:7500/

Tuesday, 20 September 2016

AngularJS

AngularJS
                                               
v  AngularJS is a JavaScript framework.
v  It is Used in SPA (Single Page Application) Projects
v  AngularJS is Open Source. 
v  AngularJS is a structural framework for dynamic web apps.
v  It is a library written in JavaScript.
v  It can be added to an HTML Page with a <script> tag.
v  Use data-ng- instead of ng-
v  AngularJS version 1.0 was released in 2012.
Library
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
AngularJS extends HTML with ng-directives.
v  The ng-app directive defines an AngularJS application.
v  The ng-model directive binds the value of HTML controls (input, select, text area) to application data.
v  The ng-bind directive binds application data to the HTML view.
v  The ng-init directive initializes AngularJS application variables.
v  The ng-controller directive defines the controller.
v  We can use data-ng-, instead of ng-
1. ng-app
<html ng-app=""> or <div ng-app="">
2. ng-model
<div ng-app="">
  <p>Name: <input type="text" ng-model="name"></p>
  <p>Hello {{name}} </p>
</div>
3. ng-bind
<div ng-app="">
 
<p>Name: <input type="text" ng-model="name"></p>
 
<p ng-bind="name"></p>
</div>
4. ng-init
<div ng-app="" ng-init="firstName='John'">
<p>name is <span ng-bind="firstName"></span></p></div>
OR
<div data-ng-app="" data-ng-init="firstName='John'">
<p>name is <span data-ng-bind="firstName"></span></p>
</div>
OR
<div ng-app="" ng-init="quantity=1; cost=5">
<p>Total in dollar: {{ quantity * cost }}</p>
</div>
OR  
<div ng-app="" ng-init="person={firstName:'John', lastName:'Doe'}">
<p>The name is {{ person.lastName }}</p>
</div>

5. ng-Controller

<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
Full Name: {{firstName + " " + lastName}}
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope)
{
    $scope.firstName= "John";
    $scope.lastName= "Doe";
});
</script>


6. ng-repeat
<div ng-app="" ng-init="names=['Jani','Hege','Kai']">
  <ul>
    <li ng-repeat="x in names">
      {{ x }}
    </li>
  </ul>
</div>
AngularJS Expressions
v  AngularJS expressions can be written inside double braces: {{ expression }}.
v  AngularJS expressions can also be written inside a directive: ng-bind="expression".

<div ng-app="">
 
<p>My first expression: {{ 5 + 5 }}</p>
</div>

OR

<div ng-app="" ng-init="quantity=1;cost=5">
<p>Total in dollar: {{ quantity * cost }}</p>
</div>
Arrays
<div ng-app="" ng-init="points=[1,15,19,2,40]">
<p>The third result is {{ points[2] }}</p>
</div>
AngularJS Module
var app = angular.module('myApp', []);
AngularJS Controller
app.controller('myCtrl', function($scope) {
    $scope.firstName= "John";
    $scope.lastName= "Doe";
});

OR
<div ng-app="myApp" ng-controller="personCtrl">
First Name: 
<input type="text" ng-model="firstName"><br>
Last Name: 
<input type="text" ng-model="lastName"><br>
<br>
Full Name: 
{{fullName()}}
</div>

<script>
var app = angular.module('myApp', []);
app.controller(
'personCtrl', function($scope) {
    $scope.firstName = 
"John";
    $scope.lastName = 
"Doe";
    $scope.fullName = 
function() {
        
return $scope.firstName + " " + $scope.lastName;
    };
});
</script>

Angular JS Directives

<body ng-app="myApp">
<w3-test-directive></w3-test-directive>
<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
    return {
        template : "<h1>Made by a directive!</h1>"
    };
});
</script>
</body>
Validation User Input

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<form ng-app="" name="myForm">
    Email:
    <input type="email" name="myAddress" ng-model="text">
    <span ng-show="myForm.myAddress.$error.email">Not a valid e-mail address</span>
</form>
<p>Enter your e-mail address in the input field. AngularJS will display an errormessage if the address is not an e-mail.</p>
</body>
</html>

OR


<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<style>
input.ng-invalid {
    background-color: lightblue;
}
</style>
<body>
<form ng-app="" name="myForm">
    Enter your name:
    <input name="myName" ng-model="myText" required>
</form>
<p>Edit the text field and it will get/lose classes according to the status.</p>
<p><b>Note:</b> A text field with the "required" attribute is not valid when it is empty.</p>
</body>
</html>

The ng-model directive adds/removes the following classes, according to the status of the form field:
v  ng-empty
v  ng-not-empty
v  ng-touched
v  ng-untouched
v  ng-valid
v  ng-invalid
v  ng-dirty
v  ng-pending
v  ng-pristine


CSS Class

v  ng-empty
v  ng-not-empty
v  ng-touched
v  ng-untouched
v  ng-valid
v  ng-invalid
v  ng-dirty
v  ng-pending
v  ng-pristine


AngularJS Scope
<div ng-app="myApp" ng-controller="myCtrl">
<h1>{{carname}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl'function($scope) {
    $scope.carname = "Volvo";
});
</script>

AngularJS Filters

AngularJS provides filters to transform data:
  • currency Format a number to a currency format.
  • date Format a date to a specified format.
  • filter Select a subset of items from an array.
  • json Format an object to a JSON string.
  • limitTo Limits an array/string, into a specified number of elements/characters.
  • lowercase Format a string to lower case.
  • number Format a number to a string.
  • orderBy Orders an array by an expression.
  • uppercase Format a string to upper case.

UpperCase:

<div ng-app="myApp" ng-controller="personCtrl">
<p>The name is {{ lastName | uppercase }}</p>
</div>

Ordinary:

<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
  
<li ng-repeat="x in names | orderBy:'country'">
    
{{ x.name + ', ' + x.country }}
  
</li>
</ul>
</div>