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

Tuesday, March 18, 2014

Basic and architecture Windows and SQL Azure interview questions and answers...

Here is the list of basic and architectural Windows Azure interview questions and answers. Will uncover and add some more as we move along and learn. Intend to grow this list further....

What are the services provided in Cloud Computing/Azure?
Services provided would be basically three fundamental models: Infrastructure as a service (IaaS), Platform as a service (PaaS), and Software as a service (SaaS).
 
What are the steps involved in creating a Windows Azure Project with Visual Studio?
Refer for detailed steps here -http://msdn.microsoft.com/en-us/library/windowsazure/ee405487.aspx 

What are various roles available in Windows Azure?
There are three roles (Web, worker, VM) available. Web and Worker roles are nearly identical: With Web and Worker roles, the OS and related patches are taken care for you; you build your app's components without having to manage a VM.

What are the three main components of Windows Azure Platform?  
  1. Compute
  2. Storage
  3. AppFabric
What are the benefits of Azure?
  • Platform as a Service (PaaS) / Infrastructure as a Service (IaaS) / Software as a Service (SaaS)
  • Variable pricing - see here (Azure retail subscription pricing calculator
  • On demand and simple service procurement
  • More predictable solution environments
  • Small infrastructure management responsibility
  • Scalability with Global model - 15 global data centers (to date) and growing...
  • Security/privacy compliance – HIPAA, PCI DSS, SOC 1, SOC 2, ISO 27007
  • Compatibility with existing development tools
What are the capabilities that are provided with Visual Studio?
  • Windows Azure Cloud Service Visual Studio Template
  • http://msdn.microsoft.com/en-us/library/windowsazure/ee405487.aspx
  • ASP.Net web role
  • WCF Service web role
  • Worker Role with Service Bus Queue
  • Worker Role
  • Cache Worker Role – provides a dedicated cache
  • Integration with Emulators
  • Sophisticated debugging and tracing capability including remote debugging w/- SDK 2.2
  • Publish capability
  • Basic Azure component management in Server Explorer
  • Azure storage error log and application diagnostic analysis
What is Windows Azure compute emulator? 
The compute emulator is a local emulator of Windows Azure that you can use to build and test your application before deploying it to Windows Azure. 
  
What is the difference between Web Sites versus Web Roles (Azure Compute Services)?
  • Web site uses .azurewebsites.net versus .cloudapp.net for web roles
  • Web sites offer very quick deployment, scaling and rollback
  • Web sites have out of box support for Git and other continuous publishing tools
  • Web sites have less capability than web roles e.g. no remote management, no traffic manager
  • Web sites are good for a 2-tier application architecture
  • 10 per region multi-tenant web sites are free
Which is the latest version of Microsoft Windows Azure? (March 2014) and what are some of the key features/capabilities that come along with SDK v2.2?

SDK v2.2 -
•BizTalk Services: EDIFACT protocol support, Service Bus Integration, Backup and Restore
•Web Sites: Backup and Restore Support
•HDInsight: Hadoop 2.2 support
•Mobile Services: .NET support, Notification Hub Integration, PhoneGap support
•Management: Co-admin limit increased from 10->200 users
•Monitoring: Service Outage Notifications Integrated within Management Portal
•Virtual Machines: VM Agent and Background Information Support
•ExpressRoute: Dedicated, private, high-throughput network connectivity with on-premises.
Pricing - $5000 per month for 10GBps connection 
•Active Directory: More SaaS apps, more reports, self-service group management
 
What are Windows Azure Data Services? 
Windows Azure SQL Database Service provides -
  • Data replication – backups are only required for user / application errors
  • Relational data structures
  • Only SQL authentication
  • No always-on availability groups
  • SQL Data Sync for mirroring
  • No SQL Server Agent – use worker roles and windows workflow foundation (WWF)
  • Data Sharding – SQL Azure Database federation:
  • http://msdn.microsoft.com/en-us/library/windowsazure/hh597452.aspx
  • Database backup and auomatic scheduled data backup to Azure Storage
What is Blob?
BLOB stands for Binary Large Object. Blob is file of any type and size.
The Azure Blob Storage offers two types of blobs –
1. Block Blob
2. Page Blob 
                                         
What is Windows Azure AppFabric? What are various services provided?
  • Windows Azure AppFabric is a part of the Microsoft Windows Azure Platform. Positioned by Microsoft as middleware, it provides several cloud computing services:
  • Access Control Service: Provides an easy way for web applications and web services to identify users, and grant access control to the applications and services.
  • AppFabric Applications: Provides tools and APIs for developing and hosting a composite application expressly for deployment through the service.
  • Service Bus: Provides secure connections between distributed and disconnected applications in the cloud.
  • Caching: Provides a distributed, in-memory, application cache service for Windows Azure and SQL Azure applications.
  • Integration: Leverages several capabilities of Microsoft BizTalk Server such as transforming messages from one format to another, or providing a queue for message passing.
What is a Queue in Azure terminology?
http://www.windowsazure.com/en-us/documentation/articles/storage-dotnet-how-to-use-queues-20/

Features provided by HDInsight?
Here's a quick start tutorial to get started and learn basics on HDInsight - http://www.windowsazure.com/en-us/documentation/articles/hdinsight-get-started/
  •  Provides nice way to also use Microsoft Office tools like Excel to view output using power query and more with power BI features.
  • HDInsight is our 100% compatible Apache Hadoop-based distribution for Windows Azure.  With HDInsight you can leverage data stored in Windows Azure Blob Storage or the native HDFS file system local to the compute nodes and crunch massive amounts of data.
    We now support Hadoop 2.2 clusters (in preview mode) with our HDInsight service.  This new update provides an order of magnitude (up to 40x) faster query response times, much better data compression (up to 80%), and enables you to leverage the benefits of YARN.
What are Azure app Services?
1 Media Services
.Net libraries (Media Services SDK) for uploading, storing, encoding, format converting, protection and delivery of media
2 Azure content delivery network (CDN) for Azure storage accounts -
http://www.windowsazure.com/en-us/documentation/articles/media-services-dotnet-get-started/
3 Service Bus Explorer- .Net library and components for message communication processing. Architecture approach for communicating between on premise and private cloud to Azure Components.
http://code.msdn.microsoft.com/Service-Bus-Explorer-f2abca5a

4 Queues (FIFO)  -
http://www.windowsazure.com/en-us/documentation/articles/service-bus-dotnet-how-to-use-queues/

5 Topics and Subscriptions – Topic filters– Special implementation of a queue that uses a subscriber model -
 
6 Relays – provides capability to communicate to existing WCF corporate domain web services
7 Notification Hubs – pushing cross-platform back end notifications to mobile clients. Get started building these applications on Windows Azure and learn about notification hubs here -
http://www.windowsazure.com/en-us/documentation/articles/notification-hubs-windows-phone-get-started/
8 Scheduler (new) -
This is an exposed API for job operations and helps create jobs on a schedule:
http://msdn.microsoft.com/en-us/library/windowsazure/dn495651.aspx
9 BizTalk Services -B2B EDI in Azure
EAI in Azure
10 Active Directory -
Identity management in Azure
Can sync with access control service (ACS)
Can sync with on premise Active Directory
11 MSFT Active Directory Federated Services - https://corp.sts.microsoft.com/Onboard/ADFSOnboard.htm
http://sharepoint/sites/windowsazure/windowsazureinternal/Pages/ADFSAuthentication.aspx

.... Cheers - DJ
  

Thursday, October 17, 2013

Microsoft officially releases Visual Studio 2013...

Microsoft officially releases Visual Studio 2013

 
Personally still haven't installed it myself but planning soon. Here are few highlights as read on MSDN forums and blogs on the new VS 2013 released:
  •   
New MVC 5 web application template and SharePointContext for SharePoint apps -
MVC web application template for app for SharePoint has been introduced since Office Developer Tools for Visual Studio 2013 Preview. In this Visual Studio 2013 RTM release, the MVC web application template in app for SharePoint has been updated based on the latest one for MVC 5.
 
SharePointContext is a set of classes (in SharePointContext.cs/SharePointContext.vb) that provides a set of APIs to relieve you from the tedious steps of dealing with communication between SharePoint and web application.

Need to decide whether your app be authenticated with Windows Azure Control Services or a certificate (high-trust)? SharePointContext makes it possible for you to use the same snippet of code no matter which way you go.

Need efficient but safe strategy to cache the access tokens? APIs in SharePointContext provide a good pattern and the default implementation for you.

Which APIs can you use for hosting web and which ones for app web? API naming convention carefully designed in SharePointContext gives you an explicit view what you can use in which case. You can also easily extend the SharePointContext helper by subclassing to provide more advanced features to fulfill your scenarios.

Apart from the Visual Studio 2013 in-box release, the new SharePointContext helper is also included in
App for SharePoint Web Toolkit - NuGet package, which means you can install the package and leverage the helper APIs in any VS 2013 or VS 2012 project that you want to communicate with SharePoint. For the app for SharePoint projects that you’ve created with VS 2013 Preview, you can simply upgrade the SharePointContext helper to the latest by updating the App for SharePoint Web Toolkit NuGet package (which is installed in the web project when you created the app for SharePoint).
 
  •   
 
Support for Windows 8.1 app development: Visual Studio 2013 provides the ideal toolset for building modern applications that leverage the next wave in Windows platform innovation (Windows 8.1), while supporting devices and services across all Microsoft platforms. Support for Windows Store app development in Windows 8.1 includes updates to the tools, controls and templates, new Coded UI test support for XAML apps, UI Responsiveness Analyzer and Energy Consumption profiler for XAML & HTML apps, enhanced memory profiling tools for HTML apps, and improved integration with the Windows Store.
 
  •   
Web development advances: Creating websites or services on the Microsoft platform provides you with many options, including ASP.NET WebForms, ASP.NET MVC, WCF or Web API services, and more. Previously, working with each of these approaches meant working with separate project types and tooling isolated to that project’s capabilities. The One ASP.NET vision unifies your web project experience in Visual Studio 2013 so that you can create ASP.NET web applications using your preference of ASP.NET component frameworks in a single project. Now you can mix and match the right tools for the job within your web projects, giving you increased flexibility and productivity.


You can download Visual Studio 2013 here - http://go.microsoft.com/fwlink/p/?LinkId=306566 
 
 
-D

Sunday, September 25, 2011

WCF Interview questions and answers (reference only, uuber level)

The intent to draft this list of questions is for learning purpose only and at very high level understanding of WCF services. This is not a dump :)

