WriteXml() public method

public WriteXml ( Stream stream ) : void
stream Stream
return void
Beispiel #1
1
        static void Main(string[] args)
        {
     // Создание Таблицы DataTable с именем "Cars"
            DataTable tablCars = new DataTable("Cars");
            // Создание столбцов
            DataColumn carsId = new DataColumn("Id", typeof(int));
            DataColumn carsName = new DataColumn("Name", typeof(string));
            DataColumn carsCountry = new DataColumn("Country", typeof(string));
            DataColumn carsPrice = new DataColumn("Price", typeof(double));
            tablCars.Columns.AddRange(new DataColumn[] { carsId, carsName, carsCountry, carsPrice });
            // Создание строки с данными 
            DataRow newRow1 = tablCars.NewRow();
            newRow1["Name"] = "BMW"; newRow1["Country"] = "Germany";
            newRow1["Price"] = "50000";
            tablCars.Rows.Add(newRow1);

            DataRow newRow2 = tablCars.NewRow();
            newRow2["Name"] = "Audi"; newRow2["Country"] = "Germany";
            newRow2["Price"] = "37500";
            tablCars.Rows.Add(newRow2);

            // Сохранить ТАБЛИЦЫ  tablCars  в виде XML
            tablCars.WriteXml("Cars.xml");
            tablCars.WriteXmlSchema("CarsSchema.xsd");
         

      // Создание Таблицы DataTable с именем "Drivers"
            DataTable tablDrivers = new DataTable("Drivers");
            // Создание столбцов
            DataColumn drId = new DataColumn("Id", typeof(int));
            DataColumn drName = new DataColumn("Name", typeof(string));
            DataColumn drAge = new DataColumn("Age", typeof(string));
            tablDrivers.Columns.AddRange(new DataColumn[] { drId, drName, drAge });
            // Создание строки с данными 
            DataRow newRow3 = tablDrivers.NewRow();
            newRow3["Name"] = "Ivan"; newRow3["Age"] = "33";
            tablDrivers.Rows.Add(newRow3);

            DataSet dataSet = new DataSet("AutoPark");
            dataSet.Tables.AddRange(new DataTable[] { tablCars, tablDrivers});


            // Сохранить DATASET  в виде XML
            dataSet.WriteXmlSchema("AutoParkSchema.xsd");
            dataSet.WriteXml("AutoPark.xml");
            
            
            // Очистить DataSet.
            dataSet.Clear();

            Console.WriteLine("XML успешно сформированы!");

            Console.ReadKey();

        }
Beispiel #2
0
 protected void btnSaveChanges_Click(object sender, EventArgs e)
 {
     using (System.Data.DataTable xmlData = Lib.Blok.GetXmlData())
     {
         foreach (GridViewRow item in dataGrid1.Rows)
         {
             switch (((CheckBox)item.Cells[0].FindControl("chkSelected")).Checked)
             {
             case true:
                 xmlData.DefaultView.RowFilter      = "";
                 xmlData.DefaultView.RowFilter      = "ID=" + BAYMYO.UI.Converts.NullToInt32(dataGrid1.DataKeys[item.RowIndex]["ID"]);
                 xmlData.DefaultView[0]["Sira"]     = BAYMYO.UI.Converts.NullToInt16(((DropDownList)item.FindControl("ddlSira")).SelectedValue);
                 xmlData.DefaultView[0]["Yer"]      = ((DropDownList)item.FindControl("ddlYer")).SelectedValue;
                 xmlData.DefaultView[0]["Dil"]      = ((DropDownList)item.FindControl("ddlDil")).SelectedValue;
                 xmlData.DefaultView[0]["TumDil"]   = ((CheckBox)item.FindControl("chkTumDil")).Checked;
                 xmlData.DefaultView[0]["TumSayfa"] = ((CheckBox)item.FindControl("chkTumSayfa")).Checked;
                 xmlData.DefaultView[0]["Aktif"]    = ((CheckBox)item.FindControl("chkAktif")).Checked;
                 break;
             }
         }
         xmlData.AcceptChanges();
         xmlData.WriteXml(Server.MapPath(Lib.Blok.XmlPath));
         infoLiteral.Text = "Tablo üzerindeki değişiklikler başarılı bir şekilde kaydedildi!";
     }
 }
 protected string GetDataTableXml(DataTable dt)
 {
     dt.TableName = "must have name for xml...";
     var writer = new StringWriter();
     dt.WriteXml(writer);
     return writer.ToString();
 }
        ///// <summary>
        ///// 序列化物件
        ///// </summary>
        ///// <typeparam name="T"></typeparam>
        ///// <param name="value"></param>
        ///// <returns></returns>
        //public string ObjectToString<T>(T value)
        //{
        //    XmlSerializer ser = new XmlSerializer(value.GetType());
        //    MemoryStream stream = new MemoryStream();
        //    ser.Serialize(stream, value);
        //    stream.Position = 0;
        //    StreamReader reader = new StreamReader(stream);
        //    string result = reader.ReadToEnd();
        //    stream.Dispose();
        //    reader.Dispose();
        //    return result;

        //}

        public string ToDataTableXmlString(IEnumerable value)
        {
            var type = value.GetType().GetGenericArguments()[0];
            DataTable dataTable = new DataTable(type.Name);
            PropertyInfo[] Props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo prop in Props)
            {
                dataTable.Columns.Add(prop.Name);
            }
            foreach (object item in value)
            {
                var values = new object[Props.Length];
                for (int i = 0; i < Props.Length; i++)
                {
                    values[i] = Props[i].GetValue(item, null);
                }
                dataTable.Rows.Add(values);
            }

            using (var memoryStream = new MemoryStream())
            {
                dataTable.WriteXml(memoryStream);
                memoryStream.Position = 0;
                using (var reader = new StreamReader(memoryStream))
                {
                    return reader.ReadToEnd();
                }
            }

        }
Beispiel #5
0
        static void Main(string[] args)
        {
            Console.WriteLine("program start!!");
               // ClinetsInfoParser.Parse();
               var tbl=new DataTable();
            tbl.TableName = "custom";
            tbl.Columns.Add("Name");
            tbl.Columns.Add("Producer");
            tbl.Columns.Add("Trash");
            tbl.Columns.Add("Expires");
            tbl.Columns.Add("Quantity");
            tbl.Columns.Add("Trash2");
            tbl.Columns.Add("Division");

            for (int i = 0; i < 15; i++)
                tbl.Rows.Add("Name" + i.ToString(), "Producer" + i.ToString(), i.ToString(), DateTime.Now.ToShortDateString(),
                             i.ToString(),i.ToString(), "Division" + i.ToString());
            var stream=new MemoryStream();
            tbl.WriteXml(stream,XmlWriteMode.WriteSchema);
               var data= Packer.Pack(stream);
               var result = new ConcurrentBag<byte[]>();
            result.Add(data);
            result.ToQueryResult();

                Console.ReadKey();
        }
