Integrate Bot Service with Website & Skype

In this section we will see how we can integrate a Bot service with websites and Skype.

Integrate Bot with WebSite

Create a Channel to connect the BotService to different components like websites, Skype.

Choose ‘All Services’ – ‘AI + Machine Learning’ then ‘Bot Service’

image001

Select ‘Bot Channel Registration’

image003

Click Create

image005

Fill the details on the screen as below

image007

Choose Auto Create AppId and password as selected. Finally click create button.

image008

Open the Resourcegroup to see the Channel created.

image009

Now select the Bot named stockbotv1 and click on Manage.

image011

This will redirect to Application Registration Portal.

image013

Click on Generate New Password and copy the new Password.

image014

Copy and Paste the ApplicationId and Password to StockBot.Bot configuration file as below.

image016

Next Republish the application

image018

 

image020

Once you deployed open the Bot Channel created and use the Test Chat option to check the channel created is working or not.

image022

Next, Click on the Channel and Get Embed Code to integrate with website. Copy the Secret Key and Embed Code and create a sample heml file and paste it.

image024

Copy the code and create a Test html file and test.

image026

Now open the webpage to Test the Bot Service integrated

image028

Step : Integrate with Skype

In this section we will see how to integrate with Skype

image029

Next Click on Add to Contacts to add to your skype account as a contact

image030

 

Advertisements
Posted in Azure

How to Deploy Bot Service to Azure

In this section we will look how to deploy a Bot Service to Azure. if you haven’t gone through the article ‘How to create a Bot Service then please go through that first. I am using the same example that we have created Stock Bot in this section.

Deploy StockBot to Azure

To deploy your Bot, the first step is to create a Production endpoint in the .bot file.

Open the StockBot.Bot file and copy the highlighted development settings and paste to add an entry for production.

image001

The updated file will look like the below.

image002

To Publish, right click on the Project file and choose Publish option

image003

This will open the below window. Click on Start button.

image004

Now select the Publish target

image005

  • Enter a unique AppName eg: StockBotAppService
  • Choose your Subscription
  • Create a Resource Group to keep all related resources of Stock Bot together. Eg: StockBotResourceGeoup
  • Choose a Hosting Plan with ‘S1’ later you can change if necessary

 Next click on Create.

image006

Now if you login to your Azure account you can see the stockbot resource group has been created.

image007

If you expand the stockbotresourcegroup you can see the resources under it

image008

Next, Publish your artifacts to the resources in the Azure. Click on Publish button

image009

What’s next? Next we will see how to integrate the Stock Bot service to Web site and Skype.

image010

Posted in Azure

Create Azure Bot Service

Open Visual Studio and select File, then New, then Project Choose Template Echo Bot

image001

In the New Project dialog, select the Bot Builder Template, name the project StockBot and click OKThe project will be created as below.

image003

Open StockBot.cs and refer OnTurnAsync method. This method will be called whenever the end-user communicates with the BotService

 

image004

The Stock Bot will ask user to enter the Ticker of Stock to show the stock details. To achieve it add a Service call to get the Stock details. For this example I have created a Web API Service using ASP.NET Core 2.2 and hosted in Azure. The below code will consume the Service and return the Stock Details for the Ticker. How to create a WebAPI and Host in Azure will be provided in a different DIY article in my Blog.

image006

Make the below change to OnTaskAsync Method. This will prompt the user to enter the Ticket of Stock

image008

Test the StockBot locally using Emulator. If not installed Bot Framework Emulator v4 (latest version available as of now!)

image010

Open the Emulator and choose the StockBot.bot file from the Project folder path as showed below.

image011

Open the StockBot.bot file.

image013

Leave the Microsoft App Id and Microsoft App Password blank and click Connect. The Emulator will show a screen as showed below.

image014

Enter the Ticker of your stock. Eg: AAPL

image016

StockBot prompts user to enter next TickerFurther you can enter multiple Ticker to test the Bot service.

image018

What’s Next? Deploy StockBot to Azure and integrate to Website and Skype.

 

Posted in Azure

Database Backups – Full vs Differential vs Incremental

dbbackup10-png

This article mainly discuss about the differences between Full Database Backup, Differential  and Incremental Database Backup.