Question 1: What is the difference WCF and Web services?
Answer: -
Web services can only be invoked by HTTP. While Service or a WCF component can be invoked by any protocol and any transport type. Second web services are not flexible. However, Services are flexible. If you make a new version of the service then you need to just expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends.
Question 2: What are different bindings supported by WCF?
Answer: -
WCF includes predefined bindings. They cover most of bindings widely needed in day-to-day application. However, just incase you find that you need to define something custom WCF does not stop you. So let us try to understand what each binding provides.
BasicHttpBinding: - This binding is used when we need to use SOAP over HTTP. This binding can also be configured to be used as HTTPS. It can be also configured to send data in plain text or in optimized form like MTOM.
WsHttpBinding: - It is same like BasicHttpBinding. In short, it uses SOAP over HTTP. But with it also supports reliable message transfer, security and transaction. WS-Reliable Messaging, security with WS-Security, and transactions with WS-Atomic Transaction supports reliable message.
NetTcpBinding: - This binding sends binary-encoded SOAP, including support for reliable message transfer, security, and transactions, directly over TCP. The biggest disadvantage of NetTcpBinding is that both server and client should be also made in .NET language.
NetMsmqBinding: - This binding sends binary-encoded SOAP over MSMQ. This binding can only be used for WCF-to-WCF communication.
NetNamedPipesBinding:-Ths binding Sends binary-encoded SOAP over named pipes. This binding is only usable for WCF-to-WCF communication between processes on the same Windows-based machine.

