remove xmlns="something" from xml document using linq to xml - asp.net

I'm parsing an xml file.
the first line of xml looks like;
<DataSetMenu xmlns="http://tempuri.org/DataSetMenu.xsd">
I'm using below code to parse the xml.
string filename = Request.QueryString["file"].ToString();
XElement xdocument = XElement.Load(Server.MapPath("xml\\" + filename));
xdocument.Attribute("xmlns").Remove();
IEnumerable<XElement> MenuGroups = xdocument.Elements();
sb.Append("<link href='StyleSheet.css' rel='stylesheet' type='text/css' />");
foreach (var xel in MenuGroups)
{
if (xel.Elements("MenuCatName").Any())
{
Int32 MenuCatID = Convert.ToInt32(xel.Element("MenuCatID").Value);
string MenuCatName = xel.Element("MenuCatName").Value;
sb.Append("<div class='CategoryDiv'><h1 class='category'>" + MenuCatName + " </h1>");
GetGroupItems(xdocument, MenuCatID);
}
}
But when ever xml file's first node contains :
xmlns="http://tempuri.org/DataSetMenu.xsd"
It doesn't work at all. when i try to access xml's data it gives me error, Object reference not set to an instance of an object
XML FILE
<DataSetMenu xmlns="http://tempuri.org/DataSetMenu.xsd">
<MenuCategories>
<MenuCatID>10108</MenuCatID>
<MenuCatName>SPEICALS</MenuCatName>
<BusinessEntityID>20137</BusinessEntityID>
<DisplayIndex>10107</DisplayIndex>
<MenuCatDesc />
<Visible>true</Visible>
<ImagePath />
</MenuCategories>
<MenuCategories>
<MenuCatID>10109</MenuCatID>
<MenuCatName>GENERAL MENU</MenuCatName>
<BusinessEntityID>20137</BusinessEntityID>
<DisplayIndex>10108</DisplayIndex>
< MenuCatDesc />
<Visible>true</Visible>
<ImagePath />
</MenuCategories>
<MenuGroups>
<MenuGroupID>110079</MenuGroupID>
<MenuCatID>10108</MenuCatID>
<MenuGroupName>SPECIAL OFFERS</MenuGroupName>
<MenuGroupDesc />
<Visible>true</Visible>
<DisplayIndex>0</DisplayIndex>
<MenuTypeID>1</MenuTypeID>
<ImagePath />
<ServiceTimeEnforced>false</ServiceTimeEnforced>
<ServiceStartTime>1900-01-01T11:00:00-06:00</ServiceStartTime>
<ServiceEndTime>1900-01-01T15:00:00-06:00</ServiceEndTime>
<Monday>true</Monday>
<Tuesday>true</Tuesday>
<Wednesday>true</Wednesday>
<Thursday>true</Thursday>
<Friday>true</Friday>
<Saturday>true</Saturday>
<Sunday>true</Sunday>
</MenuGroups>
</DataSetMenu>
Give me a solution so that it works fine. Or any way to remove this attribute.
Thanks.
Now It's now working here
private void GetGroupItems(XElement xdocument, Int32 MenuCatID)
{
var MenuGroup = from nm in xdocument.Elements("MenuGroups")
where (int)nm.Element("MenuCatID") == MenuCatID
select nm;
foreach (XElement GroupName in MenuGroup)
{
Int32 MenuGroupID = Convert.ToInt32(GroupName.Element("MenuGroupID").Value);
string MenuGroupName = GroupName.Element("MenuGroupName").Value;
sb.Append("<div class='IType'>" + MenuGroupName + " </div>");
sb.Append("<table class='restaurantlist'><tbody><tr><td class='righttd'>");
GetMenuItems(MenuGroupID, xdocument);
sb.Append("</td></tr></tbody></table>");
sb.Append("<div class='restaurantlistdiv'><div style='clear: both;'></div>");
}
}
please tell me, how should i modify this?

