WriteXmlSchema() public method

Writes the structure as an XML schema to using the specified object.
public WriteXmlSchema ( Stream stream ) : void
stream Stream A object used to write to a file.
return void
Beispiel #1
1
        private void CreateSchema()
        {
            _ds = new DataSet("VehiclesRepairs");

            var vehicles = _ds.Tables.Add("Vehicles");
            vehicles.Columns.Add("VIN", typeof(string));
            vehicles.Columns.Add("Make", typeof(string));
            vehicles.Columns.Add("Model", typeof(string));
            vehicles.Columns.Add("Year", typeof(int));
            vehicles.PrimaryKey = new DataColumn[] { vehicles.Columns["VIN"] };

            var repairs = _ds.Tables.Add("Repairs");
            var pk = repairs.Columns.Add("ID", typeof(int));
            pk.AutoIncrement = true;
            pk.AutoIncrementSeed = -1;
            pk.AutoIncrementStep = -1;
            repairs.Columns.Add("VIN", typeof(string));
            repairs.Columns.Add("Description", typeof(string));
            repairs.Columns.Add("Cost", typeof(decimal));
            repairs.PrimaryKey = new DataColumn[] { repairs.Columns["ID"] };

            _ds.Relations.Add(
                "vehicles_repairs",
                vehicles.Columns["VIN"],
                repairs.Columns["VIN"]);

            _ds.WriteXmlSchema(_xsdFile);
        }
Beispiel #2
1
        public static void SaveDataSetAsXml(DataSet set, string fileName)
        {
            string file = Regex.Replace( fileName, extPattern, fileName );
             fileName = VerifyFileExt( fileName, ".xml" );

             set.WriteXml( fileName );
             set.WriteXmlSchema( file + ".xsd" );
        }
Beispiel #3
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 #4
1
 /// <summary>
 /// Creates XSD schema for Hydromet MCF
 /// Loads MCF csv files into strongly typed DataSet
 /// </summary>
 public static void CreateMcfDataSet(string path)
 {
     DataSet ds = new DataSet("McfDataSet");
     foreach (var item in tableNames)
     {
         string fn = Path.Combine(path, item + ".csv");
         var csv = new CsvFile(fn);
         csv.TableName = item+"mcf";
         ds.Tables.Add(csv);
     }
     ds.WriteXml(Path.Combine(path,"mcf.xml"));
     ds.WriteXmlSchema(Path.Combine(path, "mcf.xml"));
 }
Beispiel #5
0
        static void Main(string[] args)
        {
            var connectionString = ConfigurationManager.ConnectionStrings["Nordwind"].ConnectionString;
            var selectStatement = "SELECT * FROM Categories";
            using (SqlConnection connection = new SqlConnection(connectionString)) {
                using (SqlCommand command = new SqlCommand(selectStatement)) {
                    command.Connection = connection;
                    SqlDataAdapter adapter = new SqlDataAdapter(command);
                    DataSet ds = new DataSet();
                    connection.Open();
                    adapter.Fill(ds, "Categories");
                    ds.WriteXml("ds.xml"); // Save this DataSet as XML
                    ds.WriteXmlSchema("ds.xsd");
                    ds.Clear();

                    ds.ReadXml("ds.xml");
                    DataTable categories = ds.Tables["Categories"];
                    foreach(DataRow item in categories.Rows)
                    {
                        Console.WriteLine("id: {0},    {1} {2}:",
                            item["CategoryID"],
                            item["CategoryName"],
                            item["Description"]);
                    }
                    Console.ReadLine();
                }
            }
        }
Beispiel #6
0
        public static Stream BuildRDLCStream(
            DataSet data, string name, string reportResource)
        {
            using (MemoryStream schemaStream = new MemoryStream())
            {
                // save the schema to a stream
                data.WriteXmlSchema(schemaStream);
                schemaStream.Seek(0, SeekOrigin.Begin);

                // load it into a Document and set the Name variable
                XmlDocument xmlDomSchema = new XmlDocument();
                xmlDomSchema.Load(schemaStream);
                xmlDomSchema.DocumentElement.SetAttribute("Name", data.DataSetName);

                // Prepare XSL transformation
                using (var sr = new StringReader(reportResource))
                using (var xr = XmlReader.Create(sr))
                {
                    // load the report's XSL file (that's the magic)
                    XslCompiledTransform xform = new XslCompiledTransform();
                    xform.Load(xr);

                    // do the transform
                    MemoryStream rdlcStream = new MemoryStream();
                    XmlWriter writer = XmlWriter.Create(rdlcStream);
                    xform.Transform(xmlDomSchema, writer);
                    writer.Close();
                    rdlcStream.Seek(0, SeekOrigin.Begin);

                    // send back the RDLC
                    return rdlcStream;
                }
            }
        }
        public void challanout()
        {
            DataTable dt = new DataTable("challandt");
            dt = (DataTable)Session["challanout_dt"];

            DataSet ds = new DataSet();
            Viewer.Report.ChallanOutrpt crystalReport = new Report.ChallanOutrpt();
            string st = HttpContext.Current.Server.MapPath("~/ChallanOutCrpt1.rpt");

            //  Label1.Text = st;
            //   Response.Write(string.Format("<script language='javascript' type='text/javascript'>alert( "+st+") </script>"));

            crystalReport.Load(st);
            if (ds.Tables.Contains("challandt") == true)
            {
                ds.Tables.Remove("challandt");
            }
            ds.Tables.Add(dt);

            ds.WriteXmlSchema(HttpContext.Current.Server.MapPath("~/App_Data/Challanout.xml"));

            crystalReport.SetDataSource(dt);
            CrystalReportViewer1.ReportSource = crystalReport;

            crystalReport.ExportToHttpResponse
               (CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, Response, true, "CHALLANOUTSHEET");
        }