Beispiel #6
0
		private static string ConvertAltmanDataTableToXml(DataTable dt)
		{
			MemoryStream stream = null;
			XmlTextWriter writer = null;
			try
			{
				stream = new MemoryStream();
				writer = new XmlTextWriter(stream, Encoding.Default);
				writer.Formatting = Formatting.Indented; 
				dt.WriteXml(writer);
				var count = (int)stream.Length;
				var arr = new byte[count];
				stream.Seek(0, SeekOrigin.Begin);
				stream.Read(arr, 0, count);
				return new UTF8Encoding().GetString(arr);
			}
			catch
			{
				return String.Empty;
			}
			finally
			{
				if (writer != null)
					writer.Close();
			}
		}
        /// <summary>
        /// Function to export all the Account data to the XML File
        /// </summary>
        private static void exportAccountData()
        {
            DataTable AccountDB = new DataTable();
            AccountDB.TableName = "Account Database";
            AccountDB.Columns.Add("AccountID");
            AccountDB.Columns.Add("Balance");
            AccountDB.Columns.Add("Type");
            AccountDB.Columns.Add("ClientID");
            AccountDB.Columns.Add("Interest");
            AccountDB.Columns.Add("Limit");

            foreach (KeyValuePair<string, Account> entry in Program.AccountData)
            {
                DataRow row = AccountDB.NewRow();
                row["AccountID"] = entry.Value.ACCOUNTID;
                row["Balance"] = entry.Value.BALANCE;
                row["Type"] = entry.Value.ACCOUNTTYPE;
                row["ClientID"] = entry.Value.CLIENTID;
                if (entry.Value.ACCOUNTTYPE=="Interest")
                {
                    AccountInterest temp1 = (AccountInterest)entry.Value;
                    row["Interest"] = temp1.INTEREST;
                    row["Limit"] = null;
                }
                else
                {
                    AccountNoInterest temp2 = (AccountNoInterest)entry.Value;
                    row["Limit"] = temp2.LIMIT;
                    row["Interest"] = null;
                }
                AccountDB.Rows.Add(row);
            }
            AccountDB.WriteXml("myAccount.xml");
        }
 private void AddTemplateToXML(string nm)
 {
     string path = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + @"\templates.xml";
     DataTable dt = new DataTable("TemplateTable");
     dt.Columns.Add("TemplateName");
     DataRow dr;
     if (lstTemplate.Items.Count > 0)
     {
         try
         {
             for (int b = 0; b < lstTemplate.Items.Count; b++)
             {
                 dr = dt.NewRow();
                 dr[0] = lstTemplate.Items[b].ToString();
                 dt.Rows.Add(dr);
             }
             if (File.Exists(path))
                 File.Delete(path);
             dt.WriteXml(path);
             MessageBox.Show("Template successfully inserted.", "CSR Assistant");
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message, "CSR Assistant");
         }
     }
 }
Beispiel #9
0
        XmlDocument ConvertToXml(object source)
        {
            XmlDocument xml = new XmlDocument();

            System.Data.DataTable dt = source as System.Data.DataTable;
            if (dt != null)
            {
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    dt.WriteXml(ms);
                    ms.Flush();
                    ms.Seek(0, System.IO.SeekOrigin.Begin);
                    xml.Load(ms);
                }
            }
            else
            {
                XmlSerializer serializer = new XmlSerializer(source.GetType());
                using (StringWriter sw = new StringWriter())
                {
                    serializer.Serialize(sw, source);
                    sw.Flush();
                    string o = sw.ToString();
                    xml.LoadXml(o);
                }
            }
            return(xml);
        }
Beispiel #10
0
 internal static string GetDeliveries()
 {
     sql = "SELECT " +
             "deliveries.id AS delivery_id, purchases.id AS purchase_id, purchases.po_number, deliveries.delivery_date, supplier_id, name AS supplier_name, " +
             "lookup_status.description AS status, lookup_status2.description AS completion_status " +
         "FROM deliveries " +
         "JOIN purchases ON purchases.id = deliveries.purchase_id " +
         "JOIN suppliers ON suppliers.id = supplier_id " +
         "JOIN lookup_status ON lookup_status.id = deliveries.status " +
         "JOIN lookup_status AS lookup_status2 ON lookup_status2.id = deliveries.completion_status " +
         "WHERE lookup_status2.description != 'Complete' ";
     dt = new DataTable();
     dt = Database.Query(sql);
     if (dt != null)
     {
         if (dt.Rows[0].ItemArray[0].ToString() == "-1")
         {
             result = dt.Rows[0].ItemArray[1].ToString();
         }
         else
         {
             StringWriter sw = new StringWriter();
             dt.WriteXml(sw);
             result = sw.ToString();
         }
     }
     else
     {
         result = Functions.FormatReturn(0, "No items found");
     }
     return result;
 }
Beispiel #11
0
        private static void SaveResultsToXml(
			string fileName,
			DataTable results
		)
        {
            results.WriteXml(fileName);
        }
        public void ToXmlVfp(string path)
        {
            DataTable dt = new DataTable();
            dt.TableName = "Tabla1";

            DataColumn campo1 = new DataColumn();
            campo1.DataType = typeof(string);
            campo1.MaxLength = 20;
            campo1.ColumnName = "Cae";

            DataColumn campo2 = new DataColumn();
            campo2.DataType = typeof(string);
            campo2.MaxLength = 500;
            campo2.ColumnName = "Problema";

            dt.Columns.Add(campo1);
            dt.Columns.Add(campo2);

            foreach (string mensaje in this.Problema)
            {
                DataRow registro1 = dt.NewRow();
                registro1[0] = this.Cae;
                registro1[1] = mensaje;
                dt.Rows.Add(registro1);
            }

            dt.WriteXml(path);
        }
Beispiel #13
0
 public string ConvertBetweenDataTableToXML(DataTable dtNeedCoveret)
 {
     System.IO.TextWriter tw = new System.IO.StringWriter();
     //if TableName is empty, WriteXml() will throw Exception.
     dtNeedCoveret.TableName = dtNeedCoveret.TableName.Length == 0 ? "Table" : dtNeedCoveret.TableName;
     dtNeedCoveret.WriteXml(tw);
     dtNeedCoveret.WriteXmlSchema(tw);
     return tw.ToString();
 }
Beispiel #14
0
 public static void CreateBackUp(DataTable dt)
 {
     try
     {
         //dt.AcceptChanges();
         dt.WriteXml(BackUpFileName);
     }
     catch(Exception)
     {}
 }
