Sunday, September 29, 2013

How can we write a good stored procedure

A few days ago there was an article with 20 tips to write a good stored procedure (requires free registration to read). The problem is that there are really only 12 good tips (and 4 bad and 4 neither good or bad). So let me go over the tips one by one and comment on them:
  1. Capital letters for keywords and proper indentation. With todays code editors with syntax high lighting I don't see why you want to high light keywords with capital letters. The code editor will do that for you. And suggesting proper indentation is not really a tip to write a good stored procedure. It's common (coding) sense! So I don't think this one counts... Score (good-not really-bad advice IMHO): 0-1-0.
  2. Use SQL-92 syntax for joins. If MS SQL server drops support for the old syntax this is good advice. Score: 1-1-0
  3. Use as few variables as possible. The article mentions cache utilization as an argument. Sounds like premature optimization to me. I'd say use as many variables as makes sense to make the code most readable. If that turns out to be a problem, then you optimize. So in general I found this advice to be bad.Score: 1-1-1
  4. Minimize usage of dynamic queries. Kudos to the article to pointing out how to minimize the bad of dynamic queries and I guess technically minimizing could mean zero but that is really the only good advice; don't use dynamic queries. So once again a bad, or at least misleading advice IMHO. Score: 1-1-2
  5. Use fully qualified names. If you don't do this you might end up with some weird behavior so this is a good advice. Score: 2-1-2
  6. Set NOCOUNT on. Good advice: Score: 3-1-2
  7. Don't use sp_ prefixScore: 4-1-2
  8. KEEPFIXED PLAN. Learn from this article and use it correctly. Hard to argue with "learn something and use it right". Score: 5-1-2
  9. Use select instead of set. Once again performance is mentioned as a motivator. However the potential bad side effects of using select rather than set are more important in my opinion. The problem with select is that the variable might not be set if a query returns no rows and the set gives you an error if the select returns more than one row. Read more about it here. I'd definitely prefer set over select. Score: 5-1-3
  10. Compare the right thing in the where clause. This advice just confuses me. The article talks about what operators are the fastest and then refers to this page talking about preference. Even though the article is confusing on this point the basic idea is correct. For example using IN is generally faster than NOT IN. So I'll call this one a draw. Score: 5-2-3
  11. Avoid OR in WHERE clause. This is good advise for good performance. Score: 6-2-3
  12. Use CAST over Convert. CAST is SQL92 standard. Convert is not. Score: 7-2-3
  13. Avoid distinct and order by. Once again this is common sense. Don't do things you don't need... Score: 7-3-3
  14. Avoid cursors. This falls into the same category as dynamic queries to me. The only good advice is don't use cursors. Score: 7-3-4
  15. Select only the columns you need. Common sense! Score: 7-4-4
  16. Sub queries vs joins. Article lists a few good rule of thumbs. I think you should use whatever is most readable. Score: 8-4-4
  17. Create table vs select into. Article points out important differences. Score: 9-4-4
  18. Use variables instead of temporary tablesScore: 10-4-4
  19. Use proper indexesScore: 11-4-4
  20. Use profiler. Many tips in the article suggest you do things to improve performance. But I think doing so before you know you have a problem is a waste of time and resources. So this advice is actually one of the best advices in the article. Score: 12-4-4

Logical Processing Order of the SELECT statement

The following steps show the logical processing order, or binding order, for a SELECT statement. This order determines when the objects defined in one step are made available to the clauses in subsequent steps. For example, if the query processor can bind to (access) the tables or views defined in the FROM clause, these objects and their columns are made available to all subsequent steps. Conversely, because the SELECT clause is step 8, any column aliases or derived columns defined in that clause cannot be referenced by preceding clauses. However, they can be referenced by subsequent clauses such as the ORDER BY clause. Note that the actual physical execution of the statement is determined by the query processor and the order may vary from this list.
  1. FROM
  2. ON
  3. JOIN
  4. WHERE
  5. GROUP BY
  6. WITH CUBE or WITH ROLLUP
  7. HAVING
  8. SELECT
  9. DISTINCT
  10. ORDER BY
  11. TOP

Thursday, September 26, 2013

Pass and get json string from page to page in Silverlight

Convert dictionary to json string:
 public static string ConvertToString<TKey, TValue>(this IDictionary<TKey, TValue> dictionary)
        {            
            IDictionary<stringstring> _dic = new Dictionary<stringstring>();
            foreach (var item in dictionary)
            {
                if (item.Key.ToString().Contains('.'))
                {
                    string key = item.Key.ToString().Split('.')[1];
                    _dic.Add(key, item.Value.ToString());
 
                }
                else
                {
                    _dic.Add(item.Key.ToString(), item.Value.ToString());
                }
            }
 
            return string.Join(",", _dic.Select(kv => kv.Key.ToString().Trim() + "*" + kv.Value.ToString().Trim()).ToArray()).Replace(' ''~').Replace('&''!');
        }

Get json to dictionary:

private void ConvertStringToList(string ColumnList)
        {
            try
            {
                if (!string.IsNullOrEmpty(ColumnList))
                {
                    ColumnList = ColumnList.Replace('~'' ');
                    ColumnList = ColumnList.Replace("!""&");
                    List<string> colList = ColumnList.Split(',').ToList<string>();
                    foreach (string colItem in colList)
                    {
                        if (colItem.Contains('*'))
                        {
                            reportColumnList.Add(colItem.Split('*')[0].ToString(), colItem.Split('*')[1].ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

Tuesday, August 27, 2013

XAML Edit in Silverlight

NameSpace:
using System.Windows.Controls;
using System.IO;
using System.Windows.Markup;
using System.Text.RegularExpressions;

Coding:
public static ResourceDictionary ChangeXAML(double incFactor, string fontStyleUri)
        {
            Uri _styleUri = new Uri(fontStyleUri, UriKind.Relative);
            if (_styleUri == null)
                return null;
            int _index = 0;
            int _count = 0;

            StreamReader strmReader = new StreamReader(Application.GetResourceStream(_styleUri).Stream);
            string resText = strmReader.ReadToEnd();

            IEnumerable<string> strFontSize = GetSubStrings(resText, "FontSize\">", "</sys:Double>");

            foreach (string value in strFontSize)
            {
                if (resText.Contains("FontSize\">" + value))
                {
                    _index = resText.IndexOf("FontSize\">" + value) + ("FontSize\">").Length;
                    _count = value.Length;
                    resText = resText.Remove(_index, _count);
                }
            }

            foreach (string value in strFontSize)
            {
                if (resText.Contains("FontSize\"></sys:Double>"))
                {
                    _index = resText.IndexOf("FontSize\"></sys:Double>") + ("FontSize\">").Length;
                    double newFontSize = Double.Parse(value) * incFactor;
                    resText = resText.Insert(_index, newFontSize.ToString());
                }
            }

            return XamlReader.Load(resText) as ResourceDictionary;
        }

        private static IEnumerable<string> GetSubStrings(string input, string start, string end)
        {
            Regex r = new Regex(Regex.Escape(start) + "(.*?)" + Regex.Escape(end));
            MatchCollection matches = r.Matches(input);
            foreach (Match match in matches)
                yield
                    return match.Groups[1].Value;
        }

Saturday, July 20, 2013

Started with the MVVM Pattern in Silverlight

Wondering what all the hype is about MVVM and whether or not you should integrate it into your Silverlight projects? In this post, Dan Wahlin walks through the fundamentals of what the MVVM pattern is and why you should learn more about it.

Thursday, June 13, 2013

Most Important Link in Silverlight

--Silverlight

http://blogs.msdn.com/b/jgoldb/archive/2008/02/04/finding-memory-leaks-in-wpf-based-applications.aspx
http://www.codeproject.com/Articles/320232/Notification-Control-in-Silverlight
http://www.codeproject.com/Articles/37633/Silverlight-MultiBindings-How-to-attach-multiple-b
http://blogs.msdn.com/b/scmorris/archive/2008/04/14/defining-silverlight-datagrid-columns-at-runtime.aspx
http://pendsevikram.blogspot.com/2009/09/silverlight-3-datagrid-beyond.html
http://msdn.microsoft.com/en-us/library/ms996459.aspx
http://www.codeproject.com/Articles/42928/DataGrid-with-Movable-Rows
http://www.codeproject.com/Articles/234150/Silverlight-Menu4U
http://www.codeproject.com/Articles/30478/Text-on-A-Path-for-Silverlight
http://www.c-sharpcorner.com/uploadfile/mahesh/graphics-path-in-silverlight/
http://www.silverlightshow.net/items/Tip-How-to-declare-a-dependancy-property-in-Silverlight.aspx
https://skydrive.live.com/?cid=2c5f5b0560e374cb&id=2C5F5B0560E374CB%21440
https://skydrive.live.com/?cid=0ee4bd0f5ea745c6&id=EE4BD0F5EA745C6%21385&authkey=!
http://www.news2news.com/vfp/?example=374&ver=vcs
http://michaelcrump.net/yet-another-beeping-p/invoke-demo-sl5-rc
http://www.silverlightshow.net/items/Defining-Silverlight-DataGrid-Columns-at-Runtime.aspx
http://www.ditran.net/silverlight-datagrid-dynamic-columns-adding-code-behind-sortabilities
http://www.componentone.com/newimages/Products/Documentation/Silverlight.DataGrid.pdf
http://www.codeproject.com/Tips/569335/Automatically-Printing-an-RDLC-file-in-ASP-NET-MVC
http://www.codeproject.com/Articles/223040/Silent-printing-in-Silverlight
http://msdn.microsoft.com/en-us/library/ms157328.aspx
http://social.msdn.microsoft.com/Forums/en-US/vsreportcontrols/thread/c29e929d-573a-453e-8393-0f3e86065921/
http://www.codeproject.com/Articles/306012/Silverlight-Dynamic-Themes
http://blog.falafel.com/blogs/josh-eastburn/2011/07/07/custom_silverlight_application_themes
http://bytescout.com/products/developer/barcodesdk/bytescoutbarcodesdk_display_barcodes_in_local_reports_rdlc.html
http://www.silverlightshow.net/items/How-to-distribute-a-Silverlight-OOB-Application.aspx
http://www.codeproject.com/Articles/21507/DAL-Class-and-Transact-SQL-Generator-for-C-and-VB
http://blogs.msdn.com/b/deepm/archive/2010/06/13/theme-pack-for-silverlight-business-application-released.aspx
https://skydrive.live.com/?cid=2c5f5b0560e374cb&id=2C5F5B0560E374CB%21560&authkey=!

http://lbrtdotnet.wordpress.com/2011/08/12/reporting-services-creating-a-dynamic-column-tablix-report-using-rdl-generator/
http://vbjunkbox.blogspot.com/2011/10/dynamically-adding-columns-to-reporting.html
http://social.msdn.microsoft.com/forums/en-US/sqlreportingservices/thread/9e6043f1-c458-4540-be59-d37b02feab8a/
http://csharpshooter.blogspot.com/2007/08/generate-rdlc-dynamically-for-vs-2005.html

http://www.w3.org/TR/WCAG20-TECHS/SL22.html
http://www.w3.org/TR/WCAG20-TECHS/SL23

--MVC 4
http://www.codeproject.com/Articles/470107/ASP-NET-MVC-4-Part-1-Introduction


--very  very important
http://www.webservicex.net/

Wednesday, May 29, 2013

XmlSerializer to Serialize Class to Xml and Bulk Load Data

you can generally store XML in a SQL Server table using normal CRUD procs.  The example below uses an XmlDocument as the source but XML from any source may be used. 
CREATE TABLE dbo.XMLTable(
  XMLTableID int NOT NULL IDENTITY(1, 1) CONSTRAINT PK_XMLTable PRIMARY KEY
  ,XMLColumn xml
 );
GO

CREATE PROC dbo.InsertXML
 @XmlParameter XML
AS
INSERT INTO dbo.XMLTable (XMLColumn) VALUES(@XmlParameter);
SELECT CAST(SCOPE_IDENTITY() AS int) AS XMLTableID;
GO
var xmlObject = new XmlDocument();
xmlObject.LoadXml("<Root><Clild>child text</Clild></Root>");
var connection = new SqlConnection(@"Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=SSPI");
connection.Open();
var command = new SqlCommand("dbo.InsertXML", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@XMLParameter", SqlDbType.Xml);
command.Parameters["@XMLParameter"].Value = xmlObject.OuterXml;
int XmlTableID = (int)command.ExecuteScalar();
connection.Close();

OR=================================================================
http://www.nullskull.com/articles/system.xml.xmlserialization.asp

private bool SerializeObject<TEntity>(TEntity obj, string xmlFilePath)
        {
            string path = xmlFilePath + ".xml";
            XmlSerializer serializer = new XmlSerializer(typeof(TEntity));
            // Create an XmlTextWriter using a FileStream.
            Stream fs = new FileStream(path, FileMode.Create);
            XmlWriter writer = new XmlTextWriter(fs, Encoding.Unicode);
            // Serialize using the XmlTextWriter.
            serializer.Serialize(writer, obj);
 
            writer.Flush();
            writer.Close();
            return true;
        }

Monday, May 27, 2013

The Philosophies of MVVM

There was a very long and interesting thread about MVVM today amongst the WPF Disciples.  The thread started out with a simple thought: using a ViewModel eliminates most scenarios where value converters are necessary.  My point was that a ViewModel class is essentially a value converter on steroids, thus rendering the IValueConverter interface irrelevant for most bindings.
This comment lead to a very engaging discussion about peoples’ fundamental philosophies regarding how a well-designed WPF application should be built.  Some people strongly disagreed with me, and gave lucid explanations of why.  It was a real eye-opener for me to have fellow MVVM advocates express opinions that, while completely valid and reasonable, are strikingly different from my own.
The thread even took a brief detour into something I’ve been thinking about for a while now but never publicly discussed: MMVVVVM!  Yeah, I know, that’s a terrible name for a design pattern…
If this sort of thing interests you, I highly suggest you set aside some time to read this thread.  What are your thoughts about this?


Thursday, May 16, 2013

Adjust Maximum Resulation in silverlight


Add Class File which is name is CResolution.cs
Copy and paste below code into above class

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows;
using System.Linq;

[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi)]
public struct DEVMODE
{
    public const int CCHDEVICENAME = 32;
    public const int CCHFORMNAME = 32;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHDEVICENAME)]
    [System.Runtime.InteropServices.FieldOffset(0)]
    public string dmDeviceName;
    [System.Runtime.InteropServices.FieldOffset(32)]
    public Int16 dmSpecVersion;
    [System.Runtime.InteropServices.FieldOffset(34)]
    public Int16 dmDriverVersion;
    [System.Runtime.InteropServices.FieldOffset(36)]
    public Int16 dmSize;
    [System.Runtime.InteropServices.FieldOffset(38)]
    public Int16 dmDriverExtra;
    [System.Runtime.InteropServices.FieldOffset(40)]
    public DM dmFields;

    [System.Runtime.InteropServices.FieldOffset(44)]
    Int16 dmOrientation;
    [System.Runtime.InteropServices.FieldOffset(46)]
    Int16 dmPaperSize;
    [System.Runtime.InteropServices.FieldOffset(48)]
    Int16 dmPaperLength;
    [System.Runtime.InteropServices.FieldOffset(50)]
    Int16 dmPaperWidth;
    [System.Runtime.InteropServices.FieldOffset(52)]
    Int16 dmScale;
    [System.Runtime.InteropServices.FieldOffset(54)]
    Int16 dmCopies;
    [System.Runtime.InteropServices.FieldOffset(56)]
    Int16 dmDefaultSource;
    [System.Runtime.InteropServices.FieldOffset(58)]
    Int16 dmPrintQuality;

    [System.Runtime.InteropServices.FieldOffset(44)]
    public POINTL dmPosition;
    [System.Runtime.InteropServices.FieldOffset(52)]
    public Int32 dmDisplayOrientation;
    [System.Runtime.InteropServices.FieldOffset(56)]
    public Int32 dmDisplayFixedOutput;

    [System.Runtime.InteropServices.FieldOffset(60)]
    public short dmColor;
    [System.Runtime.InteropServices.FieldOffset(62)]
    public short dmDuplex;
    [System.Runtime.InteropServices.FieldOffset(64)]
    public short dmYResolution;
    [System.Runtime.InteropServices.FieldOffset(66)]
    public short dmTTOption;
    [System.Runtime.InteropServices.FieldOffset(68)]
    public short dmCollate;
    [System.Runtime.InteropServices.FieldOffset(72)]
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHFORMNAME)]
    public string dmFormName;
    [System.Runtime.InteropServices.FieldOffset(102)]
    public Int16 dmLogPixels;
    [System.Runtime.InteropServices.FieldOffset(104)]
    public Int32 dmBitsPerPel;
    [System.Runtime.InteropServices.FieldOffset(108)]
    public Int32 dmPelsWidth;
    [System.Runtime.InteropServices.FieldOffset(112)]
    public Int32 dmPelsHeight;
    [System.Runtime.InteropServices.FieldOffset(116)]
    public Int32 dmDisplayFlags;
    [System.Runtime.InteropServices.FieldOffset(116)]
    public Int32 dmNup;
    [System.Runtime.InteropServices.FieldOffset(120)]
    public Int32 dmDisplayFrequency;
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct DISPLAY_DEVICE
{
    [MarshalAs(UnmanagedType.U4)]
    public int cb;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
    public string DeviceName;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
    public string DeviceString;
    [MarshalAs(UnmanagedType.U4)]
    public DisplayDeviceStateFlags StateFlags;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
    public string DeviceID;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
    public string DeviceKey;
}

public struct DISPLAY_SET
{
    public DEVMODE DeviceMode;
    public DISPLAY_DEVICE DisplayDevice;
}

public struct POINTL
{
    public Int32 x;
    public Int32 y;
}

[Flags()]
public enum DM : int
{
    Orientation = 0x1,
    PaperSize = 0x2,
    PaperLength = 0x4,
    PaperWidth = 0x8,
    Scale = 0x10,
    Position = 0x20,
    NUP = 0x40,
    DisplayOrientation = 0x80,
    Copies = 0x100,
    DefaultSource = 0x200,
    PrintQuality = 0x400,
    Color = 0x800,
    Duplex = 0x1000,
    YResolution = 0x2000,
    TTOption = 0x4000,
    Collate = 0x8000,
    FormName = 0x10000,
    LogPixels = 0x20000,
    BitsPerPixel = 0x40000,
    PelsWidth = 0x80000,
    PelsHeight = 0x100000,
    DisplayFlags = 0x200000,
    DisplayFrequency = 0x400000,
    ICMMethod = 0x800000,
    ICMIntent = 0x1000000,
    MediaType = 0x2000000,
    DitherType = 0x4000000,
    PanningWidth = 0x8000000,
    PanningHeight = 0x10000000,
    DisplayFixedOutput = 0x20000000
}

[Flags()]
public enum DisplayDeviceStateFlags : int
{
    /// <summary>The device is part of the desktop.</summary>
    AttachedToDesktop = 0x1,
    MultiDriver = 0x2,
    /// <summary>The device is part of the desktop.</summary>
    PrimaryDevice = 0x4,
    /// <summary>Represents a pseudo device used to mirror application drawing for remoting or other purposes.</summary>
    MirroringDriver = 0x8,
    /// <summary>The device is VGA compatible.</summary>
    VGACompatible = 0x10,
    /// <summary>The device is removable; it cannot be the primary display.</summary>
    Removable = 0x20,
    /// <summary>The device has more display modes than its output devices support.</summary>
    ModesPruned = 0x8000000,
    Remote = 0x4000000,
    Disconnect = 0x2000000
}

//public enum DISP_CHANGE : int
//{
//    Successful = 0,
//    Restart = 1,
//    Failed = -1,
//    BadMode = -2,
//    NotUpdated = -3,
//    BadFlags = -4,
//    BadParam = -5,
//    BadDualView = -6
//}

public class User_32
{
    [DllImport("User32.dll")]
    public static extern int ChangeDisplaySettings(ref DEVMODE devMode, int flags);

    [DllImport("User32.dll")]
    public static extern int EnumDisplaySettings(string lpszDeviceName, int iModeNum, ref DEVMODE lpDevMode);

    [DllImport("User32.dll")]
    public static extern int EnumDisplayDevices(string lpDevice, int iDevNum, ref DISPLAY_DEVICE lpDisplayDevice, int dwFlags);

    //[DllImport("User32.dll")]
    //public static extern int EnumDisplaySettings(string deviceName, int modeNum, ref DEVMODE1 devMode);
    //[DllImport("User32.dll")]
    //public static extern int ChangeDisplaySettings(ref DEVMODE1 devMode, int flags);

    public const int ENUM_CURRENT_SETTINGS = -1;
    public const int CDS_UPDATEREGISTRY = 0x01;
    public const int CDS_TEST = 0x02;
    public const int DISP_CHANGE_SUCCESSFUL = 0;
    public const int DISP_CHANGE_RESTART = 1;
    public const int DISP_CHANGE_FAILED = -1;
}

namespace CResolution
{
    public class CResolution
    {
        //get current resulation
        public DisplayInfo GetCurrentResulation()
        {
            DEVMODE dm = new DEVMODE();
            dm.dmDeviceName = new String(new char[32]);
            dm.dmFormName = new String(new char[32]);
            dm.dmSize = (short)Marshal.SizeOf(dm);
            var disInfo = new DisplayInfo();

            if (0 != User_32.EnumDisplaySettings(null, User_32.ENUM_CURRENT_SETTINGS, ref dm))
            {
                disInfo.DeviceName = dm.dmDeviceName;
                disInfo.BitsPerPel = dm.dmBitsPerPel;
                disInfo.DisplayFixedOutput = dm.dmDisplayFixedOutput;
                disInfo.Width = dm.dmPelsWidth;
                disInfo.Height = dm.dmPelsHeight;
            }
            return disInfo;
        }

        //get maximum resulation
        public DisplayInfo GetMaxResulation()
        {
            DEVMODE dm = new DEVMODE();
            dm.dmDeviceName = new String(new char[32]);
            dm.dmFormName = new String(new char[32]);
            dm.dmSize = (short)Marshal.SizeOf(dm);

            var resulationList = new List<DisplayInfo>();
            int i = 0;
            while (0 != User_32.EnumDisplaySettings(null, i, ref dm))
            {
                var disInfo = new DisplayInfo();
                disInfo.Width = dm.dmPelsWidth;
                disInfo.Height = dm.dmPelsHeight;
                resulationList.Add(disInfo);
                i++;
            }
            var diInfo = new DisplayInfo();
            int MaxHeight = resulationList.Max(x => x.Height);
            diInfo = resulationList.First(x => x.Height == MaxHeight);
            return diInfo;
        }

        //set maximum resulation
        public void SetResulation(DisplayInfo disInfo)
        {
            int iWidth = disInfo.Width;
            int iHeight = disInfo.Height;

            //DisplayDevice is a wrapper ... you can find it [here](http://pinvoke.net/default.aspx/Structures/DISPLAY_DEVICE.html)
            List<DISPLAY_DEVICE> devices = new List<DISPLAY_DEVICE>();

            bool error = false;
            //Here I am listing all DisplayDevices (Monitors)
            for (int devId = 0; !error; devId++)
            {
                try
                {
                    DISPLAY_DEVICE device = new DISPLAY_DEVICE();
                    device.cb = Marshal.SizeOf(typeof(DISPLAY_DEVICE));
                    error = User_32.EnumDisplayDevices(null, devId, ref device, 0) == 0;
                    devices.Add(device);
                }
                catch (Exception)
                {
                    error = true;
                }
            }

            List<DISPLAY_SET> devicesAndModes = new List<DISPLAY_SET>();

            foreach (var dev in devices)
            {
                error = false;
                //Here I am listing all DeviceModes (Resolutions) for each DisplayDevice (Monitors)
                for (int i = 0; !error; i++)
                {
                    try
                    {
                        //DeviceMode is a wrapper. You can find it [here](http://pinvoke.net/default.aspx/Structures/DEVMODE.html)
                        DEVMODE mode = new DEVMODE();
                        mode.dmDeviceName = new String(new char[32]);
                        mode.dmFormName = new String(new char[32]);
                        mode.dmSize = (short)Marshal.SizeOf(mode);
                        error = User_32.EnumDisplaySettings(dev.DeviceName, -1 + i, ref mode) == 0;
                        //Display
                        devicesAndModes.Add(new DISPLAY_SET { DisplayDevice = dev, DeviceMode = mode });
                    }
                    catch (Exception)
                    {
                        error = true;
                    }
                }
            }

            //Select any 800x600 resolution ...
            DEVMODE dm = devicesAndModes.Where(s => s.DeviceMode.dmPelsWidth == iWidth).First().DeviceMode;
            dm.dmBitsPerPel = (int)disInfo.BitsPerPel;
            dm.dmDisplayFixedOutput = disInfo.DisplayFixedOutput;

            //Apply the selected resolution ..
            int iRet = User_32.ChangeDisplaySettings(ref dm, User_32.CDS_TEST);
            if (iRet == User_32.DISP_CHANGE_FAILED)
            {
                MessageBox.Show("Unable to process your request");
                MessageBox.Show("Description: Unable To Process Your Request. Sorry For This Inconvenience.", "Information", MessageBoxButton.OK);
            }
            else
            {
                iRet = User_32.ChangeDisplaySettings(ref dm, User_32.CDS_UPDATEREGISTRY);
                switch (iRet)
                {
                    case User_32.DISP_CHANGE_SUCCESSFUL:
                        {
                            break;
                            //successfull change
                        }
                    case User_32.DISP_CHANGE_RESTART:
                        {
                            MessageBox.Show("Description: You Need To Reboot For The Change To Happen.\n If You Feel Any Problem After Rebooting Your Machine\nThen Try To Change Resolution In Safe Mode.", "Information", MessageBoxButton.OK);
                            break;
                            //windows 9x series you have to restart
                        }
                    default:
                        {
                            MessageBox.Show("Description: Failed To Change The Resolution.", "Information", MessageBoxButton.OK);
                            break;
                            //failed to change
                        }
                }//end of swithc case              
            }//end of else                    
        }//end of method    
    }

    public class DisplayInfo
    {
        public string DeviceName { get; internal set; }
        public int BitsPerPel { get; internal set; }
        public int DisplayFixedOutput { get; internal set; }
        public int Width { get; internal set; }
        public int Height { get; internal set; }
    }
}

Calling your application loading by this method
 #region Set Screen Resulation

        private void SetScreenResulation()
        {
            CResolution cR = new CResolution();
            //get current resulation
            DisplayInfo CurrentResulation = cR.GetCurrentResulation();
            ////get current resulation
            DisplayInfo MaximumResulation = cR.GetMaxResulation();
            MaximumResulation.BitsPerPel = CurrentResulation.BitsPerPel;
            MaximumResulation.DisplayFixedOutput = CurrentResulation.DisplayFixedOutput;

            //set height resulation
            if (MaximumResulation.Width > CurrentResulation.Width)
                cR.SetResulation(MaximumResulation);
        }

        #endregion
I think this is very important code for silverlight out of browser application.
N.B: Check 'require elevated trust when running in-browser'
 Check 'require elevated trust when running outside the browser'

Thursday, May 9, 2013

Generate String From List


public static string GetSearchString<T>(this ObservableCollection<T> source, string valueField)
        {
            try
            {
                string returnString = String.Empty;
                if (source.Count > 0)
                {
                    foreach (var obj in source)
                    {
                        returnString = returnString + obj.GetType().GetProperty(valueField).GetValue(obj, null) + ",";
                    }
                    if (returnString == String.Empty)
                    {
                        returnString = returnString.Substring(0, returnString.Length - 1);

                    }
                }
                return returnString;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

Get Data Grid Column Binding List


private void GetShowColumnList()
        {
            ShowColumnNames = "";
            ShowColumnAttributeList = new Dictionary<string, string>();
            if (PersonalizeColumnGrid.ItemsSource != null)
            {
                foreach (var objCol in PersonalizeColumnGrid.ItemsSource)
                {
                    if (((dynamic)objCol).IsSelected)
                    {
                        string headerName = ((dynamic)objCol).Column;
                        //ShowColumnNames = ShowColumnNames + headerName + ",";

                        foreach (var objGridAttribute in suppliedDataGrid.Columns)
                        {
                            if (objGridAttribute.ClipboardContentBinding != null)
                            {
                                if (objGridAttribute.Header != null)
                                {
                                    if (headerName == objGridAttribute.Header.ToString())
                                    {
                                        string colAttribute = objGridAttribute.ClipboardContentBinding.Path.Path;
                                        ShowColumnAttributeList.Add(colAttribute, headerName);
                                        break;
                                    }
                                }

                            }
                            // if( ((dynamic)objCol).Column
                        }
                    }
                }
                //ShowColumnNames = ShowColumnNames.Substring(0, ShowColumnNames.Length - 1);
                ShowColumnNames = Extension.ConvertDictinaryToString(ShowColumnAttributeList);
            }
//get

public static string ConvertDictinaryToString<TKey, TValue>(this IDictionary<TKey, TValue> dictionary)
        {
            //return string.Join(",", dictionary.Select(kv => kv.Key.ToString() + "{" + kv.Value.ToString()).ToArray()).Replace(' ', '~'); ;
            return string.Join(",", dictionary.Select(kv => kv.Key.ToString().Trim()+"*" + kv.Value.ToString().Trim()).ToArray()).Replace(' ', '~');
        }
//back

private void ConvertStringToDictionary(string ColumnList)
        {
            try
            {
                if (!string.IsNullOrEmpty(ColumnList))
                {
                    ColumnList = ColumnList.Replace('~', ' ');
                    List<string> colList = ColumnList.Split(',').ToList<string>();
                    foreach (string colItem in colList)
                    {
                        if (colItem.Contains('*'))
                        {
                            reportColumnList.Add(colItem.Split('*')[0].ToString(), colItem.Split('*')[1].ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


Find Parent Framework Element in silverligth


private FrameworkElement FindControlParent(FrameworkElement control)
        {
            FrameworkElement ctrlParent = control;
            while (typeof(UserControl) != null)
            {
                ctrlParent = (FrameworkElement)ctrlParent.Parent;
                if (ctrlParent.Parent == null)
                {
                    return (FrameworkElement)ctrlParent;
                }
            }
            return null;
        }

Wednesday, May 8, 2013

Hide and Show RDLC Column And Adjust Width


#region Adjust Report Column Width When Some Columns Hide

        //adjust hide column width into report
        private void AdjustRDLCReport(string rptFilePath, bool isOnlyLabelChange, int rowNumberOfTable)
        {
            try
            {
                //Delete Duplicate Report File File
                if (System.IO.File.Exists(virtualreportFilePath))
                    System.IO.File.Delete(virtualreportFilePath);

                //get rdlc report xml
                XmlDocument objXml = new XmlDocument();
                objXml.Load(rptFilePath);
                //set name space to change xml node
                XmlNamespaceManager objXmlNamespaceManager = new XmlNamespaceManager(objXml.NameTable);
                string uri = "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition";
                objXmlNamespaceManager.AddNamespace("rd", "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner");
                objXmlNamespaceManager.AddNamespace("rdef", uri);

                //if no header visibile,than no change into report xml
                if (reportColumnList == null || reportColumnList.Count == 0)
                {
                    //save temporary report as virtual
                    objXml.Save(virtualreportFilePath);
                    return;
                }
                //if only header change
                if (isOnlyLabelChange)//only hader change no need column hide or show
                {
                    //Change Header
                    RDLCReportLabelChange(objXml, objXmlNamespaceManager);
                }
                else
                {
                    //Change Header
                    RDLCReportLabelChange(objXml, objXmlNamespaceManager);
                    //Set visible column          
                    XmlNodeList columnList = objXml.SelectNodes("//rdef:TablixBody/rdef:TablixRows/rdef:TablixRow[" + rowNumberOfTable + "]/rdef:TablixCells/rdef:TablixCell/rdef:CellContents/rdef:Textbox/rdef:Paragraphs/rdef:Paragraph/rdef:TextRuns/rdef:TextRun/rdef:Value", objXmlNamespaceManager);
                    //Hide Or Show Report Column
                    RDLCReportColumnHideShow(columnList, objXml, objXmlNamespaceManager, uri);
                    //Visible Report Column Width Adjust
                    RDLCReportColumnWidthAdjust(columnList, objXml, objXmlNamespaceManager);
                }
                //save temporary report as virtual
                objXml.Save(virtualreportFilePath);
            }
            catch (Exception)
            {
                throw;
            }
        }//end of method

        //Rdlc report label change according to label.xml
        private void RDLCReportLabelChange(XmlDocument objXml, XmlNamespaceManager objXmlNamespaceManager)
        {
            XmlNodeList reportHeaderList = objXml.SelectNodes("//rdef:TextRun/rdef:Value", objXmlNamespaceManager);
            if (reportHeaderList == null) return;
            foreach (XmlNode node in reportHeaderList)
            {
                var reportColumn = reportColumnList.SingleOrDefault(x => x.Key == node.InnerText);
                if (reportColumn.Key == null) continue;
                node.InnerText = reportColumn.Value;
            }
        }

        //RDLC report column hide or show
        private void RDLCReportColumnHideShow(XmlNodeList columnList, XmlDocument objXml, XmlNamespaceManager objXmlNamespaceManager, string uri)
        {
            XmlNodeList columnVisibleList = objXml.SelectNodes("//rdef:TablixColumnHierarchy/rdef:TablixMembers/rdef:TablixMember", objXmlNamespaceManager);
            if (columnList != null)
            {
                if (columnVisibleList != null)
                {
                    for (int i = 0; i < columnList.Count; i++)
                    {
                        var reportColumn = reportColumnList.SingleOrDefault(x => String.Format("=Fields!{0}.Value", x.Key) == columnList[i].InnerText);
                        if (reportColumn.Key == null)
                        {
                            for (int j = 0; j < columnVisibleList.Count; j++)
                            {
                                if (i == j)
                                {
                                    XmlElement nVis = objXml.CreateElement("Visibility", uri);
                                    XmlElement nHid = objXml.CreateElement("Hidden", uri);
                                    nHid.InnerText = "true";
                                    nVis.AppendChild(nHid);
                                    columnVisibleList[j].AppendChild(nVis);
                                    break;
                                }
                            }//end of column visibility
                        }
                    }//end of all column
                }
            }
        }//end of method

        //RDLC Report Column Width Adjustment according to visible column
        private void RDLCReportColumnWidthAdjust(XmlNodeList columnList, XmlDocument objXml, XmlNamespaceManager objXmlNamespaceManager)
        {
            XmlNodeList columnWidthList = objXml.SelectNodes("//rdef:TablixBody/rdef:TablixColumns/rdef:TablixColumn/rdef:Width", objXmlNamespaceManager);
            double hideColumnWidth = 0;
            int NoOfVisibleColumn = 0;
            if (columnList != null)
            {
                if (columnWidthList != null)
                {
                    for (int i = 0; i < columnList.Count; i++)
                    {
                        var reportColumn = reportColumnList.SingleOrDefault(x => String.Format("=Fields!{0}.Value", x.Key) == columnList[i].InnerText);
                        if (reportColumn.Key == null)
                        {
                            for (int j = 0; j < columnWidthList.Count; j++)
                            {
                                if (i == j)
                                {
                                    string colWidth = columnWidthList[j].InnerText;
                                    hideColumnWidth += Convert.ToDouble(colWidth.Remove(colWidth.Length - 2));
                                    break;
                                }
                            }//end of column visibility
                        }
                        else
                        {
                            NoOfVisibleColumn++;//number fo visible column
                        }
                    }
                }//end of if
            }//end of if

            //Distribute Hode Column width into visible column width
            if (columnList != null)
            {
                if (columnWidthList != null)
                {
                    for (int i = 0; i < columnList.Count; i++)
                    {
                        var reportColumn = reportColumnList.SingleOrDefault(x => String.Format("=Fields!{0}.Value", x.Key) == columnList[i].InnerText);
                        if (reportColumn.Key != null)
                        {
                            for (int j = 0; j < columnWidthList.Count; j++)
                            {
                                if (i == j)
                                {
                                    string colWidth = columnWidthList[j].InnerText;
                                    double actualVisibleColumnWidth = Convert.ToDouble(colWidth.Remove(colWidth.Length - 2)) + (hideColumnWidth / NoOfVisibleColumn);
                                    columnWidthList[j].InnerText = String.Format("{0}in", actualVisibleColumnWidth);
                                    break;
                                }
                            }//end of column visibility
                        }
                    }
                }//end of if
            }//end of if
        }//end of method

        #endregion

calling 

 //This Dictionary Contains Report Header,That is Provided from Personalized Column Grid.
        private Dictionary<string, string> reportColumnList = new Dictionary<string, string>();
 private string virtualreportFilePath = String.Empty;

AdjustRDLCReport(reportFilePath, false, 2);// false is label change and hide column,if true only label change,here 2 is search for row number of tablix which is contains actual attribute of object
                    localReport.ReportPath = virtualreportFilePath;


Thursday, May 2, 2013

How do I adjust overall width of rdlc report when some columns are hidden?

        Problem:Lets say that I have 10 columns to view report and I want to hide 3 of these columns at runtime based on the value of parameter which the user would select. This can be easily done by setting the column visibility of each of these 3 columns based on the value of the aforesaid parameter. It's perfectly fine up till here.
The problem is when the report shows up (with 3 columns hidden) the remaining 7 columns take up the place of the hidden columns and as a result the overall width of the table reduces accordingly. I do not want this to happen. i.e. I want the table width to remain constant.That is to say the remaining columns width should somehow be able to expand so that the original overall width of the table remains same.Is this possible to achieve?
Solution:
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                String sFileName = String.Empty;
                XmlDocument objXml = new XmlDocument();
                sFileName = @"c:\users\sohel\documents\visual studio 2012\Projects\EditRdlcReport\EditRdlcReport.Web\Reports\Report1.rdlc";
                objXml.Load(sFileName);

                XmlNamespaceManager objXmlNamespaceManager = new XmlNamespaceManager(objXml.NameTable);
                objXmlNamespaceManager.AddNamespace("rd", "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner");
                objXmlNamespaceManager.AddNamespace("reportDefinition", "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition");
                //strUniquelyIdentifiedParentTagName is the control name like TextBox, Image etc.
                XmlNodeList nodeList = objXml.SelectNodes("//reportDefinition:" + "TablixColumn", objXmlNamespaceManager);
                // Nodelist will contain all Textboxes of the report.
                if (nodeList != null)
                {
                    foreach (XmlNode node in nodeList)
                    {
                        if (node["Width"].Name == "Width")
                        {
                            node["Width"].InnerText = "2.58167in";
                        }
                    }
                }

                // establish some file names              
                string virtualRdlc = "~/Reports/" + "Report2" + ".rdlc";
                // save off the resultng RDLC file
                string physicalRdlc = Server.MapPath(virtualRdlc);
                //Delete Duplicate File
                if (System.IO.Directory.Exists(@"c:\users\sohel\documents\visual studio 2012\Projects\EditRdlcReport\EditRdlcReport.Web\Reports\Report2.rdlc"))
                    System.IO.Directory.Delete(physicalRdlc);

                //save virtually new
                objXml.Save(physicalRdlc);

                LocalReport localReport = new LocalReport();
                localReport.ReportPath = Server.MapPath("~/Reports/" + "Report2" + ".rdlc");
                RenderRDLCReport(new Student().GetStudent(), "Report2", localReport);
            }
        }


#region Generae Report

        private void RenderRDLCReport<T>(List<T> objList, string reportFileName, LocalReport localReport)
        {
            string DataSetName = String.Empty;
            DataSetName = "DataSet1";

            ReportDataSource reportDataSource = new ReportDataSource(DataSetName, objList);
            localReport.DataSources.Add(reportDataSource);

            var reportType = "PDF";
            string mimeType;
            string encoding;
            string fileNameExtension;

            //The DeviceInfo settings should be changed based on the reportType
            //http://msdn2.microsoft.com/en-us/library/ms155397.aspx
            string deviceInfo =
            "<DeviceInfo>" +
            " <OutputFormat>PDF</OutputFormat>" +
            " <PageWidth>11in</PageWidth>" +
            " <PageHeight>8.5in</PageHeight>" +
            " <MarginTop>0.5in</MarginTop>" +
            " <MarginLeft>1in</MarginLeft>" +
            " <MarginRight>1in</MarginRight>" +
            " <MarginBottom>0.5in</MarginBottom>" +
            "</DeviceInfo>";

            Warning[] warnings;
            string[] streams;
            var renderedBytes = localReport.Render(
                                reportType,
                                deviceInfo,
                                out mimeType,
                                out encoding,
                                out fileNameExtension,
                                out streams,
                                out warnings);

            //Clear the response stream and write the bytes to the outputstream
            //Set content-disposition to "attachment" so that user is prompted to take an action
            //on the file (open or save)
            Response.Clear();
            Response.ContentType = mimeType;

            Response.BinaryWrite(renderedBytes);
            Response.End();
        }

        #endregion

Monday, April 29, 2013

Create Blank Data Grid According to Main Grid

Add Custom Control

public class BlankDataGrid : DataGrid
    {
        //Parent Data Grid
        private static DataGrid PdataGrid;
        //Blank Data Grid
        private static DataGrid BdataGrid;
        //how many row we will create
        private static int NoRow = 4;
        //if this value is 1 then no delete first recode,this is used for parent and child grid row color matching.
        private static int RemoveFirstRow;
        //Zero to null value converter into blank data grid.
        private static ZeroToEmptyConverter converter = new ZeroToEmptyConverter();
        //when paren data grid column hide then blank data grid column hide by this variable
        private static bool isParenDGColumnHide;
 
        //Constructor
        public BlankDataGrid()
        {
            try
            {
                this.Loaded += new RoutedEventHandler(BlankDataGrid_Loaded);
                this.LoadingRow += new System.EventHandler<DataGridRowEventArgs>(BlankDataGrid_LoadingRow);
            }
            catch (Exception)
            { throw; }
        }
 
        //when grid is loaded then it is called
        private void BlankDataGrid_Loaded(object sender, RoutedEventArgs e)
        {
            //this.HeadersVisibility = DataGridHeadersVisibility.None;
            this.AutoGenerateColumns = false;
            this.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden;
            this.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden;
        }
 
        //when every row loaded then this method is called
        private void BlankDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            try
            {
                int dgridrow = e.Row.GetIndex();
                if (dgridrow == 0)
                    if (RemoveFirstRow == 1)
                        e.Row.Visibility = Visibility.Collapsed;
            }
            catch (Exception)
            { throw; }
        }
 
        #region Paren Data Grid Properties
 
        public DataGrid ParentDataGrid
        {
            get { return (DataGrid)GetValue(ParentDataGridProperty); }
            set { SetValue(ParentDataGridProperty, value); }
        }
 
        public static readonly DependencyProperty ParentDataGridProperty =
            DependencyProperty.Register("ParentDataGrid"typeof(DataGrid), typeof(BlankDataGrid),
            new PropertyMetadata(nullnew PropertyChangedCallback(OnParentDataGridChanged)));
 
        private static void OnParentDataGridChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            try
            {
                //clear parent grid temporary list
                PdataGrid = null;
                //get parent data grid
                PdataGrid = ((BlankDataGrid)d).ParentDataGrid as DataGrid;
                if (PdataGrid == nullreturn;
                if (PdataGrid.ItemsSource == nullreturn;
 
                //Parent Grid Sized Changed Event
                PdataGrid.SizeChanged += new SizeChangedEventHandler(dataGrid_SizeChanged);
                //Parent LayoutUpdated Event fire when parent grid column hide
                PdataGrid.LayoutUpdated += new EventHandler(PdataGrid_LayoutUpdated);
 
                //Get Parent Object Type
 
                Type t;
                if (PdataGrid.ItemsSource.GetType() == typeof(PagedCollectionView))
                {
                    var pageCollectionData = PdataGrid.ItemsSource as PagedCollectionView;
                    t = (pageCollectionData.SourceCollection as IEnumerable).AsQueryable().ElementType;
                }
                else
                {
                    t = (PdataGrid.ItemsSource as IEnumerable).AsQueryable().ElementType;
                }
                if (t == nullreturn;
                //Make Blank Data List
                dynamic instant = Activator.CreateInstance(t);//create instance
                var Datalist = new ObservableCollection<dynamic>();
                for (int i = 0; i < NoRow; i++)
                    Datalist.Add(instant);
 
                //add item source
                ((BlankDataGrid)d).ItemsSource = null;
                ((BlankDataGrid)d).ItemsSource = Datalist;
 
                //Clear data grid column
                ((BlankDataGrid)d).Columns.Clear();
                foreach (var columnName in PdataGrid.Columns)
                {
                    ((BlankDataGrid)d).Columns.Add(CreateTextColumn("id"));
                }
                //adjust blank grid according to parent grid.
                AdjustWidth(PdataGrid, ((BlankDataGrid)d));
 
                //Clear blank grid teporary
                BdataGrid = null;
                //set as a further use
                BdataGrid = ((BlankDataGrid)d);
            }
            catch (Exception)
            {
                throw;
            }
        }
 
        //create blank data grid column
        private static DataGridTextColumn CreateTextColumn(string fieldName)
        {
            DataGridTextColumn column = new DataGridTextColumn();
            column.Binding = new Binding(fieldName);
            column.Binding.Converter = converter;
            column.Binding.Mode = BindingMode.OneWay;
            return column;
        }
 
        //adjust blank grid according to parent grid.
        private static void AdjustWidth(DataGrid paren, DataGrid blank)
        {
            for (int i = 0; i < blank.Columns.Count; i++)
            {
                for (int j = 0; j < PdataGrid.Columns.Count; j++)
                {
                    if (i == j)
                    {
                        blank.Columns[i].Width = new DataGridLength(PdataGrid.Columns[j].ActualWidth);
                        blank.Columns[i].Visibility = PdataGrid.Columns[j].Visibility;
                        break;
                    }
                }//end of second for
            }//end of 1st for
        }
 
        //parent grid sized changed
        private static void dataGrid_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            try
            {
                if (sender == nullreturn;
                if (BdataGrid == nullreturn;
                isParenDGColumnHide = false;
                var pGrid = sender as DataGrid;
                AdjustWidth(pGrid, BdataGrid);
            }
            catch (Exception)
            { throw; }
        }
 
        //Parent Grid LayoutUpdated Event fire when parent grid column hide
        private static void PdataGrid_LayoutUpdated(object sender, EventArgs e)
        {
            if (isParenDGColumnHide)
            {
                if (BdataGrid == nullreturn;
                if (PdataGrid == nullreturn;
                AdjustWidth(PdataGrid, BdataGrid);
                isParenDGColumnHide = false;
            }
        }
 
        #endregion
 
        #region Properties
 
        public int NumberOfRow
        {
            get { return (int)GetValue(NumberOfRowProperty); }
            set { SetValue(NumberOfRowProperty, value); }
        }
        public static readonly DependencyProperty NumberOfRowProperty =
            DependencyProperty.Register("NumberOfRow"typeof(int), typeof(BlankDataGrid),
            new PropertyMetadata(0, new PropertyChangedCallback(NumberOfRowChanged)));
 
        private static void NumberOfRowChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            try
            {
                if (d != null)
                {
                    NoRow = 0;
                    NoRow = ((BlankDataGrid)d).NumberOfRow;
                }
            }
            catch (Exception)
            { throw; }
        }
 
        public int isRemoveFirstRow
        {
            get { return (int)GetValue(isRemoveFirstRowProperty); }
            set { SetValue(isRemoveFirstRowProperty, value); }
        }
        public static readonly DependencyProperty isRemoveFirstRowProperty =
            DependencyProperty.Register("isRemoveFirstRow"typeof(int), typeof(BlankDataGrid),
            new PropertyMetadata(0, new PropertyChangedCallback(isRemoveFirstRowChanged)));
 
        private static void isRemoveFirstRowChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            try
            {
                if (d != null)
                {
                    RemoveFirstRow = ((BlankDataGrid)d).isRemoveFirstRow;
                }
            }
            catch (Exception)
            { throw; }
        }
 
        public bool isParenDataGridColumnHide
        {
            get { return (bool)GetValue(isParenDataGridColumnHideProperty); }
            set { SetValue(isParenDataGridColumnHideProperty, value); }
        }
        public static readonly DependencyProperty isParenDataGridColumnHideProperty =
            DependencyProperty.Register("isParenDataGridColumnHide"typeof(bool), typeof(BlankDataGrid),
            new PropertyMetadata(falsenew PropertyChangedCallback(isMainGridHideChanged)));
 
        private static void isMainGridHideChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            try
            {
                if (d != null)
                {
                    isParenDGColumnHide = ((BlankDataGrid)d).isParenDataGridColumnHide;
                }
            }
            catch (Exception)
            { throw; }
        }
 
        #endregion
    }

use of custom control in xaml
<lib:BlankDataGrid VerticalAlignment="Top" Grid.Row="1" Grid.Column="0" ParentDataGrid="{Binding ElementName=dgMasterGrid}"/>
                                                <sdk:DataGrid x:Name="dgMasterGrid" Grid.Row="1" Grid.Column="0" VerticalAlignment="Top"/>