Beispiel #8
0
        static void Main()
        {
            DataSet paymentRecord = new DataSet("PaymentSet");

            DataTable customers = paymentRecord.Tables.Add ( "Customers" );
            DataColumn customersId = customers.Columns.Add ( "Id", typeof (Guid) );
            customers.Columns.Add ( "FirstName", typeof (String) );
            customers.Columns.Add("LastName", typeof(String));
            customers.Columns.Add("MiddleName", typeof(String));
            customers.Columns.Add("Number", typeof(String));
            customers.PrimaryKey = new []{customersId};

            DataTable payments = paymentRecord.Tables.Add ( "Payments" );
            DataColumn paymentsId = payments.Columns.Add ( "Id", typeof (Guid) );
            payments.Columns.Add ( "PaymentDate", typeof (DateTime) );
            payments.Columns.Add ( "MonthPaid", typeof (DateTime) );
            payments.Columns.Add ( "Amount", typeof (decimal) );
            payments.Columns.Add ( "Rate", typeof (decimal) );
            DataColumn custIdForeign = payments.Columns.Add ( "CustomerId", typeof (Guid) );
            payments.PrimaryKey = new [] { paymentsId };

            paymentRecord.Relations.Add ( "CustomerIdForeignKey", customersId, custIdForeign );

            StreamWriter writer = new StreamWriter ( "PaymentSet.xsd" );
            paymentRecord.WriteXmlSchema ( writer );
            writer.Close();
        }
Beispiel #9
0
    private void button1_Click(object sender, EventArgs e)
    {
        string connectString = "Server=.\\SQLExpress;Database=adventureworkslt;Trusted_Connection=Yes";
      //create a dataset
			DataSet ds = new DataSet("XMLProducts");
			//connect to the pubs database and 
			//select all of the rows from products table

			SqlConnection conn = new SqlConnection(connectString);
            SqlDataAdapter da = new SqlDataAdapter("SELECT Name, StandardCost FROM SalesLT.Product", conn);
			da.Fill(ds, "Products");

      ds.Tables[0].Rows[0]["Name"] = "NewName";
      DataRow dr = ds.Tables[0].NewRow();
      dr["Name"] = "Unicycle";
      dr["StandardCost"] = "45.00";
      
      ds.Tables[0].Rows.Add(dr);
      ds.WriteXmlSchema("products.xdr");
      ds.WriteXml("proddiff.xml", XmlWriteMode.DiffGram);

      webBrowser1.Navigate(AppDomain.CurrentDomain.BaseDirectory + "/proddiff.xml");
      
      
      //load data into grid
			dataGridView1.DataSource = ds.Tables[0];
      
    }
Beispiel #10
0
        static void Main(string[] args)
        {
            DataSet ds = new DataSet();
           
            DataTable tablDrivers = CreateTableDrivers(); 

            DataTable tablCars = CreateTableCar();

            ds.Tables.AddRange(new[] { tablDrivers, tablCars });

            // создание отношения между таблицами Drivers и Cars
            DataRelation relation = new DataRelation("FK_DriversCars", // имя отношения 
                                         tablDrivers.Columns["Id"],    // поле родительской таблицы
                                         tablCars.Columns["IdDriver"], // поле дочерней таблицы
                                         false);                        // создавать/не создавать ограничения
            
            // после созания ограничения его нужно добавить в коллекцию Relations 
            // объекта DataSet, в которой содержаться таблицы
            // без этого шага отношение не будет работать
            ds.Relations.Add(relation);



            Console.WriteLine("Вывод информации через дочерние строки ");
            foreach (DataRow driverRow in tablDrivers.Rows)
            {
                Console.WriteLine(" Владелец: {0}", driverRow["Name"]);
                Console.WriteLine(" Автомобили: ");
                // метод GetChaildRows получает дочерние строки в виде массива DataRow[]
                foreach (DataRow carsRow in driverRow.GetChildRows(relation))
                {
                    Console.WriteLine("{0} {1}", carsRow["Name"], carsRow["Price"]);
                }
            }



            Console.WriteLine("Вывод информации через родительские строки ");
            foreach (DataRow carsRow in tablCars.Rows)
            {
                Console.Write(" Атомобиль: {0} {1}", carsRow["Name"], carsRow["Price"]);
                Console.Write(" Владелец: ");
                // метод GetParrentRow возвращает родительские строки в виде массива DataRow[]
                foreach (DataRow driverRow in carsRow.GetParentRows(relation))
                {
                    Console.WriteLine("{0}", driverRow["Name"]);
                }
            }
           

            ds.WriteXmlSchema("Registration.xsd");
            ds.WriteXml("Registration.xml");

            Console.ReadKey();
        }
        private void WriteSchema()
        {
            DataSet ds = new DataSet();
              StringBuilder sb = new StringBuilder(1024);

              ds.ReadXml(AppConfig.GetEmployeesFile());

              ds.WriteXml(AppConfig.XmlFile);
              ds.WriteXmlSchema(AppConfig.XsdFile);

              txtResult.Text = File.ReadAllText(AppConfig.XsdFile);
        }