Note: - An interprocess control (IPC) protocol is used for exchanging information between two applications, possibly running on different computers in a network. The difference between Named pipes and TCP is that named pipes have good performance in terms of communication with in processes. But when it comes to communicate across network TCP holds the best choice. So if you are using WCF to communicate with process it’s the best choice to use in terms for performance. Named pipes do not perform when the traffic is heavy as compared to TCPIP.

Question 3: What are the main components of WCF?
Answer: -
We need to define three main components in WCF:-
• Service class. • Hosting environment • End point

Question 4: What are the various ways of hosting a WCF service?
Answer: -
There are three major ways to host a WCF service:-
• Self-hosting the service in his own application domain. This we have already covered in the first section. The service comes in to existence when you create the object of Service Host class and the service closes when you call the Close of the Service Host class.
• Host in application domain or process provided by IIS Server.
• Host in Application domain and process provided by WAS (Windows Activation Service) Server.

Question 5: What is a service level message and transport level message?
Answer: -
You can log WCF message at two levels one is service level and the other is transport level. Service level:-In this the messages are logged as they enter the user code or leave the user code. Transport level: - In this the messages are logged as they are ready to be encoded / decoded. All transport level, infrastructure messages and also reliable messaging is logged. You specify the message levels in the diagnostics node as shown in the below code snippet.

