Thursday 7 September 2017

Message Broadcast using google Api. in asp.net. (firebase Push Notification on Mobile)

   public void Test(string tokenid,string messagebody,string messgaetitle)
    {
        try
        {
//This applicationid and senderid comes from mobile developer. this comes from www.console.firebase.google.com
            var applicationID = "AAAAuSEmjuQ:APA91bFewTUFbEwbHOH7-W2Cvl5a6LXDMjHp7grlv2aBBzlCS0gwgRFir3a29hNdkmqMPTjVfk8FI_px973BPs_XfO6WjsLmEDKR2FgFjQUcF6Q75uX4oYvqIBgZAT-zX7rBqD9jVO2F";
            var senderId = "795125124836";

//This device id from Database when A app install automettically his device id has post ourdatabase.
            string deviceId = tokenid;
            WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
            tRequest.Method = "post";
            tRequest.ContentType = "application/json";
            var data = new
            {
                to = deviceId,
                notification = new
                {
                    body = messgaetitle,
                    title = messagebody,
                    icon = "myicon"
                },
                priority = "high"

            };

            var serializer = new JavaScriptSerializer();
            var json = serializer.Serialize(data);
            Byte[] byteArray = Encoding.UTF8.GetBytes(json);
            tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
            tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
            tRequest.ContentLength = byteArray.Length;

            using (Stream dataStream = tRequest.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);

                using (WebResponse tResponse = tRequest.GetResponse())
                {
                    using (Stream dataStreamResponse = tResponse.GetResponseStream())
                    {
                        using (StreamReader tReader = new StreamReader(dataStreamResponse))
                        {
                            String sResponseFromServer = tReader.ReadToEnd();
                            Response.Write(sResponseFromServer);
                            txtdepartmentname.Text = sResponseFromServer;
                        }
                    }
                }
            }
        }

        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
=========================================
 protected void BtnSave_Click(object sender, EventArgs e)
    {
if (e.CommandName == "btnsend")
        {
            for (int i = 0; i < Griddepartment.Items.Count; i++)
            {
                int ID = Convert.ToInt32(((RadLabel)Griddepartment.Items[i].FindControl("lblattributeid")).Text);
                string msgbody = ((RadLabel)Griddepartment.Items[i].FindControl("lblattributename")).Text;
                string msgtitle = ((RadLabel)Griddepartment.Items[i].FindControl("lblcontrolname")).Text;
                RadCheckBox chksend = (RadCheckBox)Griddepartment.Items[i].FindControl("chksend");
                if (chksend.Checked == true)
                {
                    var tokens = GetallTokens().ToList();
                    foreach (var ss in tokens)
                    {
                        Test(ss.RegistartionToken_DeviceID, msgbody, msgtitle);
                        n1.Text = "Message Send Successfully";
                        n1.Show();
                    }
                }
            }
        }
}


Saturday 2 September 2017

Azure API Management with Swagger With Subscription Key Management and token Management from Publisher Portal and Developer Portal


  1. Develop APIs. Add and publish an API Product. Add operations. ...
  2. Secure your backend. Protect Web API backend with AAD. Connect to a virtual network. ...
  3. Configure Policies. Custom caching. Advanced monitoring. ...
  4. Customize the developer experience. Modify page content and layout. ...
  5. Manage in production. Deploy to multiple Azure regions.

Creating Azure WebApi with Swagger.

First create  WebApplication add Azure Api App Template and Select MVC.
Click OK.

Open URL https://www.nuget.org/packages/Swashbuckle to get new Swashbuckle
To install Swashbuckle - Swagger for WebApi, run the following command in the Package Manager Console
PM > Install-Package Swashbuckle -Version 5.5.3
Open SwaggerConfig.cs from App_start-> SwaggerConfig.cs.
Un comment the bellow line
//c.IncludeXmlComments(GetXmlCommentsPath());
And Replace GetXmlCommentsPath() with the following
c.IncludeXmlComments(string.Format(@"0}\bin\AzureApiSwagger.XML",System.AppDomain.CurrentDomain.BaseDirectory));

Go to the application properties -> Build -> check “XML documentation file, copy the provided path from the text box and REPLACE. AND SAVE.

Go to global.asx page and comment the following

//RouteConfig.RegisterRoutes(RouteTable.Routes);
And save

Next Go to Web Api application
1.    Add Install-Package Microsoft.AspNet.WebApi.HelpPage
2.    for Help Page which is on

