Wednesday, March 31, 2010

How to validate xml using xsd?

A lot of times I have come across this question on several forums; and to not avail the google, the question is being asked again and again. If at any point someone might feel they should google, and if google ever planned to re-rank my site to a higher level - then I'd guarantee that following code would work.



I did a reply to a post here on StackOverflow; though my code is pretty old - out of my project code - but as they say, old is gold, so here it goes.

Usage:
XMLValidator val = new XMLValidator();
if (!val.IsValidXml(File.ReadAllText(@"d:\Test2.xml"), @"D:\Test2.xsd"))
   MessageBox.Show(val.Errors);

Code:
public class CXmlValidator
{
    private int nErrors = 0;
    private string strErrorMsg = string.Empty;
    public string Errors { get { return strErrorMsg; } }
    public void ValidationHandler(object sender, ValidationEventArgs args)
    {
        nErrors++;
        strErrorMsg = strErrorMsg + args.Message + "\r\n";
    }

    public bool IsValidXml(string strXml/*xml in text*/, string strXsdLocation /*Xsd location*/)
    {
        bool bStatus = false;
        try
        {
            // Declare local objects
            XmlTextReader xtrReader = new XmlTextReader(strXsdLocation);
            XmlSchemaCollection xcSchemaCollection = new XmlSchemaCollection();
            xcSchemaCollection.Add(null/*add your namespace string*/, xtrReader);//Add multiple schemas if you want.

            XmlValidatingReader vrValidator = new XmlValidatingReader(strXml, XmlNodeType.Document, null);
            vrValidator.Schemas.Add(xcSchemaCollection);

            // Add validation event handler
            vrValidator.ValidationType = ValidationType.Schema;
            vrValidator.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);

            //Actual validation, read conforming the schema.
            while (vrValidator.Read()) ;

            vrValidator.Close();//Cleanup

            //Exception if error.
            if (nErrors > 0) { throw new Exception(strErrorMsg); }
            else { bStatus = true; }//Success
        }
        catch (Exception error) { bStatus = false; }

        return bStatus;
    }
}

Here is a kb that demonstrates the use of several types of validation. This site provides Xml/Schema validation online.

Following is the code using non deprecated methods.
public bool IsValidXmlEx(string strXmlLocation, string strXsdLocation)
{
    bool bStatus = false;
    try
    {
        // Declare local objects
        XmlReaderSettings rs = new XmlReaderSettings();
        rs.ValidationType = ValidationType.Schema;
        rs.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ReportValidationWarnings;
        rs.ValidationEventHandler += new ValidationEventHandler(rs_ValidationEventHandler);
        rs.Schemas.Add(null, XmlReader.Create(strXsdLocation));

        using (XmlReader xmlValidatingReader = XmlReader.Create(strXmlLocation, rs))
        { while (xmlValidatingReader.Read()) { } }

        ////Exception if error.
        if (nErrors > 0) { throw new Exception(strErrorMsg); }
        else { bStatus = true; }//Success
    }
    catch (Exception error) { bStatus = false; }

    return bStatus;
}

void rs_ValidationEventHandler(object sender, ValidationEventArgs e)
{
    if (e.Severity == XmlSeverityType.Warning) strErrorMsg += "WARNING: " + Environment.NewLine;
    else strErrorMsg += "ERROR: " + Environment.NewLine;
    nErrors++;
    strErrorMsg = strErrorMsg + e.Exception.Message + "\r\n";
}


Happy validation!

Monday, March 29, 2010

Preloaders.net: Cool, free loader icons!

Preloaders.net is a new startup, providing free ajax loader icons that comes handy when you in the middle of a development! The UI is simple and easy, but with quite a number of ad's distracting attention. But nothing comes for free... use it to find the icons you need right away and on the fly!

Tuesday, March 16, 2010

Joel Spolsky stops writing!

Last column in Inc.
So, having become an Internet celebrity in the narrow, niche world of programming, I've decided that it's time to retire from blogging. March 17, the 10th anniversary of Joel on Software, will mark my last major post. This also will be my last column for Inc. For the most part, I will also quit podcasting and public speaking. Twitter? "Awful, evil, must die, CB radio, sorry with only 140 chars I can't tell you why."


But he plans to come up with something different:
What we need now, I feel, is not another essay repeating No Silver Bullet for the 18,000th time. We need something that is more objective (based on measurable truth and falseness rather than just lists of anecdotes about successful projects and failed projects). We need something that reflects the best new ideas about what authorship means in 2010, not just electronic forms of 18th-century pamphlets. We need to stop rewriting the same things again and again (fail fast! NDAs are worthless! Execution matters, not ideas! Use the right tools for the job!). Instead we should start filling in the long tail of knowledge.