Beispiel #15
0
        /*
          Example Use
          string[] fieldNames = {
                               "Id",
                               "Name",
                               "Age"
                            };
                            CsvToXmlConvert("c:\\temp\\example.txt", "TempTable", ";", "c:\\temp\\example.xml", fieldNames);*/
        /// <summary>
        /// </summary>
        /// <param name="inputFile"></param>
        /// <param name="dataName"></param>
        /// <param name="separator"></param>
        /// <param name="outputFile"></param>
        /// <param name="fieldnames"></param>
        public static void CsvToXmlConvert(
            string inputFile,
            string dataName,
            char separator,
            string outputFile,
            string[] fieldnames = null)
        {
            var dt = new DataTable(dataName);
            bool firstRow = true;

            using (var sr = new StreamReader(inputFile))
            {
                while (!(sr.EndOfStream))
                {
                    string readLine = sr.ReadLine();
                    if (readLine == null)
                    {
                        continue;
                    }
                    string[] fields = readLine.Split(separator);
                    IEnumerable<string> e = from s in fields
                                            select s;
                    int c = e.Count();
                    if (firstRow)
                    {
                        for (int ii = 0;
                             ii <= c - 1;
                             ii++)
                        {
                            string fName = "";
                            if ((fieldnames == null))
                            {
                                fName = "Field" + ii.ToString("000");
                            }
                            else
                            {
                                fName = fieldnames[ii];
                            }
                            dt.Columns.Add(fName);
                        }
                        firstRow = false;
                    }

                    foreach (string field in fields)
                    {
                        dt.Rows.Add(field);
                    }
                }

                dt.WriteXml(outputFile);
                dt.Dispose();
            }
        }
Beispiel #16
0
        public string Write(TableName tname, DataTable dt)
        {
            string file = getDataFileName(tname);
            using (var writer = NewStreamWriter(file))
            {
                dt.TableName = tname.Name;
                dt.DataSet.DataSetName = tname.DatabaseName.Name;
                dt.WriteXml(writer, XmlWriteMode.WriteSchema);
            }

            return file;
        }
Beispiel #17
0
 public static void CreateCorrespondingXmlWhenNotExist()
 {
     if (!File.Exists(xmlPath))
     {
         var dtTableName = new DataTable();
         dtTableName.Columns.Add("OriName");
         dtTableName.Columns.Add("PascalName");
         dtTableName.TableName = "dt";
         dtTableName.Rows.Add(new[] { "1", "1" });
         dtTableName.WriteXml(xmlPath);
     }
 }
Beispiel #18
0
        public response GetSpecificStory(int ID)
        {
            var dataTable = new System.Data.DataTable();

            dataTable = new System.Data.DataTable {
                TableName = "Stories"
            };
            string connString = URLInfo.GetDataBaseConnectionString();

            System.IO.StringWriter writer = new System.IO.StringWriter();
            string   returnString         = "";
            response response             = new response();

            response.result = 0;
            using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(connString))
            {
                using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("GetSpecificStory", con))
                {
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.Parameters.Add("@ID", System.Data.SqlDbType.NVarChar).Value = ID;
                    con.Open();
                    var dataReader = cmd.ExecuteReader();
                    dataTable.Load(dataReader);
                    dataTable.WriteXml(writer, System.Data.XmlWriteMode.WriteSchema, false);
                    returnString = writer.ToString();
                    int numberOfRecords = dataTable.Rows.Count;
                    response.result = numberOfRecords;



                    SpecificStoryList list = new SpecificStoryList();
                    foreach (System.Data.DataRow row in dataTable.Rows)
                    {
                        specificStory myprod = new specificStory();
                        myprod.ID                 = row["ID"].ToString();
                        myprod.JakataID           = row["JakataID"].ToString();
                        myprod.AnimalType         = row["AnimalType"].ToString();
                        myprod.Comments           = row["Comments"].ToString();
                        myprod.MoralType          = row["MoralType"].ToString();
                        myprod.Stories            = row["Stories"].ToString();
                        myprod.StoryCategorytName = row["StoryCategorytName"].ToString();
                        myprod.Title              = row["Title"].ToString();


                        list.specificStory.Add(myprod);
                    }
                    response.AddSpecificStoryList(list);

                    response.log.Add(numberOfRecords + " Records found");
                }
            }
            return(response);
        }
Beispiel #19
0
 /// <summary>
 /// 将DataTable转化为XML输出
 /// </summary>
 /// <param name="dataTable">DataTable</param>
 /// <param name="fileName">文件名称</param>
 public void DataTableToXML(DataTable dataTable, string fileName)
 {
     //指定程序安装目录
     string filePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + fileName;
     using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
     {
         using (XmlWriter xmlWriter = XmlWriter.Create(fs))
         {
             dataTable.WriteXml(xmlWriter, XmlWriteMode.IgnoreSchema);
         }
     }
     Process.Start(filePath);
 }
 /// <summary>
 /// 将数据从DataTable类型转化为XElement类型数据
 /// </summary>
 /// <param name="xmlDS">数据源</param>
 /// <param name="tableName">DataTable中的表名</param>
 /// <returns></returns>
 public static XElement ConvertDataTableToXML(DataTable xmlDS, string tableName)
 {
     //定义转化需要的变量
     StringWriter sw = new StringWriter();
     //设置获取数据的表名
     xmlDS.TableName = tableName;
     //写当前数据
     xmlDS.WriteXml(sw, System.Data.XmlWriteMode.IgnoreSchema, true);
     //将数据转化为字符串
     string contents = sw.ToString();
     //返回
     return XElement.Parse(contents);
 }
