how to do push notification to i-pad on windows azure - asp.net-mvc-4

I have a MVC Web API Project & I need to send push notification to iPad. I have used .cer and .p12 files for this & it is working fine. Now I need to publish it to an azure server but I'm a newbie to azure and don't know where to store and how to access the certificate.
I have tried to upload certificate to the cloud service, but am not able to access it.
I am using the following code:
string strDeviceToken = "abcd";
string strPushMessage = "hello";
var payload1 = new NotificationPayload(strDeviceToken, strPushMessage, 1, "default");
payload1.AddCustom("RegionID", "IDQ10150");
var p = new List<NotificationPayload> { payload1 };
var push = new PushNotification(true, certificatePath, "password");
string strfilename = push.P12File;
var message1 = push.SendToApple(p);

hi i am using this code and its work
for http://www.c-sharpcorner.com/UploadFile/pandeypradip/apple-push-notification-using-Asp-Net/
Attech Dll above link
string strDeviceToken ="xyz"
string strPushMessage="test"
payload1.AddCustom("RegionID", "IDQ10150");
var p = new List { payload1 };
string certificatePath = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/certificates/xyz.p12");
var push = new PushNotification(true, certificatePath, "password");
string strfilename = push.P12File;
var message1 = push.SendToApple(p);

Related

get report G Suite account