Beispiel #12
0
        static void Main()
        {
            string strConn = "Data Source=localhost;Initial Catalog=booksourcedb;Integrated Security=True";
              string strSql = "SELECT * FROM book";
              SqlDataAdapter dataAdapter = new SqlDataAdapter(strSql, strConn);

              DataSet dataSet = new DataSet("booklist");
              dataAdapter.Fill(dataSet, "book");

              dataSet.WriteXml(@"C:\Temp\booklist.xml");
              dataSet.WriteXmlSchema(@"C:\Temp\booklist.xsd");
        }
 public static string Generate(DataSet dataSet, CodeNamespace codeNamespace, CodeDomProvider codeProvider)
 {
     if (codeProvider == null)
     {
         throw new ArgumentNullException("codeProvider");
     }
     if (dataSet == null)
     {
         throw new ArgumentException(System.Design.SR.GetString("CG_DataSetGeneratorFail_DatasetNull"));
     }
     StringWriter writer = new StringWriter(CultureInfo.CurrentCulture);
     dataSet.WriteXmlSchema(writer);
     return Generate(writer.GetStringBuilder().ToString(), null, codeNamespace, codeProvider);
 }
        public void hacer_report(String idcomprobante)
        {
            ParameterDiscreteValue parametro=new ParameterDiscreteValue();
            ParameterFields paramlist = new ParameterFields();

            DataSet ds = new DataSet("comprobante");
            db.ejecutar("select envnumcomprobante,envfecha_registro,if(clitipo=0,(select concat(natnombres,' ',natapellidos) from ste_clinatural where idclinatural=idcliente),(select jurrazonsocial from ste_clijuridico where idste_clijuridico=idcliente)) as nomcliente, cliruc, envdestinatario, envrucdestinatario, envdireccion_destino,envdireccion_origen,'" + this.txtrucremitente.Text + "' as rucremitente, ste_envio.gremision from ste_envio inner join ste_cliente on ste_envio.envidcliente=ste_cliente.idcliente where idenvio=" + idcomprobante);
            ds.Tables.Add(db.gettabla());
            db.ejecutar("select * from ste_detalleenvio where denidenvio=" + idcomprobante);
            ds.Tables.Add(db.gettabla());
            db.ejecutar("select * from ste_camionero inner join ste_unidad on ste_unidad.uniidcamionero=ste_camionero.idcamionero where ste_unidad.idunidad=" + this.cbunidad.SelectedIndex);
            ds.Tables.Add(db.gettabla());
            ds.WriteXmlSchema("./comprobante.xml");
            CrystalDecisions.CrystalReports.Engine.ReportClass rpt;
            switch (cmbtipcomprobante.SelectedIndex)
            {
                case 0://boleta
                    rpt = new reportes.boletadeventa();
                    break;
                case 1://factura
                    rpt = new reportes.factura();
                    double subt=0;
                    foreach (DataRow r in ds.Tables[1].Rows) {
                        subt +=Double.Parse(r["dencantidad"].ToString()) * Double.Parse(r["denpreciounitario"].ToString());
                        //subt += ((Double)r["dencantidad"]) * ((Double)r["denpreciounitario"]);
                    }
                    parametro.Value = aletras(subt.ToString(),true);
                    paramlist.Add("enletras", ParameterValueKind.StringParameter, DiscreteOrRangeKind.DiscreteValue).CurrentValues.Add(parametro);
                    break;
                default://orden de despacho
                    rpt = new reportes.ordendedespacho();
                    break;
            }
            rpt.SetDataSource(ds);
            //FACTURA
            formularios.Imprimir frmr = new formularios.Imprimir(rpt);
            frmr.crystalReportViewer1.ParameterFieldInfo = paramlist;
            frmr.ShowDialog(this);
            //GUIA DE REMISION
            if (cmbtipcomprobante.SelectedIndex==1)
            {
                rpt = new reportes.guiaderemision();
                rpt.SetDataSource(ds);
                frmr = new formularios.Imprimir(rpt);
                //frmr.crystalReportViewer1.ParameterFieldInfo = paramlist;
                frmr.ShowDialog(this);
            }
        }
Beispiel #15
0
        public static Boolean GuardarEsquemaXML(System.Data.DataSet ds)
        {
            Boolean todoOK = true;

            try
            {
                ds.WriteXmlSchema(AppDomain.CurrentDomain.BaseDirectory +
                                  "\\XmlDataSetSchema.xml");
            }
            catch (Exception)
            {
                todoOK = false;
            }

            return(todoOK);
        }
Beispiel #16
0
 private void PrintDebitNote(int billid)
 {
     //theReportHeading = "Upcoming ARV Pickup Report";
     string theReportSource = string.Empty;
     theReportSource = "rptPatientDebitNote.rpt";
     IPatientHome PatientManager;
     PatientManager =
         (IPatientHome)
         ObjectFactory.CreateInstance("BusinessProcess.Clinical.BPatientHome, BusinessProcess.Clinical");
     System.Data.DataSet dataTable = PatientManager.GetPatientDebitNoteDetails(billid, Convert.ToInt32(Session["PatientId"]));
     dataTable.WriteXmlSchema(Server.MapPath("..\\XMLFiles\\PatientDebitNote.xml"));
     ReportDocument rptDocument = new ReportDocument();
     rptDocument.Load(Server.MapPath(theReportSource));
     rptDocument.SetDataSource(dataTable);
     rptDocument.SetParameterValue("BillId", billid.ToString());
     rptDocument.SetParameterValue("Currency", theCurrency.ToString());
     rptDocument.SetParameterValue("FacilityName", Session["AppLocation"].ToString());
     rptDocument.ExportToDisk(ExportFormatType.PortableDocFormat, Server.MapPath("..\\ExcelFiles\\DebitNote.pdf"));
 }