Choose the right backup method

Here is a quick summary of the most common backup methods available:

Full Backup captures your entire system and all the data you want to protect. Frequent full backups result in easier recovery operations.

  • Pros: Fast, reliable recovery
  • Cons: Slower backup, lots of storage required

Incremental Backup captures only the changes made since the last incremental backup. Saves both time and storage space, and ensures that your backup is up to date.

  • Pros: Fast backups, low storage space
  • Cons: Slower recovery, risk of data loss

Differential Backup captures only the changes made since the last full backup, not since the last differential backup. This requires more storage space, but ensures an easier, more reliable restore. Many organizations struggle with incremental vs. differential backup solutions.

  • Pros: Fast backups, low storage space
  • Cons: Slower recovery

Where To Store DB Backup’s?

Once you’ve created a backup, where is the best place to store it safely? Here are the most common options:

External Hard Drive

  • Portable and comparatively less expensive
  • Widely used storage media

Cloud Storage

  • Secure offsite storage
  • Files remain safe & accessible at any time
  • Most reliable & convenient for business data

Network Attached Storage (NAS)

  • Uses NAS device
  • Accessible from anywhere on your network

Let’s See How to Do it

Phase I: DB Backup

The following DB script shows creating a Database named ‘Abraham DB’ and further creating Table and Rows in it. During each stage we take the DB Backups to understand how it can do and how to restore when it is required.

CREATE DATABASE AbrahamDB
 GO
 USE AbrahamDB
 GO
 CREATE TABLE Table1 (id INT, name varchar(250))
 GO
 BACKUP DATABASE AbrahamDB TO DISK = 'C:\Temp\DBBackUp\FULL_Backup1.bak'
 GO
 INSERT INTO Table1 VALUES (1,'A')
 GO
 BACKUP DATABASE AbrahamDB TO DISK = 'C:\Temp\DBBackUp\DIFF_Backup1.bak' WITH DIFFERENTIAL
 GO
 INSERT INTO Table1 VALUES (2,'B')
 GO
 BACKUP DATABASE AbrahamDB TO DISK = 'C:\Temp\DBBackUp\DIFF_Backup2.bak' WITH DIFFERENTIAL
 GO
 INSERT INTO Table1 VALUES (3,'C')
 GO
 BACKUP DATABASE AbrahamDB TO DISK = 'C:\Temp\DBBackUp\FULL_Backup2.bak'
 GO
 INSERT INTO Table1 VALUES (4,'D')
 GO
 BACKUP DATABASE AbrahamDB TO DISK = 'C:\Temp\DBBackUp\DIFF_Backup3.bak' WITH DIFFERENTIAL
 GO

DBBackup.png

Let us analyze the results,

DBBackup1.png

The different stages of Backup are showed below:

DBBackup3.png

Phase II: DB Restore

I hope so far it is clear to understand. Now we will try to Restore this DB from the  different stages we took the Backups before.

USE MASTER
 GO
 RESTORE DATABASE AbrahamDB FROM DISK = 'C:\Temp\DBBackUp\FULL_Backup1.bak' WITH NORECOVERY
 GO
 RESTORE DATABASE AbrahamDB FROM DISK = 'C:\Temp\DBBackUp\DIFF_Backup1.bak' WITH NORECOVERY
 GO
 RESTORE DATABASE AbrahamDB FROM DISK = 'C:\Temp\DBBackUp\DIFF_Backup2.bak' WITH NORECOVERY
 GO

The output would be the below:

DBBackup5.png

The reason because the last Restore Database command should use WITH RECOVERY instead of WITH NORECOVERY

Re-running the same with last command as WITH RECOVERY and the output would be

USE MASTER
 GO
 RESTORE DATABASE AbrahamDB FROM DISK = 'C:\Temp\DBBackUp\FULL_Backup1.bak' WITH NORECOVERY
 GO
 RESTORE DATABASE AbrahamDB FROM DISK = 'C:\Temp\DBBackUp\DIFF_Backup1.bak' WITH NORECOVERY
 GO
 RESTORE DATABASE AbrahamDB FROM DISK = 'C:\Temp\DBBackUp\DIFF_Backup2.bak' WITH RECOVERY
 GO