I'm trying to get google report activity by calling https://www.googleapis.com/admin/reports/v1/activity/users/all/applications/meet
I created a service account and I have to use the generated private key (json file) as access token.
My code was:
String PROTECTED_RESOURCE_URL = "https://www.googleapis.com/admin/reports/v1/activity/users/all/applications/meet?eventName=call_ended&maxResults=10&access_token=";
String graph = "";
try
{
JSONParser parser = new JSONParser();
JSONObject data = (JSONObject) parser.parse(
new FileReader("C:/Users/Administrateur/Desktop/GoogleApis/Interoperability-googleApis/target/classes/my-first-project-274515-361633451f1c.json"));//path to the JSON file.
String json_private_key = data.toJSONString();
URL urUserInfo = new URL(PROTECTED_RESOURCE_URL + json_private_key);
HttpURLConnection connObtainUserInfo = (HttpURLConnection) urUserInfo.openConnection();
if (connObtainUserInfo.getResponseCode() == HttpURLConnection.HTTP_OK)
{
StringBuilder sbLines = new StringBuilder("");
BufferedReader reader = new BufferedReader(new InputStreamReader(connObtainUserInfo.getInputStream(), "utf-8"));
String strLine = "";
while ((strLine = reader.readLine()) != null)
{
sbLines.append(strLine);
}
graph = sbLines.toString();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
System.out.println("--------------- Result: " + graph);
but I got null value.
Could you please tell me what I misses ?.
Big Thanks.
The Access Token is not part of your request URL. You can read here about the OAuth2 protocol and how it works.
However, Google built an API that enables you to authenticate your requests without worrying about the underlying OAuth2 process.
You should be using the Java Google Reports API to access activities. Here you can find the Java Quickstart that will help you with the first set up of your Java Application.
Here the Java translation of what you are trying to do, using the Google Reports API:
Reports service = new Reports.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
String userKey = "all";
String applicationName = "meet";
String eventName = "call_ended";
Activities result = service.activities().list(userKey, applicationName)
.setEventName(eventName)
.setMaxResults(10)
.execute();
Edit:
Be sure to use the last version of the Java API package. You can find the Java API docs here: https://developers.google.com/resources/api-libraries/documentation/admin/reports_v1/java/latest/
If you are using Gradle be sure to have this line in the dependencies parameter.
dependencies {
...
compile 'com.google.apis:google-api-services-admin-reports:reports_v1-rev89-1.25.0'
}
References
OAuth2
Google Reports API

Dialogflow .NET core, C# - detect intent not working

I want to invoke DetectIntent programatically.
I am using Google.Cloud.Dialogflow.V2 - Client libraries.
using Google.Cloud.Dialogflow.V2;
var query = new QueryInput
{
Text = new TextInput
{
Text = text,
LanguageCode = "en-us"
}
};
var sessionId = "1234567890";
var agent = "myAgentName";
var creds = GoogleCredential.FromFile("JSONFileName");
Channel channel = new Channel(
SessionsClient.DefaultEndpoint.Host, SessionsClient.DefaultEndpoint.Port, creds.ToChannelCredentials());
var client = SessionsClient.Create(channel);
DetectIntentRequest request = new DetectIntentRequest
{
SessionAsSessionName = new SessionName("smartresort-facebook-bot-fgvjh", "1111"),
QueryInput = query,
};
DetectIntentResponse response = client.DetectIntent(request);
With above code I am getting error as below
I am already using same JSON file in node js code and it is working fine. So in nodejs detect intent code is working fine. I am trying to do the same in .NET core.
After this I have tried another code snippet.
var client = SessionsClient.Create();
var response = client.DetectIntent(
session: new SessionName("smartresort-facebook-bot-fgvjh", "1234567890"),
queryInput: new QueryInput()
{
Text = new TextInput()
{
Text = text,
LanguageCode = "en-us"
}
}
);
I am not trying to write fulfillment which would be called after the intent is detected. I am trying to write the code before intent is detected. So I want to give a call to detect intent and then process the response based on which intent is detected.
Check my answer here, It is an example on how to integrate Dialogflow with .Net Core based on a working sample. If you still have more questions let me know and I will be happy to help!

Azure AD/Token/Certificates/SQL - I'm lost

I started a company 3 months ago and there is no software (CRM+other business tasks) that meets my needs. Reluctantly I decided to write my own 2 months ago and it is now 80% complete! I've been pointed here to Stack Overflow throughout my journey many times and you guys have been a great help -- first and foremost thank you! I've been able to stay quiet until now...
The problem:
I have connection strings all over the place with SQL Authentication username/password exposed. My business partner is across the country so I need to give him access and open a port etc. I've made the move to Microsoft Azure (all setup with a VPN gateway, VM's are running and linked with Azure AD) to lockdown the environment a bit. I'd like to take full advantage of what it offers and use Active Directory for authentication on login (MFA) and then use the token in my query strings removing the need for a hard coded connection string with username/passwords...
I've done a lot of research and it seems I can accomplish what I want but I can't quite figure it out.
App is written in VB.net and most Microsoft docs on the topic are in C#, requiring edits to the app.xaml.cs file which doesn't exist in vb.net, and even if I got around that piece i'm not sure how to configure the sql connection strings to use the token.
Once I get this out of the way I can get back to finishing the software so I can get on the phone and help us take off before the money runs out! Your help is greatly appreciated!
EDIT :
I'm going this route because from what I've found, I can't use Authentication = Active Directory Integrated in my sql string because my AD is not federated (no on-premise ADFS), Active Directory Password still requires the sql admin setup in Azure to be in the sql string. I looked at key vaults which while doing research led me to registering my app which seems to be exactly what I want and where my questions is derived. Microsoft provides a great example downloadable project but again its in C#...If there is a recommendation on a different option i'm all ears...
EDIT 9/3/19 -- A lot of circling and research...I need to convert this code from c# to vb.net. More information on what the below is and how it is broken down from its creator : https://colinsalmcorner.com/post/configuring-aad-authentication-to-azure-sql-databases
public async Task<string> GetAccessTokenAsync(string clientId, string clientSecret, string authority, string resource, string scope)
{
var authContext = new AuthenticationContext(authority, TokenCache.DefaultShared);
var clientCred = new ClientCredential(clientId, clientSecret); << CAN I MAKE THESE (ClientId, ClientSecret) TIED TO TEXTBOXES FOR USERNAME/PASSWORD ON MY APPLICATION?
var result = await authContext.AcquireTokenAsync(resource, clientCred);
if (result == null)
{
throw new InvalidOperationException("Could not get token");
}
return result.AccessToken; <<WHAT DOES RETURN DO HERE?
}
AND
public async Task<SqlConnection> GetSqlConnectionAsync(string tenantId, string clientId, string clientSecret, string dbServer, string dbName)
{
var authority = string.Format("https://login.windows.net/{0}", tenantId);
var resource = "https://database.windows.net/";
var scope = "";
var token = await GetTokenAsync(clientId, clientSecret, authority, resource, scope);
var builder = new SqlConnectionStringBuilder();
builder["Data Source"] = $"{dbServer}.database.windows.net";
builder["Initial Catalog"] = dbName;
builder["Connect Timeout"] = 30;
builder["Persist Security Info"] = false;
builder["TrustServerCertificate"] = false;
builder["Encrypt"] = true;
builder["MultipleActiveResultSets"] = false;
var con = new SqlConnection(builder.ToString());
con.AccessToken = token;
return con;
}
I can understand that you want to use Azure AD access token to connect to Azure SQL DB. Based on the docs you provided and my own research , for now, we can use Azure AD service principle to get access token to connect to Azure SQL only.
I believe you have did some research on it already and find the codes to implement it using C# SDK. However there is no VB.net code sample to do it which confused you .
Honestly , I am not so familiar with VB.net , but I still implemented a demo to do that for you , pls refer to the code below :
Imports System.IO
Imports System.Net
Imports System.Text
Module Module1
Sub Main()
Dim tenant = ""
Dim client_id = ""
Dim username = ""
Dim password = ""
Dim client_secret = ""
Dim sqlserverName = ""
Dim dbname = ""
Dim dbConn = New SqlClient.SqlConnection
dbConn.ConnectionString = "Data Source=" + sqlserverName + ".database.windows.net;Initial Catalog=" + dbname + ";Connect Timeout=30"
dbConn.AccessToken = getAccessToken(tenant, client_id, client_secret, username, password)
Console.WriteLine("User: " + username)
Console.WriteLine("access token value:" + dbConn.AccessToken)
dbConn.Open()
Dim sqlQuery = "select ##version"
Dim Result = New SqlClient.SqlCommand(sqlQuery, dbConn).ExecuteScalar()
Console.WriteLine("query result from Azure SQL : " + Result.ToString)
Console.ReadKey()
End Sub
Function getAccessToken(tenant, client_id, client_secret, username, password) As String
Dim request As HttpWebRequest
request = HttpWebRequest.Create("https://login.microsoftonline.com/" + tenant + "/oauth2/token")
request.Method = "POST"
request.ContentType = "application/x-www-form-urlencoded"
Dim requestBody =
"grant_type=client_credentials" +
"&client_id=" + client_id +
"&client_secret=" + WebUtility.UrlEncode(client_secret) +
"&username=" + WebUtility.UrlEncode(username) +
"&password=" + WebUtility.UrlDecode(password) +
"&resource=https%3A%2F%2Fdatabase.windows.net%2F"
Dim encoding As New UTF8Encoding
Dim byteData As Byte() = encoding.GetBytes(requestBody)
request.ContentLength = byteData.Length
Dim postreqstream As Stream = request.GetRequestStream()
postreqstream.Write(byteData, 0, byteData.Length)
postreqstream.Close()
Dim result = request.GetResponseAsync().GetAwaiter().GetResult()
Dim result_str = New StreamReader(result.GetResponseStream()).ReadToEnd
Dim tokenResp As TokenResponse = Newtonsoft.Json.JsonConvert.DeserializeObject(Of TokenResponse)(result_str)
Return tokenResp.access_token
End Function
Public Class TokenResponse
Public Property token_type As String
Public Property expires_in As String
Public Property ext_expires_in As String
Public Property expires_on As String
Public Property not_before As String
Public Property resource As String
Public Property access_token As String
End Class
End Module
Pls refer to the steps below to create associated Azure AD apps and fill all params to run it :
Creating a Azure AD app in your tenant ,type its name and click register directly, in my case , the app name is DBadmin:
Note its application ID :
Creating a client secret for this app and note the secret :
Adding Azure SQL user login permission to this app :
Grant permission as an admin:
Go to "Groups" blade ,create an Azure AD group , adding the app we just created at same time :
Go to the Azure SQL server that you want to access , and adding the group we just created in to Azure AD admin of SQL server :
Remember to click save after adding .
Ok, we have done all configs here , just modify the params in code to try to connect to your Azure SQL .
Code result :
Hope it helps . Anyway If you just want to hide connection string in your config file.Key vault should be the best choice for you .

PDF generation in mvc4 with itextsharp

I am working on pdf generation, it is successfully implemented using itextsharp.dll. It’s working fine on local environment after publish also. We have our own server at other site
But same code doesn't work on the server,pdf is not generated instead it gives an error: 'The document has no pages.'
Initially I thought it is due to no data in document but it works locally with or without data in the document.
I had code implemented as follows to make a web request Is any problem in that ??
try
{
var myHttpWebRequest = (HttpWebRequest)WebRequest.Create(strPdfData + "?objpatId=" + patID);
var response = myHttpWebRequest.GetResponse();
myHttpWebRequest.Timeout = 900000;
var stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
content = sr.ReadToEnd();
}
create a method in the controller:
[HttpGet]
public JsonResult GetFile()
{
var json = new WebClient().DownloadFile(string address, string fileName);
//This code is just to convert the file to json you can keep it in file format and send to the view
dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
var oc = Newtonsoft.Json.JsonConvert.DeserializeObject<countdata[]>(Convert.ToString(result.countdata));
return Json(oc, JsonRequestBehavior.AllowGet);
}
In the view just call this function:
#Url.Action('genPDF','GetFile');

Windows Azure UploadFromStream No Longer Works After Porting to MVC4 - Pointers?

Updated my MVC3/.Net 4.5/Azure solution to MVC4.
My code for uploading an image to blob storage appears to fail each time in the upgraded MVC4 solution. However, when I run my MVC3 solution works fine. Code that does the uploading, in a DLL, has not changed.
I’ve uploaded the same image file in the MVC3 and MVC4 solution. I’ve inspected in the stream and it appears to be fine. In both instance I am running the code locally on my machine and my connections point to blob storage in cloud.
Any pointers for debugging? Any known issues that I may not be aware of when upgrading to MVC4?
Here is my upload code:
public string AddImage(string pathName, string fileName, Stream image)
{
var client = _storageAccount.CreateCloudBlobClient();
client.RetryPolicy = RetryPolicies.Retry(3, TimeSpan.FromSeconds(5));
var container = client.GetContainerReference(AzureStorageNames.ImagesBlobContainerName);
image.Seek(0, SeekOrigin.Begin);
var blob = container.GetBlobReference(Path.Combine(pathName, fileName));
blob.Properties.ContentType = "image/jpeg";
blob.UploadFromStream(image);
return blob.Uri.ToString();
}
I managed to fix it. For some reason reading the stream directly from the HttpPostFileBase wasn't working. Simply copy it into a new memorystream solved it.
My code
public string StoreImage(string album, HttpPostedFileBase image)
{
var blobStorage = storageAccount.CreateCloudBlobClient();
var container = blobStorage.GetContainerReference("containerName");
if (container.CreateIfNotExist())
{
// configure container for public access
var permissions = container.GetPermissions();
permissions.PublicAccess = BlobContainerPublicAccessType.Container;
container.SetPermissions(permissions);
}
string uniqueBlobName = string.Format("{0}{1}", Guid.NewGuid().ToString(), Path.GetExtension(image.FileName)).ToLowerInvariant();
CloudBlockBlob blob = container.GetBlockBlobReference(uniqueBlobName);
blob.Properties.ContentType = image.ContentType;
image.InputStream.Position = 0;
using (var imageStream = new MemoryStream())
{
image.InputStream.CopyTo(imageStream);
imageStream.Position = 0;
blob.UploadFromStream(imageStream);
}
return blob.Uri.ToString();
}