Export DataList to Excel using Asp.net core - 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

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 :

DNN - getting user roles in javascript

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>

Sharepoint 2010 DocumentSets - How to Manage Programatically?

I am new to Sharepoint 2010 but not new to .Net programming. Here is a my situation, i have a large set of files to be uploaded into Sharepoint 2010 with metadata. I have decided to write a C# class library to handle the documentsets programatically. I have to use to DocumentSets and i was able to successfully create a documentset. Now i am stuck with the following:
How do i check if a documentset already exists?
How do i remove a documentSet?
Here is my code to create the documentset:
using (SPSite site = new SPSite(spURL))
{
using (SPWeb web = site.OpenWeb())
{
SPList docs = web.Lists["Documents"];
if (docs != null)
{
SPContentType docSetCT = docs.ContentTypes["Document Set"];
if (docSetCT != null)
{
Hashtable docsetProps = new Hashtable();
docsetProps.Add("New Docset", "New Docset");
DocumentSet docSet = DocumentSet.Create(docs.RootFolder, documentSetName, docSetCT.Id, docsetProps, true);
docs.Update();
}
}
}
}
The list of helper methods for working with Document Sets:
How do I check if a document set already exists?
private static bool IsDocumentSetExist(SPList list,string docSetName)
{
var folderUrl = SPUrlUtility.CombineUrl(list.RootFolder.ServerRelativeUrl, docSetName);
var folder = list.ParentWeb.GetFolder(folderUrl);
return folder.Exists;
}
Usage:
var docSetExists = IsDocumentSetExist(docs, "New Docset");
How do I remove a document set?
private static void DeleteDocumentSet(DocumentSet docSet)
{
docSet.Folder.Delete();
}

How to programmatically set the task outcome (task response) of a Nintex Flexi Task?

Is there any way of set a Nintex Flexi task completion through Sharepoint's web services? We have tried updating the "WorkflowOutcome", "ApproverComments" and "Status" fields without success (actually the comments and status are successfully updated, however I can find no way of updating the WorkflowOutcome system field).
I can't use the Nintex Web service (ProcessTaskResponse) because it needs the task's assigned user's credentials (login, password, domain).
The Asp.net page doesn't have that information, it has only the Sharepoint Administrator credentials.
One way is to delegate the task to the admin first, and then call ProcessTaskResponse, but it isn't efficient and is prone to errors.
In my tests so far, any update (UpdateListItems) to the WorkflowOutcome field automatically set the Status field to "Completed" and the PercentComplete field to "1" (100%), ending the task (and continuing the flow), but with the wrong answer: always "Reject", no matter what I try to set it to.
Did you try this code: (try-cacth block with redirection does the trick)
\\set to actual outcome id here, for ex. from OutComePanel control
taskItem[Nintex.Workflow.Common.NWSharePointObjects.FieldDecision] = 0;
taskItem[Nintex.Workflow.Common.NWSharePointObjects.FieldComments] = " Some Comments";
taskItem.Update();
try
{
Nintex.Workflow.Utility.RedirectOrCloseDialog(HttpContext.Current, Web.Url);
}
catch
{
}
?
Here are my code to change outcome of nintex flexi task. My problem is permission. I had passed admin token to site. It's solve the problem.
var siteUrl = "...";
using (var tempSite = new SPSite(siteUrl))
{
var sysToken = tempSite.SystemAccount.UserToken;
using (var site = new SPSite(siteUrl, sysToken))
{
var web = site.OpenWeb();
...
var cancelled = "Cancelled";
task.Web.AllowUnsafeUpdates = true;
Hashtable ht = new Hashtable();
ht[SPBuiltInFieldId.TaskStatus] = SPResource.GetString(new CultureInfo((int)task.Web.Language, false), Strings.WorkflowStatusCompleted, new object[0]);
ht["Completed"] = true;
ht["PercentComplete"] = 1;
ht["Status"] = "Completed";
ht["WorkflowOutcome"] = cancelled;
ht["Decision"] = CommonHelper.GetFlexiTaskOutcomeId(task, cancelled);
ht["ApproverComments"] = "cancelled";
CommonHelper.AlterTask((task as SPListItem), ht, true, 5, 100);
task.Web.AllowUnsafeUpdates = false;
}
}
}
}
}
}
public static string GetFlexiTaskOutcomeId(Microsoft.SharePoint.Workflow.SPWorkflowTask task, string outcome)
{
if (task["MultiOutcomeTaskInfo"] == null)
{
return string.Empty;
}
string xmlOutcome = HttpUtility.HtmlDecode(task["MultiOutcomeTaskInfo"].ToString());
if (string.IsNullOrEmpty(xmlOutcome))
{
return string.Empty;
}
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlOutcome);
var node = doc.SelectSingleNode(string.Format("/MultiOutcomeResponseInfo/AvailableOutcomes/ConfiguredOutcome[#Name='{0}']", outcome));
return node.Attributes["Id"].Value;
}
public static bool AlterTask(SPListItem task, Hashtable htData, bool fSynchronous, int attempts, int milisecondsTimeout)
{
if ((int)task[SPBuiltInFieldId.WorkflowVersion] != 1)
{
SPList parentList = task.ParentList.ParentWeb.Lists[new Guid(task[SPBuiltInFieldId.WorkflowListId].ToString())];
SPListItem parentItem = parentList.Items.GetItemById((int)task[SPBuiltInFieldId.WorkflowItemId]);
for (int i = 0; i < attempts; i++)
{
SPWorkflow workflow = parentItem.Workflows[new Guid(task[SPBuiltInFieldId.WorkflowInstanceID].ToString())];
if (!workflow.IsLocked)
{
task[SPBuiltInFieldId.WorkflowVersion] = 1;
task.SystemUpdate();
break;
}
if (i != attempts - 1)
{
Thread.Sleep(milisecondsTimeout);
}
}
}
var result = SPWorkflowTask.AlterTask(task, htData, fSynchronous);
return result;
}

Umbraco 5 - Adding content pages from another application

I'm trying to take a look at Umbraco 5, and trying to figure out how to add content from an outside application. In v4 I would have done something like the following,
var documentType = DocumentType.GetByAlias(UmbracoDocumentType.Country.ToString());
var parentId = DocumentFinder.GetDefaultParentIdForDocumentType(documentType.Alias);
var docs = Document.GetDocumentsOfDocumentType(documentType.Id);
var list = docs.Select(doc => Convert.ToInt32(doc.getProperty("externalId").Value)).ToList();
string name;
Document document;
foreach (DataRow dataRow in dataTable.Rows)
{
if (list.Contains(Convert.ToInt32(dataRow["Id"])))
{
document = DocumentFinder.GetDocumentByExternalId(dataRow.Field<int>("Id"), documentType.Id);
document.getProperty("name").Value = dataRow["Name"].ToString();
}
else
{
name = dataRow["Name"].ToString();
if (name == string.Empty) continue;
document = Document.MakeNew(name, documentType, administratorAsAuthor, parentId);
document.getProperty("externalId").Value = Convert.ToInt32(dataRow["Id"]);
document.getProperty("name").Value = dataRow["Name"].ToString();
}
try
{
document.Save();
}
catch (Exception ex)
{
ExceptionManager.Handle(ex);
}
}
But in v5 there are no such things, and I have searched and searched and found nothing that could help me, even put a post on thier forum, and no responses yet. So, I wanted to post here to see if anyone else might know how this done now.
I know that its still Beta, but I think that there should be a way.
Thanks,
Andrew