Error when i tried to display images from an umbraco folder - c#

The issue is encountered when I was trying to fetch some images from a folder,
The issue gets resolved whenever I switch the media to a new folder.
Any help is appreciated.
The code below is used for fetching Umbraco media
foreach (var mediaItem in mediasList)
{
IPublishedContent media = null;
Udi udiId;
if (Udi.TryParse(mediaItem, out udiId))
{
media = Umbraco.TypedMedia(udiId);
}
else
{
media = Umbraco.TypedMedia(mediaItem);
}
if (media.DocumentTypeAlias == "Folder")
{
var childrens = media.Children(); //getting error in this line
foreach (var image in childrens)
{
}
}
}

From the MSDN forum:
This isn't an error in and of itself, but more of a feature of your debugger. Some properties require code to be executed in order for the property to be read, but if this requires cross-thread interaction, then other threads may have to run as well. The debugger doesn't do this automatically, but certainly can, with your permission. Just click the little evaluate icon and it will run your code and evaluate the property.
Also, you can get the results if you do var childrens = media.Children().ToList() for example.

Related

How to Save Html data from a website to a text file using Xamarin forms and C#

I'm using C# and Xamarin forms to create a phone app that (when a button is pressed) will pull specific html data from a website in and save it into a text file (that the program can read from again later). I started with the tutorial in this video: https://www.youtube.com/watch?v=zvp7wvbyceo if you want to see what I started out with, and here's the code I have so far made using this video https://www.youtube.com/watch?v=wwPx8QJn9Kk, in the the "AboutViewModel.cs" file created in the video:
Image link because this is a new account i guess and i cant embed images or something
Paste of the code itself (but the image gives you a better look at everything):
private Task WebScraper()
{
HtmlAgilityPack.HtmlWeb web = new HtmlAgilityPack.HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = web.Load("https://www.flightview.com/airport/DAB-Daytona_Beach-FL/");
foreach (var item in doc.DocumentNode.SelectNodes("//td[#class='c1']"))
{
var itemstring = item;
File.WriteAllText("AirportData.txt", itemstring);
}
return Task.CompletedTask;
}
public ICommand OpenWebCommand { get; }
public ICommand WebScraperCommand { get; }
}
}
The only error i'm getting right now is "Cannot convert 'HtmlAgilityPack.HtmlNode' to 'string'" Which i'm working on fixing but I don't think this is the best solution so anything you have is useful. Thanks :)
HtmlNode is an object, not a simple string. You probably want to use the OuterHtml property, but consult the docs to see if that is the right fit for your use case
string output = string.Empty;
foreach (var item in doc.DocumentNode.SelectNodes("//td[#class='c1']"))
{
output += item.OuterHtml;
}
File.WriteAllText("AirportData.txt", output);
note that you need to specify a path to a writable folder, the root folder of the app is not writable. See https://learn.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/data/files?tabs=windows

How to point to the correct Store in Outlook automation by C#?