Beispiel #17
0
        private void CargarData()
        {
            DataTable project = new DataTable("Project");

            dataSet = new DataSet();
            dataSet.Tables.Add(project);

            project.Columns.Add("Id", typeof(int));
            project.Columns.Add("ParentId", typeof(int));
            project.Columns.Add("Name", typeof(string));

            project.Rows.Add(0, DBNull.Value, "Sellout");
            project.Rows.Add(1, 0, "Proceso de Importacion");
            project.Rows.Add(2, 1, "Importacion de Sellout");
            project.Rows.Add(3, 1, "Importacion de Clientes");

            project.Rows.Add(4, 0, "Proceso de Calculos");
            project.Rows.Add(5, 4, "Calculos de ABC");
            project.Rows.Add(6, 4, "Calculos de Oportunidades");
            project.Rows.Add(7, 4, "Calculos de KPIs");

            project.Rows.Add(8, 0, "Mantenimientos de Datos");
            project.Rows.Add(10, 8, "Clientes");
            project.Rows.Add(11, 8, "Agrupacion de Clientes");
            project.Rows.Add(12, 8, "Master de Productos KC");
            project.Rows.Add(13, 8, "Productos Equivalentes");
            project.Rows.Add(14, 8, "Agrupoacion de Productos");
            project.Rows.Add(15, 8, "Distribuidores");
            project.Rows.Add(16, 8, "KAMs");
            project.Rows.Add(17, 8, "Pais");
            project.Rows.Add(18, 8, "Segmentos");
            project.Rows.Add(19, 8, "Nuevos Segmentos");
            project.Rows.Add(20, 8, "Conglomerados");
            project.Rows.Add(21, 8, "Cuentas Globales");

            project.Rows.Add(22, DBNull.Value, "Sellin");

            project.Rows.Add(26, DBNull.Value, "MKTOOLS");

            dataSet.WriteXml(@"source.xml");
            dataSet.WriteXmlSchema(@"XMLSchema.xsd");
        }
        /// <summary>
        /// Creates a schema file from an xmldocument file
        /// </summary>
        /// <param name="sXmlFilePath"></param>
        /// <returns></returns>
        public static string CreateXmlSchema(string sXmlFilePath)
        {
            string sXmlSchemaPath = FileUtilities.GetUniqueTempFileName();

            try
            {
                DataSet dsXmlDoc = new DataSet();
                dsXmlDoc.ReadXml(sXmlFilePath);
                dsXmlDoc.WriteXmlSchema(sXmlSchemaPath);

                dsXmlDoc.Clear();
                dsXmlDoc = null;
            }
            catch (Exception ex)
            {
                throw new Exception("CreateXmlSchema", ex);
            }

            return sXmlSchemaPath;
        }
        /// <summary>
        /// constructs a simple report RDLC file based on a DataSet
        /// </summary>
        /// <param name="data"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string BuildRDLC(DataSet data, string name)
        {
            // establish some file names
            string virtualXslt = "xslt/rdlc.xsl";
            string virtualRdlc = "rdlc/" + name + ".rdlc";
            string virtualSchema = "rdlc/" + name + ".schema";

            // set the NAME on the DataSet
            // this may or may not be necessary, but the RDLC and DataSet
            // will both have the same name if this is done.
            data.DataSetName = name;

            // write the DataSet Schema to a file
            // we should be passing a DataSet with only one DataTable
            // the rdlc.xsl does not account for multiple DataTables
            string physicalSchema = HttpContext.Current.Server.MapPath(virtualSchema);
            data.WriteXmlSchema(physicalSchema);

            // load the DataSet schema in a DOM
            XmlDocument xmlDomSchema = new XmlDocument();
            xmlDomSchema.Load(physicalSchema);

            // append the NAME to the schema DOM
            // this is so we can pick it up in the rdlc.xsl
            // and use it
            xmlDomSchema.DocumentElement.SetAttribute("Name", name + "_Table");

            // transform the Schema Xml with rdlc.xsl
            string physicalXslt = HttpContext.Current.Server.MapPath(virtualXslt);
            string xml = HRWebsite.General.TransformXml(xmlDomSchema.OuterXml, physicalXslt);

            // save off the resultng RDLC file
            string physicalRdlc = HttpContext.Current.Server.MapPath(virtualRdlc);
            XmlDocument xmlDomRdlc = new XmlDocument();
            xmlDomRdlc.LoadXml(xml);
            xmlDomRdlc.Save(physicalRdlc);

            // return the virtual path of the RDLC file
            // this is needed by the asp:ReportViewer
            return virtualRdlc;
        }
        public void TestAsTsql()
        {
            var testItems = NoFuture.Hbm.Sorting.AllStoredProx;
            Assert.IsNotNull(testItems);
            Assert.AreNotEqual(0, testItems.Count);

            var testItem = testItems[testItems.Keys.First()];
            Assert.AreNotEqual(0, testItem.Parameters.Count);

            using (var conn = new SqlConnection("Server=localhost;Database=Whatever;Trusted_Connection=True;"))
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    using (var da = new SqlDataAdapter(cmd))
                    {
                        foreach (var ti in testItems.Keys)
                        {
                            var ds = new DataSet(ti);
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.Parameters.Clear();
                            testItems[ti].AssignSpParams(cmd.Parameters);
                            cmd.CommandText = ti;
                            cmd.CommandTimeout = 800;
                            da.Fill(ds);

                            if (ds.Tables.Count <= 0)
                                continue;

                            ds.Tables[0].TableName = "Results";

                            ds.WriteXmlSchema(
                                string.Format(@"C:\Projects\31g\trunk\Code\NoFuture.Tests\Hbm\TestFiles\{0}.xsd",
                                    ti));
                        }
                    }
                }
                conn.Close();
            }
        }
 public static string xmlCreateXSD(this string xml)
 {
     try
     {
         "Creating XSD from XML".info();
         var dataSet = new DataSet();
         dataSet.ReadXml(xml.xmlReader());
         var stringWriter = new StringWriter();
         XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
         xmlTextWriter.Formatting = Formatting.Indented;
         xmlTextWriter.field("encoding", new UTF8Encoding());	//DC: is there another to set this
         //xmlTextWriter.WriteStartDocument();
         dataSet.WriteXmlSchema(xmlTextWriter);
         xmlTextWriter.Close();
         stringWriter.Close();
         return stringWriter.ToString();
     }
     catch (Exception ex)
     {
         ex.log("in createXSDfromXmlFile");
         return "";
     }
 }
        private void CreateSchema(string dataSetName = "VehicleRepair")
        {
            ds = new DataSet(dataSetName);

            DataTable vehicles = ds.Tables.Add("Vehicles");
            DataColumn plate = vehicles.Columns.Add("Plate");
            plate.Unique = true;
            vehicles.Columns.Add("Manufacturer");
            vehicles.Columns.Add("Model");
            vehicles.Columns.Add("Year", typeof(int));
            vehicles.PrimaryKey = new DataColumn[] { plate };

            DataTable repairs = ds.Tables.Add("Repairs");
            DataColumn id = repairs.Columns.Add("ID", typeof(int));
            id.AutoIncrement = true;
            id.AutoIncrementSeed = -1;
            id.AutoIncrementStep = -1;
            DataColumn vPlate = repairs.Columns.Add("VehiclePlate");
            repairs.Columns.Add("Description");
            repairs.Columns.Add("Cost");
            repairs.PrimaryKey = new DataColumn[] { id };

            ds.Relations.Add(
                "Vehicles_Repairs",
                plate,
                vPlate);

            ds.WriteXmlSchema(schemaFile);

            vehicles.Rows.Add("ABC123", "Ford", "Gran Torino", 1972);
            vehicles.Rows.Add("DEF456", "Dodge", "Challenger", 1969);
            repairs.Rows.Add(null, "ABC123", "Oil replaced", (decimal)10.00);
            repairs.Rows.Add(null, "ABC123", "Front lights replaced", (decimal)25.00);
            repairs.Rows.Add(null, "DEF456", "Engine cleaned", (decimal)30.00);

            ds.WriteXml(xmlFile);
        }
 protected internal virtual void btnReport_Click(object sender, EventArgs e)
 {
     if (dgvDataShow.Rows.Count - 1 > 0)
     {
         Main.PGB pgb = new Main.PGB();
         pgb.progressBar1.Style = ProgressBarStyle.Marquee;
         pgb.progressBar1.MarqueeAnimationSpeed = 2000;
         pgb.Text = "啟動報表";
         pgb.label1.Text = "報表啟動中.....請稍候";
         pgb.Show();
         Application.DoEvents();
         DataSet insert = new DataSet();
         srcDataMergeDefect();
         insert.Tables.Add(mergeData);
         insert.WriteXmlSchema("TEMP.xml");
         try
         {
             DevelopmentProductDailyReportLF report = new DevelopmentProductDailyReportLF();
             report.SetDataSource(insert);
             rtpDevelopmentProduct rptdlp = new rtpDevelopmentProduct();
             rptdlp.crystalReportViewer1.ReportSource = report;
             rptdlp.Show();
             pgb.Dispose();
         }
         catch (Exception ex)
         {
             sysMessage.SystemEx(ex.Message);
         }
     }
     else
     {
         sysMessage.NoData();
     }
 }
