Umbraco 5 - Adding content pages from another application - umbraco5

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

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 :

get url of image from Umbraco examine search UDI

I'm using Umbraco with Lucene and Examine
I'm trying to get the url of a image but at the moment I get the following
"umb://media/57ad107794724d0289b4f9fe44c298a8"
How can I get the URL for the media from the UDI, my code attempt so far is below.
foreach (var item in searchResults)
{
var content = Umbraco.Content(item.Fields["id"]);
if (item.Fields.Keys.Contains("image"))
{
var image = item.Fields["image"].Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries);
var pathToImage = string.Join(",", image);
var mediaItem = Umbraco.TypedContent(pathToImage);
var test3 = mediaItem.Url; <--------------------Throws NullReferenceException
}
}
Any help appreciated
Try the following
if (item.Fields.Keys.Contains("image"))
{
var imgUdi = item.Fields["image"];
var udi = Udi.Parse(imgUdi);
var mediaTest = Umbraco.TypedMedia(udi);
string pathToImage = mediaTest.Url;
}
Notice how I'm using Udi.Parse to get the ID, then you can use that to get the url

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

asp.net web api file upload without saving

Ok, so I am writing a service to recieve file uploads from an iPhone application through phonegap. They send me a file and I am trying to grab the actual file without saving it to any type of file system. Currently this is what I have
[HttpPost]
public string processRequest()
{
string ext = "Entered";
Request.Content.ReadAsMultipartAsync<MultipartMemoryStreamProvider>(new MultipartMemoryStreamProvider()).ContinueWith((tsk) =>
{
ext = "Request";
MultipartMemoryStreamProvider prvdr = tsk.Result;
foreach (HttpContent ctnt in prvdr.Contents)
{
ext = "Foreach";
// You would get hold of the inner memory stream here
Stream stream = ctnt.ReadAsStreamAsync().Result;
if (stream == null)
{
ext = "Null Stream";
}
Image img = Image.FromStream(stream);
if (ImageFormat.Jpeg.Equals(img.RawFormat))
{
ext = "jpeg";
}
else if (ImageFormat.Png.Equals(img.RawFormat))
{
ext = "Png";
}
else if (ImageFormat.Gif.Equals(img.RawFormat))
{
ext = "Gif";
}
// do something witht his stream now
}
});
return ext;
}
I have put various responses in there so I can see where the function is getting to. Right now it always returns "Entered" which means its not even reading the content of the request, the end game is for me to grab the file object, convert it into an image and then to base 64. Any direction would be appreciated. Remember I want to do this without any file system so no solutions that involve mapping a path to a server folder.
Ok so a little update, I have edited my code according to my first response and at least it attempts to execute now but it just gets infinitely stuck inside the code. This happens during the ReadAsMultipartAsync function
[HttpPost]
public string processRequest()
{
string ext = "Entered";
Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider()).ContinueWith((tsk) =>
{
ext = "Request";
MultipartMemoryStreamProvider prvdr = tsk.Result;
foreach (HttpContent ctnt in prvdr.Contents)
{
ext = "Foreach";
// You would get hold of the inner memory stream here
Stream stream = ctnt.ReadAsStreamAsync().Result;
if (stream == null)
{
ext = "Null Stream";
}
Image img = Image.FromStream(stream);
if (ImageFormat.Jpeg.Equals(img.RawFormat))
{
ext = "jpeg";
}
else if (ImageFormat.Png.Equals(img.RawFormat))
{
ext = "Png";
}
else if (ImageFormat.Gif.Equals(img.RawFormat))
{
ext = "Gif";
}
// do something witht his stream now
}
}).Wait();
return ext;
}
The block inside ContinueWith also runs asynchronously (if you look at the signature for ContinueWith, you'll see that it returns a Task as well). So, with the above code, essentially you're returning before any of that has a chance to execute.
Try doing:
Request.Content.ReadAsMultipartAsync().ContinueWith(...).Wait();
Also, not sure you need to go to the trouble of doing Request.Content.ReadAsMultipartAsync<MultipartMemoryStreamProvider>(new MultipartMemoryStreamProvider()); I believe Request.Content.ReadAsMultipartAsync() should suffice.
Hope that helps!

Cannot use SendTweetWithMediaOptions in windows phone

I am using TweetSharp in a Windows Phone project and no matter what I do, I can't post a tweet with media.
I am getting the exception 195: Missing or invalid parameter.
I read that usually this can be a cause of invalid data, like the stream that I provide is invalid.
I have tried other way but nothing works , I get the same exception ...
The sharing code, simplified is like this:
MediaLibrary library = new MediaLibrary();
var picture = library.Pictures[0];
var options = new SendTweetWithMediaOptions
{
Images = new Dictionary<string, Stream> { { picture.Name, picture.GetImage() } },
Status = TweetTextBox.Text,
};
AutentificateTwitterService().SendTweetWithMedia(options, (status, response) =>
_dispatcher.BeginInvoke(() =>
{
DonePosting();
if (response.StatusCode == HttpStatusCode.OK)
{
_lastPostId = status.Id;
}
else
{
MessageBox.Show(String.Format(
"There was an error sending image to Twitter{0}{1}",
Environment.NewLine,
response.Error));
}
}));
I tried sharing with linqtotwitter and worked but TweetSharp is more appropriate for my project.
Finally after some time I've found the problem to this and I am sure to other more WP and SendTweetWithMediaOptions related problems.
The thing is that if you dig into SendTweetWithMedia the way it is now you will get to TwitterService.cs where WithHammock will be called, is just the images are not passed as parrameters, so they get lost right there :)
I did fix this passing the parameters and adding
private void WithHammock<T>(WebMethod method, Action<T, TwitterResponse> action, string path, IDictionary<string, Stream> files, params object[] segments) where T : class
{
var url = ResolveUrlSegments(path, segments.ToList());
var request = PrepareHammockQuery(url);
request.Method = method;
request.QueryHandling = QueryHandling.AppendToParameters;
foreach (var file in files)
{
request.AddFile("media[]", file.Key, file.Value);
}
WithHammockImpl(request, action);
}
I will try and see if I can Pull this so that everyone else can have this fix.
Hope this helps.