I have a lot of VBA automation that interlinks an Outlook and Word solution; it is fine, but time is inexorable... so, I'm start to decorating and extending that old solution, wraping it with C#/VS2017.
Through a conventional Winform I can choose my patients, and from this action I do a lot of actions, including open the correct Outlook contact; that's the problem, because I can't get the correct Store; the patients.pst, depending on the machine, may be the 1st, 2nd, 3rd...
In VBA I do this:
WhichStoreNameToPointAt="patients"
Set myNamespace = myolApp.GetNamespace("MAPI")
For i = 1 To myNamespace.Stores.Count Step 1
If myNamespace.Stores.item(i).DisplayName = WhichStoreNameToPointAt Then
intOutlookItemStore = i
End if
End If
Set myFolderPatients = myNamespace.Stores.item(intOutlookItemStore).GetDefaultFolder(olFolderContacts)
And it always functions like a charm.
In C# I tried a lot of variations, and could not point to the correct store:
public void OpenPatientContact(string patientName)
{
Outlook.Store whichStore = null;
Outlook.NameSpace nameSpace = OlkApp.Session;
int i = 1;
foreach (Outlook.Folder folder in nameSpace.Folders)
{
bool p = false;
if (whichStoreNameToPointAt == folder.Name)
{
p = true;
whichStore = folder.Store;
//Correct Store selected; I can tell because of this watch:
//whichStore.displayname == whichStoreNameToPointAt
}
i++;
if (p)
break;
}
var contactItemsOlk = whichStore.Session.GetDefaultFolder
(Outlook.OlDefaultFolders.olFolderContacts).Items;
// The problem is below; always the first Store
Outlook.ContactItem contact = (Outlook.ContactItem)contactItemsOlk
.Find(string.Format("[FullName]='{0}'", patientName)); //[1];
if (contact != null)
{
contact.Display(true);
}
else
{
MessageBox.Show("The contact information was not found.");
}
}
Unfortunately, it keeps pointing ever to the same first Store, the one that has no patients...
If I change the Store order I can get past this and test other stuff, but of course it is not the right way.
Any other heads/eyes to see the light?
TIA
While seated writing the question, looking at a yellow rubber duck - and a lot of other stuff that belongs to my 1 yo daughter ;), I realized that whichStore.Session.GetDefaultFolder is a little strange in this context. I only changed this
var contactItemsOlk = whichStore.Session.GetDefaultFolder
(Outlook.OlDefaultFolders.olFolderContacts).Items;
To that:
var contactItemsOlk = whichStore.GetDefaultFolder
(Outlook.OlDefaultFolders.olFolderContacts).Items;
Voilá! Magic happens with C# too!
Session returns the default NameSpace object for the current session.
PS: yellow rubber duck; guys of The Pragmatic Programmer really knows some secrets and tricks ;)
Thanks Thomas and Hunt!

EWS FindItemsResults<Item> Item.Move() does not move certain item types to a Mail folder such as IPM.Appointment

I have some code that is moving items into a Mail Folder from the Deleted Items. The code works well and moves all the items generally. The problem occurs when it encounters an item that is not IPM.Note. It gives the error that is a null reference (See: What is a NullReferenceException, and how do I fix it?)
Which is odd as there are items there and it can't be null.
Here is a code excerpt:
// Specify the Exchange Service
ExchangeService E_SERVICE = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
// Look at the root of the Mailbox (Top of Information Store)
FolderId fldr_id = WellKnownFolderName.MsgFolderRoot;
// Define the folder view
FolderView newFV = new FolderView(1000);
// Perform a deep traversal
newFV.Traversal = FolderTraversal.Deep;
// Get the results of all the folders in the Mailbox
FindFoldersResults f_results = E_SERVICE.FindFolders(fldr_id, newFV);
// Define the source and target folder id variables as null.
FolderId src_fldr_id = null;
FolderId tgt_fldr_id = null;
// Define the folders we are looking to move items from the source to the target
string source = "Deleted Items"
string target = "Old Deleted Items"
// Search through all the folders found in the mailbox
foreach (Folder fldr in f_results)
{
// If the source folder name is the same as the current folder name then set the source folder ID
if (fldr.DisplayName.ToLower() == source.ToLower())
{
src_fldr_id = fldr.Id;
}
// If the target folder name is the same as the current folder name then set the target folder ID
if (fldr.DisplayName.ToLower() == target.ToLower())
{
tgt_fldr_id = fldr.Id;
}
}
// Get all the items in the folder
FindItemsResults<Item> findResults = E_SERVICE.FindItems(src_fldr_id, new ItemView(1000));
// If the number of results does not equal 0
if (findResults.TotalCount != 0)
{
// For each item in the folder move it to the target folder located earlier by ID.
foreach(Item f_it in findResults)
{
f_it.Move(tgt_fldr_id);
}
}
We get the error thrown on the following line:
f_it.Move(tgt_fldr_id);
This is as a Null Reference Exception which can't be the case as there are items there and it is usually an item that is not IPM.Note.
So how would I go about getting around this and ensure the item gets moved regardless of what type it is?
I have previously posted here about this Unable to move Mail items of different Item classes from the same folder using EWS
Only to be shot down about it being a NullReferenceException when this is not the case!
So any helpful answers would be greatly appreciated.
Okay the solution to get around this issue is to ensure you Load() the item before you perform a Move()
make sure you use a try..catch block and handle the exception like below:
try
{
f_it.Move(tgt_fldr_id);
}
catch (Exception e)
{
Item draft = Item.Bind(E_SERVICE, f_it.Id);
draft.Load();
draft.Move(tgt_fldr_id);
}
This will force the item to load separately and then move it even if it does throw an error. Why, it does this is not known as yet. But should hopefully help those struggling with why you are getting a NullReferenceException
Thanks everyone!
EDIT: You may want to read https://social.msdn.microsoft.com/Forums/exchange/en-US/b09766cc-9d30-42aa-9cd3-5cf75e3ceb93/ews-managed-api-msgsender-is-null?forum=exchangesvrdevelopment on why certain items are Null as this will help you deal with Null items returned a bit better.