Beispiel #24
0
        private void RecreateDatabase()
        {
            var context = new MvcSolutionDataContext();
            var sql =
                @"
            USE MASTER
            DECLARE @i INT
            SELECT   @i=1
            DECLARE @sSPID VARCHAR(100)
            DECLARE KILL_CUR SCROLL CURSOR FOR
            SELECT SPID FROM sysprocesses WHERE DBID=DB_ID('MvcSolution')
            OPEN KILL_CUR
            IF @@CURSOR_ROWS=0 GOTO END_KILL_CUR
            FETCH FIRST FROM KILL_CUR INTO @sSPID
            EXEC('KILL   '+@sSPID)
            WHILE @i<@@CURSOR_ROWS
            BEGIN
            FETCH NEXT FROM KILL_CUR INTO @sSPID
            EXEC('KILL '+@sSPID)
            SELECT @i=@i+1
            END
            END_KILL_CUR:
            CLOSE KILL_CUR
            DEALLOCATE KILL_CUR";
            if (context.Database.Exists())
            {
                try
                {
                    context.Database.ExecuteSqlCommand(sql);
                }
                catch (Exception)
                {
                }
            }
            context.Database.Delete();
            context.Database.Create();

            var connection = new SqlConnection(this.ConnectionString);
            connection.Open();

            var contextType = typeof(MvcSolutionDataContext);
            var excludedTables = new string[] { };
            var additionTables = new string[] { };
            var tables = contextType.GetProperties()
                .Where(x => x.PropertyType.Name == "DbSet`1" && x.CanWrite)
                .Select(p => p.Name)
                .ToList();
            tables.RemoveAll(excludedTables.Contains);
            tables.AddRange(additionTables);

            var ds = new DataSet("MvcSolutionSchema");
            ds.Namespace = "http://tempuri.org/MvcSolutionSchema.xsd";
            ds.ExtendedProperties.Add("targetNamespace", ds.Namespace);
            foreach (var table in tables)
            {
                var adapter = new SqlDataAdapter("select * from " + table, connection);
                adapter.FillSchema(ds, SchemaType.Mapped, table);
            }
            ds.WriteXmlSchema("../../MvcSolutionSchema.xsd");
            connection.Close();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Session[Authenticate.CALLER_URL] = null;
            dsReport = new SimplicityDBSchema();
            dsTempReport = new DataSet();

            if (Request["environment"] != null) //request for page environment
            {
                RequestedEnvironment = Request["environment"];
            }
            else
                RequestedEnvironment = Authenticate.PRODUCTION; //put production in requested Environment

            errorLabel.Text = "";
            //if (Request["environment"].CompareTo("SANDBOX") == 0)
            if (SchemaUtilty.isDebugMode)
                TextBox1.Visible = true;

            try
            {
                dir = new System.IO.DirectoryInfo(path); //dir k ander reports ka path rakh day ga
                if (!dir.Exists)
                    dir.Create();

                dirSchema = new System.IO.DirectoryInfo(path + @"\Upload"); //dir k ander reports ka path rakh day ga
                if (!dirSchema.Exists)
                    dirSchema.Create();

            }
            catch (Exception ex)
            {
                TextBox1.Text += "\n" + ex.Message;
            }

            TextBox1.Text += "\nOutside auth";
            auth = (AuthenticationObject)Session[Authenticate.ACCESS_TOKEN];//////Taking Authentication from Session
            if (auth != null && Session[Authenticate.AUTHENTICATED_ENVIRONMENT] != null && Session[Authenticate.AUTHENTICATED_ENVIRONMENT].ToString().CompareTo(RequestedEnvironment) == 0)////Check Authenticated and Environment
            {
                TextBox1.Text += "\nInside auth";
                reportType = Request[REPORT_TYPE];
                if (reportType != null && reportType.Length > 0)
                {
                    TextBox1.Text += "\nInside report Type " + reportType;
                    ReadXMLConfiguration(reportType);

                    if (reportsDict.ContainsKey(reportType))
                    {
                        Report report = reportsDict[reportType];
                        TextBox1.Text += "\nReport_TYPE " + reportType;

                        DataSet reportDataSet = new DataSet("SimplicityDBSchema");
                        for (int iterate = 0; iterate < report.Table.Count;iterate++ )
                        {
                            try
                            {
                                String table = report.Table[iterate];

                                var result = Regex.Matches(table, "##(.*?)##");
                                foreach (Match match in result)
                                {
                                    if (Request[match.Groups[1].Value] != null)
                                    {
                                        table = table.Replace("##" + match.Groups[1].Value + "##", Request[match.Groups[1].Value]);
                                    }
                                    else
                                    {
                                        error = true;
                                        ShowError("Missing report parameter " + match.Groups[1].Value);
                                        return;
                                    }

                                }

                                String tableName = report.TableName[iterate];
                                String tableRelation = report.TableRelation[iterate];
                                SchemaUtilty.CreateDataSet(Page.Server, path, auth, tableName, reportDataSet, TextBox1);
                                SchemaUtilty.PopulateDataSet(Page.Server, auth, tableRelation, tableName, reportDataSet, table, reportParameter, TextBox1);

                            }
                            catch (Exception ex)
                            {
                                TextBox1.Text += "\n" + ex.Message;
                                TextBox1.Text += "\n" + ex.StackTrace;
                            }

                        }

                        reportDataSet.WriteXmlSchema(dirSchema.FullName + @"\SimplicityDBSchema.xsd");

                            ReportDocument ReportDoc = new ReportDocument();
                            ReportDoc.Load(dir + "\\Reports\\" + report.RPTFileName);
                            ReportDoc.SetDataSource(reportDataSet);

                            MyCrystalReportViewer.ReportSource = ReportDoc;
                            MyCrystalReportViewer.RefreshReport();
                            MyCrystalReportViewer.Visible = true;
                            TextBox1.Text += "\n Reports Loaded ";
                       // }

                    }
                    else
                        ShowError("No report with type " + reportType + " is found");

                    //String folderPath = Environment.GetFolderPath(Environment.SpecialFolder.System);

                    //TextBox1.Text = Environment.CurrentDirectory.ToString();

                    //invoiceId = Request[INVOICE_ID];
                    //ReadXMLConfiguration();

                }
            }
            else
            {
                Session["environment"] = RequestedEnvironment;
                Session[Authenticate.ACCESS_TOKEN] = null;/////Assuring to Redirect Other Environment If Login Already
                Session[Authenticate.CALLER_URL] = HttpContext.Current.Request.Url.AbsoluteUri;
                Response.Redirect("~/Authenticate.aspx");
                //lblInvoice.Text = "no auth";
            }
        }
        private void Page_Load(object sender, System.EventArgs e)
        {
            connString = new StreamReader( @"\\" +
                System.Net.Dns.GetHostName() + @"\thepuzzler_3dstyle\dbconn.txt" );
            try
            {
                conn = new OleDbConnection( connString.ReadLine() );
                connString.Close();
                conn.Open();
                cmd = conn.CreateCommand();
                cmd.CommandText = "DROP TABLE puzzleRUN";
                int queryResult = cmd.ExecuteNonQuery();

                cmd = conn.CreateCommand();
                cmd.CommandText =
                    "CREATE TABLE puzzleRUN(" +
                    "ExecutionID timestamp UNIQUE NOT NULL," +
                    "Dictionary text NOT NULL," +
                    "Puzzle text NOT NULL," +
                    "WordsFound text NOT NULL," +
                    "DictionaryTime bigint NOT NULL," +
                    "PuzzleTime bigint NOT NULL," +
                    "SolutionTime bigint NOT NULL," +
                    "PRIMARY KEY(ExecutionID) );";
                queryResult = cmd.ExecuteNonQuery();

                dataAdapter = new OleDbDataAdapter( "SELECT * FROM puzzleRUN", conn );
                DataSet dataSet = new DataSet( "thepuzzler_3dstyleSchema" );
                dataAdapter.Fill( dataSet );
                dataSet.WriteXmlSchema( @"\\" + System.Net.Dns.GetHostName() +
                    @"\thepuzzler_3dstyle\ManageStatsWebService\puzzleRUN_DataSet.xsd" );
            }
            catch( System.Exception error )
            {
                Trace.Write( error.ToString() );
                StreamWriter wr = new StreamWriter("\\error.txt", false );
                wr.WriteLine( error.ToString() );
            }
            finally
            {
                connString.Close();
                conn.Close();
            }
        }
