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