Beispiel #21
0
        /// <summary>
        /// DataTable 내용을 Xml Text로 변경한다.
        /// </summary>
        /// <param name="table">Instance of DataTable</param>
        /// <param name="writeMode">Xml Text 생성 모드</param>
        /// <returns>생성된 Xml 문자열</returns>
        public static string ToXmlText(DataTable table, XmlWriteMode writeMode = XmlWriteMode.WriteSchema) {
            table.ShouldNotBeNull("table");

            if(IsDebugEnabled)
                log.Debug("Convert DataTable to Xml Text. table=[{0}], writeMode=[{1}]", table.TableName, writeMode);

            var sb = new StringBuilder();

            using(var writer = new StringWriter(sb))
                table.WriteXml(writer, writeMode);

            return sb.ToString();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            string d_OldPath = "";
            d_OldPath = Application.StartupPath;

            SaveFileDialog d_Dialog = new SaveFileDialog();
            d_Dialog.Title = "导出数据";
            d_Dialog.Filter = "Excel 文件(*.xls)|*.xls|XML 文件(*.xml)|*.xml|TXT文件(*.txt)|*.txt|HTML 文件(*.html)|*.html|MHT 文件(*.mht)|*.mht|PDF 文件(*.pdf)|*.pdf|RFT 文件(*.rtf)|*.rtf";
            //'d_Dialog.Filter = "Excel 文件(*.xls)|*.xls|XML 文件(*.xml)|*.xml|TXT文件(*.txt)|*.txt"
            string d_PathName = "";
            try
            {
                if (d_Dialog.ShowDialog() == DialogResult.OK)
                {
                    d_PathName = d_Dialog.FileName;
                    if (d_PathName.Substring(d_PathName.Length - 3) == "xls")
                    { //'把数据导到Excel中
                        gridView1.ExportToExcelOld(d_PathName);
                    }
                    else if (d_PathName.Substring(d_PathName.Length - 3) == "xml")
                    { //'把数据导到xml中
                        DataTable d_table = new DataTable();
                        d_table = (DataTable)this.gridControl1.DataSource;
                        //'把FlexGrid里的内容写到DataSet里
                        d_table.WriteXml(d_PathName);
                    }
                    else if (d_PathName.Substring(d_PathName.Length - 3) == "txt")
                    { //'把数据导到txt中
                        gridView1.ExportToText(d_PathName);
                    }
                    else if (d_PathName.Substring(d_PathName.Length - 3) == "tml")
                    { //'把数据导到HTML中
                        gridView1.ExportToHtml(d_PathName);
                    }
                    else if (d_PathName.Substring(d_PathName.Length - 3) == "mht")
                    { //'把数据导到mht中
                        gridView1.ExportToMht(d_PathName);
                    }
                    else if (d_PathName.Substring(d_PathName.Length - 3) == "pdf")
                    { //'把数据导到PDF中
                        gridView1.ExportToPdf(d_PathName);
                    }
                    else if (d_PathName.Substring(d_PathName.Length - 3) == "rtf")
                    { //'把数据导到PDF中
                        gridView1.ExportToRtf(d_PathName);
                    }
                }

            }
            catch { }
        }
Beispiel #23
0
        public void Output(TableInfo table, DataTable data)
        {
            var outputFilename = string.Format("{0}.xml", table.OutputTableName);

            _logger.Info("Writing data to {0}...", outputFilename);

            using (var writer = new StringWriter())
            {
                data.WriteXml(writer, XmlWriteMode.IgnoreSchema, false);

                File.WriteAllText(outputFilename, writer.ToString());
            }
            _logger.Info("Finished writing data to {0}.", outputFilename);
        }
Beispiel #24
0
        public response GetJakataMaster()
        {
            var dataTable = new System.Data.DataTable();

            dataTable = new System.Data.DataTable {
                TableName = "JakataMaster"
            };
            //var conString1 = ConfigurationManager.ConnectionStrings["LocalEvolution"];
            //string connString = conString1.ConnectionString;
            string connString = URLInfo.GetDataBaseConnectionString();


            System.IO.StringWriter writer = new System.IO.StringWriter();
            string   returnString         = "";
            response response             = new response();

            response.result = 0;
            using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(connString))
            {
                using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("GetJakataMaster", con))
                {
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    con.Open();
                    var dataReader = cmd.ExecuteReader();
                    dataTable.Load(dataReader);
                    dataTable.WriteXml(writer, System.Data.XmlWriteMode.WriteSchema, false);
                    returnString = writer.ToString();
                    int numberOfRecords = dataTable.Rows.Count;
                    response.result = numberOfRecords;



                    JakataMasterList list = new JakataMasterList();
                    foreach (System.Data.DataRow row in dataTable.Rows)
                    {
                        jakataMaster myprod = new jakataMaster();
                        myprod.ID    = row["ID"].ToString();
                        myprod.Title = row["Title"].ToString();


                        list.jakataMasterLists.Add(myprod);
                    }
                    response.AddJakataMasterList(list);

                    response.log.Add(numberOfRecords + " Records found");
                }
            }
            return(response);
        }
Beispiel #25
0
 public static string ConvertDataTableToXML(DataTable sourceTable)
 {
     string xmlString = "";
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
     {
         sourceTable.WriteXml(ms);
         System.Xml.XmlTextWriter x = new System.Xml.XmlTextWriter(ms, new System.Text.UTF8Encoding(false));
         x.Formatting = System.Xml.Formatting.Indented;
         //using (x)
         //{
         xmlString = System.Text.Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length);
         //}
     }
     return xmlString;
 }
Beispiel #26
0
 public int Execute()
 {
     using (var conn = this.GetConnection())
     {
         conn.Open();
         DataTable dt = new DataTable();
         SqlDataAdapter adapter = new SqlDataAdapter(this.Command, conn);
         adapter.SelectCommand.CommandType = this.CommandType;
         adapter.Fill(dt);
         dt.TableName = "tmp";
         dt.WriteXml(this.SaveTo);
         dt.WriteXmlSchema(this.SaveTo + ".schema");
     }
     return 0;
 }
        private void btGrabar_Click(object sender, EventArgs e)
        {
            oTabla.Rows.Add();

            oTabla.Rows[oTabla.Rows.Count - 1]["nombre"]    = txtNombre.Text;
            oTabla.Rows[oTabla.Rows.Count - 1]["edad"]      = txtEdad.Text;
            oTabla.Rows[oTabla.Rows.Count - 1]["domicilio"] = txtDomicilio.Text;

            //oTabla.Rows.Add();
            //oTabla.Rows[1][0] = txtNombre.Text;
            //oTabla.Rows[1][1] = txtEdad.Text;
            //oTabla.Rows[1][2] = txtDomicilio.Text;

            oTabla.WriteXml(@"clientes.xml");
        }
Beispiel #28
0
        private void btSaveXML_Click(object sender, EventArgs e)
        {
            saveFileDialog1.InitialDirectory = "C:";
            saveFileDialog1.Title            = "Save as .XML File";
            saveFileDialog1.FileName         = "";
            saveFileDialog1.Filter           = "XML file(*.xml)|*.xml";
            saveFileDialog1.RestoreDirectory = true;


            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                DataTable dt = new DataTable();
                dt.TableName = "THONG_TIN_KHACH";

                for (int i = 0; i < dataGridViewSML.Columns.Count; i++)
                {
                    if (dataGridViewSML.Columns[i].Visible) // Add's only Visible columns (if you need it)
                    {
                        string headerText = dataGridViewSML.Columns[i].HeaderText;
                        headerText = Regex.Replace(headerText, "[-/, ]", "_");

                        DataColumn column = new DataColumn(headerText);
                        dt.Columns.Add(column);
                    }
                }
                object[] cellvalue = new object[dataGridViewSML.Columns.Count];
                foreach (DataGridViewRow DataGVRow in dataGridViewSML.Rows)
                {
                    DataRow dataRow = dt.NewRow();
                    for (int i = 0; i < DataGVRow.Cells.Count; i++)
                    {
                        cellvalue[i] = DataGVRow.Cells[i].Value;
                    }
                    dt.Rows.Add(cellvalue);
                }
                DataSet ds = new DataSet();
                ds.DataSetName = "KHAI_BAO_TAM_TRU";
                ds.Tables.Add(dt);

                MessageBox.Show("Sucsecfull!");

                var writer = XmlWriter.Create(saveFileDialog1.FileName, new XmlWriterSettings {
                    Encoding = Encoding.UTF8, Indent = true
                });
                dt.WriteXml(writer);
                writer.Close();
            }
        }