NullReferenceException when deleting a sitecore items children

i'm trying to import some legacy poll data into our sitecore solution. For part of the import, i'm trying to create new sitecore items to hold the data based off of a master page we already have set up for polls. this master has a couple of default items set up underneath of it, and I want to delete a couple of specific default items before I add the legacy poll data. however, when i attempt to delete one of the default items using item.DeleteChildren(), i get a NullReferenceException thrown by Sitecore.Tasks.ItemEventHandler.OnItemDeleted(Object sender, EventArgs args) in the sitecore kernel. if anyone has any idea what could be causing this, i'd appreciate it. we're on sitecore version 5.3.2.
here is the code i'm using to attempt to create/edit the item based off of a master. the creation all works perfectly, it's the DeleteChildren() call that doesn't work.
Guid LegacyPollFolderGuid = new Guid("8AE89A44-9DCD-4AC2-B0F3-DD438188A575");
Guid QuizOMaticMasterGuid = new Guid("74B95ABF-1898-4870-8B4F-50AF0078AE22");
var master = Sitecore.Configuration.Factory.GetDatabase("master");
var root = master.GetItem(new Sitecore.Data.ID(LegacyPollFolderGuid));
var quizMasterTemplate = master.Masters[new Sitecore.Data.ID(QuizOMaticMasterGuid)];
var quizPage = root.Add("Test Quiz", quizMasterTemplate);
if (quizPage != null)
{
var quiz = quizPage.Children["Column One"].Children["QuizOMatic"];
if (quiz != null)
{
var questionFolder = quiz.Children["Questions"];
var questionTemplate = questionFolder.Children[0].Template;
var resultsFolder = quiz.Children["Results"];
var linksFolder = quiz.Children["Links"];
using (new Sitecore.SecurityModel.SecurityDisabler())
{
questionFolder.DeleteChildren();
}
}
I've built a tool with the same functionality; removing all items under a specific folder. I got the same error, but I saw items being deleted. So I reran the tool multiple times and eventually all items were deleted.

Disable event firing not working Sharepoint 2010

I have a block of code where I'm trying to disable event firing when editing a file, once the debugger hits the item.SystemUpdate(false) line it throws an exception that states "The file xxxx has been modified by xxxxx"
HandleEventsFiring handle = new HandleEventsFiring();
handle.DisableHandleEventFiring();
try
{
web.AllowUnsafeUpdates = true;
SPFile rptFile = web.GetFile(item.Url); //item is an SPListItem
if (rptFile.Exists)
{
WordDocUtility word = new WordDocUtility();
using (System.IO.Stream stream = rptFile.OpenBinaryStream())
{
word.ReplaceKeys(stream, keys);
rptFile.SaveBinary(stream);
}
}
item.SystemUpdate(false); // the line throwing the exception
}
finally
{
handle.EnableHandleEventFiring();
web.AllowUnsafeUpdates = allowUnsafeUpdates;
}
public class HandleEventsFiring: SPItemEventReceiver
{
public void DisableHandleEventFiring()
{
this.EventFiringEnabled = false;
}
public void EnableHandleEventFiring()
{
this.EventFiringEnabled = true;
}
}
Does anyone know of a way around this or am I doing something wrong?
Any help would be greatly appreciated.
You haven't really shown enough of the code for us to point you to the exact problem. The error that you're getting means that after you pulled the list item that is in item from the content database it was later updated. Chances are, if you get the error every single time, that you're pulling down the same item more than once and your changes are conflicting with yourself. My guess is that item represents a file in a document library, and that you're modifying the file in addition to the splist item. These changes are what are conflicting. You need to fetch the item, update the item, then fetch the file and update the file. If you need to fetch the item and then update the file you will need to fetch the item again so that you don't end up updating an item when another update occurred between the fetch and update.

Categories