Question 6: For which bindings are transport, message and mixed mode supported?
Answer: -
Below is a table which shows for which binding which mode is supported. We did not discuss the mixed mode. It’s nothing but combination of transport and mixed mode. For instance data encrypted and passed over WsHttp using HTTPS is a mixed mode of security. Encryption is nothing but message security and HTTPS is a transport mode. In a combination they form mixed mode.

Question 7: Which bindings in WCF support the message streaming?
Answer: -
Following bindings supports the streaming in WCF:
1. basicHttpBinding 2. netTcpBinding 3. netNamedPipeBinding

Question 8: What are the various ways of hosting a WCF Service?
Answer: - 1.IIS 2.Self Hosting 3.WAS (Windows Activation Service)

Question 9: What is the use of ServiceBehavior attribute in WCF ?
Answer: -
ServiceBehaviour attribute is used to specify the InstanceContextMode for the WCF Service class (This can be used to maintained a state of the service or a client too).

There are three instance Context Mode in the WFC PerSession : This is used to create a new instance for a service and the same instance is used for all method for a particular client. (eg: State can be maintained per session by declaring a variable) PerCall : This is used to create a new instance for every call from the client whether same client or different. (eg: No state can be maintained as every time a new instance of the service is created) Single : This is used to create only one instance of the service and the same instance is used for all the client request. (eg: Global state can be maintained but this will be applicable for all clients)