Beispiel #29
0
        public response GetYouTube(int JakataID)
        {
            var dataTable = new System.Data.DataTable();

            dataTable = new System.Data.DataTable {
                TableName = "YouTube"
            };
            string connString = URLInfo.GetDataBaseConnectionString();

            System.IO.StringWriter writer = new System.IO.StringWriter();
            string   returnString         = "";
            response response             = new response();

            response.result = 0;
            using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(connString))
            {
                using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("GetYouTube", con))
                {
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.Parameters.Add("@JakataID", System.Data.SqlDbType.NVarChar).Value = JakataID;
                    con.Open();
                    var dataReader = cmd.ExecuteReader();
                    dataTable.Load(dataReader);
                    dataTable.WriteXml(writer, System.Data.XmlWriteMode.WriteSchema, false);
                    returnString = writer.ToString();
                    int numberOfRecords = dataTable.Rows.Count;
                    response.result = numberOfRecords;



                    YouTubeList list = new YouTubeList();
                    foreach (System.Data.DataRow row in dataTable.Rows)
                    {
                        youTube myprod = new youTube();
                        myprod.ID       = row["ID"].ToString();
                        myprod.JakataID = row["JakataID"].ToString();
                        myprod.URL      = row["URL"].ToString();


                        list.youTubeLists.Add(myprod);
                    }
                    response.AddYouTubeList(list);

                    response.log.Add(numberOfRecords + " Records found");
                }
            }
            return(response);
        }
Beispiel #30
0
 public string gameLogFromsID(string sID)
 {
     SqlCommand cmd = new SqlCommand("SELECT * FROM w00_GameLog..tGameLog WHERE tGameLog.nCharNo = (SELECT nCharNo FROM w00_Character..tCharacter WHERE sID = @sID) OR tGameLog.nTargetCharNo = (SELECT nCharNo FROM w00_Character..tCharacter WHERE sID = @sID) ORDER BY dDate;", conn);
     cmd.Parameters.AddWithValue("@sID", sID);
     DataTable bufferDT = new DataTable();
     SqlDataAdapter SQLDTA = new SqlDataAdapter();
     conn.Open();
     bufferDT.TableName = "GameLog";
     SQLDTA.SelectCommand = cmd;
     SQLDTA.Fill(bufferDT);
     conn.Close();
     StringWriter sw = new StringWriter();
     bufferDT.WriteXml(sw);
     sw.Close();
     return sw.ToString();
 }
        private void createXml()
        {
            DataTable dt = new DataTable("empTable");
            dt.Columns.Add("EmpNo",Type.GetType("System.Int32"));
            dt.Columns.Add("EmpName", Type.GetType("System.String"));
            dt.Columns.Add("Salary", Type.GetType("System.Int32"));
            DataRow r = dt.NewRow();
            r[0] = 1;
            r[1] = "Rama";
            r[2] = 1000;
            dt.Rows.Add(r);
            string str = Server.MapPath("emp.xml");
            dt.WriteXml(str);


        }
Beispiel #32
0
    public static string FormatReturn(int _flag, string _result)
    {
        string result;
        using (DataTable dt = new DataTable("table"))
        {
            dt.Columns.Add("flag");
            dt.Columns.Add("result");
            dt.Rows.Add(_flag, _result);
            StringWriter sw = new StringWriter();
            dt.WriteXml(sw);
            result = sw.ToString();
            sw.Dispose();
        }

        return result;
    }
        protected void btnExportToXML_Click(object sender, EventArgs e)
        {
            FillGrid();

            try
            {
                DataTable dtXML = new DataTable();
                dtXML = dvTeachers.ToTable("Teachers");
                dtXML.WriteXml(@"C:\Users\Core i3\Desktop\Teachers.xml");
                lblMsg.Text = "Export to XML OK!!!";
            }
            catch(Exception ex)
            {
                lblMsg.Text = "Error to Export to XML: " + ex.Message.ToString();
            }
        }
Beispiel #34
0
        public response GetStorySource()
        {
            var dataTable = new System.Data.DataTable();

            dataTable = new System.Data.DataTable {
                TableName = "StorySource"
            };
            string connString = URLInfo.GetDataBaseConnectionString();


            System.IO.StringWriter writer = new System.IO.StringWriter();
            string   returnString         = "";
            response response             = new response();

            response.result = 0;
            using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(connString))
            {
                using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("GetStorySource", con))
                {
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    con.Open();
                    var dataReader = cmd.ExecuteReader();
                    dataTable.Load(dataReader);
                    dataTable.WriteXml(writer, System.Data.XmlWriteMode.WriteSchema, false);
                    returnString = writer.ToString();
                    int numberOfRecords = dataTable.Rows.Count;
                    response.result = numberOfRecords;



                    StorySourceList list = new StorySourceList();
                    foreach (System.Data.DataRow row in dataTable.Rows)
                    {
                        storySource myprod = new storySource();
                        myprod.ID          = row["ID"].ToString();
                        myprod.StorySource = row["StorySource"].ToString();


                        list.storySourceLists.Add(myprod);
                    }
                    response.AddStorySourceList(list);

                    response.log.Add(numberOfRecords + " Records found");
                }
            }
            return(response);
        }
Beispiel #35
0
        private static string TarnsformInternal(DataTable dt, Encoding encoding, XslCompiledTransform transform)
        {
            Encoding e = encoding ?? Encoding.Default;
            XmlDocument doc = new XmlDocument();
            using (StringWriter sw = new StringWriter())
            {
                XmlWriterSettings set = new XmlWriterSettings();
                set.Encoding = e;
                using (XmlWriter xw = XmlWriter.Create(sw, set))
                {
                    dt.WriteXml(xw, false);
                    doc.LoadXml(sw.ToString());
                }
            }

            return TransformInternal(doc, transform);
        }
Beispiel #36
0
 private void CreateXml()
 {
     try
     {
         using (System.Data.DataTable dt = new System.Data.DataTable("Manset"))
         {
             using (BAYMYO.UI.Web.CustomSqlQuery query = new BAYMYO.UI.Web.CustomSqlQuery(dt, "Manset", "KayitTarihi DESC", "Aktif=1"))
             {
                 query.Top = 9;
                 query.Execute();
                 dt.WriteXml(Server.MapPath(Settings.XmlPath + "manset.xml"), System.Data.XmlWriteMode.WriteSchema);
             }
         }
     }
     catch (Exception)
     {
     }
 }