Crystal Reports Viewer: "This field name is not known.” Error!

Crystal Report Viewer "This field name is not known.” Error!

I was using Crystal Reports Viewer control in my ASP.NET web application; when some of the reports, out of thousands, didn't seem to work. Although, those reports worked fine in Crystal Reports Designer IDE; but when run in my web app, I was thrown this this field name is not known error. So, had to dig in and fix the thing up on production.

Problem symptoms:
  • When trying to view a report in Report Viewer the report prompts for parameters and then gets stuck with an error message box titled "Crystal Report Viewer" and the error is "This field name is not known."
  • Some reports are showing error that "This field name is not known." - problem in report formula?

  • Same report, I can view with CR Designer IDE but CR Viewer (web based) throws the error "This field name is not known.".

Refer to this discussion for more information. And the problem that I was having, see following figure.



Dint find anything useful on Business Objects’s search-unfriendly web forum. Then I came across this Crystal Reports Fix (HTTP location, or FTP location); following two issues made me try this fix:

 Which, un/fortunately didn't work either!

Resolution:
What actually helped, atlast, is this post here on MSDN forum, in guessing” the possible reasons of what might have been going wrong.

Following actually worked:
string strLocation = connectionInfo.DatabaseName + ".dbo." + table.Location.Substring(table.Location.LastIndexOf(".") + 1);

table.Location = strLocation;

So, after applying the new ApplyLogOnInfo(), you will need to set the table location explicitly - again - so that, it would remove old values and apply anew.

Following generic method might help:
private void SetDBLogonToTables(CrystalDecisions.Shared.ConnectionInfo connectionInfo, CrystalDecisions.CrystalReports.Engine.ReportDocument reportDocument)
{
    CrystalDecisions.CrystalReports.Engine.Tables tables = reportDocument.Database.Tables;

    foreach (CrystalDecisions.CrystalReports.Engine.Table table in tables)
    {
        CrystalDecisions.Shared.TableLogOnInfo tableLogonInfo = table.LogOnInfo;

        tableLogonInfo.ConnectionInfo = connectionInfo;
        table.ApplyLogOnInfo(tableLogonInfo);

           //Following, did the trick! 
            try
            {
                string strLocation = connectionInfo.DatabaseName + ".dbo." + table.Location.Substring(table.Location.LastIndexOf(".") + 1);

                table.Location = strLocation;
            }
            catch (Exception ex)
            {//Catch 
            }
    }
}
Will Rickards has provided a nice example, accessing multiple databases changing the datasource location of the report during runtime.

Someone pretty pissed off, wrote:
“…and no thanks to anyone involved in the development of Crystal Reports. There is no good excuse for the dozens of problems that Crystal Reports has and continues to have.
…so it won't be long before the Crystal company (currently Business Objects?) is sueing Microsoft for putting them out of business by creating a superior product.”

David Hilton in the end, adds to the post that I referred to earlier:
We don't have a good process for publishing the release notes for Crystal Reports to the SDN yet. We are discussing this issue with the program managers to have them released regularly.

