Showing posts with label XML. Show all posts
Showing posts with label XML. Show all posts

Friday, January 6, 2012

Binding dynamic XML objects to Silverlight Grids

Recently we had an requirement to bind the content of dynamic XML to Silverlight Grids.This is straightforward in ASP.NET with the help of DataSet. But we do not have DataSet in Silverlight or WPF. To achieve this we used the following approach;


The code is self-explanatory with the comments explaining each step;


public string Result
{
get
{
return _result;
}
set
{
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
//Load the xml string to XDocument
XDocument doc = XDocument.Load(new StringReader(value));
MemoryStream str = new System.IO.MemoryStream();
doc.Save(str);


//Finding the Name of the class
string objName = doc.Descendants().First().Name.LocalName.Replace("ArrayOf", "");


//Making it a fully qualified name by appending the corresponding
//namespace
objName = "MyCompany.MyApplication." + objName;


//Loading the assembly that contains the Entity which
//we are trying to de-serialize
//NOTE: To be able to do the below 3 steps, you need to ensure that
//the entities dll reference is added in Deployment.Parts of the
//App Manifest file
StreamResourceInfo sri = Application.GetResourceStream(new Uri("MyApplication.SL.Entities.dll",UriKind.Relative));
AssemblyPart myPart = new AssemblyPart();
System.Reflection.Assembly assm = myPart.Load(sri.Stream);


//Using reflection to build the List<T>
var pageToShowType = assm.GetType(objName);
Type t = typeof(List<>);
Type [] args = {pageToShowType};
Type r = t.MakeGenericType(args);


//De-serializing and assigning to the property to show in the grid
str.Position = 0;
DataContractSerializer serializer = new DataContractSerializer(r);
//Bind the ResultObject to the SL Grid
//NOTE: Ensure that SL Grid has AutoGenerateColumns = TRUE
ResultObject = serializer.ReadObject(str);
str.Close();


});


}


}

Wednesday, December 9, 2009

Data Collection Form design in ASP.NET (Input designer XML which can used for CodeSmith template)

Here is the simple code which will create the Form Designer XML in the format shown below which can be used for CodeSmith template to create .ascx and .ascx.cs files.


XML:
<FormDefinition xmlns="http://aas.com.au/FormGen">
  <PageName>zddas</PageName>
  <FormId>asdas</FormId>
  <Sections>
    <Section>
      <SectionTitle>Test Section</SectionTitle>
      <Controls>
        <Control Type="text" Id="txtField" Text="txtField" />
      </Controls>
    </Section>
  </Sections>
</FormDefinition>





Code:
void GenerateInputForCodeSmith()
        {
            XmlDocument doc = new XmlDocument();
            XmlElement rootEle = default(XmlElement);
            XmlElement elt = default(XmlElement);
            XmlElement eltChoice = default(XmlElement);
            XmlAttribute attr = default(XmlAttribute);

            doc.LoadXml("<FormDefinition xmlns=\"http://aas.com.au/FormGen\"></FormDefinition>");
           
            rootEle = doc.CreateElement("PageName");
            rootEle.InnerText = txtPageName.Text;
            doc.DocumentElement.AppendChild(rootEle);

            rootEle = doc.CreateElement("FormId");
            rootEle.InnerText = txtForm.Text;
            doc.DocumentElement.AppendChild(rootEle);

            rootEle = doc.CreateElement("Sections");
            doc.DocumentElement.AppendChild(rootEle);

            XmlElement elt1 = doc.CreateElement("Section");
            rootEle.AppendChild(elt1);

            elt = doc.CreateElement("SectionTitle");
            elt.InnerText = "Test Section";
            elt1.AppendChild(elt);

            XmlElement eltControls = doc.CreateElement("Controls");
            elt1.AppendChild(eltControls);

            Panel p = (Panel)this.form1.FindControl("pnlSection");
            IEnumerable<Section> sections = p.Controls.OfType<Section>();
            Section sec = sections.First<Section>();
            IEnumerable<Field> fields = sec.FindControl("pnlField").Controls.OfType<Field>();
            foreach (Field field in fields)
            {
                elt = doc.CreateElement("Control");
                attr = doc.CreateAttribute("Type");
                attr.InnerText = ((DropDownList)field.FindControl("cboFieldType")).SelectedValue;
                elt.Attributes.Append(attr);
                attr = doc.CreateAttribute("Id");
                attr.InnerText = ((TextBox)field.FindControl("txtFieldName")).Text;
                elt.Attributes.Append(attr);
                attr = doc.CreateAttribute("Text");
                attr.InnerText = ((TextBox)field.FindControl("txtFieldName")).Text;
                elt.Attributes.Append(attr);
                string[] options = ((TextBox)field.FindControl("txtValues")).Text.Split(";".ToCharArray());
                switch (((DropDownList)field.FindControl("cboFieldType")).SelectedValue)
                {
                    case "dropdown":
                        {
                            foreach (string option in options)
                            {
                                eltChoice = doc.CreateElement("option");
                                attr = doc.CreateAttribute("value2");
                                attr.InnerText = option;
                                eltChoice.InnerText = option;
                                eltChoice.Attributes.Append(attr);
                                elt.AppendChild(eltChoice);
                            }
                            break;

                        }
                    case "radio":
                        {
                            foreach (string option in options)
                            {
                                eltChoice = doc.CreateElement("choice");
                                attr = doc.CreateAttribute("value2");
                                attr.InnerText = option;
                                eltChoice.InnerText = option;
                                eltChoice.Attributes.Append(attr);
                                elt.AppendChild(eltChoice);
                            }
                            break;
                        }
                    case "checkbox":
                        {
                            foreach (string option in options)
                            {
                                eltChoice = doc.CreateElement("choice");
                                attr = doc.CreateAttribute("value2");
                                attr.InnerText = option;
                                eltChoice.InnerText = option;
                                eltChoice.Attributes.Append(attr);
                                elt.AppendChild(eltChoice);
                            }
                            break;
                        }
                    default:
                        break;
                }
                eltControls.AppendChild(elt);
            }

            //doc.Save(Server.MapPath("FormDesigner.xml"));
            string output = doc.OuterXml;
            output = output.Replace(" xmlns=\"\"","");
            FileStream fileStream = File.Open(Server.MapPath("FormDesigner.xml"), FileMode.Create);
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byte[] bytes = encoding.GetBytes(output);
            fileStream.Write(bytes, 0, bytes.Length);
            fileStream.Close();
            fileStream.Dispose();

        }