Beispiel #27
0
        private void Execute(ExportType exportType, string fileName)
        {
            // Make sure our server is connected...
            Dataphoria.EnsureServerConnection();

            using (var statusForm = new StatusForm(Strings.Exporting))
            {
                using (var connection = new DAEConnection())
                {
                    if (DesignerID == "SQL")
                    {
                        SwitchToSQL();
                    }
                    try
                    {
                        using (var adapter = new DAEDataAdapter(GetTextToExecute(), connection))
                        {
                            using (var dataSet = new DataSet())
                            {
                                var process =
                                    DataSession.ServerSession.StartProcess(new ProcessInfo(DataSession.ServerSession.SessionInfo));
                                try
                                {
                                    connection.Open(DataSession.Server, DataSession.ServerSession, process);
                                    try
                                    {
                                        switch (exportType)
                                        {
                                        case ExportType.Data:
                                            adapter.Fill(dataSet);
                                            dataSet.WriteXml(fileName, XmlWriteMode.IgnoreSchema);
                                            break;

                                        case ExportType.Schema:
                                            adapter.FillSchema(dataSet, SchemaType.Source);
                                            dataSet.WriteXmlSchema(fileName);
                                            break;

                                        default:
                                            adapter.Fill(dataSet);
                                            dataSet.WriteXml(fileName, XmlWriteMode.WriteSchema);
                                            break;
                                        }
                                    }
                                    finally
                                    {
                                        connection.Close();
                                    }
                                }
                                finally
                                {
                                    DataSession.ServerSession.StopProcess(process);
                                }
                            }
                        }
                    }
                    finally
                    {
                        if (DesignerID == "SQL")
                        {
                            SwitchFromSQL();
                        }
                    }
                }
            }
        }