Next Add Install-Package WebApiTestClient   for Designing Test API

For Unit Resolver You add This thing
Install-Package Unity -Version 2.1.505.2

Create an API Management instance

Note
To complete this tutorial, you need an Azure account. If you don't have an account, you can create a free account in just a couple of minutes. For details, see Azure Free Trial.
The first step in working with API Management is to create a service instance. Sign in to the Azure Portal and click NewWeb + MobileAPI Management.
API Management new instance
For Name, specify a unique sub-domain name to use for the service URL.
Choose the desired SubscriptionResource group and Location for your service instance.
Enter Contoso Ltd. for the Organization Name, and enter your email address in the Administrator E-Mail field.
Note
This email address is used for notifications from the API Management system. For more information, see How to configure notifications and email templates in Azure API Management.
New API Management service
API Management service instances are available in three tiers: Developer, Standard, and Premium.
Note
The Developer Tier is for development, testing, and pilot API programs where high availability is not a concern. In the Standard and Premium tiers, you can scale your reserved unit count to handle more traffic. The Standard and Premium tiers provide your API Management service with the most processing power and performance. You can complete this tutorial by using any tier. For more information about API Management tiers, see API Management pricing.
Click Create to start provisioning your service instance.
New API Management service
Once the service instance is created, the next step is to create or import an API.

Import an API

An API consists of a set of operations that can be invoked from a client application. API operations are proxied to existing web services.
APIs can be created (and operations can be added) manually, or they can be imported. In this tutorial, we will import the API for a sample calculator web service provided by Microsoft and hosted on Azure.
Note
For guidance on creating an API and manually adding operations, see How to create APIs and How to add operations to an API.
APIs are configured from the publisher portal. To reach it, click Publisher portal from the service toolbar.
Publisher portal
To import the calculator API, click APIs from the API Management menu on the left, and then click Import API.
Import API button
Perform the following steps to configure the calculator API:
  1. Click From URL, enter http://calcapi.cloudapp.net/calcapi.json into the Specification document URL text box, and click the Swagger radio button.
  2. Type calc into the Web API URL suffix text box.
  3. Click in the Products (optional) box and choose Starter.
  4. Click Save to import the API.
 OR YOU CAN ADD JSON FILE FROM YOUR LOCAL

Run your Api on Internet Explorer . And Save Jshon File. And Uplaod it.
Add new API
Note
API Management currently supports both 1.2 and 2.0 version of Swagger document for import. Make sure that, even though Swagger 2.0 specification declares that hostbasePath, and schemesproperties are optional, your Swagger 2.0 document MUST contain those properties; otherwise it won't get imported.
Once the API is imported, the summary page for the API is displayed in the publisher portal.
API summary
The API section has several tabs. The Summary tab displays basic metrics and information about the API. The Settings tab is used to view and edit the configuration for an API. The Operations tab is used to manage the API's operations. The Security tab can be used to configure gateway authentication for the backend server by using Basic authentication or mutual certificate authentication, and to configure user authorization by using OAuth 2.0. The Issues tab is used to view issues reported by the developers who are using your APIs. The Products tab is used to configure the products that contain this API.1
By default, each API Management instance comes with two sample products:
  • Starter
  • Unlimited
In this tutorial, the Basic Calculator API was added to the Starter product when the API was imported.
In order to make calls to an API, developers must first subscribe to a product that gives them access to it. Developers can subscribe to products in the developer portal, or administrators can subscribe developers to products in the publisher portal. You are an administrator since you created the API Management instance in the previous steps in the tutorial, so you are already subscribed to every product by default.

Call an operation from the developer portal

Operations can be called directly from the developer portal, which provides a convenient way to view and test the operations of an API. In this tutorial step, you will call the Basic Calculator API's Add two integers operation. Click Developer portal from the menu at the top right of the publisher portal.
Developer portal
Click APIs from the top menu, and then click Basic Calculator to see the available operations.
Developer portal
Note the sample descriptions and parameters that were imported along with the API and operations, providing documentation for the developers that will use this operation. These descriptions can also be added when operations are added manually.
To call the Add two integers operation, click Try it.
Try it
You can enter some values for the parameters or keep the defaults, and then click Send.
HTTP Get
After an operation is invoked, the developer portal displays the Response status, the Response headers, and any Response content.
Response

View analytics