Beispiel #37
0
        //функция записи таблицы в XML формат
        public void SaveDataTableInXML(DataTable TableForSave)
        {
            //читаем имя таблицы
            string Name = TableForSave.TableName;

            //если имя таблицы не пустое то сохраняем данные
            if (Name != "")
            {
                //добавляем к имени расширение xml
                Name += ".xml";
                //создаем специальную переменную для преобразования данных из таблицы в XML формат
                StringWriter writerXML = new StringWriter();
                //получаем данные о таблице и преобразуем их в XML формат
                TableForSave.WriteXml(writerXML, XmlWriteMode.WriteSchema, true);
                //Сохраняем преобразованные в XML данные в файл
                File.WriteAllText(Name, writerXML.ToString());
            }
        }
Beispiel #38
0
 public static void saveDataTable(DataTable data, string filePath)
 {
     // Create the FileStream to write with.
     System.IO.FileStream myFileStream = new System.IO.FileStream
        (filePath, System.IO.FileMode.Create);
     // Create an XmlTextWriter with the fileStream.
     System.Xml.XmlTextWriter myXmlWriter =
        new System.Xml.XmlTextWriter(myFileStream, System.Text.Encoding.Unicode);
     // Write to the file with the WriteXml method.
     try
     {
         data.WriteXml(myXmlWriter);
     }
     finally
     {
         myXmlWriter.Close();
     }
 }
Beispiel #39
0
        /// <summary>
        /// Gets the XML document.
        /// </summary>
        /// <param name="table">The table.</param>
        /// <returns></returns>
        public static IXPathNavigable GetXmlDocument(DataTable table)
        {
            XmlDocument doc = new XmlDocument();
            using (MemoryStream ms = new MemoryStream())
            {
                table.WriteXml(ms, XmlWriteMode.IgnoreSchema);
                ms.Position = 0;

                XmlReaderSettings settings = new XmlReaderSettings();
                settings.IgnoreComments = true;
                settings.IgnoreProcessingInstructions = true;
                settings.IgnoreWhitespace = true;

                XmlReader reader = XmlReader.Create(ms, settings);

                doc.Load(reader);
            }
            return doc;
        }
Beispiel #40
0
        //public response GetSpecificStory(Story myStoryies)
        public String GetSpecificStory(Story myStoryies)
        {
            var dataTable = new System.Data.DataTable();

            dataTable = new System.Data.DataTable {
                TableName = "Stories"
            };
            string connString = URLInfo.GetDataBaseConnectionString();

            System.IO.StringWriter writer = new System.IO.StringWriter();
            string   returnString         = "";
            response response             = new response();

            response.result = 0;
            string resultstring = "";

            SpecificStoryList list = new SpecificStoryList();



            using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(connString))
            {
                using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("GetSearchStory", con))
                {
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;



                    //cmd.Add("@JakataID", myStory.JakataID);
                    //cmd.Add("@StoryCategorytName", 1);
                    //cmd.Add("@Title", myStory.Title);
                    //cmd.Add("@AnimalType", myStory.AnimalType);


                    if (myStoryies.Title > 0)
                    {
                        cmd.Parameters.Add("@Title", System.Data.SqlDbType.NVarChar).Value = myStoryies.Title;
                    }

                    if (myStoryies.JakataID > 0)
                    {
                        cmd.Parameters.Add("@JakataID", System.Data.SqlDbType.Int).Value = myStoryies.JakataID;
                    }

                    if (myStoryies.AnimalType != "0")
                    {
                        cmd.Parameters.Add("@AnimalType", System.Data.SqlDbType.NVarChar).Value = myStoryies.AnimalType;
                    }

                    if (myStoryies.MoralType > 0)
                    {
                        cmd.Parameters.Add("@MoralType", System.Data.SqlDbType.Int).Value = myStoryies.MoralType;
                    }

                    if (myStoryies.Comments != "0")
                    {
                        cmd.Parameters.Add("@Comments", System.Data.SqlDbType.NVarChar).Value = myStoryies.Comments;
                    }

                    if (myStoryies.Stories != "0")
                    {
                        cmd.Parameters.Add("@Stories", System.Data.SqlDbType.NVarChar).Value = myStoryies.Stories;
                    }


                    con.Open();
                    var dataReader = cmd.ExecuteReader();
                    dataTable.Load(dataReader);
                    dataTable.WriteXml(writer, System.Data.XmlWriteMode.WriteSchema, false);
                    returnString = writer.ToString();

                    //return returnString;
                    int numberOfRecords = dataTable.Rows.Count;
                    response.result = numberOfRecords;



                    //SpecificStoryList list = new SpecificStoryList();
                    foreach (System.Data.DataRow row in dataTable.Rows)
                    {
                        //specificStory myprod = new specificStory();
                        resultstring = resultstring + row["ID"].ToString() + "|";


                        //list.specificStory.Add(myprod);
                    }
                    //response.AddSpecificStoryList(list);

                    //response.log.Add(numberOfRecords + " Records found");
                }
            }

            //return list;
            return(resultstring);
            //return response;
        }
