|
Hi,
I am trying to delete some nodes from an xml document. I am using LINQ to xml and want to stick to this approach. Here is my XML document:
<?xml version="1.0" encoding="utf-8"?>
<Project>
<Clips>
<Clip ID="1" Sequence="1">
<Name></Name>
<Description></Description>
<Location></Location>
<Duration></Duration>
<Images>
<Image ID="1">
<Name></Name>
<Description></Description>
<Location></Location>
<StartTime></StartTime>
<EndTime></EndTime>
</Image>
</Images>
</Clip>
<Clip ID="2" Sequence="1">
<Name>Bazingaaa</Name>
<Description>Masdljaslda</Description>
<Location>C:\Videos</Location>
<Duration>00:00:30</Duration>
<Images>
<Image ID="1">
<Name>Faheem</Name>
<Description>MyImage</Description>
<Location>C:\Images</Location>
<StartTime>00:00:00</StartTime>
<EndTime>00:00:10</EndTime>
</Image>
<Image ID="2">
<Name>Fawaz</Name>
<Description>MyImage</Description>
<Location>C:\Images</Location>
<StartTime>00:00:00</StartTime>
<EndTime>00:00:10</EndTime>
</Image>
</Images>
</Clip>
</Clips>
</Project>
I have to perform two cases. 1. Delete clip node based on ID. 2. Clear whole project root tag.
I am using the following code to delete nodes.
IEnumerable<XElement> clip = (from c in this.oProjectDoc.Element("Project").Element("Clips").Elements("Clip")
where c.Attribute("ID").Value.Equals(ID)
select c);
foreach (XElement xe in clip)
xe.Remove();
this.oProjectDoc.Save(this.oProjectPath.FullName);
Have tried this as well.
var q = from node in oProjectDoc.Root.DescendantsAndSelf("Clips")
let attr = node.Attribute("ID")
where attr != null && attr.Value == clipId
select node;
q.ToList().ForEach(x => x.Remove());
oProjectDoc.Save(this.oProjectPath.FullName);
Problem happens when i try to delete the last clip node or the clear the whole root "Project" tag. I get a lingering end node tag. Like:
</Clip>
Any solutions to that. Kindly please also tell me how can clear all my nodes from xml document. i.e. totally empty my xml document and start afresh without deleting the xml file.
Thanks in advance
Regards...
|
|
|
|
|
Instead of this:
var q = from node in oProjectDoc.Root.DescendantsAndSelf("Clips")
let attr = node.Attribute("ID")
where attr != null && attr.Value == clipId
select node;
q.ToList().ForEach(x => x.Remove());
Why can't you do this:
var q = (from node in oProjectDoc.Root.DescendantsAndSelf("Clips")
let attr = node.Attribute("ID")
where attr != null && attr.Value != clipId
select node);
oProjectDoc.Root.RemoveAll();
foreach(XElement element in q)
{
oProjectDoc.Root.Add(element);
}
".45 ACP - because shooting twice is just silly" - JSOP, 2010 ----- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010 ----- "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass." - Dale Earnhardt, 1997
|
|
|
|
|
Hi,
will u tell me, how can i display an warning message to the user if the file he/she is uploading is open in his machine..
In my Application, i can upload only a file of type *.txt or *.csv,
so could u tell me how can i display a message to the user, when he is uploading a file of (.txt or .csv)type only when that particular file is open in his machine..
As of now in my application, it makes the application crash if that uploading file is open in user machine..
please check my code here..
private void BtnBrowseClick(object sender, RoutedEventArgs e)
{
OpenFileDialog file1 = new OpenFileDialog { Multiselect = false, Filter = "All Supported Files |*.txt;*.csv|Text|*.txt|CSV |*.csv"};
if (file1.ShowDialog() == true)
{
new FileInfo(file1.FileName);
try
{
using (Stream str = file1.OpenFile())
{
TextReader reader = new StreamReader(str);
reader.ReadToEnd();
txtFileName.Text = file1.FileName;
txtFileName.IsEnabled = false;
}
}
catch
{
txtFileName.Text = file1.FileName;
txtFileName.IsEnabled = false;
MessageBox.Show("Please check the file has been Closed before you upload", "Manual File Upload");
}
}
}
It is showing warning message if i change the permission of that file(.txt or .csv) or if i dint changed the permission, it is not showing any warning message, could u tell me how can i do it in a right way..
If possible tell me with a sample code, so i change my code or alter it...
Thanks
|
|
|
|
|
There is a hack using a Try Catch Block and catching an IOException . In your case you could do something like this,
private void BtnBrowse_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog file1 = new OpenFileDialog { Multiselect = false, Filter = "All Supported Files |*.txt;*.csv|Text|*.txt|CSV |*.csv" };
if (file1.ShowDialog() == true)
{
new FileInfo(file1.FileName);
using (Stream str = file1.OpenFile())
{
try
{
System.IO.FileStream fs = System.IO.File.OpenWrite(file1.FileName);
fs.Close();
}
catch (IOException)
{
MessageBox.Show("Please check the file has been Closed before you upload", "Manual File Upload");
return;
}
TextReader reader = new StreamReader(str);
reader.ReadToEnd();
textBox1.Text = file1.FileName;
textBox1.IsEnabled = false;
}
}
}
This solution is not very elegant but it works .The only other way I know would be to use the proper Win32 API's, which is tiresome.
Happy Coding
|
|
|
|
|
I used the above code in my application,
In both the condition like if the uploading file is open and close it is executing the catch statement,
try block is not executing if the uploading file is closed in user machine...
and also the code below the catch block is not executing...
only catch block is executing in this case,
So can u tell me how can i alter it to make it run successfully...
|
|
|
|
|
Sorry for that, but in your case this won't work as the OpenFileDialog Locks the file itself, so the IOException will always be caught. I created a function like this
private bool FileInUse(string fileName)
{
try
{
System.IO.FileStream fs = System.IO.File.OpenWrite(fileName);
fs.Close();
return true;
}
catch (IOException ex)
{
return false;
}
}
and then calling it like this
OpenFileDialog file1 = new OpenFileDialog();
if (file1.ShowDialog() == true)
{
if (!FileInUse(file1.FileName))
{
MessageBox.Show("Already Open");
}
else
{
using (Stream str = file1.OpenFile())
{
TextReader reader = new StreamReader(str);
reader.ReadToEnd();
textBox1.Text = file1.FileName;
textBox1.IsEnabled = false;
}
}
}
but this only works if the file is locked by the application that opens it (such as Word), otherwise if the file is open in an application that doesn't lock the file (such as NotePad), this always returns true.
|
|
|
|
|
Hello i have tried to get find some examples that draws behind the desktop icons and the ones i found did not do this in windows 7 atleast. so i thought i would have a go at overriding the onpaint or onrender but since im not the best yet! i can't seem to find the right way to do this. so far i managed to draw a circle behind by following this code
[DllImport("user32.dll")]
static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll")]
static extern IntPtr GetDCEx(IntPtr hwnd, IntPtr hrgn, uint flags);
.......
IntPtr hdc = GetDCEx(GetDesktopWindow(), IntPtr.Zero, 1027);
using(Graphics g = Graphics.FromHdc(hdc))
{
g.FillEllipse(Brushes.Red, 0, 0, 400, 400);
}
then i tought what if i copied the e.graphics and put it into the newly created g and then tried to draw but i can't seem to copy the content of the painteventargs, is it even possible?
so i tought i ask the masters here. anyone know how to do something like this?
|
|
|
|
|
Probably impossible. You'd have to subclass the desktop window which I think is not allowed by the OS, then hook its WM_PAINT. That'd mean injecting yourself into explorer.exe (the correct instance). If you were able to accomplish that, it would be GDI/GDI+ only. I don't think you'd be able to render WPF content though.
|
|
|
|
|
oh, well i guess i have to find some other solution then. Thanks for the heads up
|
|
|
|
|
I have only begun to learn I started with vb but every time I search for an answer most of the results are in c# Is there a tut to un learn vb and convert my knowledge to C# BECAUSE I need relevant search results to learn from
Frazzle the name say's it all
|
|
|
|
|
Is shouldn't be too hard to learn C# if you already know VB.NET
The main difference is the syntax and naming conventions. Pretty much everything else is the same.
In the mean time there are some online converters you can use.
C# to VB.NET
VB.NET to C#
Here is a tut which will teach you the basics
After that just use the converters, enter a VB.NET statement and convert to see the C# syntax.
"You get that on the big jobs."
|
|
|
|
|
|
I will suggest you to refresh your C and C++ skills. As you know VB.Net, it will not be a big deal to get used to C#.
C# simply uses the syntaxes of C and C++ only.
Hope this helps.
All the best.
|
|
|
|
|
The code below works perfect with
removeUser("testuser")
but will not work with
removeUser("domain\test user name")
Does anyone have any idea as to why?
using System;
using System.IO;
using System.Text;
using Microsoft.Win32;
using System.Security;
using System.Threading;
using System.Reflection;
using System.Diagnostics;
using System.Configuration;
using System.Globalization;
using System.ComponentModel;
using System.DirectoryServices;
using System.Security.Principal;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting.Messaging;
using System.Windows.Forms;
namespace AD
{
class ActiveDirectory
{
public static void removeUser(string userName)
{
try
{
string path = string.Format("WinNT://{0},computer", Environment.MachineName);
using (DirectoryEntry dirEntry = new DirectoryEntry(path))
{
DirectoryEntry groupEntry = dirEntry.Children.Find("Administrators", "group");
if (groupEntry != null)
{
DirectoryEntry userEntry = dirEntry.Children.Find(userName, "user");
groupEntry.Invoke("Remove", new object[] { userEntry.Path.ToString() });
groupEntry.CommitChanges();
userEntry.Dispose();
}
groupEntry.Dispose();
MessageBox.Show("Account Removed Successfully");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
|
|
|
|
|
|
Hi,
Assuming that was the correct link, the remove method is almost 100% identical to the code I posted ... am I missing something?
|
|
|
|
|
If you're in the Domain (the machine, I suppose, in the case of the local computer), prepending the Domain apparently doesn't work. Are you getting an exception, or is it just not doing anything?
..and water fell from the sky like rain.
|
|
|
|
|
I'm getting an error message
I've gotten a few when trying different things, one is that " the group could not be found (Exception from HRESULT:0x800708AC) " or " The user name could not be found (Exception from HRESULT:0x800708AD ")
|
|
|
|
|
Not finding a group or user is only an exception if you then try to use them.
Step through the code and check the values, see what you're really getting back from the searches.
..and water fell from the sky like rain.
|
|
|
|
|
Here is what I found that will work, with this code you can successfully remove a domain account from a local machine
The only problem with this is that I need to somehow enumerate through the names and only try and remove it if it matches a list? And maybe make it so that it is not case sensitive.
removeUser("domain", "group")
public static void removeUser(string domainValue, string adGroupAccount)
{
try
{
string path = string.Format("WinNT://{0},computer", Environment.MachineName);
using (DirectoryEntry dirEntry = new DirectoryEntry(path))
{
DirectoryEntry groupEntry = new DirectoryEntry("WinNT://" + System.Environment.MachineName + "/Administrators,group");
try
{
groupEntry.Invoke("Remove", "WinNT://" + domainValue + @"/" + adGroupAccount + ",user");
groupEntry.CommitChanges();
MessageBox.Show("Account Removed Successfully");
groupEntry.Dispose();
}
catch (Exception cex)
{
MessageBox.Show(cex.Message + "\n" + cex.StackTrace + "\n" + cex.Source);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
|
|
|
|
|
I don't think the username is case sensitive, anyway.
But to run it from a list, you'll have to iterate through the list and call the remove function for each name. As far as I know, there's no built-in way to do it.
..and water fell from the sky like rain.
|
|
|
|
|
You are right, I got a solution working and posted it as a reply to my original thread.
Thank you very much for your help.
|
|
|
|
|
It doesn't work because "domain est username" is invalid . You didn't escape your backslash. Plus, you also generally need 4 backslashes in front:
"\\\\domain\\test username"
Other issues could be your lack of permissions.
|
|
|
|
|
Hi,
Thanks for the response, I've added the slashes in front of the domain and the same thing happened, I do have permissions both locally and globally as I'm a local and a domain admin.
Any other thoughts?
|
|
|
|
|
Ok ...
Through the help of others here and my own due diligence, this is working now (I don't think you'll need any references added). While searching for an example, I saw many many questions on how to deal with domain accounts and local administrative groups, but no answers so I wanted to post this for googlers to save them some time.
Active directory class
using System;
using System.IO;
using System.Text;
using Microsoft.Win32;
using System.Security;
using System.Threading;
using System.Reflection;
using System.Diagnostics;
using System.Configuration;
using System.Globalization;
using System.ComponentModel;
using System.DirectoryServices;
using System.Security.Principal;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting.Messaging;
using System.Windows.Forms;
using System.Collections;
namespace AD
{
class ActiveDirectory
{
public static void removeUser(string domainValue, string adGroupAccount)
{
try
{
string path = string.Format("WinNT://{0},computer", Environment.MachineName);
using (DirectoryEntry dirEntry = new DirectoryEntry(path))
{
DirectoryEntry groupEntry = new DirectoryEntry("WinNT://" + System.Environment.MachineName + "/Administrators,group");
try
{
groupEntry.Invoke("Remove", "WinNT://" + domainValue + @"/" + adGroupAccount + ",user");
groupEntry.CommitChanges();
MessageBox.Show("Account Removed Successfully");
groupEntry.Dispose();
}
catch (Exception cex)
{
MessageBox.Show(cex.Message + "\n" + cex.StackTrace + "\n" + cex.Source);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public static void addUser(string domainValue, string adGroupAccount)
{
try
{
string path = string.Format("WinNT://{0},computer", Environment.MachineName);
using (DirectoryEntry dirEntry = new DirectoryEntry(path))
{
DirectoryEntry groupEntry = new DirectoryEntry("WinNT://" + System.Environment.MachineName + "/Administrators,group");
try
{
groupEntry.Invoke("Add", "WinNT://" + domainValue + @"/" + adGroupAccount + ",user");
groupEntry.CommitChanges();
MessageBox.Show("Account Added Successfully");
groupEntry.Dispose();
}
catch (Exception cex)
{
MessageBox.Show(cex.Message + "\n" + cex.StackTrace + "\n" + cex.Source);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public static string userExists(string userName, string groupName)
{
string returnValue = "false";
try
{
DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntry userGroup = localMachine.Children.Find(groupName, "group");
object members = userGroup.Invoke("members", null);
foreach (object groupMember in (IEnumerable)members)
{
DirectoryEntry member = new DirectoryEntry(groupMember);
if (member.Name.Equals(userName, StringComparison.CurrentCultureIgnoreCase))
{
returnValue = "true";
break;
}
}
}
catch (Exception ex)
{
returnValue = "false";
}
return (returnValue);
}
}
}
Click for an image of the form
Here is the code on how to run it with a simple form that has 3 buttons and 2 textbox input boxes. Put the group name and the domain into the boxes as so. I've hard coded the group I want to search through (Administrators) so you'll have to change that if you want to search through another group. The user exists is not case sensitive.
private void button2_Click(object sender, EventArgs e)
{
string domain = textBox1.Text;
string userName = textBox2.Text;
try
{
AD.ActiveDirectory.addUser(domain, userName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button3_Click(object sender, EventArgs e)
{
string domain = textBox1.Text;
string userName = textBox2.Text;
try
{
AD.ActiveDirectory.removeUser(domain, userName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button4_Click(object sender, EventArgs e)
{
string domain = textBox1.Text;
string userName = textBox2.Text;
string result = AD.ActiveDirectory.userExists(userName, "Administrators");
MessageBox.Show("Exists equals " + result);
}
|
|
|
|