DBBackup4.png

Now trying to restore from the last differential backup :

USE MASTER
 GO
 RESTORE DATABASE AbrahamDB FROM DISK = 'C:\Temp\DBBackUp\FULL_Backup2.bak' WITH NORECOVERY
 GO
 RESTORE DATABASE AbrahamDB FROM DISK = 'C:\Temp\DBBackUp\DIFF_Backup3.bak' WITH RECOVERY
 GO

DBBackup6.png

Points to Remember:

  1. You need to use the Last Restore command with RECOVERY instead of NO RECOVERY
  2. You can restore the differential from the Full back of its Parent only. eg: Diff_Backup3.bak can Restore into its Parent Fullbackup i.e Full_Backup2.bak similarly DIFF_backup1.bak and DIFF_Backup2.bak can be Restored to its ParentFull backup i.e FULL_Backup1.bak only.DBBackup7.png

Hope it is clear. Happy Programming.

Posted in Azure

Azure Online Resource

Microsoft provides wide range of free resources of training in Azure, mainly through its Microsoft Virtual Academy (MVA).  There’s lot of articles for beginner, intermediate and advanced courses for people who use the technology or who design and sell Azure-inclusive solutions for customers.

For beginners in Azure may do best to start with the highly rated Microsoft Azure Fundamentals, which is the first of a four-part series. Other top-rated MVA Azure courses are Azure Active Directory Core Skills Jump Start, Azure Networking Fundamentals for IT Pros and the Microsoft Azure IaaS Deep Dive.

Microsoft has a few other resources worth checking out:

  • Microsoft Learning: This site gives you the scoop on both free training (the same courses you take through MVA) and paid training. You also get links to related certification exams.
  • Channel 9: Since 2004, Channel 9 has been a go-to place for Microsoft customers to view videos and webcasts, discuss issues, problems and emerging technology in the forums and generally learn about Microsoft technologies.
  • Microsoft Cloud Platform University Online (CPO): This massive open online course (MOOC) site is designed for sales and pre-sales staff. Each course runs for four weeks, with 1 to 2 hours of time required for course work each week.

For hands-on practice and general noodling within the Azure environment, Microsoft grants you a 30-day free trial (to use up to $200 in subscription fees). During the trial, you can provision up to 14 virtual machines or 40 SQL databases, build web and mobile apps (through the App Service Web Apps), play with big data analytics and lots more. You need a credit card and a Microsoft Account username to create a free Microsoft Azure account.

Other Resources

E-book lovers will find lots of great Microsoft Press Azure titles, free for the viewing. Just go to the Microsoft Press portion of MVA, open the menu on the left and select Microsoft Azure, and then download any of the e-books that you want. The following are a few examples of the Azure titles you’ll find on the site:

  • Microsoft Azure Essentials Migrating SQL Server Databases to Azure, Carl Raebler, June 2016
  • Enterprise Cloud Strategy, Barry Briggs and Eduardo Kassner, January 2016
  • Microsoft Azure Essentials: Azure Web Apps for Developers, Rich Rainey, June 2015

Happy Programming!

Posted in Azure

Azure vs AWS

Let us analyze the features provided by the two giants, some of them are close enough. The below table shows a high level comparison of the services provided.

Microsoft Azure Amazon Web Services (AWS)
Available Regions Azure Regions AWS Global Infrastructure
Compute Services Virtual Machines (VMs) Elastic Compute Cloud (EC2)
Cloud Services
Azure Websites and Apps
Amazon Elastic Beanstalk
Azure Visual Studio Online None
Container Support Docker Virtual Machine Extension (how to) EC2 Container Service (Preview)
Scaling Options Azure Autoscale (how to) Auto Scaling
Analytics/Hadoop Options HDInsight (Hadoop) Elastic MapReduce (EMR)
Government Services Azure Government AWS GovCloud
App/Desktop Services Azure RemoteApp Amazon WorkSpaces
Amazon AppStream
Storage Options Azure Storage (Blobs, Tables, Queues, Files) Amazon Simplge Storage (S3)
Block Storage Azure Blob Storage (how to) Amazon Elastic Block Storage (EBS)
Hybrid Cloud Storage StorSimple AWS Storage Gateway
Backup Options Azure Backup Amazon Glacier
Storage Services Azure Import Export (how to) Amazon Import / Export
Azure File Storage (how to) AWS Storage Gateway
Azure Site Recovery None
Content Delivery Network (CDN ) Azure CDN Amazon CloudFront
Database Options Azure SQL Database Amazon Relational Database Service (RDS)
Amazon Redshift
NoSQL Database Options Azure DocumentDB Amazon Dynamo DB
  Azure Managed Cache (Redis Cache) Amazon Elastic Cache