Beispiel #41
0
        /// <summary>
        /// конструктор класса
        /// </summary>
        /// <param name="start_day">дата первого дня учебной недели</param>
        public Data(DateTime start_day, List <int> empty_rows, List <string> grups, int fakultet)
        {
            rows = 42;
            cols = grups.Count;

            //задать соотвествие "дата-номер строки"
            DateTime curdate = start_day;

            for (int i = 0; i < empty_rows.Count; i++)
            {
                for (int j = empty_rows[i] + 1; j < empty_rows[i] + 7; j++)
                {
                    date_row.Add(j, curdate);
                }
                curdate = curdate.AddDays(1);
            }

            //задать соотвествие "группа-столбец"
            int kkk = 1;

            for (int j = 0; j < grups.Count; j++)
            {
                grupa_column.Add(kkk, grups[j]);
                column_grupa.Add(grups[j], kkk);
                kkk += 2;
            }

            //задать соотвествие "пара-номер_строки"
            for (int i = 0; i < empty_rows.Count; i++)
            {
                int para_count = 1;
                for (int j = empty_rows[i] + 1; j < empty_rows[i] + 7; j++)
                {
                    para_row.Add(j, para_count);
                    para_count++;
                }
            }

            //создать фильтр для данной недели
            int ds = start_day.Day,
                ms = start_day.Month,
                ys = start_day.Year;

            int de = start_day.AddDays(6).Day,
                me = start_day.AddDays(6).Month,
                ye = start_day.AddDays(6).Year;


            string res = "";

            res = string.Format(" and (y>={0} and y<={1}) ", ys, ye);

            if (ms == 12 && me == 1)
            {
                res = res + " and (m=1 or m=12) ";
            }
            else
            {
                res = res + string.Format(" and (m>={0} and m<={1})", ms, me);
            }

            if (de < ds)
            {
                res = res + string.Format(" and ((d>={0} and d<=31 and m={2}) or (d>=1 and d<={1} and m={3})) "
                                          , ds, de, ms, me);
            }
            else
            {
                res = res + string.Format(" and (d>={0} and d<={1}) ", ds, de);
            }

            query = string.Format("select " +
                                  " gn=grupa.name, gi=grupa.id, " +
                                  " prepn = prepod.fam + ' ' + left(prepod.im,1) + '.' + left(prepod.ot,1) + '.'," +
                                  " predmn = predmet.name_krat, " +
                                  " audn = kabinet.nomer, " +
                                  " rasp.y, rasp.d, rasp.m, rasp.predmet_id, rasp.grupa_id, rasp.prepod_id, rasp.fakultet_id, " +
                                  " rasp.kurs_id, rasp.nom_zan, rasp.vid_zan_id, " +
                                  " rasp.kabinet_id, rasp.semestr_id, rasp.potok_id, " +
                                  " rasp.subgr_nomer, chas = rasp.kol_chas, " +
                                  " rasp.id, krat_name, predmet.delenie, tema, vid_del=vid_zan.delenie, vidname = vid_zan.name, prim = isnull(prim_text,'') " +
                                  " , prfullname = predmet.name " +
                                  " from rasp " +
                                  " join grupa on grupa.id=rasp.grupa_id " +
                                  " join prepod on prepod.id=rasp.prepod_id " +
                                  " join predmet on predmet.id=rasp.predmet_id " +
                                  " join kabinet on kabinet.id=rasp.kabinet_id " +
                                  " join vid_zan on vid_zan.id=rasp.vid_zan_id " +
                                  " where rasp.fakultet_id={0} and grupa.show_in_grid=1 ", fakultet)
                    + res +
                    " order by y, m, d, nom_zan, grupa.outorder";

            //получить данные раписания на указанную неделю
            SqlDataAdapter da = new SqlDataAdapter(query, main.global_connection);

            BD = new DataTable("rasp");
            da.Fill(BD);

            //создать временную папку для размещения файлов данных
            path = Environment.GetEnvironmentVariable("TMP", EnvironmentVariableTarget.User) +
                   "\\Facultet";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            else
            {
                foreach (string f in Directory.GetFiles(path))
                {
                    try
                    {
                        File.Delete(f);
                    }
                    catch (Exception exx)
                    {
                        //
                    }
                }
            }

            if (BD.Rows.Count > 0)
            {
                BD.WriteXml(path + "\\0.xml");
            }

            // -----------------------  сздать структуру данных для хранения информации в программе

            data =
                new Dictionary <DateTime, Dictionary <string, Dictionary <int, Cell> > > ( );

            //data[DateTime.Now]["П21"][6].egz[0] = true;
            //цикл по дням недели

            int paranumber = 0;

            for (DateTime i = start_day; i <= start_day.AddDays(6); i = i.AddDays(1))
            {
                Dictionary <string, Dictionary <int, Cell> > gruppa_cell =
                    new Dictionary <string, Dictionary <int, Cell> > ( );

                for (int j = 0; j < grups.Count; j++)   //цикл по группам
                {
                    string grname = grups[j];
                    Dictionary <int, Cell> para_gruppa = new Dictionary <int, Cell> ( );

                    for (paranumber = 1; paranumber <= 6; paranumber++)   //цикл по парам
                    {
                        Cell tmpcell = new Cell( );
                        para_gruppa.Add(paranumber, tmpcell);
                    }
                    gruppa_cell.Add(grname, para_gruppa);
                }
                data.Add(i, gruppa_cell);
            }

            // ----------------------------------   заполнить структуру data данными из базы
            foreach (DataRow row in BD.Rows)
            {
                Cell     c        = new Cell( );
                DateTime currdate = new DateTime((int)row["y"], (int)row["m"], (int)row["d"]);

                if (this[currdate, row["gn"].ToString( ), (int)row["nom_zan"]].id[0] > 0 ||
                    this[currdate, row["gn"].ToString( ), (int)row["nom_zan"]].id[1] > 0)
                {
                    c = this[currdate, row["gn"].ToString( ), (int)row["nom_zan"]];
                }

                int sub = (int)row["subgr_nomer"];

                c.col[0] = column_grupa[row["gn"].ToString( )];
                c.col[1] = c.col[0] + 1;

                c.row = 0;
                foreach (int drow in date_row.Keys)
                {
                    if (date_row[drow] == currdate)
                    {
                        c.row = drow + (int)row["nom_zan"] - 6;
                    }
                }

                if (sub == 0)
                {
                    sub = 0;
                }
                else
                {
                    sub--;
                }

                c.subgr_nomer[sub] = (int)row["subgr_nomer"];

                c.id[sub] = (int)row["id"]; //задать id зантяия

                c.y[sub] = (int)row["y"];
                c.m[sub] = (int)row["m"];
                c.d[sub] = (int)row["d"];
                c.y[sub] = (int)row["y"];

                c.predmet_id[sub]       = (int)row["predmet_id"];
                c.predmet_name[sub]     = row["predmn"].ToString();
                c.predmet_fullname[sub] = row["prfullname"].ToString();

                c.prepod_id[sub]   = (int)row["prepod_id"];
                c.prepod_name[sub] = row["prepn"].ToString();

                c.grupa_id[sub] = (int)row["grupa_id"];

                c.fakultet_id[sub] = (int)row["fakultet_id"];

                c.kurs_id[sub] = (int)row["kurs_id"];

                c.nom_zan[sub] = (int)row["nom_zan"];

                c.vid_zan_id[sub]    = (int)row["vid_zan_id"];
                c.vid_zan_name[sub]  = row["krat_name"].ToString();
                c.vid_full_name[sub] = row["vidname"].ToString();
                c.vid_delenie[sub]   = (bool)row["vid_del"];

                c.kabinet_id[sub] = (int)row["kabinet_id"];
                c.aud_name[sub]   = row["audn"].ToString();

                c.semestr_id[sub] = (int)row["semestr_id"];
                c.potok_id[sub]   = (int)row["potok_id"];

                c.delenie[sub]  = (bool)row["delenie"];
                c.tema[sub]     = row["tema"].ToString();
                c.str_prim[sub] = row["prim"].ToString();
                if (!row.IsNull("chas"))
                {
                    c.col_chas[sub] = (double)row["chas"];
                }
                else
                {
                    c.col_chas[sub] = 0.0;
                }


                if ((int)row["subgr_nomer"] == 0)
                {
                    c.copy_subgroups(sub, 1 - sub);
                }

                this[currdate, row["gn"].ToString( ), (int)row["nom_zan"]] = c;
            }
        }