You have to specify namespace when you're querying your XML.
Create XNamespace instance:
var ns = XNamespace.Get("http://tempuri.org/DataSetMenu.xsd");
Then use XNamespace + String operator implementation:
public static XName operator +(
XNamespace ns,
string localName
)
within Elements() method call, like that:
IEnumerable<XElement> MenuGroups = xdocument.Elements();
sb.Append("<link href='StyleSheet.css' rel='stylesheet' type='text/css' />");
foreach (var xel in MenuGroups)
{
if (xel.Elements(ns + "MenuCatName").Any())
{
Int32 MenuCatID = Convert.ToInt32(xel.Element(ns + "MenuCatID").Value);
string MenuCatName = xel.Element(ns + "MenuCatName").Value;
sb.Append("<div class='CategoryDiv'><h1 class='category'>" + MenuCatName + " </h1>");
GetGroupItems(xdocument, MenuCatID);
}
}

The key thing to remember here is that you are not working with an attribute, but the namespace declaration. That's why you can't just remove the attribute. See if the suggestions at C#: How to remove namespace information from XML elements help.

Related

ado.net query removes file exention when adding string filename to the database

I am using the code below for saving uploaded picture and makigna thumbnail but it saves a filename without the extension to the database, therefore, I get broken links. How can I stop a strongly typed dataset and dataadapter to stop removing the file extension? my nvarchar field has nvarchar(max) so problem is not string length.
I realized my problem was the maxsize in the dataset column, not sql statement parameter, so I fixed it. You may vote to close on this question.
hasTableAdapters.has_actorTableAdapter adp1 = new hasTableAdapters.has_actorTableAdapter();
if (Convert.ToInt16(adp1.UsernameExists(username.Text)) == 0)
{
adp1.Register(username.Text, password.Text,
ishairdresser.Checked, city.Text, address.Text);
string originalfilename = Server.MapPath(" ") + "\\pictures\\" + actorimage.PostedFile.FileName;
string originalrelative = "\\pictures\\" + actorimage.FileName;
actorimage.SaveAs(originalfilename);
string thumbfilename = Server.MapPath(" ") + "\\pictures\\t_" + actorimage.PostedFile.FileName;
string thumbrelative = "\\pictures\\t_" + actorimage.FileName;
Bitmap original = new Bitmap(originalfilename);
Bitmap thumb=(Bitmap)original.GetThumbnailImage(100, 100,
new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback),
IntPtr.Zero);
thumb=(Bitmap)original.Clone(
new Rectangle(new Point(original.Width/2,original.Height/2), new Size(100,100)),
System.Drawing.Imaging.PixelFormat.DontCare);
/*
bmpImage.Clone(cropArea,bmpImage.PixelFormat);
*/
thumb.Save(thumbfilename);
adp1.UpdatePicture(originalrelative, thumbrelative, username.Text);
LoginActor();
Response.Redirect("Default.aspx");
}
}
Looks like the problem is you are using HttpPostedFile.FileName property, which returns fully-qualified file name on the client. So, this code string originalfilename = Server.MapPath(" ") + "\\pictures\\" + actorimage.PostedFile.FileName; generates something like this:
c:\inetpub\pictures\c:\Users\Username\Pictures\image1.jpg
Use FileUpload.FileName property everywhere and you will probably get what you want.
Use this to get Image or file extension :
string Extension = System.IO.Path.GetExtension(FileUpload.FileName);

How to replace the file name(particular specific folder) using Asp.net?

i can replace the file name in particular folder , i wrote like this
FileInfo fsource = new FileInfo(Server.MapPath("~/PurchaseOrder/" + lblhideid.Text));
if (fsource.Exists)
{
string[] file = lblhideid.Text.Split('.');
string fName="Z-"+System.DateTime.Now.ToString("MM-dd-yyyy")+"-"+saveConsultantID+"."+file[1];
fsource.Name.Replace(lblhideid.Text, fName);
}
lblhideid.Text=image.jpeg , so i can replace the my own name like fName , how to replace the name pls give me any suggestion.
Thank u
Hemanth
I suspect you want that last line to be:
fsource.MoveTo(Server.MapPath("~/PuchaseOrder/" + fName));
You current code is only getting the filename as a string and manipulate that string. You want to manipulate the file itself.
EDIT:
Are you sure that ~/PurchaseOrder/ exists?
Try:
string originalPath = Server.MapPath("~/PurchaseOrder/" + lblhideid.Text);
FileInfo fsource = new FileInfo(originalPath);
if (fsource.Exists)
{
string newName = string.Format("Z-{0:MM-dd-yyyy}-{1}.{2}",
System.DateTime.Now,
saveConsultantID,
fsource.Extension);
string newPath = Path.Combine(fsource.DirectoryName, newName);
fsource.MoveTo(newPath);
}
Try this, what if they put a filename like file.tar.gz ?
string extension = Path.GetExtension("~/PurchaseOrder/" + lblhideid.Text);
string newName = "MYFILE." + extension
File.Move(
"~/PurchaseOrder/" + lblhideid.Text,
"~/PurchaseOrder/" + newName );