Data Orchestration Azure Data Factory AWS Data Pipeline
Networking Options Azure Virtual Network Amazon VPC
Azure ExpressRoute AWS Direct Connect
Azure Traffic Manager Amazon Route 53
Load Balancing Load Balancing for Azure (how to) Elastic  Load Balancing
Administration & Security Azure Active Directory AWS Directory Service
AWS Identity and Access Management (IAM)
Multi-Factor Authentication Azure Multi-Factor Authentication AWS Multi-Factor Authentication
Monitoring Azure Operational Insights Amazon CloudTrail
Azure Application Insights Amazon CloudWatch
Azure Event Hubs None
Azure Notification Hubs Amazon Simple Notification Service (SNS)
Azure Key Vault (Preview) AWS Key Management Service
Compliance Azure Trust Center AWS CLoudHSM
Management Services & Options Azure Resource Manager Amazon CloudFormation
API Management Azure API Management Amazon API Gateway
Automation Azure Automation AWS OpsWorks
Azure Batch
Azure Service Bus
Amazon Simple Queue Service (SQS)
Amazon Simple Workflow (SWF)
Visual Studio AWS CodeDeploy
Azure Scheduler None
Azure Search Amazon CloudSearch
Analytics Azure Stream Analytics Amazon Kinesis
Email Services Azure BizTalk Services Amazon Simple Email Services (SES)
Media Services Azure Media Services Amazon Elastic Transcoder
Amazon Mobile Analytics
Amazon Cognitor
Other Services & Integrations Azure Machine Learning (Preview) Amazon Machine Learning
Logic Apps AWS Lambda (Preview)
Service Bus AWS Config (Preview)

Tough Judgement

Its very difficult to conclude AWS or Azure is best. It may be like comparing Lamborghini vs Ferrari!! LOL. Each has its on strength but choosing the right technology is purely based on the business requirements. If you are a strong lover of Microsoft Technologies or you already working with Microsoft Tools and IDE then you have a strong pull to Microsoft Azure than AWS. Anyways the choice is purely based on the Business needs and its case to case!!.

Happy Programming!

Posted in Azure

Web-Role/Worker-Role Startup Tasks with Impersonation

In some scenarios you want to kick an exe with Administrator Account privilege in Azure VM. The following article will help you to handle such requirements.

Please note adding Startup Task with Elevated mode will run only in SYSTEM account not in Administrator Account. This below mentioned method can be followed incase you want to run Task in ADMIN account.

Executing Startup Tasks as Administrator Account

You MUST use the OnStart() method of the class that descends from RoleEntryPoint. This class is typically created for you when you add a new WebRole or WorkerRole to your Azure project.