Question 10: How the concurrency mode is specified in WCF service?
Answer: - The concurrency mode is specified using the ServiceBehavior attribute on the class that implements the service. Ex. [ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Single)] Public class ServiceClass : IServiceInterface{ //Implementation Code } There are 3 possible values of ConcurrencyMode enumeration Single Reentrant Multiple.

Question 11: hat the different transaction options ?
Answer:-

We can specify transaction in 3 ways in WCF:-
TransactionFlowOption.NotAllowed This is a default option. Using this option no transaction will be propagated across the binding. If any client attempts to call the WCF service in a transaction it will be ignored for this option. This option specifies that client can call this WCF service in a transaction. It’s not compulsory that the service needs to be called in a transaction. You can call without the transaction also. TransactionFlowOption.Mandatory This option specifies that client must call the WCF service in a transaction mode. If the WCF service is called without transaction, ‘FaultException’ will be raised.

Question 12: Wat are the advantages of hosting WCF Services in IIS as compared to self-hosting?
Answer: - There are two main advantages of using IIS over self-hosting:-


Automatic activation IIS provides automatic activation that means the service is not necessary to be running in advance. When any message is received by the service it then launches and fulfills the request. But in case of self hosting the service should always be running.
Process recycling If IIS finds that a service is not healthy that means if it has memory leaks etc, IIS recycles the process. Ok let us try to understand what is recycling in IIS process. For every browser instance, a worker process is spawned and the request is serviced. When the browser disconnects the worker, process stops and you loose all information. IIS also restarts the worker process. By default, the worker process is recycled at around 120 minutes. So why does IIS recycle. By restarting the worker process it ensures any bad code or memory leak do not cause issue to the whole system. In case of self-hosting both the above features, you will need to code yourself.

Question 13: What is trace listener?

Answer - ‘Tracelistener’ are objects that get tracing information from the trace class and they output the data to some medium. For instance you can see from the figure ‘TraceListener’ how it listens to the trace object and outputs the same to UI, File or a windows event log. There are three different types of ‘tracelistener’ first is the ‘defaulttracelistener’ (this outputs the data to UI), second is ‘textwritertracelistener’ (this outputs to a file) and the final one is ‘Eventlogtracelistener’ which outputs the same to a windows event log.

Question 14: What is service host factory in WCF?
Answer-

1. Service host factory is the mechanism by which we can create the instances of service host dynamically as the request comes in.
2. This is useful when we need to implement the event handlers for opening and closing the service.
3. WCF provides ServiceFactory class for this purpose.

Question 15: What are the advantages of hosting WCF service in WAS?

Answer- WAS (Windows Activation Service) is a component of IIS 7.0. Following are few advantages : 1. We are not only limited to HTTP protocol. We can also use supported protocols like TCP, named pipes and MSMQ 2. No need to completely install IIS. We can only install WAS component and keep away the WebServer.

Question 16: In WCF which bindings supports the reliable session?

Answer- In WCF, following bindings supports the reliable session - 1. wsHttpBinding 2. wsDualHttpBinding 3. wsFederationHttpBinding 4. netTcpBinding

Reference - Prasham on dotnetfunda.com and Pro WCF: Practical Microsoft SOA Implementation -- Chris and Denis Mulder – Apress 2007.

- DJ

Wednesday, January 02, 2008

XSDObjectGen - nested schema (imports) error with XSD.exe tool

If you read my previous post http://archdipesh.blogspot.com/2008/01/xml-xsdexe-usage-tips.html you may be good if you are using a simple XSD file (no nesting). But if i have multiple XSD files and they are all nested then there is a problem! Using XSD.exe tool doesn't help and fails for nested schema files.

It seems XSD.exe doesn’t seem to recognize element when generating code file...and it spits out the error ... "Class generation failed, cannot recognize root element". If you are facing the same error remove imports element from the XSD just include the namespace and try specifying multiple XSD file names from the command line while executing xsd.exe tool.

OR ... sweet way would be to look at XSDObjectGen tool. This is pretty exhaustive and can handle imports/mutiple xsd files easily. (though one level down). This code can then be used as a class exposed by web services.
Download Sample Code generator from here - http://www.microsoft.com/downloads/details.aspx?familyid=89e6b1e5-f66c-4a4d-933b-46222bb01eb0&displaylang=en

Saves lot of time and pain for sure! HTH, Thanks - Dipesh

XML, XSD.exe usage tips

Here are few quick tips that can help you understand and start with XML basics...

Questions - (preferably in this sequence)
How do you generate XSD ?
You need to have a valid XML file for which you want to have a schema generated ( XSD)
If you have VS .net you can just open the xml file into VS.net and then under XML menu you should see "Create Schema" option that should generate an .xsd file for you!

How do you create classes from an XSD schema?
You can create .net (C#, VB, J#) source code from the xsd using XSD tool (command line) along with MS .net framework.
http://samples.gotdotnet.com/quickstart/howto/doc/xmlserialization/xsdtocls.aspx

How do you convert (deserialize) XML into an object that you can read through .net code?
AND
How do you write out an XML file (serialize) from an object through .net code?

http://samples.gotdotnet.com/quickstart/howto/doc/xmlserialization/rwobjfromxml.aspx

Thats simple ...is it? Thanks - Dipesh

Tuesday, May 08, 2007

Creating an XML Document using XMLDom and returning string as response...

Some answers are so straight forward but you just dont find them when you need them. I am happy that i am maintaining this blog and hopefully the next time when i need these answers i come back here.... :)

This is the XML i am trying to create -


//Create XML document
XmlDocument xmlDoc = new XmlDocument();

//Write down the XML declaration
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);

// Create the root element
XmlElement rootNode = xmlDoc.CreateElement("PropList");
xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);
xmlDoc.AppendChild(rootNode);

//
//Create an XML element
XmlElement parentNode = xmlDoc.CreateElement("Prop");
//Create an XML attribute
XmlAttribute idAttribute = xmlDoc.CreateAttribute("PropID");
idAttribute.Value = i.ToString();
//Associate the attribute to the element
parentNode.SetAttributeNode(idAttribute);

xmlDoc.DocumentElement.PrependChild(parentNode);

