Writting XML File - asp.net

hey guys in the first place I would like to thank all of you for your time and reading my question
I have an XML file which is
<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns:video="http://www.google.com/schemas/sitemap-video/1.1" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://www.MyWEbSite.com/video/ScreenImage/Photoq </loc>
<video>
<thumbnail_loc>https://www.MyWEbSite.com/video/ScreenImage/MyWEbSiteMyTitle.mp4.Jpg</thumbnail_loc>
<title>MyTitle</title>
<description>My Dec</description>
<content_loc>https://www.MyWEbSite.com/api/media/play?f=MyWEbSiteMyTitle.mp4</content_loc>
<duration>
500
</duration>
<expiration_date>2050-11-05T19:20:30+08:00</expiration_date>
<view_count>982</view_count>
<publication_date>2019-04-12</publication_date>
<family_friendly>yes</family_friendly>
<live>No</live>
<category>دين</category>
</video>
</url>
</urlset>
I want my Xml file be like this :
*<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns:video="http://www.google.com/schemas/sitemap-video/1.1" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://www.myWebsite.com</loc>
<video:video>
<video:thumbnail_loc>https://www.MyWEbSite.com/video/ScreenImage/Photoq </video:thumbnail_loc>
<video:title>MyTitle</video:title>
<video:description>My Dec</video:description>
<video:content_loc>https://www.MyWEbSite.com/api/media/MyWEbSiteMyTitle.mp4</video:content_loc>
<video:duration>
500
</video:duration>
<video:expiration_date>2050-11-05T19:20:30+08:00</video:expiration_date>
<video:view_count>982</video:view_count>
<video:publication_date>2019-04-12</video:publication_date>
<video:family_friendly>yes</video:family_friendly>
<video:live>No</video:live>
<video:category>دين</video:category>
</video:video>
</url>
</urlset>*
And this code what im using to write my xml file
string a = "video:video";
string b = "video:thumbnail_loc";
string c = "video:title";
string vd = "video:description";
string d = "video:content_loc";
string e = "video:view_count";
string f = "video:family_friendly";
string g = "video:live";
string h = "video:category";
string k = "video:publication_date";
string m = "video:duration";
string nn = "video:expiration_date";
string xmlpath = #"~/MyXmlFile.xml";
string path = Server.MapPath(xmlpath);
XmlDocument doc = new XmlDocument();
doc.Load(path);
var mainRoot = doc.DocumentElement; //urlset element
var urlRoot = mainRoot.AppendChild(doc.CreateElement("url", mainRoot.NamespaceURI));
urlRoot.AppendChild(doc.CreateElement(("loc"), mainRoot.NamespaceURI));
urlRoot.ChildNodes[0].InnerText = VideoURL;
var VidooTree = urlRoot.AppendChild(doc.CreateElement(a, ""));
VidooTree.AppendChild(doc.CreateElement(b)).InnerText = imgur;
VidooTree.AppendChild(doc.CreateElement(c)).InnerText = VideoTitle;
VidooTree.AppendChild(doc.CreateElement(vd)).InnerText = videoDec;
VidooTree.AppendChild(doc.CreateElement(d)).InnerText = VideoApi;
VidooTree.AppendChild(doc.CreateElement(m)).InnerText = duration;
VidooTree.AppendChild(doc.CreateElement(nn)).InnerText = "2050-11-05T19:20:30+08:00";
VidooTree.AppendChild(doc.CreateElement(e)).InnerText = watched;
VidooTree.AppendChild(doc.CreateElement(k)).InnerText = date;
VidooTree.AppendChild(doc.CreateElement(f)).InnerText = "yes";
VidooTree.AppendChild(doc.CreateElement(g)).InnerText = "No";
VidooTree.AppendChild(doc.CreateElement(h)).InnerText = VideoKindName;
urlRoot.AppendChild(VidooTree);
mainRoot.AppendChild(urlRoot);
doc.Save(Server.MapPath(xmlpath));
var xmlRead = File.ReadAllText(path);
var indexVideo = xmlRead.IndexOf(#"<video xmlns=""");
var sString = xmlRead.Substring(indexVideo, 15);
xmlRead = xmlRead.Replace(sString, "<video");
File.WriteAllText(path, xmlRead);
im really thankful for all of you and im really thankful for your times guys have nice day and a lot of fun

First use the overload of doc.CreateElement withnameSpaceURI
Second Isolate the substring of <Video> element, then loop through until xmlns==-1 which indicates no more xmlns attributes in the substring.
Within the loop we replace string that starts with " xmlns" and ends with ">" which matches our search criteria
.
.
var VidooTree = urlRoot.AppendChild(doc.CreateElement(a,a));
VidooTree.AppendChild(doc.CreateElement(b, b)).InnerText = "thumbNail";
VidooTree.AppendChild(doc.CreateElement(c, c)).InnerText = "VideoTitle";
.
.
doc.Save(Server.MapPath(xmlpath));
var xmlRead = File.ReadAllText(path);
var indexVideoSearch = xmlRead.IndexOf(#"<video:video xmlns:video=");
var firstPart = xmlRead.Substring(0, indexVideoSearch);
var secondPart = xmlRead.Substring(indexVideoSearch);
while( secondPart.IndexOf(#" xmlns")!=-1)
{
var index2 = secondPart.IndexOf(#" xmlns");
var lengthToCapture = secondPart.IndexOf(#""">")+1;
var differnce = lengthToCapture - index2;
var stringToRemove = secondPart.Substring(index2, differnce);
secondPart = secondPart.Replace(stringToRemove, string.Empty);
}
xmlRead = firstPart + secondPart;
File.WriteAllText(path, xmlRead);
Sample Output Format:
<url>
<loc>VideoURL</loc>
<video:video>
<video:thumbnail_loc>thumbNail</video:thumbnail_loc>
<video:title>VideoTitle</video:title>
<video:category>VideoKindName</video:category>
</video:video>
</url>

Related

Write to Spreadsheet in Google sheet from ASP.NET

I have a code, it should write in the Spreadsheet of google sheet. When I run the function, I receive this error:
Message[Requested writing within range ['6/12/2019-20:37'!A1], but
tried writing to column [B]] Location[ - ] Reason[badRequest]
Domain[global]
That its my code:
private void SheetPattern(Item webinar)
{
var valueRange = new ValueRange();
var range = $"{sheet}!A:D";
DateTime dateTime=(DateTime)webinar.webInfo.times[0].startTime;
var date = dateTime.Day+"-"+dateTime.Month+"-"+dateTime.Year;
var hour = dateTime.Hour + ":" + dateTime.Minute;
var webName = webinar.webInfo.subject;
var webDescription = webinar.webInfo.description;
var oblist = new List<object>() { date, hour, webName, webDescription};
valueRange.Values = new List<IList<object>> { oblist };
var appendRequest = service.Spreadsheets.Values.Append(valueRange, SpreadsheetId, range);
Console.WriteLine(appendRequest);
appendRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum.USERENTERED;
var appendReponse = appendRequest.Execute();
}
I found the problem its a Syntax problem, here:
var hour = dateTime.Hour + ":" + dateTime.Minute;
when I make a new sheet with a new name, google sheet doesn't permit the char : in the sheet name. So I change this code for that code:
var hour = dateTime.Hour + "-" + dateTime.Minute;

Convert string start with 0 to 2 decimal place asp.net?

I have this string:
Dim value as String = "0.11209176170341301"
And tried to use this code to convert the string into decimal with two places:
Dim value as String = "0.11209176170341301"
Dim valueInDecimal As Decimal
If [Decimal].TryParse(value, valueInDecimal) Then
Console.WriteLine(valueInDecimal.ToString("0:0.#"))
End If
I get this result:
11209176170341301D
I need to get this:
0.11
What I'm doing wrong?
I want to get as result a decimal with two placesfrom the string value
You can use basic string operations also:
string value = "0.11209176170341301";
var parts = value.Split('.');
var floatingPart = parts[1].Substring(0, 2);
var truncatedValue = parts[0] + "," + floatingPart;
decimal d = decimal.Parse(truncatedValue);
string s = d.ToString();
Console.Write(s);
Console.Read();
If you are only needed it as string then you can just truncate it as string then it will be easier like:
string value = "0.11209176170341301";
var parts = value.Split('.');
var floatingPart = parts[1].Substring(0, 2);
var truncatedValue = parts[0] + "," + floatingPart;
Console.Write(truncatedValue);
Or even you do not convert '.' to ',' then it will be like this:
string value = "0.11209176170341301";
var parts = value.Split('.');
var floatingPart = parts[1].Substring(0, 2);
var truncatedValue = string.Join(".",parts[0],floatingPart);
Console.Write(truncatedValue);
Use Math.Round function
var x = "0.11209176170341301";
Console.Write(Math.Round(Convert.ToDecimal(x), 2));

How i can current date Outputfilename Data Extract Arcgis Flex

outputFileName = (configXML.outputfilename[0] || "Dataextracted") + ".zip";
outputFileName = outputFileName.replace(/(\\|\/|:|\?|"|<|>|\|)/g, "");
"Dataextracted" change current date time
replace "Dataextracted" with
new Date()
To format it:
var df:spark.formatters.DateTimeFormatter = new DateTimeFormatter();
df.dateTimePattern = "yyyy-MMM-dd-HHmmss";
trace(df.format(new Date())); //output 2016-Oct-13-095823

Creating a request as XML in Asp.Net

I need to create a request with XMLDocument which have some specific values and i can't make it. My xml should look like that;
<?xml version="1.0" encoding="ISO-8859-9" ?>
<ePaymentMsg VersionInfo="2.0" TT="Request" RM="Direct" CT="Money">
<Operation ActionType="Sale">
<OpData>
<MerchantInfo MerchantId="006100" MerchantPassword="123" />
<ActionInfo>
<TrnxCommon TrnxID="">
<AmountInfo Amount="1.00" Currency="949" />
</TrnxCommon>
<PaymentTypeInfo>
<InstallmentInfo NumberOfInstallments="0"/>
</PaymentTypeInfo>
</ActionInfo>
<PANInfo PAN="402275******5574" ExpiryDate="201406" CVV2="***" BrandID="MASTER" />
<OrgTrnxInfo />
<CardHolderIP>127.0.0.1</CardHolderIP>
</OpData>
</Operation>
</ePaymentMsg>
Can anyone help me how to create this xml with using C# XmlDocument, XmlNode
I tried this,
XmlNode node = null;
XmlDocument _msgTemplate = new XmlDocument();
_msgTemplate.LoadXml("<?xml version=\"1.0\" encoding=\"UTF-8\" ?><ePaymentMsg VersionInfo=\"2.0\" TT=\"Request\" RM=\"Direct\" CT=\"Money\">" +
"<Operation ActionType=\"Sale\"><OpData><MerchantInfo MerchantId=\"\" MerchantPassword=\"\" />" +
"<ActionInfo><TrnxCommon TrnxID=\"\" Protocol=\"156\"><AmountInfo Amount=\"0\" Currency=\"792\" /></TrnxCommon><PaymentTypeInfo>" +
"<InstallmentInfo NumberOfInstallments=\"0\" /></PaymentTypeInfo></ActionInfo><PANInfo PAN=\"\" ExpiryDate=\"\" CVV2=\"\" BrandID=\"\" />" +
"<OrderInfo><OrderLine>0</OrderLine></OrderInfo><OrgTrnxInfo /><CustomData></CustomData><CardHolderIp></CardHolderIp></OpData></Operation></ePaymentMsg>");
node = _msgTemplate.SelectSingleNode("//ePaymentMsg/Operation/OpData/MerchantInfo");
node.Attributes["MerchantId"].Value = "006100";
node.Attributes["MerchantPassword"].Value = "123";
node = _msgTemplate.SelectSingleNode("//ePaymentMsg/Operation/OpData/ActionInfo/TrnxCommon");
node.Attributes["TrnxID"].Value = Guid.NewGuid().ToString();
node = _msgTemplate.SelectSingleNode("//ePaymentMsg/Operation/OpData/ActionInfo/TrnxCommon/AmountInfo");
string gonderilecekAmount = amount.ToString("####.00");
gonderilecekAmount = gonderilecekAmount.Replace(",", ".");
node.Attributes["Amount"].Value = gonderilecekAmount;
node.Attributes["Currency"].Value = "949";
node = _msgTemplate.SelectSingleNode("//ePaymentMsg/Operation/OpData/ActionInfo/PaymentTypeInfo/InstallmentInfo");
node.Attributes["NumberOfInstallments"].Value = "0";
node = _msgTemplate.SelectSingleNode("//ePaymentMsg/Operation/OpData/PANInfo");
node.Attributes["PAN"].Value = "402275******5574";
node.Attributes["ExpiryDate"].Value = "201406";
node.Attributes["CVV2"].Value = "***";
node.Attributes["BrandID"].Value = "VISA";
node = _msgTemplate.SelectSingleNode("//ePaymentMsg/Operation/OpData/CardHolderIp");
node.Attributes["CardHolderIp"].Value = "10.20.30.40";
request = _msgTemplate.OuterXml;
return request;
I think something wrong on CardHolderIp node. Any help would be useful.
In the
node.Attributes["CardHolderIp"].Value = "10.20.30.40";
line, i changed it to
node.InnerText= "10.20.30.40";

DateTime Not working in Global.asax in c#

I am trying to use DateTime in global.asax to give a name to a file but it gives an error. Could you please assist?
The code I am using for the DateTime;
public void callFileCreate()
{
string path = ConfigurationManager.AppSettings["LogFileFolder"].ToString();
string filename = HttpContext.Current.Server.MapPath(path + "\\Log_" + DateTime.Now.ToShortDateString().Replace("/", ".") + "_" + (DateTime.Now.ToLongTimeString()).Replace(":", "_") + ".txt");
TraceFilePath = HttpContext.Current.Server.MapPath(path + "\\Scheduler" + DateTime.Now.ToShortDateString().Replace("/", ".") + "_" + (DateTime.Now.ToLongTimeString()).Replace(":", "_") + ".txt");
FileStream fs = null, fs1 = null;
fs = File.Create(filename);
fs1 = File.Create(TraceFilePath);
ErrorFilePath = filename;
}
You should use the Path class if you work with paths:
string path = ConfigurationManager.AppSettings["LogFileFolder"].ToString();
string fileName = string.Format("{0}_{1}_{2}.txt"
, "Log"
, DateTime.Today.ToString("dd.MM.yyyy") // change according to your actual culture
, DateTime.Now.ToString("HH_mm_ss"));
string fullPath = Path.Combine(path, fileName);
Not sure if that solves your issue, but it increases readability and avoids careless mistakes anyway.
You don't write what error you get. But here are some hints about how you can simplify your code:
var dir = HttpContext.Current.Server.MapPath(
ConfigurationManager.AppSettings["LogFileFolder"].ToString());
var dt = DateTime.Now.ToString("yyyy.MM.dd_HH.mm.ss");
var logFilePath = Path.Combine(dir, string.Format("Log_{0}.txt", dt));
var traceFilePath = Path.Combine(dir, string.Format("Scheduler_{0}.txt", dt));
var fs = File.Create(logFilePath);
var fs1 = File.Create(traceFilePath);
Notes:
if the app-settings entry LogFileFolder already contains an (absolute) filesystem-path such as c:\temp, then you shouldn't call Server.MapPath().
you should call fs.Close() once you no longer need the streams (or put it in a using block). Otherwise, another attempt to create the (same) file will result in an exception.

Resources