DNN - getting user roles in javascript - dotnetnuke-7

I have an app in DotNetNuke. I would like to retrieve the list of user roles in header javascript, and check to see if it has "Administrators" role. What is the best way to do that?

You could do something like this
using DotNetNuke.Common;
using System.Collections;
using DotNetNuke.Security.Roles;
using System.Web.Script.Serialization;
var RoleController = new RoleController();
var UserRoles = new List<RoleInfo>();
//for dnn 7.3 and lower
if (Globals.DataBaseVersion.Major < 7 || (Globals.DataBaseVersion.Major == 7 && Globals.DataBaseVersion.Minor < 3))
{
UserRoles = RoleController.GetPortalRoles(PortalId).Cast<RoleInfo>().ToList();
}
else
{
//for dnn 7.3 and higher
UserRoles = RoleController.GetRoles(PortalId).ToList();
}
//convert the list to a json array
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(UserRoles.Select(x => x.RoleName));
//send the json to a client side function
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "allUserRoles", "setUserRoles('" + json + "')", true);
And the client side function. The variable json now is an Array with all the roles.
<script type="text/javascript">
function setUserRoles(roles) {
var json = JSON.parse(roles);
for (var i = 0; i < json.length; i++) {
console.log(json[i]);
}
}
</script>

Related

How to verify two Images using Azure Cognitive Face API ? Need Sample Code

