Wednesday, 31 July 2013

Import xml data from xml file into MS Access database file



DBXmlInfo.xml
<?xml version="1.0" encoding="UTF-8"?>
<dataroot xmlns:od="urn:schemas-microsoft-com:officedata" generated="2013-07-29T16:57:21">
 
  <Employees>
    <Employee>
        <EmpId>1001</EmpId>
        <Name>Ravi</Name>
        <Salary>111</Salary>
    </Employee>
    <Employee>
      <EmpId>1002</EmpId>
      <Name>Rahul</Name>
      <Salary>222</Salary>
    </Employee>
    <Employee>
      <EmpId>1003</EmpId>
      <Name>Chandan</Name>
      <Salary>333</Salary>
    </Employee>  
  </Employees>

  <studuents>
    <student>
      <StuId>2001</StuId>
      <Name>Ankit</Name>
      <RollNo>123</RollNo>
    </student>
    <student>
      <StuId>2002</StuId>
      <Name>Neetu</Name>
      <RollNo>456</RollNo>
    </student>
  </studuents>   
</dataroot>


C# Code
Microsoft.Office.Interop.Access.Application objAccess = new Microsoft.Office.Interop.Access.Application();

//objAccess.NewCurrentDatabase("c:\\TestDb.mdb", Microsoft.Office.Interop.Access.AcNewDatabaseFormat.acNewDatabaseFormatAccess2007);
objAccess.OpenCurrentDatabase("c:\\TestDb.mdb", false, "abc123");               

objAccess.ImportXML("C:\\DBXmlInfo.xml", Microsoft.Office.Interop.Access.AcImportXMLOption.acStructureAndData);

objAccess.CloseCurrentDatabase();
                objAccess.Quit(Microsoft.Office.Interop.Access.AcQuitOption.acQuitSaveAll);



Output
Above code will create two tables in TestDb.mdb database with like:
Employee
EmpId
Name
Salary
1001
Ravi
111
1002
Rahul
222
1003
Chandan
333

Student
StuId
Name
RollNo
2001
Ankit
123
2002
Neetu
456


Wednesday, 24 July 2013

WPF Performance Tips

Windows Presentation Foundation provides a very comfortable way to develop rich user experiences. A drop shadow for example can add by inserting two simple lines of XML. But this simplicity can also mislead us to overuse them. This leads to performance issues. The following tips may help you to avoid or fix them.
1) Dispatch expensive calls: either within the UI thread with a lower DispatcherPriority by calling Dispatcher.BeginInvoke() or to a background thread by using a BackgroundWorker to keep the UI responsive.
2) Fix binding errors: because they consume a lot of time, trying to resolve the path error, including searching for attached properties. You can find them by looking for System.Windows.Data Error in the Visual Studio output log.
3)  Reduce the number of visuals: by removing unneeded elements, combining layout panels and simplifying templates. This keeps the memory footprint small and improves the rendering performance.
4)   Prevent Software Rendering: the use of transparent windows by setting AllowsTransparency to true or using old BitmapEffects can cause WPF to render the UI in software on Windows XP, which is much slower.
5) Load resources when needed: even though it's the most comfortable way to merge all resources on application level it can also cost performance by loading all resources at startup. A better approach is to load only often used resources and load the other on view level.
6)    Virtualize lists and views: by using a VirtualizingStackPanel as ItemsPanel for lists. This only creates the visible elements at load time. All other elements are lazy created when they get visible. Be aware that grouping or CanContextScrol="True" prevents virtualization.
7)   Enable Container Recycling: virtualization brings a lot of performance improvements, but the containers will be disposed and recreated, this is the default. But you can gain more performance by recycle containers by setting VirtualizingStackPanel.VirtualizationMode="Recycling".
8)  Freeze Freezables: by calling Freeze() in code or PresentationOptions:Freeze="true" in XAML. This reduces memory consumption and improves performance, because the system doesn’t need to monitor for changes.
9) Disable Assembly localization: if you don't need it. By using the [NeutralResourcesLanguageAttribute]. This prevents an expensive lookup for satellite assemblies.
10) Lower the frame rate of animations: by setting Storyboard.DesiredFrameRate to lower the CPU load. The default is 60 frames/second.
11) Use StreamGeometries instead of PathGeometries: if possible to draw complex 2D geometries, because they are much more efficient and consume less memory.


Tuesday, 16 July 2013

WPF How to implement a reusable ICommand



If you are using the MVVM (model-view-viewmodel) pattern, one of the most used mechanisms to bind actions to the view is commands. To provide a command, you have to implement the ICommand interface. This is quite simple, but you have to do it over and over again. This is cumbersome.
The idea of this pattern build an universal command, that takes two delegates: One that is called, when ICommand.Execute(object param) is invoked, and one that evalues the state of the command when ICommand.CanExecute(object param) is called.
In addition to this, we need a method, which triggers the CanExecuteChanged event. This causes the UI element to reevaluate the CanExecute() of the commmand.
public class DelegateCommand : ICommand
{
    private readonly Predicate<object> _canExecute;
    private readonly Action<object> _execute;

    public event EventHandler CanExecuteChanged;

    public DelegateCommand(Action<object> execute)
                   : this(execute, null)
    {
    }

    public DelegateCommand(Action<object> execute,
                   Predicate<object> canExecute)
    {
        _execute = execute;
        _canExecute = canExecute;
    }

    public override bool CanExecute(object parameter)
    {
        if (_canExecute == null)
        {
            return true;
        }

        return _canExecute(parameter);
    }

    public override void Execute(object parameter)
    {
        _execute(parameter);
    }

    public void RaiseCanExecuteChanged()
    {
        if( CanExecuteChanged != null )
        {
            CanExecuteChanged(this, EventArgs.Empty);
        }
    }
}