Beispiel #28
0
		public void WriteXmlSchema_ConstraintNameWithSpaces ()
		{
			DataSet ds = new DataSet ();
			DataTable table1 = ds.Tables.Add ("table1");
			DataTable table2 = ds.Tables.Add ("table2");

			table1.Columns.Add ("col1", typeof (int));
			table2.Columns.Add ("col1", typeof (int));

			table1.Constraints.Add ("uc 1", table1.Columns [0], false);
			table2.Constraints.Add ("fc 1", table1.Columns [0], table2.Columns [0]);
			
			StringWriter sw = new StringWriter ();

			//should not throw an exception
			ds.WriteXmlSchema (sw);
		}
Beispiel #29
0
        ///	<summary>
        /// GenerateSchema a schema file from a given target file
        /// </summary>
        public bool GenerateSchema(string sTargetFile)
        {
            bool bResult = false;
            try
            {
                var data = new DataSet();
                data.ReadXml(new XmlNodeReader(RootNode), XmlReadMode.Auto);
                data.WriteXmlSchema(sTargetFile);
                bResult = true;
            }
            catch (Exception e)
            {
                HandleException(e);
            }

            return bResult;
        }
Beispiel #30
0
        ///	<summary>
        /// GenerateSchemaAsString based on the currently loaded Xml
        /// </summary>
        public string GenerateSchemaAsString()
        {
            string sSchemaXmlString = "";
            try
            {
                var data = new DataSet();
                data.ReadXml(new XmlNodeReader(RootNode), XmlReadMode.Auto);

                string sTempFile = Path.GetTempFileName();

                data.WriteXmlSchema(sTempFile);

                // read the data into a string
                var sr = new StreamReader(sTempFile);
                sSchemaXmlString = sr.ReadToEnd();
                sr.Close();

                if (File.Exists(sTempFile))
                    File.Delete(sTempFile);
            }
            catch (Exception e)
            {
                HandleException(e);
                sSchemaXmlString = "<root><error>" + LastErrorMessage + "</error></root>";
            }

            return sSchemaXmlString;
        }
Beispiel #31
0
		public void ReadWriteXmlSchema_Nested ()
		{
			DataSet ds = new DataSet ("dataset");
			ds.Tables.Add ("table1");
			ds.Tables.Add ("table2");
			ds.Tables[0].Columns.Add ("col");
			ds.Tables[1].Columns.Add ("col");
			ds.Relations.Add ("rel", ds.Tables [0].Columns [0],ds.Tables [1].Columns [0], true);
			ds.Relations [0].Nested = true;

			MemoryStream ms = new MemoryStream ();
			ds.WriteXmlSchema (ms);

			DataSet ds1 = new DataSet ();
			ds1.ReadXmlSchema (new MemoryStream (ms.GetBuffer ()));

			// no new relation, and <table>_Id columns, should get created when 
			// Relation.Nested = true
			Assert.AreEqual (1, ds1.Relations.Count, "#1");
			Assert.AreEqual (1, ds1.Tables [0].Columns.Count, "#2");
			Assert.AreEqual (1, ds1.Tables [1].Columns.Count, "#3");
		}
Beispiel #32
0
		[Test] public void WriteXmlSchema_Relations_ForeignKeys ()
		{
			System.IO.MemoryStream ms = null;
			System.IO.MemoryStream ms1 = null;

			DataSet ds1 = new DataSet();

			DataTable table1 = ds1.Tables.Add("Table 1");
			DataTable table2 = ds1.Tables.Add("Table 2");

			DataColumn col1_1 = table1.Columns.Add ("col 1", typeof (int));
			DataColumn col1_2 = table1.Columns.Add ("col 2", typeof (int));
			DataColumn col1_3 = table1.Columns.Add ("col 3", typeof (int));
			DataColumn col1_4 = table1.Columns.Add ("col 4", typeof (int));
			DataColumn col1_5 = table1.Columns.Add ("col 5", typeof (int));
			DataColumn col1_6 = table1.Columns.Add ("col 6", typeof (int));
			DataColumn col1_7 = table1.Columns.Add ("col 7", typeof (int));

			DataColumn col2_1 = table2.Columns.Add ("col 1", typeof (int));
			DataColumn col2_2 = table2.Columns.Add ("col 2", typeof (int));
			DataColumn col2_3 = table2.Columns.Add ("col 3", typeof (int));
			DataColumn col2_4 = table2.Columns.Add ("col 4", typeof (int));
			DataColumn col2_5 = table2.Columns.Add ("col 5", typeof (int));
			DataColumn col2_6 = table2.Columns.Add ("col 6", typeof (int));

			ds1.Relations.Add ("rel 1", 
				new DataColumn[] {col1_1, col1_2},
				new DataColumn[] {col2_1, col2_2});
			ds1.Relations.Add ("rel 2", 
				new DataColumn[] {col1_3, col1_4}, 
				new DataColumn[] {col2_3, col2_4},
				false);

			table1.Constraints.Add ("pk 1", col1_7, true);

			table2.Constraints.Add ("fk 1",
				new DataColumn[] {col1_5, col1_6},
				new DataColumn[] {col2_5, col2_6});

			ms = new System.IO.MemoryStream();
			ds1.WriteXmlSchema (ms);

			ms1 = new System.IO.MemoryStream (ms.GetBuffer());
			DataSet ds2 = new DataSet();
			ds2.ReadXmlSchema(ms1);
		
			Assert.AreEqual (2, ds2.Relations.Count, "#1");
			Assert.AreEqual (3, ds2.Tables [0].Constraints.Count, "#2");
			Assert.AreEqual (2, ds2.Tables [1].Constraints.Count, "#2");

			Assert.IsTrue (ds2.Relations.Contains ("rel 1"), "#3");
			Assert.IsTrue (ds2.Relations.Contains ("rel 2"), "#4");

			Assert.IsTrue (ds2.Tables [0].Constraints.Contains ("pk 1"), "#5");
			Assert.IsTrue (ds2.Tables [1].Constraints.Contains ("fk 1"), "#6");
			Assert.IsTrue (ds2.Tables [1].Constraints.Contains ("rel 1"), "#7");

			Assert.AreEqual (2, ds2.Relations ["rel 1"].ParentColumns.Length, "#8");
			Assert.AreEqual (2, ds2.Relations ["rel 1"].ChildColumns.Length, "#9");

			Assert.AreEqual (2, ds2.Relations ["rel 2"].ParentColumns.Length, "#10");
			Assert.AreEqual (2, ds2.Relations ["rel 2"].ChildColumns.Length, "#11");

			ForeignKeyConstraint fk = (ForeignKeyConstraint)ds2.Tables [1].Constraints ["fk 1"];
			Assert.AreEqual (2, fk.RelatedColumns.Length, "#12");
			Assert.AreEqual (2, fk.Columns.Length, "#13");
		}