//MEMSG
//Create an XML element
XmlElement newCityHocn = xmlDoc.CreateElement("CityHocn");
newCityHocn.InnerText = "MEMSG";
//Add this element as an child to Prop
parentNode.AppendChild(newCityHocn);

//1000121
//Create an XML element
XmlElement newSecFacilityID = xmlDoc.CreateElement("SecondaryFacilityID");
newSecFacilityID.InnerText = "1000121";
//Add this element as an child to Prop
parentNode.AppendChild(newSecFacilityID);
//


// Save to the XML file
//xmlDoc.Save(@"D:\test.xml");

//return string
xmlDoc.OuterXML;

If you are creating a web service and you want to return string as an response to the web method then use xmlDoc.OuterXML instead of saving to a file. String response will help non .net platforms to consume from web service as well.

Others - http://www.mastercsharp.com/article.aspx?ArticleID=69&&TopicID=9

Thanks - Dipesh

Tuesday, May 01, 2007

IE Developer toolbar...

If you're like most Web developers, when you were first learning HTML, you probably spent a great deal of your time playing around with your browser. The fact that you could simply do a "View Source" and see how an interesting web page was implemented was one of the things that helped HTML catch on so quickly. This "code sharing" is undoubtably one of the reasons the Web was able to grow as quickly as it did.
Unfortunately, these days it's not so easy to take a look at the magic going on behind the scenes of the average web page. With the emphasis on usability and appearance, the previously simple HTML has become incresingly difficult to read and these days most web pages are made up of a combination of several files and use often use as much CSS and client-side script as they do HTML. Using "View Source" simply doesn't cut it anymore. Luckily Microsoft has realized this fact and is building a tool to help developers analyze these increasingly complex web documents. It's called the Internet Explorer Developer Toolbar. In this article I'll give you a quick introduction to this powerful new tool and examine some of it's most useful features.

These features enable you to:
1 Explore and modify the document object model (DOM) of a Web page.
2 Locate and select specific elements on a Web page through a variety of techniques.
3 Selectively disable Internet Explorer settings.
4 View HTML object class names, ID's, and details such as link paths, tab index values, and access keys.
5 Outline tables, table cells, images, or selected tags.
6 Validate HTML, CSS, WAI, and RSS Web feed links.
7 Display image dimensions, file sizes, path information, and alternate (ALT) text.
8 Immediately resize the browser window to a new resolution.
9 Selectively clear the browser cache and saved cookies. Choose from all objects or those associated with a given domain.
10 Choose direct links to W3C specification references, the Internet Explorer team weblog (blog), and other resources.
11 Display a fully featured design ruler to help accurately align and measure objects on your pages.
12 Find the style rules used to set specific style values on an element.
13 View the formatted and syntax colored source of HTML and CSS.

Download the beta version from here - http://www.microsoft.com/downloads/details.aspx?FamilyID=e59c3964-672d-4511-bb3e-2d5e1db91038&displaylang=en

Check for details on IE developer tool here - http://www.15seconds.com/issue/070208.htm

- D

Convert XML data to object and back using serialization

Introduction -
This article shows you how to convert an XML to a class object and retriving back.

Saving XML to a class object is called serialization and reading back using the reverse process is called as deserialization.
1> Assuming you have a sample xsd, to convert a class from XSD, we would run the following command:

xsd C:\Contact.xsd /t:lib /l:cs /c from VS.net command prompt.
2> /// auto generated code from xsd command ran above...
using System.Xml.Serialization;
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public class Contact
{        
public ContactInfo;
}
public class ContactInfo
{        
public string Code;        
public string FirstName;        
public string LastName;        
public string Email;
}
 
3> Now, we could save an contact XML data to this class using this simple function:
public Contact ContactObject(string xml)  
{   
StringReader stream = null;   
XmlTextReader reader = null;   
try   
{    
// serialise to object    
XmlSerializer serializer = new XmlSerializer(typeof(Contact));
stream = new StringReader(xml); // read xml data    
reader = new XmlTextReader(stream);  // create reader    
// covert reader to object    
return (Contact)serializer.Deserialize(reader);   
}   
}
 