The point is that you can not use (for some reason) batch files or executable files (and configure your Startup>Tasks section in your ServiceDefinition.csdef to execute them. Attempting to impersonate an administrator in these tasks does not throw exceptions, but if your task requires administrative privileges, it will not work. However, using the OnStart() method along with impersonation works!

WorkerRole.cs

public class WorkerRole : RoleEntryPoint
{
   public override bool OnStart()
   { 
      try
      {
           // Add code here
            using (var impersonation = new MsImpersonation("", "adminUser", "adminPassword", LogonSessionType.LOGON32_LOGON_BATCH))
            {
                // Do your impersonated work here
            }
      } 
     catch (Exception e)
      { 
       Trace.WriteLine("Exception during OnStart: " + e.ToString()); 
       //Take other action as needed. 
      } 
    return base.OnStart(); 
    }
}

The RoleEntryPoint descendant class

The code listing above shows such a class. In the overridden OnStart() method, you’ll see that I’m impersonating an administrator and then doing some work that needs administrative privileges.

Impersonating Administrator in a WorkerRole EntryPoint

The class presented below helps with impersonating a Windows user. You can see it in use in the code listing above.

But the question is, how do you get the name and password of an administrator in a Azure built Virtual Machine? Well, we use a little trick here. When you publish your project to Azure, you’ll need to “Enable Remote Desktop” for all roles in the Publish Windows Azure Application wizard (screen shot show after the code listing below).

MsImpersonation.cs

using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
using System.ComponentModel;

namespace Matlus.Security
{
    public enum LogonSessionType
    {
        LOGON32_LOGON_INTERACTIVE = 2,
        LOGON32_LOGON_NETWORK = 3,
        LOGON32_LOGON_BATCH = 4,
        LOGON32_LOGON_SERVICE = 5,
        LOGON32_LOGON_UNLOCK = 7,
         
        /// Only valid in Windows 2000 and higher
        /// 
        LOGON32_LOGON_NETWORK_CLEARTEXT = 8,
         
        /// Only valid in Windows 2000 and higher
        /// 
        LOGON32_LOGON_NEW_CREDENTIALS = 9
    }

    public enum LogonProvider
    {
        LOGON32_PROVIDER_DEFAULT = 0,
        LOGON32_PROVIDER_WINNT35 = 1,
        LOGON32_PROVIDER_WINNT40 = 2,
        LOGON32_PROVIDER_WINNT50 = 3
    }

    public enum ImpersonationLevel
    {
        SecurityAnonymous = 0,
        SecurityIdentification = 1,
        SecurityImpersonation = 2,
        SecurityDelegation = 3
    }

     
    /// This class enables Loggin On and impersonating a specific user.
    /// Assembly level attributes are required in order to use this class. These attributes
    /// are typically added in the AssemblyInfo.cs file
    /// [assembly:SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode=true)]
    /// [assembly:PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")]
    /// 
    public class MsImpersonation : IDisposable
    {
        private IntPtr tokenHandle = new IntPtr(0);
        private IntPtr dupeTokenHandle = new IntPtr(0);
        private WindowsImpersonationContext windowsImpersonationContext;

        private bool disposed;

        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
          int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern bool CloseHandle(IntPtr handle);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool DuplicateToken(IntPtr ExistingTokenHandle,
          int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);

        public MsImpersonation(string domain, string userName, string password, LogonSessionType logOnSessionType)
        {
            LogOnAndImpersonateUser(domain, userName, password, logOnSessionType);
        }

        public MsImpersonation(string domain, string userName, string password, LogonSessionType logOnSessionType, LogonProvider logonProvider)
        {
            LogOnAndImpersonateUser(domain, userName, password, logOnSessionType, logonProvider);
        }

        [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
        private void LogOnAndImpersonateUser(string domain, string userName, string password, LogonSessionType logOnSessionType)
        {
            LogOnAndImpersonateUser(domain, userName, password, logOnSessionType, LogonProvider.LOGON32_PROVIDER_DEFAULT);
        }

        [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
        private void LogOnAndImpersonateUser(string domain, string userName, string password, LogonSessionType logOnSessionType, LogonProvider logonProvider)
        {
            tokenHandle = IntPtr.Zero;
            dupeTokenHandle = IntPtr.Zero;

            RevertToSelf();

            bool returnValue = LogonUser(userName, domain, password, (int)logOnSessionType, (int)logonProvider, ref tokenHandle);
            if (!returnValue)
                throw new Win32Exception(Marshal.GetLastWin32Error());
            try
            {
                bool retVal = DuplicateToken(tokenHandle, (int)ImpersonationLevel.SecurityImpersonation, ref dupeTokenHandle);
                if (!retVal)
                {
                    CloseHandle(tokenHandle);
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
                WindowsIdentity windowsIdentity = new WindowsIdentity(dupeTokenHandle);
                windowsImpersonationContext = windowsIdentity.Impersonate();
            }
            catch
            {
                if (tokenHandle != IntPtr.Zero)
                    CloseHandle(tokenHandle);
            }
            finally
            {
                if (tokenHandle != IntPtr.Zero)
                    CloseHandle(tokenHandle);
                if (dupeTokenHandle != IntPtr.Zero)
                    CloseHandle(dupeTokenHandle);
            }
        }

        [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
        private void RevertToSelf()
        {
            if (windowsImpersonationContext != null)
            {
                windowsImpersonationContext.Undo();
                windowsImpersonationContext.Dispose();
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!disposed && disposing)
            {
                RevertToSelf();
                disposed = true;
            }
        }
    }
}

Replace the User name and Password of the Administrator account in the VM. The easy way to get this account credential is using teh same RDP credentials you use to open your VM!

Happy Programming.
Posted in Azure

Web-Role/Worker-Role Startup Tasks

In many scenarios we may need to run an exe or register a com dll in Windows Azure machine and these can be achieved by a Startup Task during Role Start. To do this we need to create a bat file or cmd with the instructions and kick-off during Role Start.

For an example we will see how to create a Startup Task for configuring IIS to enable 32bit applications/dll

Step 1: You will need to create a simple text file name startup.cmd or <desiredname>.cmd first and in this file you need to add your instruction/command which will do the job during Role Start.

Startup.cmd:%windir%\system32\inetsrv\appcmd set config -section:applicationPools -applicationPoolDefaults.enable32BitAppOnWin64:true

Note: please test this cmd in your local machine before you run in Azure VM.

Step 2: Now you can update your Window Azure Service Definition file to include start up task as below with “Elevated” permission because this  needs SYSTEM Account permission to take effect.

ServiceDefinition.csdef

<Startup>
 <Task commandLine="Startup.cmd" executionContext="Elevated" taskType="simple">
 </Task>
 </Startup>

Step 3: Now make sure that the Startup.cmd file is part of  your Web Role application and set its property “Copy Local to True” so when you publish this package, it can be the part of your package.

If you want to create Environment Variables in VM read the below article from MSDN.

Add Environment variabe using Startup Tasks

 

Happy Programming

Posted in Azure

Call Web-Service from Database

How to efficiently notify your Application when there is a change in your Database/Tables? Probable solutions you are thinking may be the SQL Dependency, Query Notification, Table Dependency or Signal-R (for notifying multiple consumers)??

In the above all scenarios whether you are aware or not polling is keep on hitting your database and monitoring the table changes. Isn’t it? sometimes the application having more visitors on the day time (citation required)  during that time polling and getting the latest changes is somewhat acceptable but how about the time when there is no visitors on your site but still the polling will hit your Database and making it busy is not acceptable. More over in Cloud  polling means it counts as Network traffic/usage cost etc. unnecessary. Right?

So how to avoid this costly hit in Azure? any workarounds?

The one option I wish to bring to your notice is Calling a WebService from DB whenever a change is made to Table. In the WebSerive you can pull the data from the Table so as to get the changes. So if you do in this way you are not making unnecessary polling and making the SQL server busy.

10.png

How to implement this? There are mainly two ways you can achieve it. Either using .NET CLR and write a SP or using TSQL and create a SP. I am going to show a sample using TSQL.

In DB I have Table named Task with TaskId, TaskName and TaskStatus as mentioned below. I want to monitor  this table and the changes needs to update in my ASP.NET Application object and shared with all visitors to show the current Tasks in progress.

Task.png

Step1 : Create a WebService/WebMethod 

[WebMethod]
 public void RefreshTasks()
 {
 List<Task> TaskList = new List<Task>();

string connectionString = "Data Source = POP1977\\SQLEXPRESS; Initial Catalog = WEBSERVICE; Integrated Security = True";
 SqlConnection con = new SqlConnection(connectionString);

SqlDataAdapter adapter = new SqlDataAdapter("Select TaskId, TaskName, TaskStatus 
From Task WITH (NO LOCK)", con);
 DataSet dsTask = new DataSet();
 adapter.Fill(dsTask, "Task");

Task task = null;
 foreach (DataRow dr in dsTask.Tables["Task"].Rows)
 {
 task = new Task();
 task.TaskId = Convert.ToString(dr["TaskId"]);
 task.TaskName = Convert.ToString(dr["TaskName"]);
 task.TaskStatus = Convert.ToString(dr["TaskStatus"]);
 TaskList.Add(task);
 }

Application.Lock();
 Application["Tasks"] = TaskList;
 Application.UnLock();
 }

public class Task
 {
 public string TaskId { get; set; }
 public string TaskName { get; set; }
 public string TaskStatus { get; set; }

}

7.png

3

Note: The Select Query needs to include WITH NO LOCK option otherwise a Dead Lock will happen during Update Trigger.

Step 2: Create a Stored Procedure (or) Trigger

To use OLEAutomation you need to enable the below in SQL server:
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
5.png
Create Procedure CallWebService 
AS

Declare @Object as Int;
Declare @ResponseText as Varchar(8000);
Declare @WebServiceUrl as varchar(max)
Set @WebServiceUrl = 'http://localhost:60711/WebService1.asmx/RefreshTasks'

--Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
Exec sp_OACreate 'MSXML2.ServerXMLHTTP', @Object OUT;
Exec sp_OAMethod @Object, 'open', NULL, 'GET', @WebServiceUrl, false
Exec sp_OAMethod @Object, 'send'
Exec sp_OAGetProperty @Object, 'responseText', @ResponseText OUT
Select @ResponseText as response
Exec sp_OADestroy @Object
RETURN

Next Create a Trigger On Table to be monitored (Task) and invoke the Stored Procedure (CallWebService). T he same can be achieved with the Trigger alone but for better understanding I have made it into SP and Trigger.

6.png
CREATE TRIGGER NOTIFY
 ON Task 
 AFTER INSERT, UPDATE,DELETE
 AS
BEGIN
 EXEC dbo.CallWebService 
END

Now Run your webservice and make a change in the Table and see the Application object is filled with the latest values from DB without continuous polling.

4.png

Now Run the Webservice and make a change in the DB table it will update the Application Object with latest values.

8.png

Happy Programming.!

Posted in Azure

Azure VM – Configure IIS and Expose

After setting up VM the next important thing you may need to do is Enabling the IIS in Windows Server and provision it in Azure Portal to access it from anywhere.

This article will help you to achieve it.

Enable IIS in VM Server

The below screen shots will help you to configure IIS in VM Server.

1.png

2.png

 

3.png

4.png

5.png

6.png

7.png

8.png

9.png

10.png

11.png

12.png

13.png

Installing IIS Features on Windows 7

The following are the steps to install IIS including HTTP activation in VM Server

  1. On the Start menu, choose Control Panel, and then choose Programs.
  2. Under Programs and Features, choose Turn Windows features on or off.
  3. In the Windows features list, expand Internet Information Services, and then expand World Wide Web Services.
  4. Expand Application Development Features, and select the following features:
    • .NET Extensibility
    • ASP.NET
    • ISAPI Extensions
    • ISAPI Filters
  5. Expand Security, and then select the following features:
    • Request Filtering
    • Windows Authentication
  6. Expand Common HTTP Features, and then select the Static Content feature.
  7. To install Internet Information Service (IIS) Manager, under Internet Information Services, expand Web Management Tools, and then selectIIS Management Console.This step is optional. You use Internet Information Service IIS Manager to manage local and remote web servers and sites.
  8. Choose the OK button to complete the installation.
  9. In the Windows features list, expand Microsoft .NET Framework, and then select Windows Communication Foundation HTTP Activation.
  10. To verify that the web server has been installed correctly, start your browser, and then type http://localhost in the address.The default web site opens and should display an IIS 7 image. If the IIS 7 image does not appear, then verify that you have configured static content on IIS, as described in step 6.

After configuring IIS in VM the next challenge would be to access the hosted sites in IIS from outside of VM.

Login to new Azure portal and choose VM

NewVM

There are 2 options to create a new port either using an existing ‘Network Security Group’ and add an In-Bound Rule or create a new ‘Network Security Group’ and add new rule into it.

For creating a new rule choose Add +New option from portal as showed below.

NewResourceGroup.png

After creating new ‘Network Security Group’ you need to create an Inbound Rule.ResourcrGroup2.png

Choose Inbound Security Rules from Settings and fill new port value as showed below:

14.png

Choose  Protocol TCP and enter Destination Port as 80 and Save

15.png

Click Save.

16.png

Now you have created the HTTP default port 80 allowing to VM as inbound rule.

Happy Programming

 

Posted in Azure