Creating a request as XML in Asp.Net - 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";

Related

Writting XML File

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>

i want to add a new value in access but when i run this it inserts the last viewed data [duplicate]

I have a webpage that has a web form on it. The form is pre-populated with data from a SQL Server database. The user can go in and edit any of the fields and click the "Save" button on the bottom to update the record in the database. For some reason, the update statement isnt updating the record in the database when I have the form pre-filled with data. If I remove the code pre-filling the form on the page load method the update statement works as it should. When I have the form pre-filled with data in the page load method, the update statement appears to be updating the record with the same data that it already had in it, not the new information the user entered. I am completely lost on how to fix this issue as the form has to have data preloaded in it so the user can edit the form respectively.
Can someone point out an error or some correction that I need to make? I've hit the proverbially brick wall :(
Below you will find the page load method and the save button click event handler.
protected void Page_Load(object sender, EventArgs e)
{
String projectID = Request.QueryString["jobID"];
String reportID = Request.QueryString["reportID"];
string selectStatement = "SELECT * FROM ahu_data WHERE unit_ID = " + reportID;
string sqlConnectionString = "Removed for Security";
using (SqlConnection connection1 = new SqlConnection(sqlConnectionString))
{
SqlCommand selectCommand = new SqlCommand(selectStatement, connection1);
connection1.Open();
using (SqlDataReader reader = selectCommand.ExecuteReader())
{
while (reader.Read())
{
UMTextBox.Text = reader["make"].ToString();
UMOTextBox.Text = reader["model"].ToString();
UTTextBox.Text = reader["type"].ToString();
USITextBox.Text = reader["size"].ToString();
USTextBox.Text = reader["serial"].ToString();
UATextBox.Text = reader["arrangement"].ToString();
UCTextBox.Text = reader["class"].ToString();
UDTextBox.Text = reader["discharge"].ToString();
UMSTextBox.Text = reader["make_sheave"].ToString();
USDTextBox.Text = reader["sheave_diameter"].ToString();
USBTextBox.Text = reader["sheave_bore"].ToString();
UBNTextBox.Text = reader["belts"].ToString();
UBSTextBox.Text = reader["belt_size"].ToString();
UFNTextBox.Text = reader["filters"].ToString();
UFSTextBox.Text = reader["filter_size"].ToString();
TCFMDTextBox.Text = reader["unitTotalCFMDesign"].ToString();
TCFMATextBox.Text = reader["unitTotalCFMActual"].ToString();
RACFMDTextBox.Text = reader["unitReturnAirCFMDesign"].ToString();
RACFMATextBox.Text = reader["unitReturnAirCFMActual"].ToString();
OACFMDTextBox.Text = reader["unitOutsideAirCFMDesign"].ToString();
OACFMATextBox.Text = reader["unitOutsideAirCFMActual"].ToString();
EACFMDTextBox.Text = reader["unitExhaustAirCFMDesign"].ToString();
EACFMATextBox.Text = reader["unitExhaustAirCFMActual"].ToString();
FRPMDTextBox.Text = reader["unitFanRPMDesign"].ToString();
FRPMATextBox.Text = reader["unitFanRPMActual"].ToString();
MRPMDTextBox.Text = reader["unitMotorRPMDesign"].ToString();
MRPMATextBox.Text = reader["unitMotorRPMActual"].ToString();
MVDTextBox.Text = reader["unitMotorVoltsDesign"].ToString();
MVATextBox.Text = reader["unitMotorVoltsActual"].ToString();
MADTextBox.Text = reader["unitMotorAmpsDesign"].ToString();
MAATextBox.Text = reader["unitMotorAmpsActual"].ToString();
MMTextBox.Text = reader["motor_make"].ToString();
MFTextBox.Text = reader["motor_frame"].ToString();
MHPTextBox.Text = reader["motor_hp"].ToString();
MRPMTextBox.Text = reader["motor_rpm"].ToString();
MVTextBox.Text = reader["motor_volts"].ToString();
MPHTextBox.Text = reader["motor_phasehz"].ToString();
MFLATextBox.Text = reader["motor_fl_amps"].ToString();
MSFTextBox.Text = reader["motor_sf"].ToString();
MMSTextBox.Text = reader["motor_make_sheave"].ToString();
MSDTextBox.Text = reader["motor_sheave_diameter"].ToString();
MSBTextBox.Text = reader["motor_sheave_bore"].ToString();
MODTextBox.Text = reader["motor_operating_diameter"].ToString();
MSCDTextBox.Text = reader["motor_sheave_center_distance"].ToString();
TSPDTextBox.Text = reader["motorTotalSPDesign"].ToString();
TSPATextBox.Text = reader["motorTotalSPActual"].ToString();
ESPDTextBox.Text = reader["motorEnteringSPDesign"].ToString();
ESPATextBox.Text = reader["motorEnteringSPActual"].ToString();
SSPDTextBox.Text = reader["motorSuctionSPDesign"].ToString();
SSPATextBox.Text = reader["motorSuctionSPActual"].ToString();
DSPDTextBox.Text = reader["motorDischargeSPDesign"].ToString();
DSPATextBox.Text = reader["motorDischargeSPActual"].ToString();
PCSPDTextBox.Text = reader["motorPreheatCoilSPDesign"].ToString();
PCSPATextBox.Text = reader["motorPreheatCoilSPActual"].ToString();
CCSPDTextBox.Text = reader["motorCoolingCoilSPDesign"].ToString();
CCSPATextBox.Text = reader["motorCoolingCoilSPActual"].ToString();
RCSPDTextBox.Text = reader["motorReheatCoilSPDesign"].ToString();
RCSPATextBox.Text = reader["motorReheatCoilSPActual"].ToString();
FSPDTextBox.Text = reader["motorFilterSPDesign"].ToString();
FSPATextBox.Text = reader["motorFilterSPActual"].ToString();
AFSPDTextBox.Text = reader["motorAfterFilterSPDesign"].ToString();
AFSPATextBox.Text = reader["motorAfterFilterSPActual"].ToString();
WSPDTextBox.Text = reader["motorWheelSPDesign"].ToString();
WSPATextBox.Text = reader["motorWheelSPActual"].ToString();
RemarksTextArea.Text = reader["remarks"].ToString();
}
}
connection1.Close();
}
}
And here is the Save button click handler that updates the record in the database.
protected void SaveReportButton_Click(object sender, EventArgs e)
{
String projectID = Request.QueryString["jobID"];
String reportID = Request.QueryString["reportID"];
string unitMake = UMTextBox.Text;
string unitModel = UMOTextBox.Text;
string unitType = UTTextBox.Text;
string unitSize = USITextBox.Text;
string unitSerial = USTextBox.Text;
string unitArrangement = UATextBox.Text;
string unitClass = UCTextBox.Text;
string unitDischarge = UDTextBox.Text;
string unitMS = UMSTextBox.Text;
string unitSD = USDTextBox.Text;
string unitSB = USBTextBox.Text;
string unitBeltNumber = UBNTextBox.Text;
string unitBeltSize = UBSTextBox.Text;
string unitFilterNumber = UFNTextBox.Text;
string unitFilterSize = UFSTextBox.Text;
string unitTotalCFMDesign = TCFMDTextBox.Text;
string unitTotalCFMActual = TCFMATextBox.Text;
string unitReturnAirCFMDesign = RACFMDTextBox.Text;
string unitReturnAirCFMActual = RACFMATextBox.Text;
string unitOutsideAirCFMDesign = OACFMDTextBox.Text;
string unitOutsideAirCFMActual = OACFMATextBox.Text;
string unitExhaustAirCFMDesign = EACFMDTextBox.Text;
string unitExhaustAirCFMActual = EACFMATextBox.Text;
string unitFanRPMDesign = FRPMDTextBox.Text;
string unitFanRPMActual = FRPMATextBox.Text;
string unitMotorRPMDesign = MRPMDTextBox.Text;
string unitMotorRPMActual = MRPMATextBox.Text;
string unitMotorVoltsDesign = MVDTextBox.Text;
string unitMotorVoltsActual = MVATextBox.Text;
string unitMotorAmpsDesign = MADTextBox.Text;
string unitMotorAmpsActual = MAATextBox.Text;
string motorMake = MMTextBox.Text;
string motorFrame = MFTextBox.Text;
string motorHP = MHPTextBox.Text;
string motorRPM = MRPMTextBox.Text;
string motorVolts = MVTextBox.Text;
string motorPhaseHz = MPHTextBox.Text;
string motorFullLoadAmps = MFLATextBox.Text;
string motorSF = MSFTextBox.Text;
string motorMakeSheave = MMSTextBox.Text;
string motorSheaveDiameter = MSDTextBox.Text;
string motorSheaveBore = MSBTextBox.Text;
string motorOperatingDiameter = MODTextBox.Text;
string motorSheaveCDistance = MSCDTextBox.Text;
string motorTotalSPDesign = TSPDTextBox.Text;
string motorTotalSPActual = TSPATextBox.Text;
string motorEnteringSPDesign = ESPDTextBox.Text;
string motorEnteringSPActual = ESPATextBox.Text;
string motorSuctionSPDesign = SSPDTextBox.Text;
string motorSuctionSPActual = SSPATextBox.Text;
string motorDischargeSPDesign = DSPDTextBox.Text;
string motorDischargeSPActual = DSPATextBox.Text;
string motorPreheatCoilSPDesign = PCSPDTextBox.Text;
string motorPreheatCoilSPActual = PCSPATextBox.Text;
string motorCoolingCoilSPDesign = CCSPDTextBox.Text;
string motorCoolingCoilSPActual = CCSPATextBox.Text;
string motorReheatCoilSPDesign = RCSPDTextBox.Text;
string motorReheatCoilSPActual = RCSPATextBox.Text;
string motorFilterSPDesign = FSPDTextBox.Text;
string motorFilterSPActual = FSPATextBox.Text;
string motorAfterFilterSPDesign = AFSPDTextBox.Text;
string motorAfterFilterSPActual = AFSPATextBox.Text;
string motorWheelSPDesign = WSPDTextBox.Text;
string motorWheelSPActual = WSPATextBox.Text;
string remarks = RemarksTextArea.Text;
string updateStatement = #"UPDATE ahu_data SET make=#UNITMAKE, model=#UNITMODEL, type=#UNITTYPE, size=#UNITSIZE, serial=#UNITSERIAL, arrangement=#UNITARRANGEMENT,
class=#UNITCLASS, discharge=#UNITDISCHARGE, make_sheave=#UNITMS, sheave_diameter=#UNITSD, sheave_bore=#UNITSB,
belts=#UNITBELTNUMBER, belt_size=#UNITBELTSIZE, filters=#UNITFILTERNUMBER, filter_size=#UNITBELTSIZE,
unitTotalCFMDesign=#UNITTOTALCFMDESIGN, unitTotalCFMActual=#UNITTOTALCFMACTUAL, unitReturnAirCFMDesign=#UNITRETURNAIRCFMDESIGN,
unitReturnAirCFMActual=#UNITRETURNAIRCFMACTUAL, unitOutsideAirCFMDesign=#UNITOUTSIDEAIRCFMDESIGN,
unitOutsideAirCFMActual=#UNITOUTSIDEAIRCFMACTUAL, unitExhaustAirCFMDesign=#UNITEXHAUSTAIRCFMDESIGN,
unitExhaustAirCFMActual=#UNITEXHAUSTAIRCFMACTUAL, unitFanRPMDesign=#UNITFANRPMDESIGN,
unitFanRPMActual=#UNITFANRPMACTUAL, unitMotorRPMDesign=#UNITMOTORRPMDESIGN, unitMotorRPMActual=#UNITMOTORRPMACTUAL,
unitMotorVoltsDesign=#UNITMOTORVOLTSDESIGN, unitMotorVoltsActual=#UNITMOTORVOLTSACTUAL, unitMotorAmpsDesign=#UNITMOTORAMPSDESIGN,
unitMotorAmpsActual=#UNITMOTORAMPSACTUAL, motor_make=#MOTORMAKE, motor_frame=#MOTORFRAME, motor_hp=#MOTORHP,
motor_rpm=#MOTORRPM, motor_volts=#MOTORVOLTS, motor_phasehz=#MOTORPHASEHZ, motor_fl_amps=#MOTORFULLLOADAMPS,
motor_sf=#MOTORSF, motor_make_sheave=#MOTORMAKESHEAVE, motor_sheave_diameter=#MOTORSHEAVEDIAMETER,
motor_sheave_bore=#MOTORSHEAVEBORE, motor_operating_diameter=#MOTOROPERATINGDIAMETER, motor_sheave_center_distance=#MOTORSHEAVECDISTANCE,
motorTotalSPDesign=#MOTORTOTALSPDESIGN, motorTotalSPActual=#MOTORTOTALSPACTUAL, motorEnteringSPDesign=#MOTORENTERINGSPDESIGN,
motorEnteringSPActual=#MOTORENTERINGSPACTUAL, motorSuctionSPDesign=#MOTORSUCTIONSPDESIGN, motorSuctionSPActual=#MOTORSUCTIONSPACTUAL,
motorDischargeSPDesign=#MOTORDISCHARGESPDESIGN, motorDischargeSPActual=#MOTORDISCHARGESPACTUAL, motorPreheatCoilSPDesign=#MOTORPREHEATCOILSPDESIGN,
motorPreheatCoilSPActual=#MOTORPREHEATCOILSPACTUAL, motorCoolingCoilSPDesign=#MOTORCOOLINGCOILSPDESIGN, motorCoolingCoilSPActual=#MOTORCOOLINGCOILSPACTUAL,
motorReheatCoilSPDesign=#MOTORREHEATCOILSPDESIGN, motorReheatCoilSPActual=#MOTORREHEATCOILSPACTUAL, motorFilterSPDesign=#MOTORFILTERSPDESIGN,
motorFilterSPActual=#MOTORFILTERSPACTUAL, motorAfterFilterSPDesign=#MOTORAFTERFILTERSPDESIGN, motorAfterFilterSPActual=#MOTORAFTERFILTERSPACTUAL,
motorWheelSPDesign=#MOTORWHEELSPDESIGN, motorWheelSPActual=#MOTORWHEELSPACTUAL, remarks=#REMARKS WHERE unit_ID = " + reportID;
string sqlConnectionString = "Removed for Security";
using (SqlConnection connection1 = new SqlConnection(sqlConnectionString))
{
connection1.Open();
using (SqlCommand updateCommand = new SqlCommand(updateStatement, connection1))
{
updateCommand.Parameters.AddWithValue("#UNITMAKE", unitMake);
updateCommand.Parameters.AddWithValue("#UNITMODEL", unitModel);
updateCommand.Parameters.AddWithValue("#UNITTYPE", unitType);
updateCommand.Parameters.AddWithValue("#UNITSIZE", unitSize);
updateCommand.Parameters.AddWithValue("#UNITSERIAL", unitSerial);
updateCommand.Parameters.AddWithValue("#UNITARRANGEMENT", unitArrangement);
updateCommand.Parameters.AddWithValue("#UNITCLASS", unitClass);
updateCommand.Parameters.AddWithValue("#UNITDISCHARGE", unitDischarge);
updateCommand.Parameters.AddWithValue("#UNITMS", unitMS);
updateCommand.Parameters.AddWithValue("#UNITSD", unitSD);
updateCommand.Parameters.AddWithValue("#UNITSB", unitSB);
updateCommand.Parameters.AddWithValue("#UNITBELTNUMBER", unitBeltNumber);
updateCommand.Parameters.AddWithValue("#UNITBELTSIZE", unitBeltSize);
updateCommand.Parameters.AddWithValue("#UNITFILTERNUMBER", unitFilterNumber);
updateCommand.Parameters.AddWithValue("#UNITFILTERSIZE", unitFilterSize);
updateCommand.Parameters.AddWithValue("#UNITTOTALCFMDESIGN", unitTotalCFMDesign);
updateCommand.Parameters.AddWithValue("#UNITTOTALCFMACTUAL", unitTotalCFMActual);
updateCommand.Parameters.AddWithValue("#UNITRETURNAIRCFMDESIGN", unitReturnAirCFMDesign);
updateCommand.Parameters.AddWithValue("#UNITRETURNAIRCFMACTUAL", unitReturnAirCFMActual);
updateCommand.Parameters.AddWithValue("#UNITOUTSIDEAIRCFMDESIGN", unitOutsideAirCFMDesign);
updateCommand.Parameters.AddWithValue("#UNITOUTSIDEAIRCFMACTUAL", unitOutsideAirCFMActual);
updateCommand.Parameters.AddWithValue("#UNITEXHAUSTAIRCFMDESIGN", unitExhaustAirCFMDesign);
updateCommand.Parameters.AddWithValue("#UNITEXHAUSTAIRCFMACTUAL", unitExhaustAirCFMActual);
updateCommand.Parameters.AddWithValue("#UNITFANRPMDESIGN", unitFanRPMDesign);
updateCommand.Parameters.AddWithValue("#UNITFANRPMACTUAL", unitFanRPMActual);
updateCommand.Parameters.AddWithValue("#UNITMOTORRPMDESIGN", unitMotorRPMDesign);
updateCommand.Parameters.AddWithValue("#UNITMOTORRPMACTUAL", unitMotorRPMActual);
updateCommand.Parameters.AddWithValue("#UNITMOTORVOLTSDESIGN", unitMotorVoltsDesign);
updateCommand.Parameters.AddWithValue("#UNITMOTORVOLTSACTUAL", unitMotorVoltsActual);
updateCommand.Parameters.AddWithValue("#UNITMOTORAMPSDESIGN", unitMotorAmpsDesign);
updateCommand.Parameters.AddWithValue("#UNITMOTORAMPSACTUAL", unitMotorAmpsActual);
updateCommand.Parameters.AddWithValue("#MOTORMAKE", motorMake);
updateCommand.Parameters.AddWithValue("#MOTORFRAME", motorFrame);
updateCommand.Parameters.AddWithValue("#MOTORHP", motorHP);
updateCommand.Parameters.AddWithValue("#MOTORRPM", motorRPM);
updateCommand.Parameters.AddWithValue("#MOTORVOLTS", motorVolts);
updateCommand.Parameters.AddWithValue("#MOTORPHASEHZ", motorPhaseHz);
updateCommand.Parameters.AddWithValue("#MOTORFULLLOADAMPS", motorFullLoadAmps);
updateCommand.Parameters.AddWithValue("#MOTORSF", motorSF);
updateCommand.Parameters.AddWithValue("#MOTORMAKESHEAVE", motorMakeSheave);
updateCommand.Parameters.AddWithValue("#MOTORSHEAVEDIAMETER", motorSheaveDiameter);
updateCommand.Parameters.AddWithValue("#MOTORSHEAVEBORE", motorSheaveBore);
updateCommand.Parameters.AddWithValue("#MOTOROPERATINGDIAMETER", motorOperatingDiameter);
updateCommand.Parameters.AddWithValue("#MOTORSHEAVECDISTANCE", motorSheaveCDistance);
updateCommand.Parameters.AddWithValue("#MOTORTOTALSPDESIGN", motorTotalSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORTOTALSPACTUAL", motorTotalSPActual);
updateCommand.Parameters.AddWithValue("#MOTORENTERINGSPDESIGN", motorEnteringSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORENTERINGSPACTUAL", motorEnteringSPActual);
updateCommand.Parameters.AddWithValue("#MOTORSUCTIONSPDESIGN", motorSuctionSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORSUCTIONSPACTUAL", motorSuctionSPActual);
updateCommand.Parameters.AddWithValue("#MOTORDISCHARGESPDESIGN", motorDischargeSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORDISCHARGESPACTUAL", motorDischargeSPActual);
updateCommand.Parameters.AddWithValue("#MOTORPREHEATCOILSPDESIGN", motorPreheatCoilSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORPREHEATCOILSPACTUAL", motorPreheatCoilSPActual);
updateCommand.Parameters.AddWithValue("#MOTORCOOLINGCOILSPDESIGN", motorCoolingCoilSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORCOOLINGCOILSPACTUAL", motorCoolingCoilSPActual);
updateCommand.Parameters.AddWithValue("#MOTORREHEATCOILSPDESIGN", motorReheatCoilSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORREHEATCOILSPACTUAL", motorReheatCoilSPActual);
updateCommand.Parameters.AddWithValue("#MOTORFILTERSPDESIGN", motorFilterSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORFILTERSPACTUAL", motorFilterSPActual);
updateCommand.Parameters.AddWithValue("#MOTORAFTERFILTERSPDESIGN", motorAfterFilterSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORAFTERFILTERSPACTUAL", motorAfterFilterSPActual);
updateCommand.Parameters.AddWithValue("#MOTORWHEELSPDESIGN", motorWheelSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORWHEELSPACTUAL", motorWheelSPActual);
updateCommand.Parameters.AddWithValue("#REMARKS", remarks);
updateCommand.ExecuteNonQuery();
}
connection1.Close();
}
}
ASP.NET page lifecycle causes this situation if you don't protect the Page_Load from reexecuting the code that fill your textboxes.
if (!IsPostBack)
{
string selectStatement = "SELECT * FROM ahu_data WHERE unit_ID = " + reportID;
string sqlConnectionString = "Removed for Security";
using (SqlConnection connection1 = new SqlConnection(sqlConnectionString))
{
.... rest of code that pre-fill your fields
Page.IsPostBack is a boolean property of the Page that informs your code if the page is called for the first time or if it is called as a consequence of some event that need to be processed server-side.
In the latter case you should not execute again the code that fills your textboxes otherwise, when the flow reaches your button code, you will find the textboxes with the original values instead of the modified ones because the Page_Load has resetted everything.
And do not forget the comment above about parameterizing your first query. You have already done the biggest part parameterizing the UPDATE, just one parameter remains and it is complete.
The update is working just fine, the problem is that it's using the same data that's already in the table, so it won't change anything.
When you click the save button the page does a postback to run the code on the server. First the Page_Load event runs and loads the original data that will replace the data that you entered in the form. Then the SaveReportButton_Click event runs that updates the record.
To keep the Page_Load event handler from replacing the data in the form, you should use the isPostBack property to check if the page is loaded due to a postback:
if (!IsPostBack) {
// load the data from the database in here
}

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.

Getting an Error Meassage "System.IO.FileFormatException: Compressed part has inconsistent data length" calling XmlDocument.Load()

I'm new to OpenXML,here i'm trying to export chart data to powerpoint.Here in the code i trying to save it as excel file and then to powerpoint,while trying click on the export button it showing me an error message(Written as aheading).here i'm my code.
protected void btnExport_Click(object sender, EventArgs e)
{
try
{
// Open an existing Presentation
PresentationDocument oPDoc = PresentationDocument.Open(#"D:\Chart.pptx", true);
PresentationPart oPPart = oPDoc.PresentationPart;
// Get the ReleationshipId of the first Slide
SlideId slideId = oPPart.Presentation.SlideIdList.GetFirstChild<SlideId>();
string relId = slideId.RelationshipId;
// Get the slide part by the relationship ID.
SlidePart slidePart = (SlidePart)oPPart.GetPartById(relId);
// Add a new chart part
ChartPart chPrt = slidePart.AddNewPart<ChartPart>();
XmlDocument xDoc = new XmlDocument();
String strFileName = "D:\\chart1.xml";
xDoc.Load(strFileName);
StreamWriter objDocMainWrt = new StreamWriter(chPrt.GetStream(FileMode.Create, FileAccess.Write));
xDoc.Save(objDocMainWrt);
// Add the data Sheet for the Chart
ExtendedPart objEmbPart = chPrt.AddExtendedPart("http://schemas.openxmlformats.org/officeDocument/2006/relationships/package", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".xlsx");
strFileName = "D:\\chartData.xlsx";
FileStream partStream = new FileStream(strFileName, FileMode.Open, FileAccess.Read);
objEmbPart.FeedData(partStream);
// Change the Data releation ID used in Chart.xml
// Elemenet changed : c:externalData
string relChtDataID = chPrt.GetIdOfPart(objEmbPart);
XmlNamespaceManager nsManager1 = new XmlNamespaceManager(xDoc.NameTable);
XmlNamespaceManager nsManagerDraw = new XmlNamespaceManager(xDoc.NameTable);
//nsManager1.AddNamespace("c", "http://schemas.openxmlformats.org/drawingml/2006/chart");
nsManagerDraw.AddNamespace("d", "http://schemas.openxmlformats.org/drawingml/2006/chart");
//XmlNodeList nodeTest = xDoc.SelectNodes("//c:externalData", nsManager1);
XmlNodeList nodeTest = xDoc.SelectNodes("//d:chart1", nsManagerDraw);
foreach (XmlNode node in nodeTest)
{
node.Attributes["r:id"].Value = relChtDataID;
}
// Save changes back to Chart.xml
xDoc.Save(chPrt.GetStream(FileMode.Create, FileAccess.Write));
// Get the SlidePart Stream
const string presentationmlNamespace = "http://schemas.openxmlformats.org/presentationml/2006/main";
NameTable nt = new NameTable();
XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
nsManager.AddNamespace("p", presentationmlNamespace);
XmlDocument presXML = new XmlDocument(nt);
presXML.Load(slidePart.GetStream());
// Get the spTree Element in SlidePart
XmlNode nodeTree = presXML.SelectSingleNode("//p:spTree", nsManager);
string rid = slidePart.GetIdOfPart(chPrt).ToString();
// Generate the Graphic Element for the Chart
XmlNode childNode = GenerateNode(rid);
//Append the Graphic Element to spTree Element in SlidePart
nodeTree.AppendChild(presXML.ImportNode(childNode, true));
Stream o = slidePart.GetStream();
presXML.Save(o);
oPDoc.Close();
}
catch (Exception msg)
{
Response.Write(msg.ToString());
}
}
private XmlNode GenerateNode(String rId)
{
XmlDocument xwb = new XmlDocument();
xwb.AppendChild(xwb.CreateXmlDeclaration("1.0", "UTF-8", "yes"));
XmlNamespaceManager xmlns = new XmlNamespaceManager(xwb.NameTable);
xmlns.AddNamespace("p", "http://schemas.openxmlformats.org/presentationml/2006/main");
xmlns.AddNamespace("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
xmlns.AddNamespace("a", "http://schemas.openxmlformats.org/drawingml/2006/main");
XmlElement eleGraphic = xwb.CreateElement("p:graphicFrame", xmlns.LookupNamespace("p"));
xwb.AppendChild(eleGraphic);
XmlElement eleGrpFrm = xwb.CreateElement("p:nvGraphicFramePr", xmlns.LookupNamespace("p"));
eleGraphic.AppendChild(eleGrpFrm);
XmlElement elePpr = xwb.CreateElement("p:cNvPr", xmlns.LookupNamespace("p"));
eleGrpFrm.AppendChild(elePpr);
XmlAttribute attrRid = xwb.CreateAttribute("id");
attrRid.Value = "4";
elePpr.SetAttributeNode(attrRid);
XmlAttribute attrName = xwb.CreateAttribute("name");
attrName.Value = "Chart 2";
elePpr.SetAttributeNode(attrName);
XmlElement elecNvGraphicFramePr = xwb.CreateElement("p:cNvGraphicFramePr", xmlns.LookupNamespace("p"));
eleGrpFrm.AppendChild(elecNvGraphicFramePr);
XmlElement elenvPr = xwb.CreateElement("p:nvPr", xmlns.LookupNamespace("p"));
eleGrpFrm.AppendChild(elenvPr);
XmlElement elexfrm = xwb.CreateElement("p:xfrm", xmlns.LookupNamespace("p"));
eleGraphic.AppendChild(elexfrm);
XmlElement eleoff = xwb.CreateElement("a:off", xmlns.LookupNamespace("a"));
elexfrm.AppendChild(eleoff);
XmlAttribute xvalue = xwb.CreateAttribute("x");
xvalue.Value = "1524000";
eleoff.SetAttributeNode(xvalue);
XmlAttribute yvalue = xwb.CreateAttribute("y");
yvalue.Value = "1397000";
eleoff.SetAttributeNode(yvalue);
XmlElement eleext = xwb.CreateElement("a:ext", xmlns.LookupNamespace("a"));
elexfrm.AppendChild(eleext);
XmlAttribute cxvalue = xwb.CreateAttribute("cx");
cxvalue.Value = "6096000";
eleext.SetAttributeNode(cxvalue);
XmlAttribute cyvalue = xwb.CreateAttribute("cy");
cyvalue.Value = "4064000";
eleext.SetAttributeNode(cyvalue);
//<c:chart xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" r:id="rId2"/></a:graphicData></a:graphic></p:graphicFrame>
XmlElement elegraphic = xwb.CreateElement("a:graphic", xmlns.LookupNamespace("a"));
eleGraphic.AppendChild(elegraphic);
XmlElement elegraphicData = xwb.CreateElement("a:graphicData", xmlns.LookupNamespace("a"));
elegraphic.AppendChild(elegraphicData);
XmlAttribute uri = xwb.CreateAttribute("uri");
uri.Value = "http://schemas.openxmlformats.org/drawingml/2006/chart";
elegraphicData.SetAttributeNode(uri);
XmlElement elechart = xwb.CreateElement("c:chart", "http://schemas.openxmlformats.org/drawingml/2006/chart");
elegraphicData.AppendChild(elechart);
XmlAttribute id = xwb.CreateAttribute("r:id", xmlns.LookupNamespace("r"));
id.Value = rId;
elechart.SetAttributeNode(id);
XmlNode ss1 = xwb.SelectSingleNode("//p:graphicFrame", xmlns);
return ss1;
//xwb.Save(#"C:\temp\test1.xml");
}
Please let me know where i have done mistake.
Try this below code,before that create empty ppt template and excel with two chart controls.
string paramPresentationPath = #"D:\Chart.pptx";
string paramWorkbookPath = #"D:\chartData.xlsx";
object paramMissing = Type.Missing;
powerpointApplication = new pptNS.Application();
// Create an instance Excel.
excelApplication = new xlNS.Application();
// Open the Excel workbook containing the worksheet with the chart
// data.
excelWorkBook = excelApplication.Workbooks.Open(paramWorkbookPath,
paramMissing, paramMissing, paramMissing,
paramMissing, paramMissing, paramMissing,
paramMissing, paramMissing, paramMissing,
paramMissing, paramMissing, paramMissing,
paramMissing, paramMissing);
// Get the worksheet that contains the chart.
targetSheet = (xlNS.Worksheet)(excelWorkBook.Worksheets[1]);//here 1 is sheet no.
// Get the ChartObjects collection for the sheet.
chartObjects = (xlNS.ChartObjects)(targetSheet.ChartObjects(paramMissing));
// Get the chart to copy.
existingChartObject = (xlNS.ChartObject)(chartObjects.Item("Chart Name in Excel"));
// Create a PowerPoint presentation.
pptPresentation = powerpointApplication.Presentations.Add(
Microsoft.Office.Core.MsoTriState.msoTrue);
// Add a blank slide to the presentation.
pptSlide = pptPresentation.Slides.Add(1, pptNS.PpSlideLayout.ppLayoutBlank);
// Copy the chart from the Excel worksheet to the clipboard.
existingChartObject.Copy();
// Paste the chart into the PowerPoint presentation.
shapeRange = pptSlide.Shapes.Paste();
// Position the chart on the slide.
shapeRange.Left = 30;
shapeRange.Top = 100;
// Width and Height on the Slide.
shapeRange.Width = 600;
shapeRange.Height = 400;
///<summary>
///Second Slide
///</summary>
// Get the worksheet that contains the chart.
targetSheet = (xlNS.Worksheet)(excelWorkBook.Worksheets[2]);
// Get the ChartObjects collection for the sheet.
chartObjects = (xlNS.ChartObjects)(targetSheet.ChartObjects(paramMissing));
// Get the chart to copy.
existingChartObject = (xlNS.ChartObject)(chartObjects.Item("Chart Name in excel"));
//// Create a PowerPoint presentation.
//pptPresentation = powerpointApplication.Presentations.Add(
// Microsoft.Office.Core.MsoTriState.msoTrue);
// Add a blank slide to the presentation.
pptSlide = pptPresentation.Slides.Add(2, pptNS.PpSlideLayout.ppLayoutBlank);
// Copy the chart from the Excel worksheet to the clipboard.
existingChartObject.Copy();
// Paste the chart into the PowerPoint presentation.
shapeRange = pptSlide.Shapes.Paste();
// Position the chart on the slide.
shapeRange.Left = 30;
shapeRange.Top = 100;
// Width and Height on the Slide.
shapeRange.Width = 600;
shapeRange.Height = 400;
// Save the presentation.
pptPresentation.SaveAs(paramPresentationPath,
pptNS.PpSaveAsFileType.ppSaveAsOpenXMLPresentation,
Microsoft.Office.Core.MsoTriState.msoTrue);
//pptPresentation.Close();
}
catch (Exception msg)
{
Response.Write(msg.ToString());
}
finally
{
shapeRange = null;
pptSlide = null;
object paramMissing = Type.Missing;
// Close and release the Presentation object.
if (pptPresentation != null)
{
pptPresentation.Close();
Marshal.FinalReleaseComObject(pptPresentation);
//Marshal.ReleaseComObject(pptPresentation.Slides);
pptPresentation = null;
}
// Quit PowerPoint and release the ApplicationClass object.
if (powerpointApplication != null)
{
powerpointApplication.Quit();
Marshal.FinalReleaseComObject(powerpointApplication);
powerpointApplication = null;
}
// Release the Excel objects.
targetSheet = null;
chartObjects = null;
existingChartObject = null;
//Close and release the Excel Workbook object.
if (excelWorkBook != null)
{
excelWorkBook.Close(false, paramMissing, paramMissing);
Marshal.FinalReleaseComObject(excelWorkBook);
excelWorkBook = null;
}
// Quit Excel and release the ApplicationClass object.
if (excelApplication != null)
{
excelApplication.Quit();
Marshal.FinalReleaseComObject(excelApplication);
excelApplication = null;
//System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApplication);
}
////releaseObject(ref excelApplication);
////releaseObject(ref powerpointApplication);
System.Diagnostics.Process[] excelprc = System.Diagnostics.Process.GetProcessesByName("EXCEL");
if (excelprc.Length == 1)
{
excelprc[0].Kill();
}
System.Diagnostics.Process[] ppprc = System.Diagnostics.Process.GetProcessesByName("POWERPNT");
if (ppprc.Length == 1)
{
ppprc[0].Kill();
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();

Dynamic parameter and query

I'm creating a search engine for my asp page.There are 15 pieces filtering options like Price,Date,Name etc.
Also,The use of Filtering Options is optional.If the filtering options are left blank,search will be made.
I found a solution by using if and string.
string sorgu = "";
dbcommand cmd = CommandClassım.YeniCommand();
sorgu += "Select * From Urunler Where ";
if(UrunAdi.Text != string.Empty)
{
sorgu += "UrunAdi = #UrunAdi";
dbparameters prm = cmd.createparameter();
prm.Parametername = "#UrunAdi";
prm.Value = UrunAdi.Text;
prm.DbType = DbType.String;
cmd.Parameters.Add(prm);
}
cmd.CommandText = sorgu;
it's running upper code without problem.However,I want to using a parameter to filter dynamic.
So,the user choose those categories through checkbox inside search engine.
When I try to run below code,I got the following error.
Must declare the scalar variable "#cat0".
Code:
string sorgu = "";
DbCommand cmd = CommandClassım.YeniCommand();
sorgu += "Select * From Urunler Where ";
DbParameter prm = cmd.CreateParameter;
for(int i = 0; i < Category.Length; i++)
{
sorgu += "Kategori = #cat" + i.ToString();
prm.ParameterName = "#cat" + i.ToString();
prm.Value = Category.Value;
prm.DbType = DbType.String;
cmd.Parameters.Add(prm);
}
cmd.CommandText = sorgu;
Just a hunch, but could it be that you're not providing the indexer for Category?
prm.Value = Category.Value;
I would think it should be:
prm.Value = Category[i].Value;

Resources