Beispiel #33
0
        private void buttonOK_Click(object sender, System.EventArgs e)
        {
            string tableName = "Table";

            if (this.checkedListBoxTables.CheckedItems.Count == 0)
            {
                MessageBox.Show("No tables were selected to be added to the dataset.",
                    "Generate " + DATASETNAME_PREFIX);
                return;
            }
            string entry = this.checkedListBoxTables.CheckedItems[0].ToString();
            int i = entry.LastIndexOf(" (");
            if (i == -1)  // should never happen
                return;
            tableName = entry.Substring(0, i);

            DbDataAdapter adapter = GetDataAdapterClone( this.dbDataAdapter );
            if (adapter == null)  // return if badly configured adapter
                return;

            string dsName = "Table";
            if (this.radioButtonNew.Checked)
                dsName = this.textBoxNew.Text.Trim();
            else
            {
                string s = this.comboBoxExisting.Text;
                i = s.LastIndexOf('.');
                if (i == -1)
                    dsName = s.Trim();
                else
                    if (i < (s.Length-1))
                        dsName = s.Substring(i+1).Trim();
                    else
                        dsName = String.Empty;

            }

            if (dsName.Length == 0)
            {
                MessageBox.Show("Dataset name is invalid.",
                    "Generate " + DATASETNAME_PREFIX);
                return;
            }

            // make a DataSet that the DbAdapter can fill in
            DataSet ds = new DataSet(dsName);

            Cursor cursor = Cursor.Current;   // save cursor, probably Arrow
            Cursor.Current = Cursors.WaitCursor;  // hourglass cursor
            adapter.MissingSchemaAction = MissingSchemaAction.Add;
            adapter.MissingMappingAction=
                (this.dbDataAdapter.MissingMappingAction==
                    MissingMappingAction.Error)?
                MissingMappingAction.Ignore :
                this.dbDataAdapter.MissingMappingAction;
            try { adapter.FillSchema(ds, SchemaType.Mapped); }
            catch(Exception ex)
            {
                Cursor.Current = cursor;
                MessageBox.Show(ex.Message,
                    "Unable to generate " + DATASETNAME_PREFIX);
                return;
            }
            finally { Cursor.Current = cursor; } // restored Arrow cursor

            ds.Namespace = "http://www.tempuri.org/" + dsName+".xsd";

            // strip the useless MaxLength info that adds clutter to the XML
            foreach (DataTable dataTable in ds.Tables)
                for (int j=0; j<dataTable.Columns.Count; j++)
                {
                    DataColumn dataColumn = dataTable.Columns[j];
                    dataColumn.MaxLength = -1;
                }

            string fileName =
                System.IO.Path.Combine(currentProjectFullPath, dsName+".xsd");

            ds.WriteXmlSchema(fileName);  // write the ingresDataSetn.xsd file

            EnvDTE.ProjectItem projItem = null;
            if (this.radioButtonExisting.Checked)  // if  existing project item
            {
                i = this.comboBoxExisting.SelectedIndex;
                projItem =
                    (EnvDTE.ProjectItem)(this.existingDataSetProjectItems[i]);
            }
            else                                       // else new project item
            {
                projItem = currentProject.ProjectItems.AddFromFile(fileName);
                EnvDTE.Property pp;
                pp = projItem.Properties.Item("CustomTool");
                pp.Value = "MSDataSetGenerator";
            }

            VSLangProj.VSProjectItem vsprojItem =
                projItem.Object as VSLangProj.VSProjectItem;
            if (vsprojItem != null)
                vsprojItem.RunCustomTool();    // update the .cs or .vb file

            if (!this.checkBoxAddToDesigner.Checked)  // return if all done
            {
                this.DialogResult = DialogResult.OK;
                return;
            }

            // add the new dataset to the component tray
            string componentBaseName;
            if (currentProjectNamespace.Length == 0)
                componentBaseName = dsName;
            else
                componentBaseName = currentProjectNamespace + "." + dsName;

            System.ComponentModel.Design.IDesignerHost host =
                serviceProvider.GetService(
                typeof(System.ComponentModel.Design.IDesignerHost))
                as System.ComponentModel.Design.IDesignerHost;
            if (host == null)
            {
                MessageBox.Show(
                    "The IDesignerHost service interface " +
                    "could not be obtained to process the request.",
                    "Generate " + DATASETNAME_PREFIX);
                return;
            }

            Type componentType;
            try
            {
                componentType = host.GetType(componentBaseName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,
                    "Unable to get Type of " + componentBaseName);
                return;
            }

            IComponent newComponent;
            try
            {
                newComponent = host.CreateComponent(componentType);
                host.Container.Add(newComponent);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,
                    "Unable to create component for " + componentBaseName);
                return;
            }

            // move the select pointer to the new component in the tray
            ISelectionService selService = newComponent.Site.GetService(
                typeof(ISelectionService)) as ISelectionService;
            if (selService != null)
            {
                ArrayList selList= new ArrayList(1);
                selList.Add(newComponent);
                selService.SetSelectedComponents(  // move the selection to new
                    selList, SelectionTypes.Replace);
            }

            this.DialogResult = DialogResult.OK;
        }