Happy crystallizing the reports! (0:

Friday, March 12, 2010

Active Directory: Not showing all users issue

Issue: Active Directory not showing all users

There is an active directory related issue, which does not list all users available in the AD. This occurs because of the fact that if DirectorySearcher.PageSize is not set then the server defaults that property to 1000.

Set .PageSize property of your searcher object to 1000, sets the page size and LDAP handles the pagination internally automatically. And Michael Freidgeim is a great guy!

Happy roaming around the active directory (0:

.NET: How to merge multiple Excel workbooks into one?

How to merge multiple Excel workbooks into one?

Only if you want something like: Merge(@"E:\Test", @"E:\FinalDestination.xls");

Use following code.
private void Merge(string strSourceFolder, string strDestinationFile)
{
    try
    {
        //1. Validate folder,
        //2. Instantiate excel object
        //3. Loop through the files
        //4. Add sheets
        //5. Save and enjoy!

        object missing = System.Reflection.Missing.Value;
        Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
        ExcelApp.Visible = false;

        //Create destination object
        Microsoft.Office.Interop.Excel.Workbook objBookDest = ExcelApp.Workbooks.Add(missing);


        foreach (string filename in Directory.GetFiles(strSourceFolder))
        {
            if (File.Exists(filename))
            {
                //create an object
                Microsoft.Office.Interop.Excel.Workbook objBookSource = ExcelApp.Workbooks._Open
              (filename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing
              , Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);


                //Browse through all files.
                foreach (Microsoft.Office.Interop.Excel.Worksheet sheet in objBookSource.Worksheets)
                {
                    sheet.Copy(Type.Missing, objBookDest.Worksheets[objBookSource.Worksheets.Count]);
                }

                objBookSource.Close(Type.Missing, Type.Missing, Type.Missing);
                objBookSource = null; 

            }
        }
        objBookDest.SaveAs(strDestinationFile, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
        objBookDest.Close(Type.Missing, Type.Missing, Type.Missing);
       
        objBookDest = null;
        ExcelApp = null;


    }
    catch (System.Exception e)
    {
        //Catch
    }
}

Btw, this was in response to a post on StackOverflow.

Thursday, March 11, 2010

Dependency Graphs: Visualizing Object Graphs

Dependency Graphs: Visualizing object graphs with DGML

Among several, Visual Studio.NET 2010 has a new feature that allows you to create nice directed graphs with a markup language called DGML (Directed Graph Markup Language).

Jason Zander provides explains the feature in nice visuals; while Cameron Skinner writes in detail of how it works. 



If you are too much into the debugging scenario then, Mohammed Mahmoud has a debugger-extension that takes the output of !gcroot and creates a graph that one can interact with easily in Visual Studio 2010. If this feature sounds cool then this discussion is a must go-through.

Saturday, March 6, 2010

GWave: Google Wave

Google Wave has a lot of innovative features, but here are just a few:
  • Real-time: In most instances, you can see what someone else is typing, character-by-character.
  • Embedd'ability: Waves can be embedded on any blog or website.
  • Applications and Extensions: Just like a Facebook (Facebook) application or an iGoogle gadget, developers can build their own apps within waves. They can be anything from bots to complex real-time games.
  • Wiki functionality: Anything written within a Google Wave can be edited by anyone else, because all conversations within the platform are shared. Thus, you can correct information, append information, or add your own commentary within a developing conversation.
  • Open source: The Google Wave code will be open source, to foster innovation and adoption amongst developers.
  • Playback: You can playback any part of the wave to see what was said.
  • Natural language: Google Wave can autocorrect your spelling, even going as far as knowing the difference between similar words, like “been” and “bean.” It can also auto-translate on-the-fly.
  • Drag-and-drop file sharing: No attachments; just drag your file and drop it inside Google Wave and everyone will have access.
You can find a complete guide at Mashable.

Is Google Wave a Twitter Killer?
Alot of debate goes on todate if twitter or facebook is going to fade away with the rise in visibility of google wave across the "consumer" community.
What Google is after here is the ability to construct conversations and not just a thread but where each participant came in. So we have the originator, that asked a question, the first respondent and the third, not just the third respondent, but where and how that third respondent entered the conversation and why. You can fill in the rest. - Chris Lang, follow on GBuzz.
Even if FB is not going to be killed, it would be provided with tough a time maintaining Facebook or Twitter; akin to Yahoo fading away when Google walked in. But to gain market control, Google would want consumers as well corporate-consumers (probably Twitter, FB and the likes) to build upon/surrounding the wave APIs.

So when should you use Google Wave? Some of the areas that you can cater using google wave are:
  • Organizing events
  • Group projects
  • Photo sharing
  • Meeting notes
  • Brainstorming
  • Interactive games
Another application for third party software vendors, in case if you are interested in a collaborative diagramming app, take a look at the following video. Midway through the video, you can see several users collaboratively editing a SAP business process flow.



The IDE in the video is Eclipse, NetWeaver Developer Studio (NWDS) for SAP development, but thats just the framework.

Another application of using dynamic work flow using Google Wave for corporate customers is worth checking out.


Sign up? Would you still want to sign up for google wave, here you go.

Developing upon Google Wave?
If you are interested in running your own wave setup using the information here and experiment with, try logging onto waveprotocol.org;

At this time the sandbox doesn't allow robots to run other than on AppEngine at the moment - if you know any Java at all you might want to follow the Java Robot Tutorial to get an idea of the kind of thing you'll be able to do; that Jon Skeet is maintaining.

Here is Google Wave developer preview:



You might also need the Google Wave API forum along with the API/SDK FAQ list. This resource contains more information.

Should you feel like digging more into it; this article is a definite read; the guy has come up with a small program called Bingy Bot; a bot that answers to your question. It uses Bing APIs (link requires you to login) to search for the question asked; the bot gets plugged into the wave.
Type a question, like "what is an elephant?" or just key in a flight number to get the status. Bingy will answer if it knows. Bingy interfaces with Bing using the XML APIs to do instant searches.
Wave Gadgets site is already up and running in production, where you can find - the community maintained -  catalog for extensions to Google Wave. Currently listing 39 gadgets and 116 robots.

Now that the Wave of Google Wave is here, only time would tell what lies there in future. Or probably, as someone pointed out, Google Wave is here for us to:
  1. Making life "more" unsocial;
  2. Make communications that would be ill-advised in real-life
  3. Buy things we haven't seen in real life
  4. Unlearn things that are useful in real life (like spelling)
Happy Waving! (0:

Friday, March 5, 2010

EF4: ADO.NET Entity Framework v4.0

ADO.NET: Entity Framework v4.0 EF4

EF, sometimes called EF4 because it forms a part of .NET v4.0, is a relatively new ORM growing fast in Microsoft Developer Community. It is expected to leave NHB behind; at this time nHibernate is has an edge that it is mature; but it does come with a bit of learning curve where HBM mapping files are concerned.

FIG1: System
Why Use? The primary goal of the is to raise the level of abstraction for data programming, to eliminate the mismatch between data models and between languages that application developers would otherwise have to deal with.

Entity Data Model (EDM) is defined by CSDL, SSDL, and MSL. Conceptual Schema Definition Language(CSDL) is a design template used to declare and define entities, its associations; the classes are generated using CSDL. If you do have Visual Studio IDE then it would do that for you. Store schema definition language(SSDL), contains formal description of the database that persist data. And Mapping specification language(MSL), used to connect the types declared in CSDL to database metadata.
FIG2: Model Classes Generated by IDE


Large models and entity splitting?
Why would you split entity in EF? Entity Splitting involves mapping a single entity in the conceptual layer to multiple tables in the store.

And sometimes with big models say 500+ tables with alot of database relation you might encounter problems with performance. Therefore in general as a rule of thumb "you should start thinking about breaking up a model when it has reached 50-100 entities". So then you think about handling large datastore. Here is how you would split your edmx files?

EF4 performance and benchmark(1000+ tables)?
Gergely Orosz did a performance test between nHibernate and Entity Framework, which is worth checking out. Measurement was done by implementing two simple applications using the same table structure and doing the same operations on the same data. But at this time the designer response starts fluctuating with 150+ tables and you may experience something that you wouldn't want.

EF4 Security Considerations?
MSDN article provides a list of security considerations that are specific to developing, deploying, and running EF based applications.


I believe its the lack of maturity of the product that some see current state of EF as a concern. Its only a matter of time for EF to prove itself. The points that are raised are:
  • Inordinate focus the data aspect of entities leads to degraded entity architectures
  • Excess code needed to deal with lack of lazy loading
  • Shared, canonical model contradicts software best practices
  • Lack of persistence ignorance causes business logic to be harder to read, write, and modify, causing development and maintenance costs to increase at an exaggerated rate
  • Excessive merge conflicts with source control in team environments
They expect the future of the entity framework, would be fully equipped with Lazy Loading, TableValueFunctions, Less-Xml.

VS2010-Beta 2 includes some great new features and updates for the Entity Framework 4 and ADO.NET Data Services 4.

A good place to start? Depending on what you are most interested in, you should consider getting started with this quickstart that illustrates a series of tasks; or look into the topics in Getting Started. These tasks are designed to help become familiar with the EF.

You can find samples here at Documentation Samples website for Visual Studio 2008. Although EF comes with VS2008 SP1; but if you must, then download it from here.

Besides that EF4, when used with ASP.NET MVC, creates Model classes automatically, which helps reduce the development time radically; this article goes way deeper to build n-tier apps with EF4.

However, at the end of the day the real deal is about Performance - and Delighted Customer; well, and in terms of project-growth, any tool that we use "requires attention".

Thursday, March 4, 2010

Getting Results - The Agile Way

I did get a chance to go through the one page guide of an ebook "Getting Started with Agile Results". There are 3 keys to getting started with Agile Results. To adopt the Agile Results system:

  1. Adopt The Rule of 3 to avoid overwhelm and get mindful about your results.
  2. Adopt the Monday Vision, Daily Outcomes, Friday Reflection pattern for weekly results.
  3. Set boundaries in your Hot Spots to find work life balance.


By Dr. Rick Kirschner a motivational speaker and educator. The book is free (in draft form) while it's being written.

WUFOO

http://WUFOO.com

A cool online html form builder. Good thing is that it provides free signup, from which you can create 3 forms for free. Not so good thing is that the site itself is not free and has pricing plans from USD 15 to 200!

But the site is worth checking out.

Related Posts

Popular Posts