Trying to figure out why this isn't working, the list is to retrieve photos using the combobox item (which lists local HDDs root address as items) when selected that item it is converted into a string and supposed to be used as a path for the GetFiles Method but screws up on the (string path = ) line when running, I get "object reference not set to instance of an object" much appreciated If someone could tell me what is going wrong
public List<Photos> LoadImages ///List Retrieves and Loads Photos
{
get
{
List<Photos> Image = new List<Photos>();
string path = HDDSelectionBox.SelectedItem.ToString(); //ComboBox SelectedItem Converted To String As Path
foreach (string filename in Directory.GetFiles(path, "*jpg"))
{
try
{
Image.Add( //Add To List
new Photos(
new BitmapImage(
new Uri(filename)),
System.IO.Path.GetFileNameWithoutExtension(filename)));
}
catch { } //Skips Any Image That Isn't Image/Cant Be Loaded
}
return Image;
}
}
You should put . before the file extension in the line:
Directory.GetFiles(path, "*.jpg")
You also need to check if HDDSelectionBox.SelectedItem is not null:
public List<Photos> LoadImages ///List Retrieves and Loads Photos
{
get
{
List<Photos> images = new List<Photos>();
if (HDDSelectionBox.SelectedItem != null)
{
string path = HDDSelectionBox.SelectedItem.ToString(); //ComboBox SelectedItem Converted To String As Path
foreach (string filename in Directory.GetFiles(path, "*.jpg"))
{
try
{
images.Add( //Add To List
new Photos(
new BitmapImage(
new Uri(filename)),
System.IO.Path.GetFileNameWithoutExtension(filename)));
}
catch { } //Skips Any Image That Isn't Image/Cant Be Loaded
}
}
return images;
}
}
Also, this is probably better suited to a method rather than a property as it does quite a lot of processing...
Related
Is it possible to enumerate all XAML resources defined in an Assembly? I know how to retrieve a resource if you have it's Key available, but it isn't the case in my situation.
EDIT:
Seems like I wasn't clear enough. I want to list XAML resources defined in an external Assembly that I know full path to.
yeah, you can iterate resources through loops. For example, using foreach loop:
foreach (var res in Application.Current.Resources)
{
Console.WriteLine(res);
}
Update:
To get all ResourceDictionary'ies from external library, you should, at first, load the library, then get ManifestResourceInfo. Let me show an example:
string address = #"WpfCustomControlLibrary.dll";
List<Stream> bamlStreams = new List<Stream>();
Assembly skinAssembly = Assembly.LoadFrom(address);
string[] resourceDictionaries = skinAssembly.GetManifestResourceNames();
foreach (string resourceName in resourceDictionaries)
{
ManifestResourceInfo info = skinAssembly.GetManifestResourceInfo(resourceName);
if (info.ResourceLocation != ResourceLocation.ContainedInAnotherAssembly)
{
Stream resourceStream = skinAssembly.GetManifestResourceStream(resourceName);
using (ResourceReader reader = new ResourceReader(resourceStream))
{
foreach (DictionaryEntry entry in reader)
{
//Here you can see all your ResourceDictionaries
//entry is your ResourceDictionary from assembly
}
}
}
}
You can see all your ResourceDictionary's in reader. Please, see the above code.
I've tested this code and it works.
Try below code:
ResourceDictionary dictionary = new ResourceDictionary();
dictionary.Source = new Uri("pack://application:,,,/WpfControlAssembly;Component/RD1.xaml", UriKind.Absolute);
foreach (var item in dictionary.Values)
{
//Operations
}
Here WpfControlAssembly is name of your assembly.Component is fixed value and then RD1.xaml is a Resource Dictionary.
Below is the output:
Resource Dictionary
Code Output:
PS: All ResourceDictionary Files should have Build Action as 'Resource' or 'Page'.
Update :
Finally I'm able to do this. Please use below method:
public ResourceDictionary GetResourceDictionary(string assemblyName)
{
Assembly asm = Assembly.LoadFrom(assemblyName);
Stream stream = asm.GetManifestResourceStream(asm.GetName().Name + ".g.resources");
using (ResourceReader reader = new ResourceReader(stream))
{
foreach (DictionaryEntry entry in reader)
{
var readStream = entry.Value as Stream;
Baml2006Reader bamlReader = new Baml2006Reader(readStream);
var loadedObject = System.Windows.Markup.XamlReader.Load(bamlReader);
if (loadedObject is ResourceDictionary)
{
return loadedObject as ResourceDictionary;
}
}
}
return null;
}
OUTPUT:
Without any try-catch & expected Exceptions and I think in more WPF(instead of converting everything to ResourceDictionary) way.
I have a function GetDirectories() which returns me the List of directory info : Now i need to reconstruct a tree view out of it , based on the its parent
Here is my function Getdirectories which return the List:
public List<DirectoryInfo> GetDirectories()
{
DirectoryInfo di = new DirectoryInfo("D:\\python_code");
folders.Clear();
FullDirList(di, "*");
return folders;
}
static List<DirectoryInfo> folders = new List<DirectoryInfo>(); // List that hold direcotries that cannot be accessed
static void GetFullDirList(DirectoryInfo dir, string searchPattern)
{
try
{
foreach (FileInfo f in dir.GetFiles(searchPattern))
{
files.Add(f);
}
}
catch
{
}
foreach (DirectoryInfo d in dir.GetDirectories())
{
folders.Add(d);
FullDirList(d, searchPattern);
}
}
I need something like this to be constructed from the List , which contain all the DirectoryInfo elements i.e it contains its parent info also .
so far i am trying to get the elements whose parent are same and populate it to tree view and do it recursively :
But i am not able to get the recursive function written through .
I know their other easier ways to do the same , but this is a recruitment of a big picture i am trying to draw .
any help would be extremly appretiated .
Assuming you have WinForms treeview you can use the key argument of the Find method on the Nodes collection to build up your hierarchy. You don't need recursion for that. Here is the Add method:
void Add(DirectoryInfo di)
{
if (di.Parent != null )
{
// find our parent node
var node = treeView1.Nodes.Find(di.Parent.FullName,true);
if (node.Length == 0)
{
// not found, add it as root
// FullName becomes the key
treeView1.Nodes.Add(di.FullName, di.Name);
}
else
{
// not sure what is going on if node.Length > 1
// anyway, add it to the first node, to be our parent
node[0].Nodes.Add(di.FullName, di.Name);
}
}
else
{
treeView1.Nodes.Add(di.FullName, di.Name);
}
}
And a simple iterator will drive this method:
var list = GetDirectories();
foreach(var di in list)
{
Add(di);
}
So I am wanting to load an image with the use of a function that receives as a string the name of the image it needs to load and then have it load it however I cannot get this to work as I think the program is simply trying to load the variable name rather that the the string it stores(which is the actual name of the image). Sorry if that's badly worded hopefully my code clears up what I mean.
bool FlagDisplay(PictureBox team, string teamName)//Displays the flag of the team that was selected
{
if (teamName == "Canada")
{
team.Image = Properties.Resources.Canada;
}
else if (teamName == "New Zealand")
{
team.Image = Properties.Resources.NZ;
}
else if (teamName == "South Africa")
{
team.Image = Properties.Resources.RSA;
}
return (true);
}
I want my code to work more like
bool FlagDisplay(PictureBox team, string teamName)//Displays the flag of the team that was selected
{
team.Image = Properties.Resources.teamName;
}
var imageToShow = Properties.Resources.ResourceManager.GetObject(teamName);
imageToShow will be a System.Drawing.Bitmap.
See https://msdn.microsoft.com/en-us/library/963f81yd(v=vs.110).aspx
A PictureBox only contains one Picture. If you want to change the image that it is displaying , then you need to pass an actual Image to it, not just a string.
so , try this:
public void FlagDisplay(PictureBox team, string teamName)//Displays the flag of the team that was selected
{
// note here you probably need to add .jpg or .png to the teamName
var imageToShow = new Bitmap(teamName); // this takes filename
team.Image = (Image) imageToShow;
}
I would be inclined to code your FlagDisplay method like this:
bool FlagDisplay(PictureBox team, string teamName)
{
var images = new Dictionary<string, string>()
{
{ "Canada", Properties.Resources.Canada },
{ "New Zealand", Properties.Resources.NZ },
{ "South Africa", Properties.Resources.RSA },
};
if (images.ContainsKey(teamName))
{
team.Image = new Bitmap(images[teamName]);
return true;
}
return false;
}
The advantage with this approach is that you can pull the dictionary out of the method and build it dynamically to handle different countries or image locations without necessarily needing to recompile your FlagDisplay source.
If that causes an error then you don't have full image paths in your resources.
I would like to use a list of old and the corresponding new names in a CSV file(source of CSV is a Excel sheet), in order to rename files. Obviously replace the old name with the new name specified for each case.
For Example:
Find what Replace With
C:\Users\Documents\Pump Station.doc C:\Users\Documents\Awesome Pump Station.doc
C:\Users\Documents\Pump Selection.doc C:\Users\Documents\Great Pump Selection.doc
C:\Users\Documents\Pump Sizing Calc.xlsx C:\Users\Documents\Hectic Pump Sizing Calc.xlsx
I am very new to coding and I am having trouble finishing this off. This is what I have so far. I do not necessarily need to even put the list user interface (which it currently does). Ultimately I would like to loop through the rows in my CSV file, check if the old name specified exists and if so, rename it to the new name specified.
I really appreciate any help in advance and sorry for any rookie errors I may have made in my code below.
public class OldNew
{
public string oldFile { get; set; }
public string newFile { get; set; }
}
public static class OldNewService
{
public static new List<OldNew>ReadFile(string filepath)
{
var lines = File.ReadAllLines(filepath);
var data = from l in lines.Skip(1)
let split = l.Split(',')
select new OldNew
{
oldFile = split[0],
newFile = split[1],
};
return data.ToList();
}
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = OldNewService.ReadFile(#"C:\Users\cch\Documents\Batch Edit\Lookup Table.csv");
}
}
}
In my opinion, a better solution would be to use a plain old foreach and not a call to ToList().ForEach().
var lines = File.ReadAllLines(filepath);
var data = from l in lines.Skip(1)
let split = l.Split(',')
select new OldNew
{
oldFile = split[0],
newFile = split[1],
};
foreach(var f in data)
{
if (File.Exists(f.oldFile)
{
File.Move(f.oldFile, f.newFile);
}
}
See: http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx for an explanation.
From what I understand, you want to get the new value of the file if an old one exists. To get the new value of the file from your list, try something like:
data.ForEach(d =>
{
if (!string.IsNullOrEmpty(d.oldFile))
{
File.Move(d.oldFile, d.newFile);
}
});
Wouldn't it make sense to rename the old filename if a new one exists?
Hope this helps.
I've created a Standard SharePoint 2013 Event Receiver on a custom list.
Watched Event = "ItemAdded".
Later in my code I need to retrieve the attachments of the list item in the same order as the user inserted them. But unfortunately it seems that SharePoint does not do this by Default.
Example:
The User creates a list item and attach the following files
Picture_front.jpg
Picture_back.png
Picture_231.jpg
Now in my Event Receiver it is possible that I first get 'Picture_back' then 'Picture_front'... or in any other order.
How can I retrieve the attachments in the same order as they have been attached to the list item?
I tried to use the SPFile Property 'TimeCreated' but this is also not working... They got the same timestamp :( (also if I am using 'Ticks')
Any ideas or I am doing something wrong?
Here is my Code:
public override void ItemAdded(SPItemEventProperties properties)
{
SPAttachmentCollection attachments = properties.ListItem.Attachments;
if (attachments.Count > 0)
{
int p = 1;
Dictionary<string, string> attachementDict = new Dictionary<string, string>();
try
{
foreach (string attachement in attachments)
{
SPFile attachementFile = properties.ListItem.ParentList.ParentWeb.GetFile(properties.ListItem.Attachments.UrlPrefix + attachement);
string imageUrlPath = properties.WebUrl + attachementFile.ServerRelativeUrl;
string imageTimestamp = attachementFile.TimeCreated.Ticks.ToString();
// This Dict is used lator for sorting
// but at the Moment I get here the error that the same key already exists because of the same timestamp of the files :(
attachementDict.Add(imageTimestamp, imageUrlPath);
}
}
catch (Exception ex)
{
// SPLog
}
}
here my code ..i hope it help you!
try
{
string strUrl = SPContext.Current.Site.Url + "/" + subSite;
using (SPSite Site = new SPSite(strUrl))
{
using (SPWeb Web = Site.OpenWeb())
{
SPList List = Web.Lists[listName];
SPListItem item = List.GetItemById(ID);
foreach (String attachmentname in item.Attachments)
{
AnnouncementsCommon objAnnouncementsCommon = new AnnouncementsCommon();
String attachmentAbsoluteURL = item.Attachments.UrlPrefix + attachmentname;
objAnnouncementsCommon.AttachmentName = attachmentname;
objAnnouncementsCommon.AttachmentURL = attachmentAbsoluteURL;
lstAnnouncementsCommon.Add(objAnnouncementsCommon);
}
}
}
}
catch (Exception Exc)
{
Microsoft.Office.Server.Diagnostics.PortalLog.LogString("SSC DAL Exception Occurred: {0} || {1}", Exc.Message, Exc.StackTrace);
}
return lstAnnouncementsCommon;
}
As an alternative approach you could use your receiver to store the attachments in a picture library and add two fields to this library: a lookup column to your original custom list item and an option column with "default", "front view", "back view" (or similar).
One advantage is that you can easily update your images in the future and another is that SharePoint automatically creates two preview miniatures in convenient sizes for your images which allows you to reduce bandwidth.