Wednesday, September 30, 2009

XML Transformation using XSLT


public static XmlElement Transfomer(string xsltFilePath, XmlDocument bericht)
        {
            XslCompiledTransform transformer = new XslCompiledTransform();
            XsltSettings xsltSettings = new XsltSettings(false, true);
            transformer.Load(xsltFilePath, xsltSettings, new XmlUrlResolver());



            XmlDocument transformedMessage = new XmlDocument();

            using (MemoryStream memoryStream = new MemoryStream())
            {
                XmlWriterSettings writerSettings = new XmlWriterSettings();
                writerSettings.Indent = true;
                writerSettings.IndentChars = "\t";
                writerSettings.Encoding = System.Text.Encoding.UTF8;
                writerSettings.ConformanceLevel = ConformanceLevel.Fragment;
                writerSettings.OmitXmlDeclaration = true;

                XmlWriter writer = XmlWriter.Create(memoryStream, writerSettings);

                transformer.Transform(bericht, writer);
                writer.Flush();
                memoryStream.Position = 0;
                transformedMessage.Load(memoryStream);
            }

            return transformedMessage.DocumentElement;
        }

Tuesday, September 22, 2009

Binding an XML to TreeView using C#

Here is the code for binding an XML to TreeView control


private void button1_Click(object sender, EventArgs e)
        {
            inputFile.ShowDialog();
            txtInputFile.Text = inputFile.FileName;
        }


private void updateTreeView(string filename)
        {
            try
            {
                txtInputFile.Text = filename;
                tvXMLView.Nodes.Clear();
                tmpxmldoc = new XmlDocument();
                tmpxmldoc.Load(filename);
                FillTree(tmpxmldoc.DocumentElement, tvXMLView.Nodes);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        private void FillTree(XmlNode node, TreeNodeCollection parentnode)
        {
            // End recursion if the node is a text type
            if (node == null || node.NodeType == XmlNodeType.Text || node.NodeType == XmlNodeType.CDATA)
                return;

            TreeNodeCollection tmptreenodecollection = AddNodeToTree(node, parentnode);

            // Add all the children of the current node to the treeview
            foreach (XmlNode tmpchildnode in node.ChildNodes)
            {
                FillTree(tmpchildnode, tmptreenodecollection);
            }
        }


        private TreeNodeCollection AddNodeToTree(XmlNode node, TreeNodeCollection parentnode)
        {
            TreeNode newchildnode = CreateTreeNodeFromXmlNode(node);

            // if nothing to add, return the parent item
            if (newchildnode == null) return parentnode;

            // add the newly created tree node to its parent
            if (parentnode != null) parentnode.Add(newchildnode);

            return newchildnode.Nodes;
        }


        private TreeNode CreateTreeNodeFromXmlNode(XmlNode node)
        {
            TreeNode tmptreenode = new TreeNode();

            if ((node.HasChildNodes) && (node.FirstChild.Value != null))
            {
                tmptreenode = new TreeNode(node.Name);
                //TreeNode tmptreenode2 = new TreeNode(node.FirstChild.Value);
                //tmptreenode.Nodes.Add(tmptreenode2);
            }
            else if (node.NodeType != XmlNodeType.CDATA)
            {
                tmptreenode = new TreeNode(node.Name);
            }

            return tmptreenode;
        }