And to get the XML based on the Contact class object, use the following function:
public string ContactXML(Contact cont)  
{   
MemoryStream stream = null;   
TextWriter writer = null;   
try   
{    
stream = new MemoryStream(); 
// read xml in memory    
writer = new StreamWriter(stream, Encoding.Unicode) ;    
// get serialise object    
XmlSerializer serializer = new XmlSerializer(typeof(Contact));    
serializer.Serialize(writer, cont); 
// read object    
int count = (int) stream.Length; 
// saves object in memory stream    
byte[] arr = new byte[count];    
stream.Seek(0, SeekOrigin.Begin);    
// copy stream contents in byte array    
stream.Read(arr, 0, count);    
UnicodeEncoding utf = new UnicodeEncoding(); 
// convert byte array to string    
return utf.GetString(arr).Trim();   
}   
}
 
Hope this helps for all working on XML!
Thanks - DJ

Thursday, April 26, 2007

Validate XML against your schema XSD

Hi - This post is basically to demenstrate how you can validate your XML input against a specified XML schema. The sample below uses new .net 2.o objects rather than obsolete .net 1.1 objects. I have commented few obsolete objects to highlight the differences.

using System;
using System.Xml;
using System.Xml.Schema;
using System.IO;

namespace ConsoleApplication3
{
///
/// Summary description for Class1.
///


class Class1
{
///
/// The main entry point for the application.
///


System.Boolean m_success;
[STAThread]
static void Main(string[] args)
{

//XmlValidatingReader reader = null; //obsolete in .net 2
XmlReader reader1 = null;

//XmlSchemaCollection myschema = new XmlSchemaCollection(); //obsolete in .net 2
XmlSchemaSet myschema1 = new XmlSchemaSet();
ValidationEventHandler eventHandler = new ValidationEventHandler(Class1.ShowCompileErrors);

try
{
//Create the XML fragment to be parsed.

// String xmlFrag = "YOUR XML string here" ;

//Create the XmlParserContext.
XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None);

//Implement the reader.
//reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context); //obsolete in .net 2.0
XmlReaderSettings rs = new XmlReaderSettings();

rs.ValidationType = ValidationType.Schema;
myschema1.Add("http://www.newmarketinc.com", Server.Mappath("DirectBook.xsd"));
rs.Schemas.Add(myschema1);
StringReader srXml = new StringReader(xmlFrag);
reader1 = XmlReader.Create(srXml, rs, context);

//Add the schema.
//myschema.Add("http://www.newmarketinc.com", "D:\\Documents and Settings\\Administrator\\Desktop\\MI\\DirectBook.xsd");

//Set the schema type and add the schema to the reader.
//reader.ValidationType = ValidationType.Schema;
//reader.Schemas.Add(myschema);
while (reader1.Read())
{ //empty loop;
}
Console.WriteLine("Completed validating xmlfragment");
}
catch (XmlException XmlExp)
{
Console.WriteLine(XmlExp.Message);
}
catch (XmlSchemaException XmlSchExp)
{
Console.WriteLine(XmlSchExp.Message);
}
catch (Exception GenExp)
{
Console.WriteLine(GenExp.Message);
}
finally
{
Console.Read();
}
}
public static void ShowCompileErrors(object sender, ValidationEventArgs args)
{
Console.WriteLine("Validation Error: {0}", args.Message);
}
}
}

References -
.net 1.1 - http://www.codeproject.com/cs/webservices/XmlSchemaValidator.asp,
http://support.microsoft.com/kb/318504

.net 2.0 - http://aspalliance.com/941

Cheers - Dj

XSD Element

The any element enables us to extend the XML document with elements not specified by the schema!

The any element enables us to extend the XML document with elements not specified by the schema.
The following example is a fragment from an XML schema called "family.xsd". It shows a declaration for the "person" element. By using the element we can extend (after lastname) the content of "person" with any element:

[person - last name, firstname, any]
any can contain any additonal information (any other element from other schema as well)
So you can define another child.xsd and add it in your XML
Your XML can contain something like -
[person - lastname, firstname, [children - childname] ]
Its little difficult to format the XML output in this blog so please reference this link - http://www.w3schools.com/schema/schema_complex_any.asp

BTW, w3schools is the best site for all your questions regarding XML schema.
Cheers - Dj