public static List<RssFeedItem> ReadFeed(string url) { //create a new list of the rss feed items to return List<RssFeedItem> rssFeedItems = new List<RssFeedItem>(); //create an http request which will be used to retrieve the rss feed HttpWebRequest rssFeed = (HttpWebRequest)WebRequest.Create(url); //use a dataset to retrieve the rss feed using (DataSet rssData = new DataSet()) { //read the xml from the stream of the web request rssData.ReadXml(rssFeed.GetResponse().GetResponseStream()); //loop through the rss items in the dataset and populate the list of rss feed items foreach (DataRow dataRow in rssData.Tables["item"].Rows) { rssFeedItems.Add(new RssFeedItem { ChannelId = Convert.ToInt32(dataRow["channel_Id"]), Description = Convert.ToString(dataRow["description"]), ItemId = Convert.ToInt32(dataRow["item_Id"]), Link = Convert.ToString(dataRow["link"]), PublishDate = Convert.ToDateTime(dataRow["pubDate"]), Title = Convert.ToString(dataRow["title"]) }); } } //return the rss feed items return rssFeedItems; }
protected void Page_Load(object sender, EventArgs e) { var ds = new DataSet(); ds.ReadXml(StrXml); ReportViewer1.DataBind(); }
public void XmlLoadCustomTypesTest() { string xml = "<CustomTypesData>" + Environment.NewLine + "<CustomTypesTable>" + Environment.NewLine + "<Dummy>99</Dummy>" + Environment.NewLine + "<FuncXml> " + Environment.NewLine + "<Func Name=\"CUT_IntPassiveIn()\" Direction=\"PASSIVE_MOCK\">" + Environment.NewLine + "<Param Name=\"paramLen\" Type=\"int\" Len=\"1\" InOut=\"IN\" Union=\"FALSE\" " + Environment.NewLine + "Callback=\"\" CSharpType=\"int\" Value=\"\" ExpectedValue=\"1\" IsExpGetRef=\"\" " + Environment.NewLine + "IsGetRef=\"\" IsSetRef=\"\" ChildSelected=\"FALSE\" UnionIndex=\"-1\" HandleInput=\"DEC\" " + Environment.NewLine + "Enum=\"\">" + Environment.NewLine + "</Param>" + Environment.NewLine + Environment.NewLine + "<Param Name=\"single\" Type=\"int\" Len=\"1\" InOut=\"IN\" Union=\"FALSE\" " + Environment.NewLine + "Callback=\"\" CSharpType=\"int\" Value=\"\" ExpectedValue=\"16\" IsExpGetRef=\"\" " + Environment.NewLine + "IsGetRef=\"\" IsSetRef=\"\" ChildSelected=\"FALSE\" UnionIndex=\"-1\" HandleInput=\"DEC\" " + Environment.NewLine + "Enum=\"\">" + Environment.NewLine + "</Param>" + Environment.NewLine + Environment.NewLine + "<Param Name=\"arraySizeParam\" Type=\"int*\" Len=\"4\" InOut=\"IN\" " + Environment.NewLine + "Union=\"FALSE\" Callback=\"\" CSharpType=\"int\" Value=\"\" ExpectedValue=\"\" " + Environment.NewLine + "IsExpGetRef=\"\" IsGetRef=\"\" IsSetRef=\"\" ChildSelected=\"FALSE\" UnionIndex=\"-1\" " + Environment.NewLine + "HandleInput=\"HEX\" Enum=\"\">" + Environment.NewLine + Environment.NewLine + "<Param1 Name=\"arraySizeParam0\" Type=\"int\" Len=\"0\" InOut=\"IN\" " + Environment.NewLine + "Union=\"FALSE\" Callback=\"\" CSharpType=\"int\" Value=\"\" ExpectedValue=\"1\" " + Environment.NewLine + "IsExpGetRef=\"\" IsGetRef=\"\" IsSetRef=\"\" ChildSelected=\"FALSE\" UnionIndex=\"-1\" " + Environment.NewLine + "HandleInput=\"DEC\" Enum=\"\">" + Environment.NewLine + "</Param1>" + Environment.NewLine + Environment.NewLine + "<Param1 Name=\"arraySizeParam1\" Type=\"int\" Len=\"0\" InOut=\"IN\" " + Environment.NewLine + "Union=\"FALSE\" Callback=\"\" CSharpType=\"int\" Value=\"\" ExpectedValue=\"\" " + Environment.NewLine + "IsExpGetRef=\"\" IsGetRef=\"\" IsSetRef=\"\" ChildSelected=\"FALSE\" UnionIndex=\"-1\" " + Environment.NewLine + "HandleInput=\"HEX\" Enum=\"\">" + Environment.NewLine + "</Param1>" + Environment.NewLine + Environment.NewLine + "<Param1 Name=\"arraySizeParam2\" Type=\"int\" Len=\"0\" InOut=\"IN\" " + Environment.NewLine + "Union=\"FALSE\" Callback=\"\" CSharpType=\"int\" Value=\"\" ExpectedValue=\"\" " + Environment.NewLine + "IsExpGetRef=\"\" IsGetRef=\"\" IsSetRef=\"\" ChildSelected=\"FALSE\" UnionIndex=\"-1\" " + Environment.NewLine + "HandleInput=\"HEX\" Enum=\"\">" + Environment.NewLine + "</Param1>" + Environment.NewLine + Environment.NewLine + "<Param1 Name=\"arraySizeParam3\" Type=\"int\" Len=\"0\" InOut=\"IN\" " + Environment.NewLine + "Union=\"FALSE\" Callback=\"\" CSharpType=\"int\" Value=\"\" ExpectedValue=\"\" " + Environment.NewLine + "IsExpGetRef=\"\" IsGetRef=\"\" IsSetRef=\"\" ChildSelected=\"FALSE\" UnionIndex=\"-1\" " + Environment.NewLine + "HandleInput=\"HEX\" Enum=\"\">" + Environment.NewLine + "</Param1>" + Environment.NewLine + Environment.NewLine + "</Param>" + Environment.NewLine + "<Return Name=\"retVal\" Type=\"int\" Len=\"1\" InOut=\"OUT\" Union=\"FALSE\" " + Environment.NewLine + "Callback=\"\" CSharpType=\"int\" Value=\"1\" ExpectedValue=\"\" IsExpGetRef=\"\" " + Environment.NewLine + "IsGetRef=\"\" IsSetRef=\"\" ChildSelected=\"FALSE\" UnionIndex=\"-1\" HandleInput=\"DEC\" " + Environment.NewLine + "Enum=\"\">" + Environment.NewLine + "</Return>" + Environment.NewLine + "</Func>" + Environment.NewLine + "</FuncXml>" + Environment.NewLine + "</CustomTypesTable>" + Environment.NewLine + "</CustomTypesData>" + Environment.NewLine; StringReader sr = new StringReader(xml); XmlTextReader xr = new XmlTextReader(sr); DataTable tbl = new DataTable("CustomTypesTable"); tbl.Columns.Add("Dummy", typeof(uint)); tbl.Columns.Add("FuncXml", typeof(CustomTypeXml)); DataSet ds = new DataSet("CustomTypesData"); ds.Tables.Add(tbl); ds.ReadXml(xr); Assert.Equal(1, ds.Tables["CustomTypesTable"].Rows.Count); xr.Close(); }
public void ReadWriteXml() { var ds = new DataSet(); ds.ReadXml(new StringReader(DataProvider.region)); TextWriter writer = new StringWriter(); ds.WriteXml(writer); string TextString = writer.ToString(); string substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal("<Root>", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" <Region>", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" <RegionID>1</RegionID>", substring); // Here the end of line is text markup "\n" substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" <RegionDescription>Eastern", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" </RegionDescription>", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" </Region>", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" <Region>", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" <RegionID>2</RegionID>", substring); // Here the end of line is text markup "\n" substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" <RegionDescription>Western", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" </RegionDescription>", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" </Region>", substring); Assert.Equal("</Root>", TextString); }
public void ReadWriteXml3() { string input = @"<FullTextResponse> <Domains> <AvailResponse info='y' name='novell-ximian-group' /> <AvailResponse info='n' name='ximian' /> </Domains> </FullTextResponse>"; var ds = new DataSet(); ds.ReadXml(new StringReader(input)); StringWriter sw = new StringWriter(); XmlTextWriter xtw = new XmlTextWriter(sw); xtw.Formatting = Formatting.Indented; xtw.QuoteChar = '\''; ds.WriteXml(xtw); xtw.Flush(); Assert.Equal(input.Replace("\r\n", "\n"), sw.ToString().Replace("\r\n", "\n")); }
public void XmlSpace() { string xml = "<?xml version=\"1.0\" standalone=\"yes\"?>" + "<NewDataSet>" + " <Table>" + " <Name>Miguel</Name>" + " <FirstName xml:space=\"preserve\"> de Icaza</FirstName>" + " <Income>4000</Income>" + " </Table>" + " <Table>" + " <Name>Chris</Name>" + " <FirstName xml:space=\"preserve\">Toshok </FirstName>" + " <Income>3000</Income>" + " </Table>" + "</NewDataSet>"; var ds = new DataSet(); ds.ReadXml(new StringReader(xml)); Assert.Equal(1, ds.Tables.Count); Assert.Equal("Table", ds.Tables[0].TableName); Assert.Equal(3, ds.Tables[0].Columns.Count); Assert.Equal("Name", ds.Tables[0].Columns[0].ColumnName); Assert.Equal(0, ds.Tables[0].Columns[0].Ordinal); Assert.Equal("FirstName", ds.Tables[0].Columns[1].ColumnName); Assert.Equal(1, ds.Tables[0].Columns[1].Ordinal); Assert.Equal("Income", ds.Tables[0].Columns[2].ColumnName); Assert.Equal(2, ds.Tables[0].Columns[2].Ordinal); }
public void ReadComplexElementDocument() { var ds = new DataSet(); ds.ReadXml(new StringReader(xml29)); }
protected override void ReadXmlSerializable(XmlReader reader) { Reset(); var ds = new DataSet(); ds.ReadXml(reader); if ((ds.Tables["Order Details"] != null)) { Tables.Add(new Order_DetailsDataTable(ds.Tables["Order Details"])); } if ((ds.Tables["Orders"] != null)) { Tables.Add(new OrdersDataTable(ds.Tables["Orders"])); } DataSetName = ds.DataSetName; Prefix = ds.Prefix; Namespace = ds.Namespace; Locale = ds.Locale; CaseSensitive = ds.CaseSensitive; EnforceConstraints = ds.EnforceConstraints; Merge(ds, false, MissingSchemaAction.Add); InitVars(); }
private void Tree_AfterSelect(object sender, TreeViewEventArgs e) { if (e.Node.Text == "Nupp-Button") { Controls.Add(_btn); status = true; } else if (e.Node.Text == "Sint-Label") { Controls.Add(_lbl); } else if (e.Node.Text == "Märkeruut-Checkbox") { _box_btn = new CheckBox { Text = "Näine nupp", Location = new Point(170, 100) }; _box_lbl = new CheckBox { Text = "Näita silt", Location = new Point(170, 120) }; Controls.Add(_box_btn); Controls.Add(_box_lbl); _box_btn.CheckedChanged += Box_btn_CheckedChanged; _box_lbl.CheckedChanged += Box_lbl_CheckedChanged; } else if (e.Node.Text == "Radionupp-Radiobutton") { r1 = new RadioButton { Text = "Vasakule", Location = new Point(170, 30), Checked = true }; r1.CheckedChanged += R1OnCheckedChanged; r2 = new RadioButton { Text = "Paremale", Location = new Point(170, 50) }; r2.CheckedChanged += R1OnCheckedChanged; Controls.Add(r1); Controls.Add(r2); } else if (e.Node.Text == "Tekstkast-TextBox") { _txt_box = new TextBox { Multiline = true, Text = "", Location = new Point(300, 500), Width = 200, Height = 200 }; Controls.Add(_txt_box); string text; try { text = File.ReadAllText("result.txt"); } catch { text = "Tekst puudub"; } } else if (e.Node.Text == "Pildikast-Picturebox") { _pic_box = new PictureBox { Image = new Bitmap("1.png"), Location = new Point(300, 0), Size = new Size(600, 400), SizeMode = PictureBoxSizeMode.StretchImage, BorderStyle = BorderStyle.Fixed3D }; Controls.Add(_pic_box); status_pic = true; } else if (e.Node.Text == "Kaart-TabControl") { _tabcontroll = new TabControl { Location = new Point(300, 300), Size = new Size(200, 100) }; _tab_1 = new TabPage("Java"); _tab_2 = new TabPage("Python"); _tab_3 = new TabPage("C#"); string tabctl = Interaction.InputBox("Millist programmeerimiskeelt näidata?", "Inputbox", "C# , Python"); if (tabctl == "c#" || tabctl == "C#") { Controls.Add(_tabcontroll); _tabcontroll.Controls.Add(_tab_1); _tab_1.BackColor = Color.Red; _tabcontroll.Controls.Add(_tab_2); _tab_2.BackColor = Color.Gold; _tabcontroll.Controls.Add(_tab_3); _tab_3.BackColor = Color.DarkGoldenrod; _tabcontroll.SelectedTab = _tab_3; } else if (tabctl == "Python") { Controls.Add(_tabcontroll); _tabcontroll.Controls.Add(_tab_1); _tabcontroll.Controls.Add(_tab_2); _tabcontroll.Controls.Add(_tab_3); _tabcontroll.SelectedTab = _tab_2; } } else if (e.Node.Text == "MessageBox") { MessageBox.Show("MessageBox", "Kõige listsam aken"); var answer = MessageBox.Show("Tahad InputBoxi näha?", "Aken koos nupudega", MessageBoxButtons.YesNo); if (answer == DialogResult.Yes) { string text = Interaction.InputBox("Sisesta siia mingi tekst", "InputBox", "Mingi tekst"); var text2 = MessageBox.Show("Tahad testi salvestaga?", "Aken", MessageBoxButtons.YesNoCancel); if (text2 == DialogResult.Yes) { var text3 = MessageBox.Show("Tahad label näga?", "Näga Label", MessageBoxButtons.YesNoCancel); if (text3 == DialogResult.Yes) { Controls.Add(_lbl); _lbl.Text = text; } } } } else if (e.Node.Text == "ListBox") { string[] _colorName = new string[] { "Kollane", "Punane", "Sinine", "Roheline" }; _Color_List = new Color[] { Color.Yellow, Color.Red, Color.Blue, Color.Green }; _List1 = new ListBox { Location = new Point(550, 500), Width = _colorName.OrderByDescending(n => n.Length).First().Length * 10, Height = _colorName.Length * 15 }; foreach (var i in _Color_List) { _List1.Items.Add(i); } _List1.SelectedIndexChanged += List1_SelectedIndexChanged; Controls.Add(_List1); } else if (e.Node.Text == "DataGridView") { DataSet dataSet = new DataSet("Näide"); dataSet.ReadXml("..//..//files//simple.xml"); _dataGrid = new DataGridView { DataSource = dataSet, AutoGenerateColumns = true, DataMember = "email", Location = new Point(700, 500), Height = 200, Width = 200 }; Controls.Add(_dataGrid); } else if (e.Node.Text == "Menu") { MainMenu menu = new MainMenu(); MenuItem menuitem1 = new MenuItem("File"); MenuItem menuItem2 = new MenuItem("My"); menuitem1.MenuItems.Add("Exit", new EventHandler(menuItem1_exit)); menuItem2.MenuItems.Add("Random Color", new EventHandler(RandomColor_Menu)); menuItem2.MenuItems.Add("Radiobutton OFF", new EventHandler(RadioButtonOff)); menuItem2.MenuItems.Add("Picturebox ON/OFF", new EventHandler(PictureboxONOFF)); menu.MenuItems.Add(menuitem1); menu.MenuItems.Add(menuItem2); this.Menu = menu; } }
public static string SendSms(string queue, int isRemoteQueue, string remoteQueueIP, int smsSendType, int pageNo, string sender, Guid privateNumberGuid, int totalCount, string receivers, string serviceID, string message, int smsLen, int tryCount, long smsIdentifier, int smsPartIndex, int isFlash, int isUnicode, string id, string guid, string username, string password, string domain, string sendLink, string receiveLink, string deliveryLink, int agentReference) { try { string messageId = Guid.Empty.ToString(); InProgressSms inProgressSms; BatchMessage batch = new BatchMessage(); batch.CheckId = random.Next().ToString(); batch.QueueName = queue; batch.SmsSendType = smsSendType; batch.SenderNumber = sender; batch.PrivateNumberGuid = privateNumberGuid; batch.ServiceId = serviceID; batch.SmsText = message; batch.SmsLen = smsLen; batch.MaximumTryCount = tryCount; batch.SmsIdentifier = smsIdentifier; batch.SmsPartIndex = smsPartIndex; batch.IsFlash = isFlash == 1 ? true : false; batch.IsUnicode = isUnicode == 1 ? true : false; batch.Id = long.Parse(id); batch.Guid = Guid.Parse(guid); batch.Username = username; batch.Password = password; batch.Domain = domain; batch.SendLink = sendLink; batch.ReceiveLink = receiveLink; batch.DeliveryLink = deliveryLink; batch.SmsSenderAgentReference = agentReference; batch.PageNo = pageNo; batch.TotalCount = totalCount; DataSet dtsReceivers = new DataSet(); dtsReceivers.ReadXml(new StringReader(receivers)); List <InProgressSms> lstInProgressSms = new List <InProgressSms>(); foreach (DataRow row in dtsReceivers.Tables[0].Rows) { inProgressSms = new InProgressSms(); inProgressSms.SendTryCount = 0; inProgressSms.RecipientNumber = row["Mobile"].ToString(); inProgressSms.OperatorType = int.Parse(row["Operator"].ToString()); inProgressSms.IsBlackList = int.Parse(row["IsBlackList"].ToString()); inProgressSms.SendStatus = 2; //WatingForSend inProgressSms.DeliveryStatus = 12; //IsSending inProgressSms.ReturnID = string.Empty; inProgressSms.CheckID = random.Next().ToString(); inProgressSms.SaveToDatabase = false; lstInProgressSms.Add(inProgressSms); } batch.Receivers = lstInProgressSms.ToList(); if (isRemoteQueue == 0) { messageId = ManageQueue.SendMessage(queue, batch, string.Format("{0}-{1}", id, pageNo)); } else if (isRemoteQueue == 1) { messageId = ManageQueue.SendMessage(queue, remoteQueueIP, batch, string.Format("{0}-{1}", id, pageNo)); } return(messageId.Split('\\')[1]); } catch (Exception ex) { return(string.Format("Message:{0},StackTrace:{1}", ex.Message, ex.StackTrace)); } }
private List <string> SaveToBaseCSV(string nameCSV, string nameConfig) { // Load Data from csv file List <string> str = new List <string>(); DataTable csvData = GetDataCSV(nameCSV); // Load config from xml file DataSet ds = new DataSet(); ds.ReadXml(nameConfig); DataTable xmlData = new DataTable(); xmlData = ds.Tables[0]; // ReLoad Data from csv table to DB by field from xml config file using (EFDBContext dbContext = new EFDBContext()) { var st = from myZip in csvData.AsEnumerable() where myZip.Field <string>("Бренд") == "555" select myZip; IEnumerable <string> fldVendor = from p in xmlData.AsEnumerable() where p.Field <string>("FIELD") == "Vendor" select p.Field <string>("SOURCE"); IEnumerable <string> fldNumber = from p in xmlData.AsEnumerable() where p.Field <string>("FIELD") == "Number" select p.Field <string>("SOURCE"); IEnumerable <string> fldDescription = from p in xmlData.AsEnumerable() where p.Field <string>("FIELD") == "Description" select p.Field <string>("SOURCE"); IEnumerable <string> fldPrice = from p in xmlData.AsEnumerable() where p.Field <string>("FIELD") == "Price" select p.Field <string>("SOURCE"); IEnumerable <string> fldCount = from p in xmlData.AsEnumerable() where p.Field <string>("FIELD") == "Count" select p.Field <string>("SOURCE"); foreach (DataRow row in csvData.Rows) { string vendor = row.Field <string>(fldVendor.First()); string number = row.Field <string>(fldNumber.First()); string schVendor = Regex.Replace(row.Field <string>(fldVendor.First()), @"[^A-Za-zА-Яа-я0-9]+", "").ToUpper(); string schNumber = Regex.Replace(row.Field <string>(fldNumber.First()), @"[^A-Za-zА-Яа-я0-9]+", "").ToUpper(); string description = row.Field <string>(fldDescription.First()); string strPrice = row.Field <string>(fldPrice.First()).Replace(",", "."); int count = Convert.ToInt32(Regex.Match(row.Field <string>(fldCount.First()), @"[0-9]+$").Value); string query = $"INSERT INTO ZipItems (Vendor, Number, SearchVendor, SearchNumber, Description, Price, Count) VALUES (N'{vendor}', N'{number}', N'{schVendor}', N'{schNumber}', N'{description}', {strPrice}, {count})"; int qan = dbContext.Database.ExecuteSqlCommand(query); } //"INSERT INTO ZipItems (Vendor, Number, Description, Price, Count) VALUES (@vendor, 'SA-1712L', '666', 'SA1712L', 'Рычаг подвески | перед лев |', '1343', '2')"; //int qan = dbContext.Database.ExecuteSqlCommand(query); dbContext.Dispose(); } ViewBag.Table = xmlData; return(str); }
internal DataSet ReadXml(DataSet ds, string filePath) { ds.ReadXml(filePath); return(ds); }
protected void actualizarDatos() { // Incentivos DataSet ds = new DataSet(); chkIncentivos.Checked = false; ddlIncentivos.Text = ""; System.Xml.XmlDocument CVAR = sgwFunciones.CONEAU.Docentes.cvarLeerXML(Session["CUIT"].ToString(), "cargosDocencia/categorizacionesIncentivos"); ds.ReadXml(new XmlNodeReader(CVAR)); try { if (ds.Tables.Count > 0) { foreach (DataRow row in ds.Tables[0].Rows) { if ((row["fechaFin"].ToString() == "") || (DateTime.Parse(row["fechaFin"].ToString()) > DateTime.Now)) { chkIncentivos.Checked = true; ddlIncentivos.Text = row["claseCargo"].ToString(); } } } } catch { if (ds.Tables.Count > 0) { foreach (DataRow row in ds.Tables[0].Rows) { chkIncentivos.Checked = true; ddlIncentivos.Text = row["claseCargo"].ToString(); } } } pnlIncentivos.Visible = chkIncentivos.Checked; // CONICET ds = new DataSet(); chkCONICET.Checked = false; ddlCONICET.Text = ""; CVAR = sgwFunciones.CONEAU.Docentes.cvarLeerXML(Session["CUIT"].ToString(), "cargosDocencia/cargosOrganismosCyT"); ds.ReadXml(new XmlNodeReader(CVAR)); try { if (ds.Tables.Count > 0) { foreach (DataRow row in ds.Tables[0].Rows) { if ((row["fechaFin"].ToString() == "") || (DateTime.Parse(row["fechaFin"].ToString()) > DateTime.Now)) { if (row["carrera"].ToString() == "Carrera de investigador científico y tecnológico (CONICET)") { chkCONICET.Checked = true; ddlCONICET.Text = row["categoria"].ToString(); } } } } } catch { if (ds.Tables.Count > 0) { foreach (DataRow row in ds.Tables[0].Rows) { if (row["carrera"].ToString() == "Carrera de investigador científico y tecnológico (CONICET)") { chkCONICET.Checked = true; ddlCONICET.Text = row["categoria"].ToString(); } } } } pnlCONICET.Visible = chkCONICET.Checked; }
protected void actualizarDatosProyectoInvestigacion() { DataSet ds = new DataSet(); System.Xml.XmlDocument CVAR = sgwFunciones.CONEAU.Docentes.cvarLeerXML(Session["CUIT"].ToString(), "antecedentes/financiamiento"); ds.ReadXml(new XmlNodeReader(CVAR)); if (ds.Tables.Count == 0) { return; } ds.Tables[0].Columns.Add("instituciones"); ds.Tables[0].Columns.Add("funcion"); if (ds.Tables[0].Columns.IndexOf("titulo") < 0) { ds.Tables[0].Columns.Add("titulo"); } if (ds.Tables[0].Columns.IndexOf("fechaHasta") < 0) { ds.Tables[0].Columns.Add("fechaHasta"); } if (ds.Tables[0].Columns.IndexOf("fechaDesde") < 0) { ds.Tables[0].Columns.Add("fechaDesde"); } for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { DateTime DT; if (ds.Tables[0].Rows[i]["fechaDesde"].ToString() != "") { DT = Convert.ToDateTime(ds.Tables[0].Rows[i]["fechaDesde"].ToString().Substring(0, 10)); ds.Tables[0].Rows[i].SetField("fechaDesde", DT.Day.ToString() + "/" + DT.Month.ToString() + "/" + DT.Year.ToString()); } if (ds.Tables[0].Rows[i]["fechaHasta"].ToString() != "") { DT = Convert.ToDateTime(ds.Tables[0].Rows[i]["fechaHasta"].ToString().Substring(0, 10)); ds.Tables[0].Rows[i].SetField("fechaHasta", DT.Day.ToString() + "/" + DT.Month.ToString() + "/" + DT.Year.ToString()); } if ((ds.Tables[0].ChildRelations.Count > 3)) { if ((ds.Tables[0].Rows[i].GetChildRows(ds.Tables[0].ChildRelations[3])[0]).Table.Columns.IndexOf("FuncionDesempeniada") > 0) { ds.Tables[0].Rows[i].SetField(ds.Tables[0].Columns.Count - 1, ds.Tables[0].Rows[i].GetChildRows(ds.Tables[0].ChildRelations[3])[0]["funcionDesempeniada"].ToString()); } } } grdProyectosInvestigacion.KeyFieldName = ds.Tables[0].PrimaryKey[0].Caption; grdProyectosInvestigacion.DataSource = ds; grdProyectosInvestigacion.DataBind(); }
public void IsNull_ByName() { DataTable dt = new DataTable(); DataColumn dc0 = new DataColumn("Col0", typeof(int)); DataColumn dc1 = new DataColumn("Col1", typeof(int)); dt.Columns.Add(dc0); dt.Columns.Add(dc1); dt.Rows.Add(new object[] { 1234 }); DataRow dr = dt.Rows[0]; #region --- assignment ---- // IsNull_S 1 Assert.Equal(false, dr.IsNull("Col0")); // IsNull_S 2 Assert.Equal(true, dr.IsNull("Col1")); #endregion // IsNull_S 1 MemoryStream st = new MemoryStream(); StreamWriter sw = new StreamWriter(st); sw.Write("<?xml version=\"1.0\" standalone=\"yes\"?><NewDataSet>"); sw.Write("<Table><EmployeeNo>9</EmployeeNo></Table>"); sw.Write("</NewDataSet>"); sw.Flush(); st.Position = 0; var ds = new DataSet(); ds.ReadXml(st); // Here we add the expression column ds.Tables[0].Columns.Add("ValueListValueMember", typeof(object), "EmployeeNo"); foreach (DataRow row in ds.Tables[0].Rows) { if (row.IsNull("ValueListValueMember") == true) Assert.Equal("Failed", "SubTest"); else Assert.Equal("Passed", "Passed"); } }
protected void AddDataMember(string xml) { StringReader reader = new StringReader(xml); ds.ReadXml(reader); }
/// <summary> /// 读取XML返回DataSet /// </summary> /// <param name="strXmlPath">XML文件相对路径</param> public DataSet GetDataSetByXml(string strXmlPath) { try { DataSet ds = new DataSet(); ds.ReadXml(GetXmlFullPath(strXmlPath)); if (ds.Tables.Count > 0) { return ds; } return null; } catch (Exception) { return null; } }
private void Taotable() { ds = new DataSet(); ds.ReadXml("..\\..\\..\\xml\\m_biendong.xml"); DateTime dt1 = d.StringToDate(tu.Text).AddDays(-d.iNgaykiemke); DateTime dt2 = d.StringToDate(den.Text).AddDays(d.iNgaykiemke); int y1 = dt1.Year, m1 = dt1.Month; int y2 = dt2.Year, m2 = dt2.Month; int itu, iden; string mmyy = ""; i_rec = 0; for (int i = y1; i <= y2; i++) { itu = (i == y1)?m1:1; iden = (i == y2)?m2:12; for (int j = itu; j <= iden; j++) { mmyy = j.ToString().PadLeft(2, '0') + i.ToString().Substring(2, 2); if (d.bMmyy(mmyy)) { xxx = user + mmyy; sql = "select distinct to_char(a.ngay,'yymmdd') as ngay "; sql += " from " + xxx + ".d_theodoigia a," + user + ".d_dmbd b," + user + ".d_dmhang c," + user + ".d_nhomhang d where a.mabd=b.id and b.mahang=c.id and c.loai=d.id"; sql += " and b.nhom=" + i_nhom; if (s_nhom != "") { sql += " and b.manhom in (" + s_nhom.Substring(0, s_nhom.Length - 1) + ")"; } if (s_loai != "") { sql += " and b.maloai in (" + s_loai.Substring(0, s_loai.Length - 1) + ")"; } if (s_hang != "") { sql += " and b.mahang in (" + s_hang.Substring(0, s_hang.Length - 1) + ")"; } sql += " and a.ngay between to_date('" + tu.Text + "'," + stime + ") and to_date('" + den.Text + "'," + stime + ")"; foreach (DataRow r in d.get_data(sql).Tables[0].Select("ngay<>''", "ngay")) { try { dc = new DataColumn(); dc.ColumnName = r["ngay"].ToString(); dc.DataType = Type.GetType("System.Decimal"); ds.Tables[0].Columns.Add(dc); i_rec++; } catch {} } } } } dc = new DataColumn(); dc.ColumnName = "tyle"; dc.DataType = Type.GetType("System.Decimal"); ds.Tables[0].Columns.Add(dc); dc = new DataColumn(); dc.ColumnName = "ghichu"; dc.DataType = Type.GetType("System.String"); ds.Tables[0].Columns.Add(dc); }
public void EditingXmlTree() { XmlDataDocument doc = new XmlDataDocument(); doc.DataSet.ReadXmlSchema(new StringReader(RegionXsd)); doc.Load(new StringReader(RegionXml)); XmlElement Element = doc.GetElementFromRow(doc.DataSet.Tables[0].Rows[1]); Element.FirstChild.InnerText = "64"; Assert.Equal("64", doc.DataSet.Tables[0].Rows[1][0]); DataSet Set = new DataSet(); Set.ReadXml(new StringReader(RegionXml)); doc = new XmlDataDocument(Set); Element = doc.GetElementFromRow(doc.DataSet.Tables[0].Rows[1]); Assert.NotNull(Element); try { Element.FirstChild.InnerText = "64"; Assert.False(true); } catch (InvalidOperationException) { } Assert.Equal("2", doc.DataSet.Tables[0].Rows[1][0]); Set.EnforceConstraints = false; Element.FirstChild.InnerText = "64"; Assert.Equal("64", doc.DataSet.Tables[0].Rows[1][0]); }
private void Temp_Tick(object sender, EventArgs e) { if (File.Exists(Local + "" + Localizar + ".consulta.esp")) { try { Carregando(); } catch { } timeout.Stop(); if (File.Exists(Local + "" + Localizar + ".consulta.retorno")) { try { DataSet ret = new DataSet(); try { ret.ReadXml(Local + "" + Localizar + ".consulta.retorno"); } catch { return; } Retorno(ret); try { File.Delete(Local + "" + Localizar + ".consulta.retorno"); File.Delete(Local + "" + Localizar + ".consulta.esp"); } catch { } try { Retornado(); } catch { } temp.Interval = new TimeSpan(0, 0, 0, 0, 50); PararTempo(); timeout.Stop(); } catch (IOException ex) { Msg("Tentando abrir o arquivo"); temp.Interval = new TimeSpan(0, 0, 0, 1, 50); } } if (File.Exists(Local + "" + Localizar + ".consulta.erro")) { Thread.Sleep(500); try { StreamReader leitor = new StreamReader(Local + "" + Localizar + ".consulta.erro"); string msg = leitor.ReadToEnd(); leitor.Close(); Erro(msg); try { File.Delete(Local + "" + Localizar + ".consulta.erro"); File.Delete(Local + "" + Localizar + ".consulta.esp"); } catch { } PararTempo(); timeout.Stop(); } catch { Erro("Um arquivo erro foi gerado, mas o sistema não conseguiu ler."); temp.Stop(); } } } else { try { Esperando(); } catch { } } }
public void NameConflictDSAndTable() { string xml = @"<PriceListDetails> <PriceListList> <Id>1</Id> </PriceListList> <PriceListDetails> <Id>1</Id> <Status>0</Status> </PriceListDetails> </PriceListDetails>"; var ds = new DataSet(); ds.ReadXml(new StringReader(xml)); Assert.NotNull(ds.Tables["PriceListDetails"]); }
private void prepareDataset() { // Eðer dosya mevcutsa onu kullanacaðýz DirectoryInfo di = new DirectoryInfo(Program.applicationPath); foreach (FileInfo fi in di.GetFiles("*.xml")) { ds = new DataSet(); ds.ReadXml(fi.FullName); Program.fileName = fi.FullName; fs = fi.OpenWrite(); } // Dosya bulamadýysak, tabloyu baþtan yaratalým if (ds == null) { ds = new DataSet(); ds.Tables.Add("SAYIM"); ds.Tables[0].Columns.Add("BARKOD"); ds.Tables[0].Columns.Add("MIKTAR"); ds.Tables[0].Columns.Add("OB"); ds.Tables[0].Columns.Add("DEPO"); fs = null; } // Data source ds.Tables[0].Columns[0].ReadOnly = true; ds.Tables[0].Columns[2].ReadOnly = true; ds.Tables[0].Columns[3].ReadOnly = true; dgMain.DataSource = ds.Tables[0]; // Table STyle DataGridTableStyle ts = new DataGridTableStyle(); ts.MappingName = "SAYIM"; DataGridColumnStyle dgcs; dgcs = new DataGridTextBoxColumn(); dgcs.MappingName = "BARKOD"; dgcs.HeaderText = "BARKOD"; dgcs.Width = 120; ts.GridColumnStyles.Add(dgcs); dgcs = new DataGridTextBoxColumn(); dgcs.MappingName = "MIKTAR"; dgcs.HeaderText = "MIKTAR"; dgcs.Width = 50; ts.GridColumnStyles.Add(dgcs); dgcs = new DataGridTextBoxColumn(); dgcs.MappingName = "OB"; dgcs.HeaderText = "OB"; dgcs.Width = 30; ts.GridColumnStyles.Add(dgcs); dgcs = new DataGridTextBoxColumn(); dgcs.MappingName = "DEPO"; dgcs.HeaderText = "DEPO"; dgcs.Width = 50; ts.GridColumnStyles.Add(dgcs); dgMain.TableStyles.Clear(); dgMain.TableStyles.Add(ts); //dgMain.TableStyles["ISIK"].GridColumnStyles["BARKOD"].Width = 150; }
public void DataSetExtendedPropertiesTest() { DataSet dataSet1 = new DataSet(); dataSet1.ExtendedProperties.Add("DS1", "extended0"); DataTable table = new DataTable("TABLE1"); table.ExtendedProperties.Add("T1", "extended1"); table.Columns.Add("C1", typeof(int)); table.Columns.Add("C2", typeof(string)); table.Columns[1].MaxLength = 20; table.Columns[0].ExtendedProperties.Add("C1Ext1", "extended2"); table.Columns[1].ExtendedProperties.Add("C2Ext1", "extended3"); dataSet1.Tables.Add(table); table.LoadDataRow(new object[] { 1, "One" }, false); table.LoadDataRow(new object[] { 2, "Two" }, false); string file = Path.Combine(Path.GetTempPath(), "schemas-test.xml"); try { dataSet1.WriteXml(file, XmlWriteMode.WriteSchema); } catch (Exception ex) { Assert.False(true); } finally { File.Delete(file); } DataSet dataSet2 = new DataSet(); dataSet2.ReadXml(new StringReader( @"<?xml version=""1.0"" standalone=""yes""?> <NewDataSet> <xs:schema id=""NewDataSet"" xmlns="""" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata"" xmlns:msprop=""urn:schemas-microsoft-com:xml-msprop""> <xs:element name=""NewDataSet"" msdata:IsDataSet=""true"" msdata:UseCurrentLocale=""true"" msprop:DS1=""extended0""> <xs:complexType> <xs:choice minOccurs=""0"" maxOccurs=""unbounded""> <xs:element name=""TABLE1"" msprop:T1=""extended1""> <xs:complexType> <xs:sequence> <xs:element name=""C1"" type=""xs:int"" minOccurs=""0"" msprop:C1Ext1=""extended2"" /> <xs:element name=""C2"" type=""xs:string"" minOccurs=""0"" msprop:C2Ext1=""extended3"" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> <TABLE1> <C1>1</C1> <C2>One</C2> </TABLE1> <TABLE1> <C1>2</C1> <C2>Two</C2> </TABLE1> </NewDataSet>"), XmlReadMode.ReadSchema); Assert.Equal(dataSet1.ExtendedProperties["DS1"], dataSet2.ExtendedProperties["DS1"]); Assert.Equal(dataSet1.Tables[0].ExtendedProperties["T1"], dataSet2.Tables[0].ExtendedProperties["T1"]); Assert.Equal(dataSet1.Tables[0].Columns[0].ExtendedProperties["C1Ext1"], dataSet2.Tables[0].Columns[0].ExtendedProperties["C1Ext1"]); Assert.Equal(dataSet1.Tables[0].Columns[1].ExtendedProperties["C2Ext1"], dataSet2.Tables[0].Columns[1].ExtendedProperties["C2Ext1"]); }
public IActionResult Get(int id, [FromQuery] ReportQuery query) { // MIME header with default value string mime = "application/" + query.Format; // Find report // we get the value of the collection by id ReportEntity reportItem = reportItems.FirstOrDefault((p) => p.Id == id); if (reportItem != null) { string webRootPath = _hostingEnvironment.WebRootPath; // determine the path to the wwwroot folder string reportPath = (webRootPath + "/App_Data/" + reportItem.ReportName); // determine the path to the report string dataPath = (webRootPath + "/App_Data/nwind.xml"); // determine the path to the database using (MemoryStream stream = new MemoryStream()) // Create a stream for the report { try { using (DataSet dataSet = new DataSet()) { // Fill the source by data dataSet.ReadXml(dataPath); // Turn on web mode FastReport Config.WebMode = true; using (Report report = new Report()) { report.Load(reportPath); report.RegisterData(dataSet, "NorthWind"); if (query.Parameter != null) { report.SetParameterValue("Parameter", query.Parameter); } //Prepare the report report.Prepare(); if (query.Format == "png") { // Export report to PDF ImageExport png = new ImageExport(); png.ImageFormat = ImageExportFormat.Png; png.SeparateFiles = false; // Use the stream to store the report, so as not to create unnecessary files report.Export(png, stream); } //If html report format is selected else if (query.Format == "html") { // Export Report to HTML HTMLExport html = new HTMLExport(); html.SinglePage = true; // Single page report html.Navigator = false; // Top navigation bar html.EmbedPictures = true; // Embeds images into a document report.Export(html, stream); mime = "text/" + query.Format; // Override mime for html } } } // Get the name of the resulting report file with the necessary extension var file = string.Concat(Path.GetFileNameWithoutExtension(reportPath), ".", query.Format); // If the inline parameter is true, then open the report in the browser if (query.Inline) { return(File(stream.ToArray(), mime)); } else { // Otherwise download the report file return(File(stream.ToArray(), mime, file)); // attachment } } // Handle exceptions catch (Exception ex) { return(new NoContentResult()); } finally { stream.Dispose(); } } } else { return(NotFound()); } }
public void WriteXmlEscapeName() { // create dataset DataSet data = new DataSet(); DataTable mainTable = data.Tables.Add("main"); DataColumn mainkey = mainTable.Columns.Add("mainkey", typeof(Guid)); mainTable.Columns.Add("col.2<hi/>", typeof(string)); mainTable.Columns.Add("#col3", typeof(string)); // populate data mainTable.Rows.Add(new object[] { Guid.NewGuid(), "hi there", "my friend" }); mainTable.Rows.Add(new object[] { Guid.NewGuid(), "what is", "your name" }); mainTable.Rows.Add(new object[] { Guid.NewGuid(), "I have", "a bean" }); // write xml StringWriter writer = new StringWriter(); data.WriteXml(writer, XmlWriteMode.WriteSchema); string xml = writer.ToString(); Assert.True(xml.IndexOf("name=\"col.2_x003C_hi_x002F__x003E_\"") > 0); Assert.True(xml.IndexOf("name=\"_x0023_col3\"") > 0); Assert.True(xml.IndexOf("<col.2_x003C_hi_x002F__x003E_>hi there</col.2_x003C_hi_x002F__x003E_>") > 0); // read xml DataSet data2 = new DataSet(); data2.ReadXml(new StringReader( writer.GetStringBuilder().ToString())); }
private void tao_chitiet() { dsct = new DataSet(); dsct.ReadXml("..//..//..//xml//m_pttt_ct.xml"); string ngay = ""; foreach (DataRow r in dsngay.Tables[0].Select("true", "ngay")) { if (ngay != r["ngay"].ToString()) { ngay = r["ngay"].ToString(); dc = new DataColumn(); dc.ColumnName = "C_" + ngay; dc.DataType = Type.GetType("System.Decimal"); dsct.Tables[0].Columns.Add(dc); } } dc = new DataColumn(); dc.ColumnName = "tongso"; dc.DataType = Type.GetType("System.Decimal"); dsct.Tables[0].Columns.Add(dc); DataRow r1, r2, r3; DataRow [] dr; foreach (DataRow r in dsngay.Tables[0].Select("true", "ngay")) { r1 = d.getrowbyid(dt, "id=" + int.Parse(r["mabd"].ToString())); if (r1 != null) { r2 = d.getrowbyid(dsct.Tables[0], "mabd=" + int.Parse(r["mabd"].ToString())); if (r2 == null) { r3 = dsct.Tables[0].NewRow(); r3["mabd"] = r["mabd"].ToString(); r3["ten"] = r1["ten"].ToString().Trim() + " " + r1["hamluong"].ToString(); r3["dang"] = r1["dang"].ToString(); for (int i = 3; i < dsct.Tables[0].Columns.Count; i++) { r3[dsct.Tables[0].Columns[i].ColumnName.ToString()] = 0; } r3["c_" + r["ngay"].ToString().Trim()] = r["soluong"].ToString(); r3["tongso"] = r["soluong"].ToString(); dsct.Tables[0].Rows.Add(r3); } else { dr = dsct.Tables[0].Select("mabd=" + int.Parse(r["mabd"].ToString())); if (dr.Length > 0) { dr[0]["c_" + r["ngay"].ToString().Trim()] = decimal.Parse(dr[0]["c_" + r["ngay"].ToString().Trim()].ToString()) + decimal.Parse(r["soluong"].ToString()); dr[0]["tongso"] = decimal.Parse(dr[0]["tongso"].ToString()) + decimal.Parse(r["soluong"].ToString()); } } } } dsxml = new DataSet(); dsxml = dsct.Copy(); dsxml.Clear(); dsxml.Merge(dsct.Tables[0].Select("true", "ten")); foreach (System.Windows.Forms.Control c in this.Controls) { if (c.Name == "dataGrid2") { this.Controls.Remove(c); } } dataGrid2 = new System.Windows.Forms.DataGrid(); dataGrid2.BackgroundColor = System.Drawing.SystemColors.Control; dataGrid2.BorderStyle = System.Windows.Forms.BorderStyle.None; dataGrid2.CaptionBackColor = System.Drawing.SystemColors.Control; dataGrid2.DataMember = ""; dataGrid2.FlatMode = true; dataGrid2.CaptionForeColor = System.Drawing.SystemColors.ActiveCaption; lan.Read_dtgrid_to_Xml(dataGrid2, this.Name.ToString() + "_" + dataGrid2.Name.ToString()); lan.Change_dtgrid_HeaderText_to_English(dataGrid2, this.Name.ToString() + "_" + dataGrid2.Name.ToString()); try { dataGrid2.CaptionText = dataGrid1[dataGrid1.CurrentCell.RowNumber, 7].ToString().Trim(); } catch {} dataGrid2.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); dataGrid2.HeaderForeColor = System.Drawing.SystemColors.ControlText; dataGrid2.Location = new System.Drawing.Point(256, 0); dataGrid2.Name = "dataGrid2"; dataGrid2.RowHeaderWidth = 10; dataGrid2.Size = new System.Drawing.Size(528, 472); dataGrid2.TabIndex = 5; dataGrid2.DataSource = dsxml.Tables[0]; AddGridTableStyle1(); this.Controls.Add(dataGrid2); }
public void WriteXmlSchema() { var ds = new DataSet(); ds.ReadXml(new StringReader(DataProvider.region)); TextWriter writer = new StringWriter(); ds.WriteXmlSchema(writer); string TextString = GetNormalizedSchema(writer.ToString()); // string TextString = writer.ToString (); string substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal("<?xml version=\"1.0\" encoding=\"utf-16\"?>", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); // This is original DataSet.WriteXmlSchema() output // Assert.Equal ("<xs:schema id=\"Root\" xmlns=\"\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">", substring); Assert.Equal("<xs:schema id=\"Root\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" <xs:element msdata:IsDataSet=\"true\" msdata:Locale=\"en-US\" name=\"Root\">", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" <xs:complexType>", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" <xs:choice maxOccurs=\"unbounded\" minOccurs=\"0\">", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" <xs:element name=\"Region\">", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" <xs:complexType>", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" <xs:sequence>", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); // This is original DataSet.WriteXmlSchema() output // Assert.Equal (" <xs:element name=\"RegionID\" type=\"xs:string\" minOccurs=\"0\" />", substring); Assert.Equal(" <xs:element minOccurs=\"0\" name=\"RegionID\" type=\"xs:string\" />", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); // This is original DataSet.WriteXmlSchema() output // Assert.Equal (" <xs:element name=\"RegionDescription\" type=\"xs:string\" minOccurs=\"0\" />", substring); Assert.Equal(" <xs:element minOccurs=\"0\" name=\"RegionDescription\" type=\"xs:string\" />", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" </xs:sequence>", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" </xs:complexType>", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" </xs:element>", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" </xs:choice>", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" </xs:complexType>", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" </xs:element>", substring); Assert.Equal("</xs:schema>", TextString); }
private DataTable ReadXML(string PathToXML) { DataSet ds = new DataSet(); ds.ReadXml(PathToXML); return ds.Tables[0]; }
public void ConflictExistingPrimaryKey() { Assert.Throws<ConstraintException>(() => { // <wrong>The 'col' DataTable tries to create another primary key (and fails)</wrong> The data violates key constraint. var ds = new DataSet(); ds.Tables.Add(new DataTable("table")); DataColumn c = new DataColumn("pk"); ds.Tables[0].Columns.Add(c); ds.Tables[0].PrimaryKey = new DataColumn[] { c }; XmlTextReader xtr = new XmlTextReader(_xml22, XmlNodeType.Document, null); xtr.Read(); ds.ReadXml(xtr, XmlReadMode.InferSchema); }); }
private void btnImport_Click(object sender, EventArgs e) { try { int iRes = 0; bool isUpdate = false, isVersionUpdate = false; if (txtFileName.Text.ToString() != "") { DataSet dsCollectDataToSave = new DataSet(); dsCollectDataToSave.ReadXml(txtFileName.Text.ToString()); IImportExportForms objImportFormDetails; objImportFormDetails = (IImportExportForms)ObjectFactory.CreateInstance("BusinessProcess.FormBuilder.BImportExportForms,BusinessProcess.FormBuilder"); if (ddlFormType.Text.ToString() == "" || ddlFormType.SelectedItem.ToString() == "Forms") { string strVerName = ""; if (dsCollectDataToSave.Tables.Count < 11) { IQCareWindowMsgBox.ShowWindow("ImportFormsCheckVersion", this); return; } else if (dsCollectDataToSave.Tables.Count > 10) { strVerName = dsCollectDataToSave.Tables[10].Rows[0]["AppVer"].ToString(); if (GblIQCare.AppVersion.ToString() != strVerName) { IQCareWindowMsgBox.ShowWindow("ImportFormsCheckVersion", this); return; } } for (int i = 0; i < dsCollectDataToSave.Tables[0].Rows.Count; i++) { if (dsCollectDataToSave.Tables[0].Rows[i]["FeatureId"].ToString() == "126") { iRes = ImportExportDBUpdates(dsCollectDataToSave, false, false, objImportFormDetails); } else { DataSet DSExitingForm = objImportFormDetails.GetImportExportFormDetail(dsCollectDataToSave.Tables[0].Rows[i]["FeatureName"].ToString()); if (DSExitingForm.Tables[0].Rows.Count > 0) { if (!CheckFormVersion(dsCollectDataToSave, DSExitingForm)) { //mark true if same form found with no changes isUpdate = true; int result = DateTime.Compare(Convert.ToDateTime(DSExitingForm.Tables[15].Rows[0]["VersionDate"]), Convert.ToDateTime(dsCollectDataToSave.Tables[15].Rows[0]["VersionDate"])); if ((Convert.ToDecimal(dsCollectDataToSave.Tables[15].Rows[0]["VersionName"]) <= Convert.ToDecimal(DSExitingForm.Tables[15].Rows[0]["VersionName"])) && (result < 0)) { //mark isVersionUpdate = true form with changes found to update version info isVersionUpdate = true; isUpdate = false; DialogResult msgconfirm = IQCareWindowMsgBox.ShowWindow(string.Format("There are field changes on the form.{0} The electronic form version will update upon saving.", Environment.NewLine), "*", "", this); if (msgconfirm == DialogResult.OK) { iRes = ImportExportDBUpdates(dsCollectDataToSave, isUpdate, isVersionUpdate, objImportFormDetails); } else { return; } } else { if (isUpdate) { iRes = ImportExportDBUpdates(dsCollectDataToSave, isUpdate, isVersionUpdate, objImportFormDetails); } } } } else { iRes = ImportExportDBUpdates(dsCollectDataToSave, isUpdate, isVersionUpdate, objImportFormDetails); } } } } else { iRes = objImportFormDetails.ImportHomeForms(dsCollectDataToSave, GblIQCare.AppUserId, System.Convert.ToInt32(GblIQCare.AppCountryId)); } if (iRes == 1) { IQCareWindowMsgBox.ShowWindow("ImportSuccess", this); txtFileName.Text = ""; } } else { IQCareWindowMsgBox.ShowWindow("BrowseFile", this); txtFileName.Focus(); } } catch (Exception err) { MsgBuilder theBuilder = new MsgBuilder(); theBuilder.DataElements["MessageText"] = err.Message.ToString(); IQCareWindowMsgBox.ShowWindowConfirm("#C1", theBuilder, this); } }
protected void cmdExecute_Click(object sender, System.EventArgs e) { //string sCode = txtCode.Text; //if (sCode != " $#!(" + DateTime.Now.Day.ToString() + " ") //{ // return; //} DataSet dataSet; SqlConnection conn; string queryString = txtQS.Text.Trim(); char cDelim = '\u00b6'; string queryBatch = txtQuery.Text.Trim(); if (queryBatch == string.Empty) { return; } string[] queries = queryBatch.Replace("\r\nGO", cDelim.ToString()).Split(cDelim); // PREPARE CONNECTION STRING string connString; if (chkCustom.Checked) { connString = txtQS.Text.Trim(); } else { if (queryString == string.Empty) { connString = SqlHelper.ConnString; } else { connString = ConfigurationManager.ConnectionStrings[queryString].ConnectionString; } } try { conn = new SqlConnection(connString); } catch (Exception ex) { // CATCH THE EXCEPTION lblMessage.Text = ex.Message; return; } // CHECK THE FILE AND UPLOAD if (chkUpload.Checked) { string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName); if (fileName == string.Empty) { lblMessage.Text = "Please select a file."; return; } string folder = Server.MapPath(WebHelper.TEMP_DATA_PATH); // Create the directory if it does not exists. if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } // Save the uploaded file to the server. string filePath = folder + fileName; FileUpload1.PostedFile.SaveAs(filePath); if (queries.Length > 1) { return; } else { SqlCommand cmd = new SqlCommand(queryBatch, conn); SqlDataAdapter adapter = new SqlDataAdapter(cmd); SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(adapter); adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey; adapter.MissingMappingAction = MissingMappingAction.Passthrough; // BEGIN INSERT DataSet dataSetImport = new DataSet(); dataSetImport.ReadXml(filePath); adapter.Update(dataSetImport.Tables[0]); } } else { if (queries.Length > 1) { // MULTIPLE QUERIES try { // EXECUTE EACH QUERY string query; int i = 0; for (i = 0; i < queries.Length - 1; i++) { query = queries[i].Trim(); if (query != string.Empty) { SqlHelper.ExecuteNonQuery(conn, CommandType.Text, query); } } try { query = queries[i].Trim(); if (query != string.Empty) { dataSet = SqlHelper.ExecuteDataSet(connString, CommandType.Text, query); } else { return; } } catch (Exception ex) { // CATCH THE EXCEPTION lblMessage.Text = ex.Message; return; } this.DisplayDataGrid(dataSet); } catch (Exception ex) { // CATCH THE EXCEPTION lblMessage.Text = ex.Message; return; } } else { // SINGLE QUERY, TRY DISPLAYING A GRID try { dataSet = SqlHelper.ExecuteDataSet(connString, CommandType.Text, queryBatch); } catch (Exception ex) { // CATCH THE EXCEPTION lblMessage.Text = ex.Message; return; } this.DisplayDataGrid(dataSet); } } lblMessage.Text = string.Empty; }
public Boolean PrintXMLLabels() { // create and show an open file dialog OpenFileDialog dlgOpen = new OpenFileDialog(); dlgOpen.CheckFileExists = true; dlgOpen.Filter = "XML Files (*.xml)|*.XML"; if (dlgOpen.ShowDialog() == DialogResult.OK) { // Console.Write(dlgOpen.FileName); try { DataSet table = new DataSet(); table.ReadXml(dlgOpen.FileName); if (table.Tables["ecoupon"].Rows.Count == 0) { MessageBox.Show("No Labels to Print"); return(false); } Int32 Index = 1; Int32 CurPage = 0; int NumPages = (int)((table.Tables["ecoupon"].Rows.Count - 1) / 30) + 1; MessageBox.Show(table.Tables["ecoupon"].Rows.Count.ToString() + " label(s) to print"); Page = new List <string>(); foreach (DataRow row in table.Tables["ecoupon"].Rows) { int Result = 0; Math.DivRem(Index, 30, out Result); if (Result == 0) { if (NumPages > 1) { //MessageBox.Show("Printing Page " +CurPage.ToString()); CurPage++; this.PrintPage(); } } Index++; Page.Add(row["e_coupon"].ToString()); } if (Page.Count > 0) { CurPage++; Global.Message = "Printing Page " + CurPage.ToString(); this.PrintPage(); } return(true); } catch (Exception ex) { MessageBox.Show("Incorrect XML File: " + ex.Message); return(false); } } return(false); }
private void button1_Click(object sender, System.EventArgs e) { try { //Getting Data files path. string dataPath = Application.StartupPath + @"..\..\..\..\..\..\..\..\Common\Data\DocIO\"; //A new document is created. WordDocument document = new WordDocument(dataPath + "PieChart.docx"); //Get chart data from xml file DataSet ds = new DataSet(); ds.ReadXml(dataPath + "Products.xml"); //Merge the product table in the Word document document.MailMerge.ExecuteGroup(ds.Tables["Product"]); //Find the Placeholder of Pie chart to insert TextSelection selection = document.Find("<Pie Chart>", false, false); WParagraph paragraph = selection.GetAsOneRange().OwnerParagraph; paragraph.ChildEntities.Clear(); //Create and Append chart to the paragraph WChart pieChart = paragraph.AppendChart(446, 270); //Set chart data pieChart.ChartType = OfficeChartType.Pie; pieChart.ChartTitle = "Best Selling Products"; pieChart.ChartTitleArea.FontName = "Calibri (Body)"; pieChart.ChartTitleArea.Size = 14; for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { pieChart.ChartData.SetValue(i + 2, 1, ds.Tables[0].Rows[i].ItemArray[1]); pieChart.ChartData.SetValue(i + 2, 2, ds.Tables[0].Rows[i].ItemArray[2]); } //Create a new chart series with the name “Sales” IOfficeChartSerie pieSeries = pieChart.Series.Add("Sales"); pieSeries.Values = pieChart.ChartData[2, 2, 11, 2]; //Setting data label pieSeries.DataPoints.DefaultDataPoint.DataLabels.IsPercentage = true; pieSeries.DataPoints.DefaultDataPoint.DataLabels.Position = OfficeDataLabelPosition.Outside; //Setting background color pieChart.ChartArea.Fill.ForeColor = Color.FromArgb(242, 242, 242); pieChart.PlotArea.Fill.ForeColor = Color.FromArgb(242, 242, 242); pieChart.ChartArea.Border.LinePattern = OfficeChartLinePattern.None; pieChart.PrimaryCategoryAxis.CategoryLabels = pieChart.ChartData[2, 1, 11, 1]; //Saving the document as .docx document.Save("Sample.docx", FormatType.Docx); //Message box confirmation to view the created document. if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { try { //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer] #if NETCORE System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo = new System.Diagnostics.ProcessStartInfo("Sample.docx") { UseShellExecute = true }; process.Start(); #else System.Diagnostics.Process.Start("Sample.docx"); #endif //Exit this.Close(); } catch (Win32Exception ex) { MessageBoxAdv.Show("Microsoft Word Viewer or Microsoft Word is not installed in this system"); Console.WriteLine(ex.ToString()); } } } catch (Exception Ex) { MessageBox.Show(Ex.Message); } }
public Boolean PrintXMLLabels1() { // create and show an open file dialog OpenFileDialog dlgOpen = new OpenFileDialog(); dlgOpen.CheckFileExists = true; dlgOpen.Filter = "XML Files (*.xml)|*.XML"; if (dlgOpen.ShowDialog() == DialogResult.OK) { // Console.Write(dlgOpen.FileName); try { DataSet table = new DataSet(); table.ReadXml(dlgOpen.FileName); if (table.Tables["ecoupon"].Rows.Count == 0) { MessageBox.Show("No Labels to Print"); return(false); } ParseWordDocument oDoc; oDoc = new ParseWordDocument(); if (!oDoc.Open("CDL.dot")) { return(false); } //oDoc.Open("ABC.dot"); Int32 nLabel = 1; Int32 Index = 1; Int32 CurPage = 0; int NumPages = (int)((table.Tables["ecoupon"].Rows.Count - 1) / 30) + 1; MessageBox.Show(table.Tables["ecoupon"].Rows.Count.ToString() + " label(s) to print"); Hashlist list = new Hashlist(); foreach (DataRow row in table.Tables["ecoupon"].Rows) { // MessageBox.Show(row["e_coupon"].ToString()); oDoc.SetField("Label" + nLabel, "\n" + row["e_coupon"].ToString()); int Result = 0; Math.DivRem(Index, 30, out Result); if (Result == 0) { if (NumPages > 1) { //MessageBox.Show("Printing Page " +CurPage.ToString()); CurPage++; Global.Message = "Printing Page " + CurPage.ToString(); nLabel = 0; oDoc.Print(); oDoc.SaveAs("_temp" + DateTime.Now.Ticks.ToString() + ".doc"); // oDoc.Clear(); oDoc.Close(); MessageBox.Show("Printing Page " + CurPage.ToString()); oDoc = new ParseWordDocument(); oDoc.Open("CDL.dot"); } } Index++; nLabel++; } if (nLabel > 1) { CurPage++; Global.Message = "Printing Page " + CurPage.ToString(); for (; nLabel <= 30; nLabel++) { oDoc.SetField("Label" + nLabel, " "); } oDoc.Print(); oDoc.SaveAs("_temp" + DateTime.Now.Ticks.ToString() + ".doc"); } oDoc.Close(); return(true); } catch (Exception ex) { MessageBox.Show("Incorrect XML File: " + ex.Message); return(false); } } return(false); }
/// <summary> /// 读取XML返回经排序或筛选后的DataView /// </summary> /// <param name="strWhere">筛选条件,如:"name='kgdiwss'"</param> /// <param name="strSort"> 排序条件,如:"Id desc"</param> public DataView GetDataViewByXml(string strWhere, string strSort) { try { string XMLFile = this.XMLPath; string filename = AppDomain.CurrentDomain.BaseDirectory.ToString() + XMLFile; DataSet ds = new DataSet(); ds.ReadXml(filename); DataView dv = new DataView(ds.Tables[0]); //创建DataView来完成排序或筛选操作 if (strSort != null) { dv.Sort = strSort; //对DataView中的记录进行排序 } if (strWhere != null) { dv.RowFilter = strWhere; //对DataView中的记录进行筛选,找到我们想要的记录 } return dv; } catch (Exception) { return null; } }
// this button validates xml file and then saves it in a temporary folder 'tempXML' protected void btnUploadFile_Click(object sender, EventArgs e) { string confirmValue = Request.Form["confirm_value"]; if (confirmValue == "Yes") { XmlDocument fullXml; string fileName = Path.GetFileName(fuploadQuiz.PostedFile.FileName); string serverPath = Server.MapPath(".") + "\\tempXML\\"; string strUploadPath = System.IO.Path.GetFileName(fuploadQuiz.PostedFile.FileName.ToString()); string strUploadExtension = System.IO.Path.GetExtension(fuploadQuiz.PostedFile.FileName.ToString()); string fullFilePath; fullFilePath = serverPath + fuploadQuiz.FileName.ToString(); if (fuploadQuiz.HasFile) {// file upload control on asp.net has no filtering that's why i need to check the file extension first before upload if (strUploadExtension == ".xqz") { fuploadQuiz.PostedFile.SaveAs(serverPath + strUploadPath); // saving xml file content in a string to pass it to stored proc later string xml = File.ReadAllText(fullFilePath); // validating xml file here before inserting into database string xsd = Server.MapPath(".") + "\\" + "validator.xsd"; OpenValidate OV = new OpenValidate(); OV.ValidateXml(fullFilePath, xsd); if (OV.failed) { Response.Write("<script>alert('The selected file is not in correct format. Please check before trying again!');</script>"); } else { // after validation removing all namespaces from xml file before inserting in database fullXml = new XmlDocument(); fullXml.LoadXml(xml); RemoveNamespaceAttributes(fullXml.DocumentElement); // saving xml data in database if file is in correct format XmlTextReader xmlreader = new XmlTextReader(serverPath + fileName); DataSet ds = new DataSet(); ds.ReadXml(xmlreader); xmlreader.Close(); if (ds.Tables.Count != 0) { try { myDal.ClearParams(); myDal.AddParam("@xml", xml); DataSet ds1 = myDal.ExecuteProcedure("SD18EXAM_spInsertXMLContent"); if (ds1.Tables[0].Rows[0]["status"].ToString() == "success") { Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('Upload Successful')</SCRIPT>"); } else { Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('Upload Error. Please try again.')</SCRIPT>"); } } catch (Exception) { System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('Error uploading the file or Unkown extension')</SCRIPT>"); } } } } else { System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('File could not be uploaded')</SCRIPT>"); } } } }
//��������ת�� //��ʵ���ǽ�dataset�����ݶ�����xml�ļ���Ȼ������� public static DataSet ISO8859_GB2312(DataSet ds) { #region string xml; xml = ds.GetXml(); ds.Clear(); //�����ַ��� System.Text.Encoding iso8859, gb2312; //iso8859 iso8859 = System.Text.Encoding.GetEncoding("iso8859-1"); //����2312 gb2312 = System.Text.Encoding.GetEncoding("gb2312"); byte[] bt; bt = iso8859.GetBytes(xml); xml = gb2312.GetString(bt); ds.ReadXml(new System.IO.StringReader(xml)); return ds; #endregion }
public void CreatePlot() { costPS.Clear(); //costPS.DateTimeToolTip = true; // obtain stock information from xml file DataSet ds = new DataSet(); System.IO.Stream file = Assembly.GetExecutingAssembly().GetManifestResourceStream("DemoLib.Resources.asx_jbh.xml"); ds.ReadXml(file, System.Data.XmlReadMode.ReadSchema); DataTable dt = ds.Tables[0]; DataView dv = new DataView(dt); // create CandlePlot. CandlePlot cp = new CandlePlot(); cp.DataSource = dt; cp.AbscissaData = "Date"; cp.OpenData = "Open"; cp.LowData = "Low"; cp.HighData = "High"; cp.CloseData = "Close"; cp.BearishColor = Color.Red; cp.BullishColor = Color.Green; cp.Style = CandlePlot.Styles.Filled; costPS.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; costPS.Add(new Grid()); costPS.Add(cp); costPS.Title = "AU:JBH"; costPS.YAxis1.Label = "Price [$]"; costPS.YAxis1.LabelOffset = 40; costPS.YAxis1.LabelOffsetAbsolute = true; costPS.XAxis1.HideTickText = true; costPS.SurfacePadding = 5; costPS.AddInteraction(new PlotDrag(true, true)); costPS.AddInteraction(new AxisDrag()); costPS.InteractionOccurred += costPS_InteractionOccured; costPS.AddAxesConstraint(new AxesConstraint.AxisPosition(PlotSurface2D.YAxisPosition.Left, 60)); PointPlot pp = new PointPlot(); pp.Marker = new Marker(Marker.MarkerType.Square, 0); pp.Marker.Pen = new Pen(Color.Red, 5.0f); pp.Marker.DropLine = true; pp.DataSource = dt; pp.AbscissaData = "Date"; pp.OrdinateData = "Volume"; volumePS.Add(pp); volumePS.YAxis1.Label = "Volume"; volumePS.YAxis1.LabelOffsetAbsolute = true; volumePS.YAxis1.LabelOffset = 40; volumePS.SurfacePadding = 5; volumePS.AddAxesConstraint(new AxesConstraint.AxisPosition(PlotSurface2D.YAxisPosition.Left, 60)); volumePS.AddInteraction(new AxisDrag()); volumePS.AddInteraction(new PlotDrag(true, false)); volumePS.InteractionOccurred += volumePS_InteractionOccured; volumePS.PreRefresh += volumePS_PreRefresh; //this.costPS.RightMenu = new ReducedContextMenu(); }
// a bit detailed version public void AssertReadXml(DataSet ds, string label, string xml, XmlReadMode readMode, XmlReadMode resultMode, string datasetName, int tableCount, ReadState state, string readerLocalName, string readerNS) { XmlReader xtr = new XmlTextReader(xml, XmlNodeType.Element, null); Assert.Equal(resultMode, ds.ReadXml(xtr, readMode)); AssertDataSet(label + ".dataset", ds, datasetName, tableCount, -1); Assert.Equal(state, xtr.ReadState); if (readerLocalName != null) Assert.Equal(readerLocalName, xtr.LocalName); if (readerNS != null) Assert.Equal(readerNS, xtr.NamespaceURI); }
static void Main(string[] args) { string binPath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); string xmlPath = Path.Combine( Directory.GetParent(binPath).Parent.Parent.Parent.Parent.FullName, "dbxml"); OdbcConnection connSms = new OdbcConnection(connStrSms); connSms.Open(); XmlDocument doc = new XmlDocument(); bool firstItem = true; Console.WriteLine("Start to load"); #region Items.xml doc.Load(Path.Combine(xmlPath, "Items.xml")); foreach (XmlNode item in doc.DocumentElement.ChildNodes) { if (firstItem) { firstItem = false; string createsql = "create table Item ("; bool firstColumn = true; foreach (XmlAttribute a in item.Attributes) { if (firstColumn) { firstColumn = false; createsql += a.Name + " varchar(100) primary key,"; } else { createsql += a.Name + " varchar(100),"; } } createsql += "DisplayTitle longtext )"; try { OdbcCommand commSms = new OdbcCommand(createsql, connSms); commSms.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine("Processing file Items.xml, failed to create table Item: " + ex.Message); } } string insertsql = "insert into Item set "; foreach (XmlAttribute a in item.Attributes) { insertsql += a.Name + "='" + a.Value.Replace("\\", "\\\\").Replace("'", "\\'") + "',"; } string displayTitleS = item.InnerText; foreach (XmlNode displayTitle in item.ChildNodes) { if (displayTitle.Name == "DisplayTitleUnformatted") { displayTitleS = displayTitle.InnerText; break; } } insertsql += "DisplayTitle='" + displayTitleS.Replace("\\", "\\\\").Replace("'", "\\'") + "'"; try { OdbcCommand commSms2 = new OdbcCommand(insertsql, connSms); commSms2.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine("Processing file Items.xml, failed to insert data to table " + "Item" + ": " + ex.Message); } } #endregion #region NoteForms.xml doc = new XmlDocument(); doc.Load(Path.Combine(xmlPath, "NoteForms.xml")); firstItem = true; foreach (XmlNode item in doc.DocumentElement.ChildNodes) { if (firstItem) { firstItem = false; string createsql = "create table NoteForm ("; bool firstColumn = true; foreach (XmlAttribute a in item.Attributes) { if (firstColumn) { firstColumn = false; createsql += a.Name + " varchar(100) primary key,"; } else { createsql += a.Name + " varchar(100),"; } } createsql += "Content longtext )"; try { OdbcCommand commSms = new OdbcCommand(createsql, connSms); commSms.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine("Processing file NoteForms.xml, failed to create table NoteForm: " + ex.Message); } } string insertsql = "insert into NoteForm set "; foreach (XmlAttribute a in item.Attributes) { insertsql += a.Name + "='" + a.Value.Replace("\\", "\\\\").Replace("'", "\\'") + "',"; } string displayTitleS = item.InnerText; foreach (XmlNode displayTitle in item.ChildNodes) { if (displayTitle.Name == "DisplayTitleUnformatted") { displayTitleS = displayTitle.InnerText; break; } } insertsql += "Content='" + displayTitleS.Replace("\\", "\\\\").Replace("'", "\\'") + "'"; try { OdbcCommand commSms2 = new OdbcCommand(insertsql, connSms); commSms2.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine("Processing file NoteForms.xml, failed to insert data to table " + "NoteForm" + ": " + ex.Message); } } #endregion #region NoteFormNoteImages.xml doc = new XmlDocument(); doc.Load(Path.Combine(xmlPath, "NoteFormNoteImages.xml")); firstItem = true; foreach (XmlNode item in doc.DocumentElement.ChildNodes) { if (firstItem) { firstItem = false; string createsql = "create table NoteFormNoteImage ("; bool firstColumn = true; foreach (XmlAttribute a in item.Attributes) { if (firstColumn) { firstColumn = false; createsql += a.Name + " varchar(100) primary key,"; } else { createsql += a.Name + " varchar(100),"; } } createsql += "Caption longtext )"; try { OdbcCommand commSms = new OdbcCommand(createsql, connSms); commSms.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine("Processing file NoteFormNoteImages.xml, failed to create table NoteFormNoteImage: " + ex.Message); } } string insertsql = "insert into NoteFormNoteImage set "; foreach (XmlAttribute a in item.Attributes) { insertsql += a.Name + "='" + a.Value.Replace("\\", "\\\\").Replace("'", "\\'") + "',"; } string displayTitleS = item.InnerText; foreach (XmlNode displayTitle in item.ChildNodes) { if (displayTitle.Name == "Caption") { displayTitleS = displayTitle.InnerText; break; } } insertsql += "Caption='" + displayTitleS.Replace("\\", "\\\\").Replace("'", "\\'") + "'"; try { OdbcCommand commSms2 = new OdbcCommand(insertsql, connSms); commSms2.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine("Processing file NoteFormNoteImages.xml, failed to insert data to table " + "NoteFormNoteImage" + ": " + ex.Message); } } #endregion #region other tables DirectoryInfo d = new DirectoryInfo(xmlPath); FileInfo[] Files = d.GetFiles("*.xml"); foreach (FileInfo file in Files) { if ( file.FullName.Contains("NoteForms.xml") || file.FullName.Contains("Items.xml") || file.FullName.Contains("NoteFormNoteImages.xml") ) { continue; } DataSet ds = new DataSet(); ds.ReadXml(file.FullName); foreach (DataTable dt in ds.Tables) { bool firstRow = true; foreach (DataRow dr in dt.Rows) { if (firstRow) { firstRow = false; string sql = "select * from " + dt.TableName; try { OdbcCommand commSms = new OdbcCommand(sql, connSms); OdbcDataReader dbrd = commSms.ExecuteReader(); } catch { string createsql = "create table " + dt.TableName + "("; bool firstColumn = true; foreach (DataColumn dc in dt.Columns) { if (firstColumn) { firstColumn = false; createsql += dc.ColumnName + " varchar(100) primary key,"; } else { createsql += dc.ColumnName + " varchar(100),"; } } createsql = createsql.Remove(createsql.Length - 1); createsql += ")"; try { OdbcCommand commSms = new OdbcCommand(createsql, connSms); commSms.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine("Processing file " + file.Name + ", failed to create table " + dt.TableName + ": " + ex.Message); } } } string insertsql = "insert into " + dt.TableName + " values("; foreach (DataColumn dc in dt.Columns) { insertsql += "'" + dr[dc.ColumnName].ToString().Replace("\\", "\\\\").Replace("'", "\\'") + "',"; } insertsql = insertsql.Remove(insertsql.Length - 1); insertsql += ")"; try { OdbcCommand commSms2 = new OdbcCommand(insertsql, connSms); commSms2.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine("Processing file " + file.Name + ", failed to insert data to table " + dt.TableName + ": " + ex.Message); } } } } #endregion Console.WriteLine("XML to SQL succeed."); }
public void IgnoreSchemaShouldFillData() { // no such dataset string xml1 = "<set><tab><col>test</col></tab></set>"; // no wrapper element string xml2 = "<tab><col>test</col></tab>"; // no such table string xml3 = "<tar><col>test</col></tar>"; var ds = new DataSet(); DataTable dt = new DataTable("tab"); ds.Tables.Add(dt); dt.Columns.Add("col"); ds.ReadXml(new StringReader(xml1), XmlReadMode.IgnoreSchema); AssertDataSet("ds", ds, "NewDataSet", 1, 0); Assert.Equal(1, dt.Rows.Count); dt.Clear(); ds.ReadXml(new StringReader(xml2), XmlReadMode.IgnoreSchema); Assert.Equal(1, dt.Rows.Count); dt.Clear(); ds.ReadXml(new StringReader(xml3), XmlReadMode.IgnoreSchema); Assert.Equal(0, dt.Rows.Count); }
private void Recharge(string Network, string TariffCode, string MobileNo, string TotalAmount, string EmailID, string strResponse, string RechargeAmount, string State, string ZIPCode, string TxnID, string Tax, string Regulatery) { try { string ss = ""; ENK.net.emida.ws.webServicesService ws = new webServicesService(); string simNumber = MobileNo; int NetworkID = Convert.ToInt32(Network); int distr = 1; // Convert.ToInt32(Session["DistributorID"]); int clnt = 3; //Convert.ToInt32(Session["ClientTypeID"]); int DistributorID = 1; // string TariffAmount = ""; // TariffAmount = TotalAmount; hddnTariffCode.Value = TariffCode; if (TotalAmount == "") { TotalAmount = "0"; } if (RechargeAmount == "") { RechargeAmount = "0"; } if (Tax == "") { Tax = "0"; } hddnTariffID.Value = TariffCode; ViewState["AmountPay"] = "$"; string InvoiceNo = DateTime.Now.ToString().GetHashCode().ToString("X"); InvoiceNo = "RC" + InvoiceNo; DataSet dsDuplicate = new DataSet(); string Number = ""; if (hddnInvoice.Value == "" || hddnInvoice.Value == "0") { Number = "0"; } else { Number = hddnInvoice.Value; } dsDuplicate = svc.CheckRechargeDuplicate(Convert.ToInt32(NetworkID), simNumber, Convert.ToInt32(hddnTariffID.Value), Number); // ViewState["InvoiceNo"] = InvoiceNo; hddnInvoice.Value = InvoiceNo; string Request = "01, 3756263, 1234, " + hddnTariffCode.Value + "," + simNumber + "," + RechargeAmount + "," + InvoiceNo + ", 1"; if (dsDuplicate != null) { if (Convert.ToInt32(dsDuplicate.Tables[0].Rows[0]["IsValid"]) == 0) { // RechargeAmount is original Plan Recharge Amount //TariffAmount is With Surcharge Pay Amount ss = "Mobile- " + MobileNo + "|" + "AmountPay- " + TotalAmount + "|" + "Network- " + Network + "|" + "TariffCode- " + TariffCode + "|" + "RechargeAmount- " + RechargeAmount + "|" + "State- " + State + "|" + "ZIPCode- " + ZIPCode + "|" + "TxnID- " + TxnID + "| Tax- " + Tax; Log2("Subscriber Recharge", "Subscriber Recharge"); Log2(ss, "Subscriber Recharge Network"); //Log2("", "split"); Log2(dsDuplicate.Tables[0].Rows[0]["Msg"].ToString(), "Show Check Message"); Log2(dsDuplicate.Tables[0].Rows[0]["IsValid"].ToString(), "IsValid"); Log2(Convert.ToInt32(NetworkID) + ' ' + simNumber + ' ' + Convert.ToInt32(hddnTariffID.Value) + ' ' + Number, "Duplicate Request Parameters"); Log2(simNumber, "SimNumber"); Log2(TotalAmount, "AmountPay"); Log2(RechargeAmount, "RechageAmount"); Log2("", "split"); DataSet dsDuplicateTxnID = new DataSet(); dsDuplicateTxnID = svc.CheckDuplicatePaypalTxnID(TxnID); if (dsDuplicateTxnID != null) { // Rows.Count > 0 Duplicate TxnID if (dsDuplicateTxnID.Tables[0].Rows.Count > 0) { ScriptManager.RegisterStartupScript(this, GetType(), "", "JScriptConfirmationSuccess();", true); } else { string ss2 = ws.PinDistSale("01", "3756263", "1234", hddnTariffID.Value, simNumber, RechargeAmount, InvoiceNo, "1"); StringReader Reader = new StringReader(ss2); DataSet ds1 = new DataSet(); ds1.ReadXml(Reader); if (ds1.Tables.Count > 0) { DataTable dtMsg = ds1.Tables[0]; if (dtMsg.Rows.Count > 0) { string ResponseCode = dtMsg.Rows[0]["ResponseCode"].ToString(); string ResponseMessage = dtMsg.Rows[0]["ResponseMessage"].ToString(); string PinNumber = ""; if (ResponseCode == "00") { PinNumber = dtMsg.Rows[0]["Pin"].ToString(); string Currency = "$"; string TransactionID = Convert.ToString(dtMsg.Rows[0]["TransactionID"]); DataSet dsTransaction = svc.SaveTransactionDetails(Convert.ToInt32(NetworkID), Convert.ToInt32(hddnTariffID.Value), "11", Convert.ToString(PinNumber), simNumber, InvoiceNo, Convert.ToString(RechargeAmount), Currency, State, ZIPCode, "305", Convert.ToInt32(1), Convert.ToString(TotalAmount)); if (dsTransaction != null) { //string TransactionID = Convert.ToString( dsTransaction.Tables[0].Rows[0]["TransactionID"]); //int DistributorID = Convert.ToInt32(Session["DistributorID"]); int loginID = 1; string RechargeStatus = "27"; string @RechargeVia = "29"; int TransactionStatusID = 27; SendMail(EmailID, (simNumber + " Recharge successful!"), PinNumber, simNumber, "", NetworkID); int s1 = svc.UpdateAccountBalanceAfterRecharge(Convert.ToInt32(NetworkID), Convert.ToInt32(hddnTariffID.Value), Convert.ToString(simNumber), Convert.ToDecimal(TotalAmount), DistributorID, Convert.ToString(ZIPCode), RechargeStatus, RechargeVia, Request, ss2, loginID, 9, "Cash", TransactionID, 1, "Subscriber Recharge successfully", TransactionStatusID, PinNumber, State, TxnID, Tax, Convert.ToString(RechargeAmount), InvoiceNo, "Subscriber", Regulatery.ToString()); // MakeReceipt(strResponse); Log2("Recharge Transaction Success", "Reason"); Log2(Request, "Request"); Log2(ResponseCode, "Response"); Log2(ResponseMessage, "ResponseMessage"); Log2(ss, "Detail"); Log2("", "split"); lblMessage.Text = "Mobile Number " + simNumber + " Recharge successfully , Pin Number " + PinNumber; ws.Logout("01", "A&HPrepaid", "95222", "1"); string redirecturl = ""; redirecturl = simNumber + "," + RechargeAmount + "," + TotalAmount + "," + Network + "," + TxnID + "," + ResponseMessage; Response.Redirect("~/RechargePrint.aspx?RechrgeSuccess=" + redirecturl); return; } } else { string TransactionID = Convert.ToString(0); //int DistributorID = Convert.ToInt32(Session["DistributorID"]); int loginID = 1; string RechargeStatus = "28"; string RechargeVia = "29"; int TransactionStatusID = 28; int s1 = svc.UpdateAccountBalanceAfterRecharge(Convert.ToInt32(NetworkID), Convert.ToInt32(hddnTariffID.Value), Convert.ToString(simNumber), Convert.ToDecimal(TotalAmount), DistributorID, Convert.ToString(""), RechargeStatus, RechargeVia, Request, ss2, loginID, 9, "Cash", TransactionID, 1, "Subscriber Recharge Fail", TransactionStatusID, PinNumber, State, TxnID, Tax, Convert.ToString(RechargeAmount), InvoiceNo, "Subscriber", Regulatery.ToString()); Log2("Recharge Transaction Fail", "Reason"); Log2(Request, "Request"); Log2(ResponseCode, "Response"); Log2(ResponseMessage, "ResponseMessage"); Log2("", "split"); lblMessage.Text = ResponseMessage; SendFailureMailRecharge(EmailID, (simNumber + " Recharge Failed!"), simNumber, Convert.ToInt32(NetworkID), TariffCode, RechargeAmount, "", ""); ShowPopUpMsg(ResponseMessage); ScriptManager.RegisterStartupScript(this, GetType(), "", "JScriptConfirmationFail();", true); return; } } else { Log2("NO Record from API PinDistSale", "PinDistSale"); Log2(Request, "Request"); Log2(simNumber, "SimNumber"); Log2(TotalAmount, "AmountPay"); Log2(hddnTariffID.Value, "TariffCode"); Log2(State, "State-City"); Log2(ZIPCode, "Zip"); Log2(RechargeAmount, "RechargeAmount"); Log2("", "split"); ScriptManager.RegisterStartupScript(this, GetType(), "", "JScriptConfirmationFail();", true); } } else { Log2("NO Record from API PinDistSale", "PinDistSale"); Log2(Request, "Request"); Log2(simNumber, "SimNumber"); Log2(TotalAmount, "AmountPay"); Log2(hddnTariffID.Value, "TariffCode"); Log2(State, "State-City"); Log2(ZIPCode, "Zip"); Log2(RechargeAmount, "RechargeAmount"); Log2("", "split"); ScriptManager.RegisterStartupScript(this, GetType(), "", "JScriptConfirmationFail();", true); } } } } else { try { string RechargeDate = Convert.ToString(dsDuplicate.Tables[0].Rows[0]["RechargeDate"]).ToString(); string amt = Convert.ToString(dsDuplicate.Tables[0].Rows[0]["Amount"]).ToString(); lblmsg.Text = "You already Recharged " + simNumber + " with Amount " + amt + " at " + RechargeDate + " Successfully. If you want to recharge it again please wait 5 min."; lblmsg.Visible = true; } catch { } Log2("Recharge Transaction Duplicate Recharge", "Duplicate Recharge"); Log2(dsDuplicate.Tables[0].Rows[0]["Msg"].ToString(), "Show Check Duplicate Message"); Log2(dsDuplicate.Tables[0].Rows[0]["IsValid"].ToString(), "IsValid"); Log2(simNumber, "SimNumber"); Log2(RechargeAmount, "AmountPay"); Log2("", "split"); ScriptManager.RegisterStartupScript(this, GetType(), "", "JScriptConfirmationFail();", true); } } } catch (Exception ex) { lblmsg.Text = ex.Message; lblmsg.Visible = true; Log2("Transaction", "CatchFail"); Log2(MobileNo, "SimNumber"); Log2(TxnID, "TxnID"); Log2(hddnTariffID.Value, "TariffCode"); Log2(State, "State-City"); Log2(ZIPCode, "Zip"); Log2(RechargeAmount, "RechargeAmount"); Log2("", "split"); ScriptManager.RegisterStartupScript(this, GetType(), "", "JScriptConfirmationFail();", true); } }
public void ColumnOrder() { string xml = "<?xml version=\"1.0\" standalone=\"yes\"?>" + "<NewDataSet>" + " <Table>" + " <Name>Miguel</Name>" + " <FirstName>de Icaza</FirstName>" + " <Income>4000</Income>" + " </Table>" + " <Table>" + " <Name>25</Name>" + " <FirstName>250</FirstName>" + " <Address>Belgium</Address>" + " <Income>5000</Income>" + "</Table>" + "</NewDataSet>"; var ds = new DataSet(); ds.ReadXml(new StringReader(xml)); Assert.Equal(1, ds.Tables.Count); Assert.Equal("Table", ds.Tables[0].TableName); Assert.Equal(4, ds.Tables[0].Columns.Count); Assert.Equal("Name", ds.Tables[0].Columns[0].ColumnName); Assert.Equal(0, ds.Tables[0].Columns[0].Ordinal); Assert.Equal("FirstName", ds.Tables[0].Columns[1].ColumnName); Assert.Equal(1, ds.Tables[0].Columns[1].Ordinal); Assert.Equal("Address", ds.Tables[0].Columns[2].ColumnName); Assert.Equal(2, ds.Tables[0].Columns[2].Ordinal); Assert.Equal("Income", ds.Tables[0].Columns[3].ColumnName); Assert.Equal(3, ds.Tables[0].Columns[3].Ordinal); }
public DataTable Select(string whereClause, string sort, string tableName, string schemaFileName) { DataTable dtReturnTable = null; DataSet dsTemp = new DataSet(); string filename = ""; //if(!appPath.ToLower().Contains("\\data")) // appPath = appPath + "\\data"; //else filename = appPath + "\\" + tableName.ToString() + ".xml"; if (System.IO.File.Exists(filename)) { if (!schemaFileName.ToLower().Contains(".xsd")) { schemaFileName = schemaFileName + ".xsd"; } try { dsTemp.ReadXml(filename); } catch (Exception ex) { } if (dsTemp.Tables.Count > 0) { applyNewSchema(dsTemp.Tables[0], filename, appPath + "\\" + schemaFileName); dsTemp = new DataSet(); dsTemp.ReadXmlSchema(appPath + "\\" + schemaFileName); try { dsTemp.ReadXml(filename); } catch (Exception ex) { } DataRow[] drFoundRows = null; if (whereClause.Trim().Length > 0 && whereClause.Trim() != "*") { drFoundRows = dsTemp.Tables[0].Select(whereClause, sort); } else if (dsTemp.Tables.Count > 0) { drFoundRows = dsTemp.Tables[0].Select("", sort); } if (drFoundRows != null && drFoundRows.Length > 0) { dtReturnTable = dsTemp.Tables[0].Clone(); for (int x = 0; x < drFoundRows.Length; x++) { dtReturnTable.Rows.Add(drFoundRows[x].ItemArray); } } } } else { throw new Exception("Didn't find xml file " + filename); } return(dtReturnTable); }
public void TestSameColumnName() { string xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><resource resource_Id_0=\"parent\">" + "<resource resource_Id_0=\"child\" /></resource>"; var ds = new DataSet(); ds.ReadXml(new StringReader(xml)); AssertReadXml(ds, "SameColumnName", xml, XmlReadMode.Auto, XmlReadMode.IgnoreSchema, "NewDataSet", 1); }
public int Insert(string valuesToInsert, string tableFileName, string schemaFileName) { int newRowID = 0; int counter = 0; try { DataTable dtReturnTable = new DataTable(tableFileName.Replace("\\", ".")); string fullTableFileName = appPath + "\\" + tableFileName; string fullSchemaFileName = appPath + "\\" + schemaFileName; if (!fullTableFileName.ToLower().Contains(".xml")) { fullTableFileName += ".xml"; } if (!fullSchemaFileName.ToLower().Contains(".xsd")) { fullSchemaFileName += ".xsd"; } checkTableFile(fullTableFileName); DataSet dsTemp = new DataSet(); dsTemp.ReadXmlSchema(fullSchemaFileName); try { dsTemp.ReadXml(fullTableFileName); } catch (Exception ex) { Common.WriteToFile(ex); } dsTemp.Tables[0].Columns[0].AutoIncrement = true; dsTemp.Tables[0].Columns[0].AutoIncrementSeed = 1; dsTemp.Tables[0].Columns[0].AutoIncrementStep = 1; string[] tempValues = valuesToInsert.Split(new string[] { ") values(" }, StringSplitOptions.None); tempValues[0] = tempValues[0].Substring(1); tempValues[1] = tempValues[1].Substring(0, tempValues[1].Length - (tempValues[1].Length - tempValues[1].LastIndexOf(')'))); string[] columns = tempValues[0].Split(new string[] { "|,|" }, StringSplitOptions.None); string[] values = tempValues[1].Split(new string[] { "|,|" }, StringSplitOptions.None); DataRow drNewRow = dsTemp.Tables[0].NewRow(); foreach (string column in columns) { //if ((column.ToLower().Trim() != "id" || values[counter].ToString().Trim().Length > 0) && values[counter].ToString().Trim() != "999999") // drNewRow[column] = values[counter]; if (tableFileName.Contains("Transactions_") || (column.ToLower().Trim() != "id" && (values[counter].ToString().Trim().Length > 0) && values[counter].ToString().Trim() != "999999")) { drNewRow[column] = values[counter]; } counter++; } drNewRow["dateCreated"] = DateTime.Now; newRowID = int.Parse(drNewRow[0].ToString()); dsTemp.Tables[0].Rows.Add(drNewRow); dsTemp.Tables[0].WriteXml(fullTableFileName); } catch (Exception ex) { Common.WriteToFile(ex); newRowID = 0; } return(newRowID); }
public void ReadWriteXml2() { string xml = "<FullTextResponse><Domains><AvailResponse info='y' name='novell-ximian-group' /><AvailResponse info='n' name='ximian' /></Domains></FullTextResponse>"; var ds = new DataSet(); ds.ReadXml(new StringReader(xml)); AssertDataSet("ds", ds, "FullTextResponse", 2, 1); DataTable dt = ds.Tables[0]; AssertDataTable("dt1", dt, "Domains", 1, 1, 0, 1, 1, 1); dt = ds.Tables[1]; AssertDataTable("dt2", dt, "AvailResponse", 3, 2, 1, 0, 1, 0); StringWriter sw = new StringWriter(); XmlTextWriter xtw = new XmlTextWriter(sw); xtw.QuoteChar = '\''; ds.WriteXml(xtw); Assert.Equal(xml, sw.ToString()); }
/// <summary> /// 从上传的试题包xml中导入试题到数据库 /// </summary> /// <returns></returns> public static string XmltoQuiz(FileUpload fud) { string msg = ""; if (Uploadxml(fud)) { string xmlFile = QuizStorage() + "Quiz.xml"; if (File.Exists(xmlFile)) { DataSet ds = new DataSet(); ds.ReadXml(xmlFile); DataTable dt = ds.Tables["Quiz"]; if (dt != null) { int count = dt.Rows.Count; if (count > 0) { for (int i = 0; i < count; i++) { LearnSite.Model.Quiz model = new LearnSite.Model.Quiz(); if (dt.Rows[i]["Qid"].ToString() != "") { model.Qid = int.Parse(dt.Rows[i]["Qid"].ToString()); } if (dt.Rows[i]["Qtype"].ToString() != "") { model.Qtype = int.Parse(dt.Rows[i]["Qtype"].ToString()); } model.Question = dt.Rows[i]["Question"].ToString(); model.Qanswer = dt.Rows[i]["Qanswer"].ToString(); model.Qanalyze = dt.Rows[i]["Qanalyze"].ToString(); if (dt.Rows[i]["Qscore"].ToString() != "") { model.Qscore = int.Parse(dt.Rows[i]["Qscore"].ToString()); } model.Qclass = dt.Rows[i]["Qclass"].ToString(); if (dt.Rows[i]["Qselect"].ToString() != "") { if ((dt.Rows[i]["Qselect"].ToString() == "1") || (dt.Rows[i]["Qselect"].ToString().ToLower() == "true")) { model.Qselect = true; } else { model.Qselect = false; } } LearnSite.BLL.Quiz bll = new LearnSite.BLL.Quiz(); bll.Add(model); } msg = "成功导入" + count.ToString() + "条试题!"; File.Delete(xmlFile);//删除上传文件 ds.Dispose(); } else { msg = "试题包为空!"; } } else { msg = "试题包不正确!"; } } else { msg = "试题包不存在!"; } } else { msg = "试题包格式不正确!"; } return(msg); }
public void WriteXmlModeSchema1() { string SerializedDataTable = @"<rdData> <MyDataTable CustomerID='VINET' CompanyName='Vins et alcools Chevalier' ContactName='Paul Henriot' /> </rdData>"; string expected = @"<rdData> <xs:schema id=""rdData"" xmlns="""" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata""> <xs:element name=""rdData"" msdata:IsDataSet=""true"" " + @"msdata:Locale=""en-US"">" + @" <xs:complexType> <xs:choice minOccurs=""0"" maxOccurs=""unbounded""> <xs:element name=""MyDataTable""> <xs:complexType> <xs:attribute name=""CustomerID"" type=""xs:string"" /> <xs:attribute name=""CompanyName"" type=""xs:string"" /> <xs:attribute name=""ContactName"" type=""xs:string"" /> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> <MyDataTable CustomerID=""VINET"" CompanyName=""Vins et alcools Chevalier"" ContactName=""Paul Henriot"" /> </rdData>"; DataSet set; set = new DataSet(); set.ReadXml(new StringReader(SerializedDataTable)); StringWriter w = new StringWriter(); set.WriteXml(w, XmlWriteMode.WriteSchema); string result = w.ToString(); Assert.Equal(expected.Replace("\r", ""), result.Replace("\r", "")); }
private void GetReportList() { try { LoginBO(); string reportFolderCUID = GetReportFolderCUID(); string folderId = GetIDfromCUID(reportFolderCUID); //WUIN-632 change: as it can list only 50 documents info max at a time, need a logic to increment the offset and limt values by 50 each time till all the documents are fetched //and get the one present in the folder int offset = 0; DataSet dsBOReports; DataTable dtBOReports; DataTable dtBOReportsFolderLevel; DataTable dtBOReportsInFolder = new DataTable(); while (true) { string InfoStoreURI = baseURL + "raylight/v1/documents?offset=" + offset + "&limit=50"; HttpWebRequest myWebRequestParam = (HttpWebRequest)WebRequest.Create(InfoStoreURI); myWebRequestParam.ContentType = "application/xml"; myWebRequestParam.Headers.Add("X-SAP-LogonToken", rwsLogonToken); myWebRequestParam.Timeout = webReqTimeout; myWebRequestParam.Method = "GET"; WebResponse myWebResponseParam = myWebRequestParam.GetResponse(); StreamReader srParam = new StreamReader(myWebResponseParam.GetResponseStream()); string outputParam = srParam.ReadToEnd(); XmlDocument docParam = new XmlDocument(); docParam.LoadXml(outputParam); dsBOReports = new DataSet(); dsBOReports.ReadXml(new XmlTextReader(new StringReader(outputParam))); dtBOReports = dsBOReports.Tables[0]; DataRow[] drBOReportsFolderLevel = dtBOReports.Select("folderId='" + folderId + "'"); if (drBOReportsFolderLevel.Count() > 0) { dtBOReportsFolderLevel = dtBOReports.Select("folderId='" + folderId + "'").CopyToDataTable(); } else { dtBOReportsFolderLevel = new DataTable(); } //add the reports in folder to the final list to be displayed on screen if (offset == 0) { //clone only for the first time dtBOReportsInFolder = dtBOReportsFolderLevel.Clone(); } foreach (DataRow dr in dtBOReportsFolderLevel.Rows) { dtBOReportsInFolder.ImportRow(dr); } if (dtBOReports.Rows.Count < 50) { break; } else { //Exception handling if this is the end of document list and there are no other documents //check if there are other documents or this is the last one in the list //this is needed as if this is the end of document list and if tried to query from next offset value, exception is thrown //need to handle this exception try { string InfoStoreURIExp = baseURL + "raylight/v1/documents?offset=" + (offset + 50) + "&limit=50"; HttpWebRequest myWebRequestParamExp = (HttpWebRequest)WebRequest.Create(InfoStoreURIExp); myWebRequestParamExp.ContentType = "application/xml"; myWebRequestParamExp.Headers.Add("X-SAP-LogonToken", rwsLogonToken); myWebRequestParamExp.Timeout = webReqTimeout; myWebRequestParamExp.Method = "GET"; WebResponse myWebResponseParamExp = myWebRequestParamExp.GetResponse(); } catch (Exception ex) { break; } } //increment offset value to next possible value i.e is +50 offset = offset + 50; } if (dtBOReportsInFolder.Rows.Count > 0) { Session["BOReportsData"] = dtBOReportsInFolder; gvBOReports.DataSource = dtBOReportsInFolder; gvBOReports.DataBind(); } else { DataTable dtEmpty = new DataTable(); gvBOReports.DataSource = dtEmpty; gvBOReports.EmptyDataText = "No reports available in BO"; gvBOReports.DataBind(); } } catch (Exception ex) { ExceptionHandler("Error in loading report list", ex.Message); } finally { LogOffBO(); } }
public void ReadDiff() { DataSet dsTest = new DataSet("MonoTouchTest"); var dt = new DataTable("123"); dt.Columns.Add(new DataColumn("Value1")); dt.Columns.Add(new DataColumn("Value2")); dsTest.Tables.Add(dt); dsTest.ReadXml(new StringReader(@" <diffgr:diffgram xmlns:msdata='urn:schemas-microsoft-com:xml-msdata' xmlns:diffgr='urn:schemas-microsoft-com:xml-diffgram-v1'> <MonoTouchTest> <_x0031_23 diffgr:id='1231' msdata:rowOrder='0'> <Value1>Row1Value1</Value1> <Value2>Row1Value2</Value2> </_x0031_23> </MonoTouchTest> </diffgr:diffgram> ")); Assert.Equal("123", dsTest.Tables[0].TableName); Assert.Equal(1, dsTest.Tables[0].Rows.Count); }
private void LoadDataSetFromXml(Stream XmlStream) { _metaDataCollectionsDataSet = new DataSet(); _metaDataCollectionsDataSet.Locale = System.Globalization.CultureInfo.InvariantCulture; _metaDataCollectionsDataSet.ReadXml(XmlStream); }
public void ReadWriteXmlDiffGram() { var ds = new DataSet(); // It is not a diffgram, so no data loading should be done. ds.ReadXml(new StringReader(DataProvider.region), XmlReadMode.DiffGram); TextWriter writer = new StringWriter(); ds.WriteXml(writer); string TextString = writer.ToString(); Assert.Equal("<NewDataSet />", TextString); ds.WriteXml(writer, XmlWriteMode.DiffGram); TextString = writer.ToString(); Assert.Equal("<NewDataSet /><diffgr:diffgram xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\" xmlns:diffgr=\"urn:schemas-microsoft-com:xml-diffgram-v1\" />", TextString); ds = new DataSet(); ds.ReadXml(new StringReader(DataProvider.region)); DataTable table = ds.Tables["Region"]; table.Rows[0][0] = "64"; ds.ReadXml(new StringReader(DataProvider.region), XmlReadMode.DiffGram); ds.WriteXml(writer, XmlWriteMode.DiffGram); TextString = writer.ToString(); string substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal("<NewDataSet /><diffgr:diffgram xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\" xmlns:diffgr=\"urn:schemas-microsoft-com:xml-diffgram-v1\" /><diffgr:diffgram xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\" xmlns:diffgr=\"urn:schemas-microsoft-com:xml-diffgram-v1\">", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" <Root>", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" <Region diffgr:id=\"Region1\" msdata:rowOrder=\"0\" diffgr:hasChanges=\"inserted\">", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" <RegionID>64</RegionID>", substring); // not '\n' but literal '\n' substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" <RegionDescription>Eastern", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" </RegionDescription>", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" </Region>", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" <Region diffgr:id=\"Region2\" msdata:rowOrder=\"1\" diffgr:hasChanges=\"inserted\">", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" <RegionID>2</RegionID>", substring); // not '\n' but literal '\n' substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" <RegionDescription>Western", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" </RegionDescription>", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" </Region>", substring); substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' })); TextString = TextString.Substring(TextString.IndexOf('\n') + 1); Assert.Equal(" </Root>", substring); Assert.Equal("</diffgr:diffgram>", TextString); }
private void rptBbkiemke_Load(object sender, System.EventArgs e) { user = ttb.user; i_dongiale = ttb.d_dongia_le(i_nhom); if (bnhom) { label14.Text = "Nhóm :"; } kho.DisplayMember = "TEN"; kho.ValueMember = "ID"; sql = "select * from " + user + ".ttb_dmkho where nhom=" + i_nhom; if (s_kho != "") { sql += " and id in (" + s_kho.Substring(0, s_kho.Length - 1) + ")"; } sql += " order by stt"; kho.DataSource = ttb.get_data(sql).Tables[0]; // //Load_nguon nguon.DisplayMember = "TEN"; nguon.ValueMember = "ID"; sql = "select * from " + user + ".ttb_dmnguon where nhom=" + i_nhom; sql += " order by stt"; nguon.DataSource = ttb.get_data(sql).Tables[0]; nguon.SelectedIndex = -1; // if (!bnhom) { bln_noingoai = ttb.bNoiNgoai_Hang(i_nhom) || ttb.bNoiNgoai_Nuoc(i_nhom); } if (bln_noingoai) { if (ttb.bNoiNgoai_Hang(i_nhom)) { sql = "select a.*, b.stt, b.ten as tennhom, e.loai as idnn, f.ten as noingoai,e.ten as tenhang from " + user + ".ttb_dmbd a, " + user + ".ttb_dmnhom b, " + user + ".ttb_dmhang e, " + user + ".ttb_nhomhang f"; sql += " where a.manhom=b.id and a.mahang=e.id and e.loai=f.id and a.nhom=" + i_nhom + " order by a.id"; } else { sql = "select a.*, b.stt, b.ten as tennhom, e.loai as idnn, f.ten as noingoai,e.ten as tenhang from " + user + ".ttb_dmbd a, " + user + ".ttb_dmnhom b, " + user + ".ttb_dmnuoc e, " + user + ".ttb_nhomnuoc f"; sql += " where a.manhom=b.id and a.manuoc=e.id and e.loai=f.id and a.nhom=" + i_nhom + " order by a.id"; } } else { sql = "select a.*, b.stt, b.ten as tennhom, a.maloai as idnn, f.ten as noingoai from " + user + ".ttb_dmbd a, " + user + ".ttb_dmnhom b, " + user + ".ttb_dmhang e, " + user + ".ttb_dmloai f"; sql += " where a.manhom=b.id and a.mahang=e.id and a.maloai=f.id and a.nhom=" + i_nhom + " order by a.id"; } dt = ttb.get_data(sql).Tables[0]; // dtnhom = ttb.get_data("select * from " + user + ".ttb_dmnhom where nhom=" + i_nhom + " order by id").Tables[0]; ds.ReadXml("..\\..\\..\\xml\\ttb_Bbkiemke.xml"); dsrpt.ReadXml("..\\..\\..\\xml\\ttb_Bbkiemke.xml"); ttb.ins_thongso(i_nhom, 601, 616); foreach (DataRow r in ttb.get_data("select * from " + user + ".ttb_thongso where id between 601 and 616 and nhom=" + i_nhom).Tables[0].Rows) { switch (int.Parse(r["id"].ToString())) { case 601: c1.Text = r["ten"].ToString().Trim(); break; case 602: c2.Text = r["ten"].ToString().Trim(); break; case 603: c3.Text = r["ten"].ToString().Trim(); break; case 604: c4.Text = r["ten"].ToString().Trim(); break; case 605: c5.Text = r["ten"].ToString().Trim(); break; case 606: c6.Text = r["ten"].ToString().Trim(); break; case 607: c7.Text = r["ten"].ToString().Trim(); break; case 608: c8.Text = r["ten"].ToString().Trim(); break; case 609: c11.Text = r["ten"].ToString().Trim(); break; case 610: c12.Text = r["ten"].ToString().Trim(); break; case 611: c13.Text = r["ten"].ToString().Trim(); break; case 612: c14.Text = r["ten"].ToString().Trim(); break; case 613: c15.Text = r["ten"].ToString().Trim(); break; case 614: c16.Text = r["ten"].ToString().Trim(); break; case 615: c17.Text = r["ten"].ToString().Trim(); break; case 616: c18.Text = r["ten"].ToString().Trim(); break; } } noingoai.DisplayMember = "TEN"; noingoai.ValueMember = "ID"; if (bln_noingoai) { if (ttb.bNoiNgoai_Hang(i_nhom)) { noingoai.DataSource = ttb.get_data("select * from " + user + ".ttb_nhomhang where nhom=" + i_nhom + " order by stt").Tables[0]; } else { noingoai.DataSource = ttb.get_data("select * from " + user + ".ttb_nhomnuoc where nhom=" + i_nhom + " order by stt").Tables[0]; } } else if (bnhom) { noingoai.DataSource = ttb.get_data("select * from " + user + ".ttb_dmnhom where nhom=" + i_nhom + " order by stt").Tables[0]; } else { noingoai.DataSource = ttb.get_data("select * from " + user + ".ttb_dmloai where nhom=" + i_nhom + " order by stt").Tables[0]; } noingoai.SelectedIndex = -1; }
public void WriteXmlToStream() { string xml = "<set><table1><col1>sample text</col1><col2/></table1><table2 attr='value'><col3>sample text 2</col3></table2></set>"; var ds = new DataSet(); ds.ReadXml(new StringReader(xml)); MemoryStream ms = new MemoryStream(); ds.WriteXml(ms); MemoryStream ms2 = new MemoryStream(ms.ToArray()); StreamReader sr = new StreamReader(ms2, Encoding.UTF8); string result = @"<set> <table1> <col1>sample text</col1> <col2 /> </table1> <table2 attr=""value""> <col3>sample text 2</col3> </table2> </set>"; Assert.Equal(sr.ReadToEnd().Replace("\r\n", "\n"), result.Replace("\r\n", "\n")); }
//등록 자료 생성 public static string ConvertRegister(string path, string xmlZipcodeAreaPath, string xmlZipcodePath) { System.Text.Encoding _encoding = System.Text.Encoding.GetEncoding(strEncoding); //기본 인코딩 //FileInfo _fi = null; StreamReader _sr = null; //파일 읽기 스트림 StreamWriter _swError = null; StreamWriter _sw = null; byte[] _byteAry = null; string _strBankID = "", _strBankName = "", _strZipcode = "", _strAreaGroup = "", strBank_code = "", strIssue_code = ""; //2013.06.26 태희철 _strValue : 영업점코드 : 2 = 영업점, 3 = 제3영업점, 4 = 강제영업점 string _strReturn = "", _strLine = "", _strValue = null; DataTable _dtable = null; DataSet _dsetZipcodeArea = null; //DataRow _dr = null; DataRow[] _drs = null; int _iCount = 0; string _strDong = null, _strVIP = null, _strSC = null, _strYe = null, _strChk_add = "", strBank_Chk = "", strSang_chk = ""; try { _dtable = new DataTable("CONVERT"); _dtable.Columns.Add("card_bank_ID"); _dtable.Columns.Add("card_zipcode"); _dtable.Columns.Add("data"); _dsetZipcodeArea = new DataSet(); _dsetZipcodeArea.ReadXml(xmlZipcodeAreaPath); //파일 읽기 Stream과 오류시 저장할 쓰기 Stream 생성 _sr = new StreamReader(path, _encoding); _swError = new StreamWriter(path + ".Error", false, _encoding); while ((_strLine = _sr.ReadLine()) != null) { _byteAry = _encoding.GetBytes(_strLine); _strBankID = _encoding.GetString(_byteAry, 8, 2); _strZipcode = _encoding.GetString(_byteAry, 139, 6); //2011-10-14 태희철 수정 //영업점코드 : 2 = 영업점, 3 = 제3영업점, 4 = 강제영업점 _strValue = _encoding.GetString(_byteAry, 145, 1); _strDong = _encoding.GetString(_byteAry, 247, 1); //2012-05-15 태희철 추가 _strVIP = _encoding.GetString(_byteAry, 296, 1); //2012-05-15 태희철 추가 _strSC = _encoding.GetString(_byteAry, 297, 2); //2012-06-04 태희철 추가 Ye치과 구분 _strYe = _encoding.GetString(_byteAry, 245, 1); //우리은행 통신사별지 2017.08.14 //_strChk_add = _encoding.GetString(_byteAry, 1765, 1); _strChk_add = _encoding.GetString(_byteAry, 2765, 1); strBank_Chk = _encoding.GetString(_byteAry, 250, 3); strSang_chk = _encoding.GetString(_byteAry, 542, 6); //상품제휴코드 _drs = _dsetZipcodeArea.Tables[0].Select("zipcode=" + _strZipcode); _iCount++; // [1] 동의서 1~8은 동의서 | 299,1 의 1 or 2 는 긴급은 따로 분류 // 2012-05-22 태희철 수정 BLISS, 인피니트 카드 추가 //2013.04.08 태희철 수정 인피니트 업무종료 8번 코드도 일반으로 취급 //if (_strVIP == "8") //{ // _sw = new StreamWriter("INP_3000", true, _encoding); //} //2013.04.02 태희철 추가[S] 비씨카드 다이아/시그니쳐 //if (_byteAry.Length != 1739) //if (_byteAry.Length != 1741) //if (_byteAry.Length != 1765) // if (_byteAry.Length != 2766) { _sw = new StreamWriter(path + "총byte오류", true, _encoding); _sw.WriteLine(_strLine); } //대구영업점 2017.11.01 else if ((_strValue == "2" || _strValue == "3" || _strValue == "4") && (_strDong == "1" || _strDong == "2" || _strDong == "3" || _strDong == "4" || _strDong == "5" || _strDong == "6" || _strDong == "7" || _strDong == "8" || _strDong == "9") && strBank_Chk == "031") { _sw = new StreamWriter(path + "be10000_대구영업점_동의서출력", true, _encoding); _sw.WriteLine(_strLine + "0B" + "0013103"); } else if (_strVIP == "6") { if (_strValue == "2" || _strValue == "3" || _strValue == "4") { if (_encoding.GetString(_byteAry, 245, 1) == "3") { //_sw = new StreamWriter(path + "bc14000_Dia_본인", true, _encoding); //_sw.WriteLine(_strLine + "0B" + "0011113"); _sw = new StreamWriter(path + "bc44000_Dia_본인", true, _encoding); _sw.WriteLine(_strLine + "0B" + "0013208"); } else { //_sw = new StreamWriter(path + "bc6000_Dia", true, _encoding); //_sw.WriteLine(_strLine + "0B" + "0011106"); _sw = new StreamWriter(path + "bc43000_Dia", true, _encoding); _sw.WriteLine(_strLine + "0B" + "0013207"); } } //다이아/시그니처 동의서도 일반동의서와 동일하게 구분 else if (_strDong == "1" || _strDong == "2" || _strDong == "3" || _strDong == "4" || _strDong == "5" || _strDong == "6" || _strDong == "7" || _strDong == "8" || _strDong == "9") { switch (Convert_Bank_Code(strBank_Chk)) { case "국민": _sw = new StreamWriter(path + "bcd2000_국민", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012102"); break; case "농협": _sw = new StreamWriter(path + "bcd8000_농협", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012107"); break; case "우리": if (_strDong == "1") { _sw = new StreamWriter(path + "bcd33000_우리(롯데멤버스)", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012130"); } else if (_strDong == "4") { _sw = new StreamWriter(path + "bcd31000_우리국기원", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012128"); } else { if (_strChk_add == "1" || _strChk_add == "2" || _strChk_add == "3") { _sw = new StreamWriter(path + "bcd32000_우리(통신)", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012129"); } else { _sw = new StreamWriter(path + "bcd1000_우리", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012101"); } //_sw = new StreamWriter(path + "bcd1000_우리", true, _encoding); //_sw.WriteLine(_strLine + "0A" + "0012101"); } break; //case "하나": // if (strSang_chk == "251082" || strSang_chk == "251095" || strSang_chk == "251105" || // strSang_chk == "251121" || strSang_chk == "251134" || strSang_chk == "251147" // ) // { // _sw = new StreamWriter(path + "bcd36000_하나(우체국별지)", true, _encoding); // _sw.WriteLine(_strLine + "0A" + "0012131"); // } // else // { // _sw = new StreamWriter(path + "bcd5000_하나", true, _encoding); // _sw.WriteLine(_strLine + "0A" + "0012104"); // } // break; case "하나": _sw = new StreamWriter(path + "bcd5000_하나", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012104"); break; case "SC제일": if (_strDong == "5") { _sw = new StreamWriter(path + "bcd25000_SC(아이행복)", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012122"); } else if (_strDong == "6") { _sw = new StreamWriter(path + "bcd28000_SC(신세계)", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012125"); } else if (_strDong == "9") { _sw = new StreamWriter(path + "bcd29000_SC(이마트)", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012126"); } else { _sw = new StreamWriter(path + "bcd3000_SC", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012103"); } break; case "기업": //2014.09.26 태희철 추가 GS칼텍스 보너스 (업무개시 : 09월29일) if (_strDong == "1") { _sw = new StreamWriter(path + "bcd22000_기업칼텍스", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012119"); } else if (_strDong == "2") { _sw = new StreamWriter(path + "bcd12000_기업GS", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012109"); } else if (_strDong == "4") { _sw = new StreamWriter(path + "bcd13000_기업SK", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012110"); } else if (_strDong == "5") { _sw = new StreamWriter(path + "bcd14000_기업에코", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012111"); } else if (_strDong == "9") { _sw = new StreamWriter(path + "bcd24000_기업롯데맴버스", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012121"); } else { _sw = new StreamWriter(path + "bcd11000_기업공용", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012108"); } break; case "신한": _sw = new StreamWriter(path + "bcd15000_신한", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012112"); break; case "경남": _sw = new StreamWriter(path + "bcd7000_경남", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012106"); break; case "대구": _sw = new StreamWriter(path + "bcd6000_대구", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012105"); break; case "부산": _sw = new StreamWriter(path + "bcd16000_부산", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012113"); break; case "전북": if (_strDong == "9") { _sw = new StreamWriter(path + "bcd4000_전북", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012115"); } else { _sw = new StreamWriter(path + "오류_전북4000", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012115"); } //_sw = new StreamWriter(path + "bcd4000_전북", true, _encoding); //_sw.WriteLine(_strLine + "0A" + "0012115"); break; case "제주": _sw = new StreamWriter(path + "bcd26000_제주", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012123"); break; case "광주": _sw = new StreamWriter(path + "bcd27000_광주", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012124"); break; case "바로": _sw = new StreamWriter(path + "bcd30000_바로", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012127"); break; case "SSG": _sw = new StreamWriter(path + "bcd32000_SSG", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012130"); break; case "그외": _sw = new StreamWriter(path + "동의서_영업점코드확인", true, _encoding); _sw.WriteLine(_strLine + "0A"); break; default: _sw = new StreamWriter(path + "동의서_영업점코드확인", true, _encoding); _sw.WriteLine(_strLine + "0A"); break; } } else { if (_encoding.GetString(_byteAry, 245, 1) == "3") { _sw = new StreamWriter(path + "bc44000_Dia_본인", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0013208"); } else { _sw = new StreamWriter(path + "bc43000_Dia", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0013207"); } } } //2013.05.02 태희철 수정[S] 블리스 차수 통합 //2014.11.07 태희철 수정 블리스 동의서의 경우 기업(공용)으로 추가 else if (_strVIP == "Z") { if (_strValue == "2" || _strValue == "3" || _strValue == "4") { //2016.07.29 특송담당자 수정 요청 동의서 제외처리 if (_encoding.GetString(_byteAry, 245, 1) == "3") { _sw = new StreamWriter(path + "bc42000_BLISS_본인", true, _encoding); _sw.WriteLine(_strLine + "0B" + "0013206"); } else { //_sw = new StreamWriter(path + "bc2000_BLISS", true, _encoding); //_sw.WriteLine(_strLine + "0B" + "0011102"); _sw = new StreamWriter(path + "bc41000_BLISS", true, _encoding); _sw.WriteLine(_strLine + "0B" + "0013205"); } } else { if (_strDong == "1" || _strDong == "2" || _strDong == "3" || _strDong == "4" || _strDong == "5" || _strDong == "6" || _strDong == "7" || _strDong == "8" || _strDong == "9") { _sw = new StreamWriter(path + "bcd11000_기업공용", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012108"); } else { if (_encoding.GetString(_byteAry, 245, 1) == "3") { _sw = new StreamWriter(path + "bc42000_BLISS_본인", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0013206"); } else { _sw = new StreamWriter(path + "bc41000_BLISS", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0013205"); } } } } else if (_strValue == "2" || _strValue == "3" || _strValue == "4") { _sw = new StreamWriter(path + "be6000", true, _encoding); _sw.WriteLine(_strLine + "0B" + "0013101"); //if (_strVIP == "Z") // _sw = new StreamWriter("BLISS2500", true, _encoding); //else // _sw = new StreamWriter("be6000", true, _encoding); } //BC_YE치과카드 분류 추가 2012-06-04 태희철 추가 else if (_strYe == "2") { _sw = new StreamWriter(path + "BC_YE_1000", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0013401"); } // 2012-05-15 태희철 수정 SC은행의 경우 bwe7000차에 합류 else if ((_encoding.GetString(_byteAry, 299, 1) != "1" || _encoding.GetString(_byteAry, 299, 1) != "2") && ((_strDong == "1" || _strDong == "2" || _strDong == "3" || _strDong == "4" || _strDong == "5" || _strDong == "6" || _strDong == "7" || _strDong == "8" || _strDong == "9"))) { switch (Convert_Bank_Code(strBank_Chk)) { case "국민": _sw = new StreamWriter(path + "bcd2000_국민", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012102"); break; case "농협": _sw = new StreamWriter(path + "bcd8000_농협", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012107"); break; case "우리": if (_strDong == "1") { _sw = new StreamWriter(path + "bcd33000_우리(롯데멤버스)", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012130"); } else if (_strDong == "4") { _sw = new StreamWriter(path + "bcd31000_우리국기원", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012128"); } else { //2017.08.14 if (_strChk_add == "1" || _strChk_add == "2" || _strChk_add == "3") { _sw = new StreamWriter(path + "bcd32000_우리(통신)", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012129"); } else { _sw = new StreamWriter(path + "bcd1000_우리", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012101"); } //_sw = new StreamWriter(path + "bcd1000_우리", true, _encoding); //_sw.WriteLine(_strLine + "0A" + "0012101"); } break; //case "하나": // if (strSang_chk == "251082" || strSang_chk == "251095" || strSang_chk == "251105" || // strSang_chk == "251121" || strSang_chk == "251134" || strSang_chk == "251147" // ) // { // _sw = new StreamWriter(path + "bcd36000_하나(우체국별지)", true, _encoding); // _sw.WriteLine(_strLine + "0A" + "0012131"); // } // else // { // _sw = new StreamWriter(path + "bcd5000_하나", true, _encoding); // _sw.WriteLine(_strLine + "0A" + "0012104"); // } // break; case "하나": _sw = new StreamWriter(path + "bcd5000_하나", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012104"); break; case "SC제일": if (_strDong == "5") { _sw = new StreamWriter(path + "bcd25000_SC(아이행복)", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012122"); } else if (_strDong == "6") { _sw = new StreamWriter(path + "bcd28000_SC(신세계)", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012125"); } else if (_strDong == "9") { _sw = new StreamWriter(path + "bcd29000_SC(이마트)", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012126"); } else { _sw = new StreamWriter(path + "bcd3000_SC", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012103"); } break; case "기업": if (_strDong == "1") { _sw = new StreamWriter(path + "bcd22000_기업칼텍스", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012119"); } else if (_strDong == "2") { _sw = new StreamWriter(path + "bcd12000_기업GS", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012109"); } else if (_strDong == "4") { _sw = new StreamWriter(path + "bcd13000_기업SK", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012110"); } else if (_strDong == "5") { _sw = new StreamWriter(path + "bcd14000_기업에코", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012111"); } else if (_strDong == "9") { _sw = new StreamWriter(path + "bcd24000_기업롯데맴버스", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012121"); } else { _sw = new StreamWriter(path + "bcd11000_기업공용", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012108"); } break; case "신한": _sw = new StreamWriter(path + "bcd15000_신한", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012112"); break; case "경남": _sw = new StreamWriter(path + "bcd7000_경남", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012106"); break; case "대구": _sw = new StreamWriter(path + "bcd6000_대구", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012105"); break; case "부산": _sw = new StreamWriter(path + "bcd16000_부산", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012113"); break; case "전북": //2014.09.26 태희철 추가 GS칼텍스 보너스 (업무개시 : 09월29일) if (_strDong == "9") { _sw = new StreamWriter(path + "bcd4000_전북", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012115"); } else { _sw = new StreamWriter(path + "오류_전북4000", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012115"); } //_sw = new StreamWriter(path + "bcd4000_전북", true, _encoding); //_sw.WriteLine(_strLine + "0A" + "0012115"); break; case "제주": _sw = new StreamWriter(path + "bcd26000_제주", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012123"); break; case "광주": _sw = new StreamWriter(path + "bcd27000_광주", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012124"); break; case "바로": _sw = new StreamWriter(path + "bcd30000_바로", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012127"); break; case "SSG": _sw = new StreamWriter(path + "bcd32000_SSG", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0012130"); break; case "그외": _sw = new StreamWriter(path + "동의서_영업점코드확인", true, _encoding); _sw.WriteLine(_strLine + "0A"); //_sw = GetStreamWriter(_strBankID + ".txt"); break; default: _sw = new StreamWriter(path + "동의서_영업점코드확인", true, _encoding); _sw.WriteLine(_strLine + "0A"); break; } } else if (strBank_Chk.Equals("023") && _strSC == "01") { if (_encoding.GetString(_byteAry, 245, 1) == "3") { _sw = new StreamWriter(path + "bwe9000_본인", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0013204"); } else { _sw = new StreamWriter(path + "bwe7000", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0013201"); } } else { if (_encoding.GetString(_byteAry, 299, 1) == "2") { //2012-01-03 태희철 수정 5000차를 7000차와 통합 //2012-01-16 인수분부터 적용으로 변경 //_sw = new StreamWriter("bwe5000", true, _encoding); if (_encoding.GetString(_byteAry, 245, 1) == "3") { _sw = new StreamWriter(path + "bwe9000_본인", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0013204"); } else { _sw = new StreamWriter(path + "bwe7000", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0013201"); } } //2017.07.18 _encoding.GetString(_byteAry, 299, 1) == "3" /사용안하지만 라운지카드 코드로 확인 //else if (_encoding.GetString(_byteAry, 299, 1) == "3") //{ // _sw = new StreamWriter(path + "bc_오류", true, _encoding); // _sw.WriteLine(_strLine + "0A" + "0011101"); //} else if (_encoding.GetString(_byteAry, 298, 1) == "0") { _sw = new StreamWriter(path + "bc10000_농협면세유", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0011105"); } else if (_encoding.GetString(_byteAry, 298, 1) == "1") { if (_encoding.GetString(_byteAry, 244, 1) == "1") { _sw = new StreamWriter(path + "bwe19000", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0013202"); } else { if (_encoding.GetString(_byteAry, 245, 1) == "3") { _sw = new StreamWriter(path + "bwe9000_본인", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0013204"); } else { _sw = new StreamWriter(path + "bwe7000", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0013201"); } } } else if (_encoding.GetString(_byteAry, 298, 1) == "2") { if (_encoding.GetString(_byteAry, 245, 1) == "3") { _sw = new StreamWriter(path + "bbe9000_본인", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0013303"); } else { _sw = new StreamWriter(path + "bbe7500", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0013301"); } } else if (_encoding.GetString(_byteAry, 245, 1) == "1") { _sw = new StreamWriter(path + "bc500_기업세이브", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0011104"); } else if (_encoding.GetString(_byteAry, 245, 1) == "3") { _sw = new StreamWriter(path + "bc9000_일반본인", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0011109"); } else { _sw = new StreamWriter(path + "bc100_일반", true, _encoding); _sw.WriteLine(_strLine + "0A" + "0011101"); } } _sw.Close(); } _drs = _dtable.Select("", ""); for (int i = 0; i < _drs.Length; i++) { _sw.WriteLine(_strLine); } _strReturn = "성공"; } catch (Exception ex) { _strReturn = string.Format("{0}번째 우편번호 오류", _iCount); if (_swError != null) { _swError.WriteLine(ex.Message); } } finally { if (_sr != null) { _sr.Close(); } if (_sw != null) { _sw.Close(); } if (_swError != null) { _swError.Close(); } } return(_strReturn); }
public void XmlLoadTest() { var ds = new DataSet(); ds.ReadXmlSchema(new StringReader( @"<?xml version=""1.0"" standalone=""yes""?> <xs:schema id=""NewDataSet"" xmlns="""" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata""> <xs:element name=""NewDataSet"" msdata:IsDataSet=""true"" msdata:MainDataTable=""DESC"" msdata:UseCurrentLocale=""true""> <xs:complexType> <xs:choice minOccurs=""0"" maxOccurs=""unbounded""> <xs:element name=""DESC""> <xs:complexType> <xs:sequence> <xs:element name=""ColumnName"" msdata:ReadOnly=""true"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""DataType"" msdata:DataType=""System.Type, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" msdata:ReadOnly=""true"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""IsAutoIncrement"" msdata:ReadOnly=""true"" type=""xs:boolean"" minOccurs=""0"" /> <xs:element name=""AllowDBNull"" msdata:ReadOnly=""true"" type=""xs:boolean"" minOccurs=""0"" /> <xs:element name=""IsReadOnly"" msdata:ReadOnly=""true"" type=""xs:boolean"" minOccurs=""0"" /> <xs:element name=""IsKey"" msdata:ReadOnly=""true"" type=""xs:boolean"" minOccurs=""0"" /> <xs:element name=""IsUnique"" msdata:ReadOnly=""true"" type=""xs:boolean"" minOccurs=""0"" /> <xs:element name=""ColumnSize"" msdata:ReadOnly=""true"" type=""xs:int"" minOccurs=""0"" /> <xs:element name=""ColumnNumber"" msdata:ReadOnly=""true"" type=""xs:int"" minOccurs=""0"" /> <xs:element name=""Summary"" type=""xs:boolean"" minOccurs=""0"" /> <xs:element name=""Print"" type=""xs:boolean"" minOccurs=""0"" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> <xs:unique name=""Constraint1""> <xs:selector xpath="".//DESC"" /> <xs:field xpath=""ColumnName"" /> </xs:unique> </xs:element> </xs:schema>")); ds.ReadXml(new StringReader( @"<?xml version=""1.0"" standalone=""yes""?> <DocumentElement> <DESC> <ColumnName>ColumnName</ColumnName> <DataType>System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</DataType> <IsAutoIncrement>false</IsAutoIncrement> <AllowDBNull>true</AllowDBNull> <IsReadOnly>true</IsReadOnly> <IsKey>false</IsKey> <IsUnique>false</IsUnique> <ColumnSize>0</ColumnSize> </DESC> <DESC> <ColumnName>DataType</ColumnName> <DataType>System.Type, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</DataType> <IsAutoIncrement>false</IsAutoIncrement> <AllowDBNull>true</AllowDBNull> <IsReadOnly>true</IsReadOnly> <IsKey>false</IsKey> <IsUnique>false</IsUnique> <ColumnSize>0</ColumnSize> </DESC> <DESC> <ColumnName>IsAutoIncrement</ColumnName> <DataType>System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</DataType> <IsAutoIncrement>false</IsAutoIncrement> <AllowDBNull>true</AllowDBNull> <IsReadOnly>true</IsReadOnly> <IsKey>false</IsKey> <IsUnique>false</IsUnique> <ColumnSize>0</ColumnSize> </DESC> <DESC> <ColumnName>AllowDBNull</ColumnName> <DataType>System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</DataType> <IsAutoIncrement>false</IsAutoIncrement> <AllowDBNull>true</AllowDBNull> <IsReadOnly>true</IsReadOnly> <IsKey>false</IsKey> <IsUnique>false</IsUnique> <ColumnSize>0</ColumnSize> </DESC> <DESC> <ColumnName>IsReadOnly</ColumnName> <DataType>System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</DataType> <IsAutoIncrement>false</IsAutoIncrement> <AllowDBNull>true</AllowDBNull> <IsReadOnly>true</IsReadOnly> <IsKey>false</IsKey> <IsUnique>false</IsUnique> <ColumnSize>0</ColumnSize> </DESC> <DESC> <ColumnName>IsKey</ColumnName> <DataType>System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</DataType> <IsAutoIncrement>false</IsAutoIncrement> <AllowDBNull>true</AllowDBNull> <IsReadOnly>true</IsReadOnly> <IsKey>false</IsKey> <IsUnique>false</IsUnique> <ColumnSize>0</ColumnSize> </DESC> <DESC> <ColumnName>IsUnique</ColumnName> <DataType>System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</DataType> <IsAutoIncrement>false</IsAutoIncrement> <AllowDBNull>true</AllowDBNull> <IsReadOnly>true</IsReadOnly> <IsKey>false</IsKey> <IsUnique>false</IsUnique> <ColumnSize>0</ColumnSize> </DESC> <DESC> <ColumnName>ColumnSize</ColumnName> <DataType>System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</DataType> <IsAutoIncrement>false</IsAutoIncrement> <AllowDBNull>true</AllowDBNull> <IsReadOnly>true</IsReadOnly> <IsKey>false</IsKey> <IsUnique>false</IsUnique> <ColumnSize>0</ColumnSize> </DESC> <DESC> <ColumnName>ColumnNumber</ColumnName> <DataType>System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</DataType> <IsAutoIncrement>false</IsAutoIncrement> <AllowDBNull>true</AllowDBNull> <IsReadOnly>true</IsReadOnly> <IsKey>false</IsKey> <IsUnique>false</IsUnique> <ColumnSize>0</ColumnSize> </DESC> <DESC> <ColumnName>Summary</ColumnName> <DataType>System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</DataType> <IsAutoIncrement>false</IsAutoIncrement> <AllowDBNull>true</AllowDBNull> <IsReadOnly>true</IsReadOnly> <IsKey>false</IsKey> <IsUnique>false</IsUnique> <ColumnSize>0</ColumnSize> </DESC> <DESC> <ColumnName>Print</ColumnName> <DataType>System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</DataType> <IsAutoIncrement>false</IsAutoIncrement> <AllowDBNull>true</AllowDBNull> <IsReadOnly>true</IsReadOnly> <IsKey>false</IsKey> <IsUnique>false</IsUnique> <ColumnSize>0</ColumnSize> </DESC> </DocumentElement>")); }
/// <summary> /// Try to Import from selected File /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void Import_OnClick([NotNull] object sender, [NotNull] EventArgs e) { // import selected file (if it's the proper format)... if (!this.importFile.PostedFile.ContentType.StartsWith("text")) { this.PageContext.AddLoadMessage( this.GetText("ADMIN_REPLACEWORDS_IMPORT", "MSG_IMPORTED_FAILEDX").FormatWith( "Invalid upload format specified: " + this.importFile.PostedFile.ContentType)); return; } try { // import replace words... var dsReplaceWords = new DataSet(); dsReplaceWords.ReadXml(this.importFile.PostedFile.InputStream); if (dsReplaceWords.Tables["YafReplaceWords"] != null && dsReplaceWords.Tables["YafReplaceWords"].Columns["badword"] != null && dsReplaceWords.Tables["YafReplaceWords"].Columns["goodword"] != null) { int importedCount = 0; DataTable replaceWordsList = this.GetRepository <Replace_Words>().List(); // import any extensions that don't exist... foreach (DataRow row in dsReplaceWords.Tables["YafReplaceWords"].Rows.Cast <DataRow>().Where( row => replaceWordsList.Select( "badword = '{0}' AND goodword = '{1}'".FormatWith(row["badword"], row["goodword"])).Length == 0)) { // add this... this.GetRepository <Replace_Words>() .Save( replaceWordID: null, badWord: row["badword"].ToString(), goodWord: row["goodword"].ToString()); importedCount++; } this.PageContext.LoadMessage.AddSession( importedCount > 0 ? this.GetText("ADMIN_REPLACEWORDS_IMPORT", "MSG_IMPORTED").FormatWith(importedCount) : this.GetText("ADMIN_REPLACEWORDS_IMPORT", "MSG_NOTHING"), importedCount > 0 ? MessageTypes.Success : MessageTypes.Warning); YafBuildLink.Redirect(ForumPages.admin_replacewords); } else { this.PageContext.AddLoadMessage(this.GetText("ADMIN_REPLACEWORDS_IMPORT", "MSG_IMPORTED_FAILED")); } } catch (Exception x) { this.PageContext.AddLoadMessage( this.GetText("ADMIN_REPLACEWORDS_IMPORT", "MSG_IMPORTED_FAILEDX").FormatWith(x.Message)); } }
public void ContainsSchema() { var ds = new DataSet(); DataTable dt1 = new DataTable(); ds.Tables.Add(dt1); DataColumn dc1 = new DataColumn("Col1"); dt1.Columns.Add(dc1); dt1.Rows.Add(new string[] { "aaa" }); DataTable dt2 = new DataTable(); ds.Tables.Add(dt2); DataColumn dc2 = new DataColumn("Col2"); dt2.Columns.Add(dc2); dt2.Rows.Add(new string[] { "bbb" }); DataRelation rel = new DataRelation("Rel1", dc1, dc2, false); ds.Relations.Add(rel); StringWriter sw = new StringWriter(); ds.WriteXml(sw, XmlWriteMode.WriteSchema); ds = new DataSet(); ds.ReadXml(new StringReader(sw.ToString())); sw = new StringWriter(); ds.WriteXml(sw); XmlDocument doc = new XmlDocument(); doc.LoadXml(sw.ToString()); Assert.Equal(2, doc.DocumentElement.ChildNodes.Count); }
static void Main(string[] args) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); DataSet ds = new DataSet(); Console.WriteLine("XML file name with full path:"); string filepath = Console.ReadLine(); //Convert the XML into Dataset ds.ReadXml(filepath); Console.WriteLine("Start!"); try { Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application(); Workbook xlWorkBook = ExcelApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); foreach (System.Data.DataTable dt in ds.Tables) { System.Data.DataTable dtDataTable1 = dt; for (int i = 1; i > 0; i--) { Sheets xlSheets = null; Worksheet xlWorksheet = null; //Create Excel sheet xlSheets = ExcelApp.Sheets; xlWorksheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing); xlWorksheet.Name = dt.TableName; for (int j = 1; j < dtDataTable1.Columns.Count + 1; j++) { ExcelApp.Cells[i, j] = dtDataTable1.Columns[j - 1].ColumnName; //ExcelApp.Cells[1, j].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green); //ExcelApp.Cells[i, j].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.WhiteSmoke); } // for the data of the excel for (int k = 0; k < dtDataTable1.Rows.Count; k++) { for (int l = 0; l < dtDataTable1.Columns.Count; l++) { ExcelApp.Cells[k + 2, l + 1] = dtDataTable1.Rows[k].ItemArray[l].ToString(); } } ExcelApp.Columns.AutoFit(); } //((Worksheet)ExcelApp.ActiveWorkbook.Sheets[ExcelApp.ActiveWorkbook.Sheets.Count]).Delete(); Console.WriteLine(dt.TableName + " created."); } ExcelApp.Visible = true; } catch (Exception ex) { Console.WriteLine(ex.Message); } /* * foreach (DataTable dt in ds.Tables) * { * // Create an Excel object * Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); * * //Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Open(Filename: str + dt.TableName + ".xlsx"); * //Create worksheet object * Microsoft.Office.Interop.Excel.Worksheet worksheet; * worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Application.Worksheets.Add(); * * //((Microsoft.Office.Interop.Excel._Worksheet)worksheet).Activate(); * //Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.NewWindow(); * * worksheet.Name = dt.TableName; * // Column Headings * int iColumn = 0; * * foreach (DataColumn c in dt.Columns) * { * iColumn++; * excel.Cells[1, iColumn] = c.ColumnName; * } * * // Row Data * int iRow = worksheet.UsedRange.Rows.Count - 1; * * foreach (DataRow dr in dt.Rows) * { * iRow++; * * // Row's Cell Data * iColumn = 0; * foreach (DataColumn c in dt.Columns) * { * iColumn++; * excel.Cells[iRow + 1, iColumn] = dr[c.ColumnName]; * } * } * * //((Microsoft.Office.Interop.Excel._Worksheet)worksheet).Activate(); * //((Microsoft.Office.Interop.Excel._Worksheet)worksheet).SaveAs(dt.TableName); * worksheet = null; * * //Save the workbook * workbook.Save(); * * //Close the Workbook * workbook.Close(); * * // Finally Quit the Application * ((Microsoft.Office.Interop.Excel._Application)excel).Quit(); * } */ Console.WriteLine("End!"); Console.ReadLine(); }