To view analytics for Basic Calculator, switch back to the publisher portal by selecting Managefrom the menu at the top right of the developer portal.
Manage
The default view for the publisher portal is the Dashboard, which provides an overview of your API Management instance.
Dashboard
Hover the mouse over the chart for Basic Calculator to see the specific metrics for the usage of the API for a given time period.
Note
If you don't see any lines on your chart, switch back to the developer portal and make some calls into the API, wait a few moments, and then come back to the dashboard.
Click View Details to view the summary page for the API, including a larger version of the displayed metrics.
Analytics
Summary
For detailed metrics and reports, click Analytics from the API Management menu on the left.
Overview


Main Thing is Create Policy
For API Security Reason You add below line in your Web API config
 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.Filters.Add(new UseApiManagementAttributes());
            // Web API routes
            config.MapHttpAttributeRoutes();
            
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
==============================
Next Step you add a folder which name is Filters on Api. and add a class name UseApiManagementAttributes.
And add below code
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Net.Http;
using System.Globalization;
using System.Net;

namespace API.Filters
{
    public class UseApiManagementAttributes:ActionFilterAttribute
    {
        #region Methods
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var configkey = ConfigurationManager.AppSettings["Api.Key"];
            IEnumerable<string> Keys = null;
            var error = false;
            var checkKey = true;
            if(String.IsNullOrEmpty(configkey))
            {
                error = true;
            }
            else
            {
                if (actionContext.Request.Headers.Contains("Ocp-Apim-Subscription-Key"))
                {
                    //Seems like we are called from Azure API Management here.Be aware that this code is anythng.
                    //but secure. It simple assume that Ocp-Apim-Subscription-Key and User-Agent are present in the header
                    //This is Because of the lack of certificate in current azure portal.
                    error = !actionContext.Request.Headers.TryGetValues("Ocp-Apim-Subscription-Key", out Keys) || Keys.Any();
                    if(!error)
                    {
                        //if the magic Apim-key is present check now, if the agent is correct.
                        var agent = string.Empty;
                        var agents = actionContext.Request.Headers.GetValues("User-Agent");
                        error=!agent.Any() || !agents.First().Equals("EMA-Gateway",StringComparison.OrdinalIgnoreCase);
                    }
                    //We don't need to check the key because it is managed by API Management.
                    checkKey = false;
                }
                else if(actionContext.Request.Headers.Contains("api_Key"))
                {
                    //This could be valid APi call using a static secerate API from request.
                    error=!actionContext.Request.Headers.TryGetValues("api_Key",out Keys)||!Keys.Any();
                }
                else if(actionContext.Request.RequestUri.ParseQueryString().HasKeys() && actionContext.Request.RequestUri.ParseQueryString().HasKeys())
                {
                    //This could be a valid API call a static API key from URL like swagger case.
                    Keys = new[] { actionContext.Request.RequestUri.ParseQueryString().Get("api_Key") };
                }
                else
                {
                    error = true;
                }
            }
            if(!error && checkKey && !Keys.First().Equals(configkey,StringComparison.Ordinal))
            {
                error = true;
            }
            if(error)
            {
                var message = string.Format(CultureInfo.InvariantCulture, "Request are only allocated using the api management URLS.");
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.UseProxy, message);
                return;
            }
            base.OnActionExecuting(actionContext);
        }

        #endregion

    }
}
===================
Set on API Web Config Below Code
<appSettings>
    <add key="Api.Key" value="1234" />
  </appSettings>
===========================
Next When you call api on your Project Below code Example
===========================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class APITEST : System.Web.UI.Page
{
    HttpClient client = new HttpClient();
    List<Department> DepartmentList = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "dbe20779b9ce47cab9e60c132da99e82");
        var path = "https://swashapimanagementservice.azure-api.net/Trinty/api/Department";
        //  var appsurl = ConfigurationManager.AppSettings["APIPath"].ToString();
        client.BaseAddress = new Uri(path);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        GetData();
    }

    private List<Department> GetData()
    {
        HttpResponseMessage skill = client.GetAsync("Department").Result;
        if (skill.IsSuccessStatusCode)
        {
            DepartmentList = skill.Content.ReadAsAsync<List<Department>>().Result;
            return DepartmentList.Where(a => a.IsActive == true).OrderByDescending(a => a.Department_ID).ToList();

        }
        else
        {
            return null;
        }
    }
}