How do I load content into Request.Files collection for latter retrieval on server side?

I'm using a multi-upload input control and it is not server sided i.e pure HTML not asp: tagged.
Now the issue is on the server side I'm trying to access the Request object's Files collection hoping that after an upload, the input control will put the files into this collection in question.
I even imported some scripts in javascript to make it work but whenever I step through the code behind, the Request.Files property, which should contain the browsed and chosen files, is always empty. What should I do? Ooooops! sorry i didnt show some code:
var x = this.Page.FindControl("FileUpload1");
lbuploadmessage.Text = x.GetType().ToString();
HttpFileCollection hfc = Request.Files;
List<L2SQLData.PatientFile> list = new List<L2SQLData.PatientFile>();
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0 && hpf.ContentLength < 1024000)
{
string filename = Path.GetFileName(hpf.FileName);
string ext = Path.GetExtension(hpf.FileName);
var guidname = Guid.NewGuid().ToString();
//FileUpload1.SaveAs(Server.MapPath("~/Uploads/DocClerkings/") + guidname + ext);
hpf.SaveAs(Server.MapPath("~/Uploads/DocClerkings/") + guidname + ext );
lbuploadmessage.Text = "Upload status:" + hpf.FileName + " successfully uploaded!";
As you can see I named the control-"FileUpload1" but at runtime (Debug) the object x is null and Request.Files collection that's supposed to contain the browsed files is empty too. The multi - upload control looks like this:
<input id = "FileUpload1" type="file" class="multi"/>
with two scripts i added as follows:
<script src="jquery-latest.js" type="text/javascript" language="javascript"></script>
<script src="jquery.MultiFile.js" type="text/javascript" language="javascript"></script>
So what did I leave out?
Cheers
To make it work you need to change it
<asp:FileUpload ID="FileUpload1" runat="server" class="multi" />
That plugin is unobstrusive and knows from class="multi" that you want it to do something...
For a complete walkthrough on how to make it work see http://www.dotnetcurry.com/ShowArticle.aspx?ID=317 and http://www.codeproject.com/KB/aspnet/multiple_file_upload.aspx
Remark: your usage is not working because this plugin does NOT upload anything, it is "only" for providing some nice additions on the client side - from http://www.fyneworks.com/jquery/multiple-file-upload/#tab-Uploading
Can this plugin upload files?
No, this jQuery plugin does not upload files
I finally found the missing link at http://docs.jquery.com/Tutorials:Multiple_File_Upload_Magic
var fileMax = 3;
$("input[#type=file]").change(function(){
doIt(this, fileMax);
});
These lines are all in the designer mark up. Of course the server code still remains the same as detailed in Yahia's solution above-reason why I accepted it :D. Here it is- in the upload button place this:
HttpFileCollection hfc = Request.Files;
List<L2SQLData.PatientFile> list = new List<L2SQLData.PatientFile>();
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0 && hpf.ContentLength < 1024000)
{
string filename = Path.GetFileName(hpf.FileName);
string ext = Path.GetExtension(hpf.FileName);
var guidname = Guid.NewGuid().ToString();
hpf.SaveAs(Server.MapPath("~/Uploads/DocClerkings/") + guidname + ext );
lbuploadmessage.Text = "Upload status:" + hpf.FileName + " successfully uploaded!";
Thanks for the assistance Yahia and everyone. You guys on Stack Overfolow are the best!

HTML being encoded automatically

I have a .htm file with some template stuff that looks a little like this:
<div>
<h1>My template</h1>
<div>
<%replacable%>
</div>
</div>
I get my helper to read it in:
string str = Helper.ReadFile("~/Templates/myTemplate.htm");
I replace my stuff:
str = str.Replace("<%replacable%>", "tadah!");
I set my editor:
AjaxHTMLEditor.Content = str;
by the time it gets to the editor it's all bloody crap :(
%Address1%><br /><%Address2%>, <%Address3%><br/><%Postcode%><br /><br />
and here's my readfile code:
public static string ReadFile(string filename)
{
string contents = "";
filename = HttpContext.Current.Server.MapPath(filename);
if (File.Exists(filename))
{
StreamReader sr;
sr = File.OpenText(filename);
contents = sr.ReadToEnd();
}
return contents;
}
Why is my HTML being encoded????
if I set the AjaxHTMLEditor with a direct string then it's fine:
AjaxHTMLEditor.Content = "<div> <h1>My template</h1> <div> tadah! </div> </div>";
Any help appreciated
I replace my stuff:
str.Replace("<%replacable%>", "tadah!");
You are not replacing anything here. You don't return a value. In .NET strings are immutable so the .Replace method returns the new value.
If you wanted to replace you would do:
var filename = HttpContext.Current.Server.MapPath("~/Templates/myTemplate.htm");
string str = File.ReadAllText(filename).Replace("<%replacable%>", "tadah!");
At this stage the str variable will contain unencoded value.
What happens next will greatly depend on what you are doing with this str variable. For example if AjaxEditor.Content already HTML encodes the value (whatever this AjaxEditor is) this is probably the reason why you get HTML encoded at the end.

Formatting JSON in ASP.NET HttpResponse

I'm sending back a bunch of image tags via JSON in my .ashx response.
I am not sure how to format this so that the string comes back with real tags. I tried to HtmlEncode and that sort of fixed it but then I ended up with this stupid \u003c crap:
["\u003cimg src=\"http://www.sss.com/image/65.jpg\" alt=\"\"\u003e\u003c/li\u003e","\u003cimg src=\"http://www.xxx.com/image/61.jpg\" alt=\"\"\u003e\u003c/li\u003e"]
What the heck is \u003c ?
here's my code that created the JSON for response to my .ashx:
private void GetProductsJSON(HttpContext context)
{
context.Response.ContentType = "text/plain";
int i = 1;
...do some more stuff
foreach(Product p in products)
{
string imageTag = string.Format(#"<img src=""{0}"" alt=""""></li>", WebUtil.ImageUrl(p.Image, false));
images.Add(imageTag);
i++;
}
string jsonString = images.ToJSON();
context.Response.Write(HttpUtility.HtmlEncode(jsonString));
}
the toJSON is simply using the helper method outlined here:
http://weblogs.asp.net/scottgu/archive/2007/10/01/tip-trick-building-a-tojson-extension-method-using-net-3-5.aspx
\u003c is an escaped less-than character in unicode (Unicode character 0x003C).
The AJAX response is fine. When that string is written to the DOM, it will show up as a normal "<" character.
You are returning JSON array. Once parsed using eval("("+returnValue+")") it is in readily usable condition.
EDIT: This code is from jquery.json.js file:
var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;
var meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
$.quoteString = function(string)
// Places quotes around a string, inteligently.
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
{
if (escapeable.test(string))
{
return '"' + string.replace(escapeable, function (a)
{
var c = meta[a];
if (typeof c === 'string') {
return c;
}
c = a.charCodeAt();
return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
}) + '"';
}
return '"' + string + '"';
};
Hope this gives you some direction to go ahead.
all you need to do is to use javascript eval function to get a pure HTML (XML) markup on the front end.
i.e. in a ajax call to a webservice, this can be the success handler of tha call,
the service returns a complex html element:
...
success: function(msg) {$(divToBeWorkedOn).html(**eval(**msg**)**);alert(eval(msg));},
...

Resources