Beispiel #42
0
        public response GetSpecificStoryDropdownStatus(int ID)
        {
            var dataTable = new System.Data.DataTable();

            dataTable = new System.Data.DataTable {
                TableName = "JakataMaster"
            };
            string connString = URLInfo.GetDataBaseConnectionString();


            System.IO.StringWriter writer = new System.IO.StringWriter();
            string   returnString         = "";
            response response             = new response();

            response.result = 0;
            using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(connString))
            {
                using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("GetSpecificStoryDropdownStatus", con))
                {
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.Parameters.Add("@StoryImported", System.Data.SqlDbType.NVarChar).Value = ID;
                    con.Open();
                    var dataReader = cmd.ExecuteReader();
                    dataTable.Load(dataReader);
                    dataTable.WriteXml(writer, System.Data.XmlWriteMode.WriteSchema, false);
                    returnString = writer.ToString();
                    int numberOfRecords = dataTable.Rows.Count;
                    response.result = numberOfRecords;

                    //JakataMasterList list = new JakataMasterList();
                    //foreach (DataRow row in dataTable.Rows)
                    //{
                    //    jakataMaster myprod = new jakataMaster();
                    //    myprod.ID = row["JakataID"].ToString();
                    //    myprod.Title = row["Title"].ToString();


                    //    list.jakataMasterLists.Add(myprod);
                    //}


                    ToDoList list = new ToDoList();
                    foreach (System.Data.DataRow row in dataTable.Rows)
                    {
                        toDo myprod = new toDo();
                        myprod.ID    = row["JakataID"].ToString();
                        myprod.Title = row["Title"].ToString();


                        list.toDoLists.Add(myprod);
                    }
                    //response.AddJakataMasterList(list);
                    response.AddToDoList(list);
                    //response.AddToDoList(list);



                    response.log.Add(numberOfRecords + " Records found");
                }
            }
            return(response);
        }
Beispiel #43
0
        private void ExportResults()
        {
            //SS:01/03/2018:2018-R1:ABSEXCH-19796: When Running the ExchDVT.exe, SQL Admin Passwords are visible in dump file.
            ADODB.Connection conn = new ADODB.Connection();
            ADODB.Command    cmd  = new ADODB.Command();

            if (CompanyCode == null)
            {
                cmd.CommandText = "SELECT [IntegrityErrorNo]" +
                                  ", [IntegrityErrorCode]" +
                                  ", [Severity]" +
                                  ", [IntegrityErrorMessage]" +
                                  ", [IntegritySummaryDescription]" +
                                  ", [SchemaName]" +
                                  ", [TableName]" +
                                  ", [PositionId]" +
                                  "FROM [common].[SQLDataValidation] ";
            }
            else
            {
                cmd.CommandText = "SELECT [IntegrityErrorNo]" +
                                  ", [IntegrityErrorCode]" +
                                  ", [Severity]" +
                                  ", [IntegrityErrorMessage]" +
                                  ", [IntegritySummaryDescription]" +
                                  ", [SchemaName]" +
                                  ", [TableName]" +
                                  ", [PositionId] " +
                                  "FROM [common].[SQLDataValidation] " +
                                  "WHERE SchemaName = '" + CompanyCode + "'";
            }

            cmd.CommandTimeout = 10000;

            if (conn.State == 0)
            {
                if (ConnPassword.Trim() == "")
                {
                    conn.Open();
                }
                else
                {
                    conn.Open(ExchequerCommonSQLConnection, "", ConnPassword.Trim(),
                              (int)ADODB.ConnectModeEnum.adModeUnknown);
                }
            }
            conn.CursorLocation = ADODB.CursorLocationEnum.adUseClient;

            System.Data.DataTable dataTable = new System.Data.DataTable {
                TableName = "resultSet"
            };

            try
            {
                cmd.CommandType      = ADODB.CommandTypeEnum.adCmdText;
                cmd.ActiveConnection = conn;
                ADODB.Recordset recordSet = null;
                object          objRecAff;
                recordSet = (ADODB.Recordset)cmd.Execute(out objRecAff, Type.Missing, (int)ADODB.CommandTypeEnum.adCmdText);

                System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter();
                adapter.Fill(dataTable, recordSet);

                if (conn.State == 1)
                {
                    conn.Close();
                }
            }
            catch
            {
                throw;
            }

            Type officeType = Type.GetTypeFromProgID("Excel.Application");

            if (officeType == null)
            {
                //no Excel installed
                SaveFileDialog.Filter           = "XML File | *.xml";
                SaveFileDialog.InitialDirectory = ExchequerPath + "\\Logs";
                SaveFileDialog.DefaultExt       = "XML";
                SaveFileDialog.OverwritePrompt  = true;
                SaveFileDialog.FileName         = "ExchSQLDataValidationResults";
                if (CompanyCode != null)
                {
                    SaveFileDialog.FileName = SaveFileDialog.FileName + "-" + CompanyCode;
                }
                SaveFileDialog.ShowDialog();
                this.UseWaitCursor = true;

                txtCompanyName.Enabled  = false;
                txtContactName.Enabled  = false;
                txtEmailAddress.Enabled = false;
                btnSaveResults.Enabled  = false;
                System.Windows.Forms.Application.DoEvents();

                XmlTextWriter writer = new XmlTextWriter(@SaveFileDialog.FileName, null);
                writer.WriteStartDocument(true);
                writer.Formatting = Formatting.Indented;

                writer.WriteStartElement("SQLDataValidationResults");

                writer.WriteStartElement("CompanyName");
                writer.WriteString(txtCompanyName.Text);
                writer.WriteEndElement();

                writer.WriteStartElement("ContactName");
                writer.WriteString(txtContactName.Text);
                writer.WriteEndElement();

                writer.WriteStartElement("EmailAddress");
                writer.WriteString(txtEmailAddress.Text);
                writer.WriteEndElement();

                writer.WriteStartElement("VersionInfo");
                writer.WriteString(VersionInfo);
                writer.WriteEndElement();

                dataTable.WriteXml(writer);

                writer.WriteEndDocument();

                writer.Close();
            }
            else
            {
                //Excel installed
                SaveFileDialog.Filter           = "Excel File | *.xlsx";
                SaveFileDialog.InitialDirectory = ExchequerPath + "\\Logs";
                SaveFileDialog.DefaultExt       = "XLSX";
                SaveFileDialog.OverwritePrompt  = true;
                SaveFileDialog.FileName         = "ExchSQLDataValidationResults";
                if (CompanyCode != null)
                {
                    SaveFileDialog.FileName = SaveFileDialog.FileName + "-" + CompanyCode;
                }
                SaveFileDialog.ShowDialog();

                this.UseWaitCursor = true;

                txtCompanyName.Enabled  = false;
                txtContactName.Enabled  = false;
                txtEmailAddress.Enabled = false;
                btnSaveResults.Enabled  = false;
                System.Windows.Forms.Application.DoEvents();

                clsExcelUtlity obj = new Data_Integrity_Checker.clsExcelUtlity();

                obj.WriteDataTableToExcel(dataTable, "ExchSQL Data Validation Results", SaveFileDialog.FileName, txtCompanyName.Text, txtContactName.Text, txtEmailAddress.Text, VersionInfo);
            }

            this.UseWaitCursor = false;
            dataTable          = null;

            Close();
        }