How to verify two Images using Azure Cognitive Face API ? Need Sample Code
I have two images of a single person. Now I want to compare those images and check whether those images are of same person or not. From the documentation I came to know that, I have to send two faceid's along with the url. I tried that, but it is not working. May be, I am missing something. Please help me for the same & provide me some sample code for the same if possible.
Waiting for your response.
Try the console app code below :
using Microsoft.Azure.CognitiveServices.Vision.Face;
using Microsoft.Azure.CognitiveServices.Vision.Face.Models;
using System;
using System.IO;
using System.Linq;
using System.Threading;
namespace FaceIdentityTest
{
class Program
{
static void Main(string[] args)
{
string persionPicPath = #"<some path>\personPic.jpg";
String[] picsPath = { #"<some path>\pic1.jpg", #"<some path>\pic2.jpg" };
string endpoint = #"https://<your endpoint name>.cognitiveservices.azure.com/";
string subscriptionKey = "<your subscription key>";
IFaceClient faceClient = new FaceClient(
new ApiKeyServiceClientCredentials(subscriptionKey),
new System.Net.Http.DelegatingHandler[] { });
faceClient.Endpoint = endpoint;
// Create an empty PersonGroup
Console.WriteLine("create person group");
string personGroupId = "demogroup";
faceClient.PersonGroup.CreateAsync(personGroupId, "demo group").GetAwaiter().GetResult();
// Define a person named Bill
Console.WriteLine("create a person in group");
var createPersonResult = faceClient.PersonGroupPerson.CreateAsync(
// Id of the PersonGroup that the person belonged to
personGroupId,
// Name of the person
"Bill"
).GetAwaiter().GetResult();
//Add a face to Bill
Console.WriteLine("Add a face to person");
using (Stream s = File.OpenRead(persionPicPath))
{
// Detect faces in the image and add to Anna
faceClient.PersonGroupPerson.AddFaceFromStreamAsync(
personGroupId, createPersonResult.PersonId, s).GetAwaiter().GetResult();
}
//Train person group
Console.WriteLine("start train person group...");
faceClient.PersonGroup.TrainAsync(personGroupId).GetAwaiter().GetResult();
//Check train status
TrainingStatus trainingStatus = null;
while (true)
{
trainingStatus = faceClient.PersonGroup.GetTrainingStatusAsync(personGroupId).GetAwaiter().GetResult();
if (trainingStatus.Status != TrainingStatusType.Running)
{
break;
}
else {
Console.WriteLine("trainning person group...");
}
Thread.Sleep(1000);
}
foreach (var pic in picsPath) {
Console.WriteLine("start identify faces in :" + pic);
using (Stream s = File.OpenRead(pic))
{
var faces = faceClient.Face.DetectWithStreamAsync(s).GetAwaiter().GetResult();
var faceIds = faces.Select(face => (Guid)face.FaceId).ToList();
var results = faceClient.Face.IdentifyAsync(faceIds, personGroupId).GetAwaiter().GetResult();
foreach (var identifyResult in results)
{
Console.WriteLine("Result of face: {0}", identifyResult.FaceId);
if (identifyResult.Candidates.Count == 0)
{
Console.WriteLine("No one identified");
}
else
{
// Get top 1 among all candidates returned
var candidateId = identifyResult.Candidates[0].PersonId;
var person = faceClient.PersonGroupPerson.GetAsync(personGroupId, candidateId).GetAwaiter().GetResult();
Console.WriteLine("Identified as {0}", person.Name);
}
}
}
}
Console.ReadKey();
}
}
}
My pics :
Result :
Btw, no matter which programming language you are using , just follow the steps in this demo will be able to use Face API to identify faces .
Hope it helps .
You can import Microsoft.Azure.CognitiveServices.Vision.Face here in VS :

How to use the continuationtoken in TFS 2015 Object Model: GetBuildsAsync?

I am using the following code
BuildHttpClient service = new BuildHttpClient(tfsCollectionUri,
new Microsoft.VisualStudio.Services.Common.VssCredentials(true));
var asyncResult = service.GetBuildsAsync(project: tfsTeamProject);
var queryResult = asyncResult.Result;
This returns only the first 199 builds.
Looks like in need to use the continuationtoken but am not sure how to do this. The docs say that the REST API will return the token. I am using the Object Model, and am looking for how to retrieve the token!
I am using Microsoft.TeamFoundationServer.Client v 14.102.0; Microsoft.TeamFoundationServer.ExtendedClient v 14.102.0, Microsoft.VisualStudio.Service.Client v 14.102.0 and Microsoft.VisualStudio.Services.InteractiveClient v 14.102.0
Question
How do I use the continuation token **when using the TFS Object model?
The continuationToken is in the response header after the first call to the API:
x-ms-continuationtoken: xxxx
It can not be retrieved from .net client library. You have to use the rest api to retrieve the header information. Here is an example for your reference:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace GetBuilds
{
class Program
{
public static void Main()
{
Task t = GetBuilds();
Task.WaitAll(new Task[] { t });
}
private static async Task GetBuilds()
{
try
{
var username = "xxxxx";
var password = "******";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", username, password))));
using (HttpResponseMessage response = client.GetAsync(
"http://tfs2015:8080/tfs/DefaultCollection/teamproject/_apis/build/builds?api-version=2.2").Result)
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
You have to use 'GetBuildsAsync2', which returns an IPagedList. You can retrieve the ContinuationToken from the IPagedList:
// Iterate to get the full set of builds
string continuationToken = null;
List<Build> builds = new List<Build>();
do
{
IPagedList<Build> buildsPage = service.GetBuildsAsync2(tfsTeamProject, continuationToken: continuationToken).Result;
//add the builds
builds.AddRange(buildsPage);
//get the continuationToken for the next loop
continuationToken = buildsPage.ContinuationToken;
}
while (continuationToken != null);

PostAsync request with Array parameter on MVC Web API

I have Xamarin application that has POST request with array list of parameter and on my MVC WEB API we used code first Entity framework. Both was separated project solutions (.sln).
On my Xamarin project, I have PostAsync request which supplies List of array values.
using (var client = new HttpClient())
{
Parameter = string.Format("type={0}&param={1}",type, param[]);
var data = JsonConvert.SerializeObject(parameters);
var content = new StringContent(data, Encoding.UTF8, "application/json");
using (var response = await client.PostAsync(url, content))
{
using (var responseContent = response.Content)
{
result = await responseContent.ReadAsStringAsync();
}
}
}
Then In my Web API controller I have same parameter with my client side also.
[System.Web.Http.AcceptVerbs("GET", "POST")]
[System.Web.Http.HttpPost]
[Route("type={type}&param={param}")]
public BasicResponse applog([FromUri] ProfilingType type , List<string> param)
{
if (ModelState.IsValid == false)
{
throw new ModelValidationException("Model state is invalid.");
}
try
{
if(type == ProfilingType.Login)
{
var command = new SendDataProfilingCommand(param);
CommandHandler.Execute(command);
}
else
{
var command = new UpdateDataProfilingCommand(type,param);
CommandHandler.Execute(command);
}
}
catch (Exception e)
{
throw new Exception(e.Message);
}
return new BasicResponse
{
Status = true,
Message = Ok().ToString()
};
}
Since I'm not with the API, I want to test it first on Postman or even in the URL. but my problem was when i Try to test it using this url below
http://localhost:59828/api/users/applog?type=1&param=[1,Caloocan,Metro Manila,Philippines,0,0]
I received this message : No HTTP resource was found that matches the request URI ......
My Question is, How can I test my Web API with List Parameter on URL or in the Postman ? and What Format I can use when sending a post request into my Xamarin PostAsync request?
You don't need to send as Content.
using (var client = new HttpClient())
{
Parameter = string.Format("type={0}&param={1}",type, param[]);
url = url + "?" + Parameter;
using (var response = await client.PostAsync(url))
{
using (var responseContent = response.Content)
{
result = await responseContent.ReadAsStringAsync();
}
}
}

Export DataList to Excel using Asp.net core

I want to export data list to Excel format but I could not find any third party library or any refrence. I am building my project on .net core. Any one expert here to suggest any solution. Thanks
If cross plattform (Windows, Linux, Mac) is a major concern for you then you have to use some "pre release" stuff.
There is an issue for .NET Core support for OpenXML, which can be used to create Open XML Office Documents (e.g. XLSX), (https://github.com/OfficeDev/Open-XML-SDK/issues/65). Some work has to be done before it is ready.
Someone who had your demand as well ported it to .NET Core and published his project on GitHub (https://github.com/xrkolovos/Open-XML-SDK-for-NET-Platform-Standard). I have not tried it myself, but it may be worthwile to try.
If your application runs on Windows only, then you can build your ASP.NET Core project on top of the full .NET Framework (with the well known third party libraries for creating Excel).
i had posted this question almost 7 months ago and i have found the solution, so i want to share it.
add "PdfRpt.Core": "1.0.0-*" on project.json
on controller
[HttpGet("exportexcell")]
public async Task<FileContentResult> ExportExcel()
{
var loggedUser = await GetCurrentUserAsync();
var users = _userManager.Users.Select(u => new UserListVM
{
Id = u.Id,
Name = u.UserName,
Email = u.Email
}).ToList();
if (users == null) return null;
//column Header name
var columnsHeader = new List<string>{
"S/N",
"User Name",
"Email"
};
var filecontent = ExportExcell(users, columnsHeader, "Users");
return File(filecontent, "application/ms-excel", "users.xlsx"); ;
}
helper method
private static byte[] ExportExcell(List<UserListVM> data, List<string> columns, string heading)
{
byte[] result = null;
using (ExcelPackage package = new ExcelPackage())
{
// add a new worksheet to the empty workbook
var worksheet = package.Workbook.Worksheets.Add(heading);
using (var cells = worksheet.Cells[1, 1, 1, 7])
{
cells.Style.Font.Bold = true;
cells.Style.Fill.PatternType = ExcelFillStyle.Solid;
cells.Style.Fill.BackgroundColor.SetColor(Color.Green);
}
//First add the headers
for (int i = 0; i < columns.Count(); i++)
{
worksheet.Cells[1, i + 1].Value = columns[i];
}
//Add values
var j = 2;
var count = 1;
foreach (var item in data)
{
worksheet.Cells["A" + j].Value = count;
worksheet.Cells["B" + j].Value = item.Name;
worksheet.Cells["C" + j].Value = item.Email;
worksheet.Cells["D" + j].Value = item.RoleNam
j++;
count++;
}
result = package.GetAsByteArray();
}
return result;
}
//it work fine for me.. it may help to you too.
you can find demo here

Web Api Service

I am Consuming web api service from one project (project1) to another project (project2) but when i try to get the response from project2 to project1 with this code
using (var client = new WebClient())
{
string json = URL;
Var jdownload = client.DownloadString(json);
}
It's adding back slashed into "jdownload" Var please guide me how i can get that response without that backslashes
i.e
“servicefor” = “GetData”,
“settings” = {
\"stringname\":5,
\"url\":\"null",
\"services\":\"GetSet\",
\"interval\":2.0,
\"alldatacontains\":200,
\"netamountname\":\"BulkFetch\"
}
I got the solution how can i get the Clean Jason
public JObject GetData(string dataO)
{
var data = MethodToGetData(dataO);
JObject pobj = JObject.FromObject(new
{
type = "stgdats",
val = "val",
d_id = id,
sat = data
}
);
return pobj;
}