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(null, new 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 == null) return;
                if (PdataGrid.ItemsSource == null) return;
 
                //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 == null) return;
                //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 == null) return;
                if (BdataGrid == null) return;
                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 == null) return;
                if (PdataGrid == null) return;
                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(false, new 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"/>

Thursday, April 11, 2013

Silverlight Tree View Control

See the link
http://social.msdn.microsoft.com/Forums/en-US/silverlightcontrols/thread/64c166f0-9110-456f-aee0-a33a296f161e

Check Network Connection in Silverlight

Copy and Paste the code below into your main page loading

--Constructor
this.Loaded += new RoutedEventHandler(LoginPage_Loaded);


 #region Get Network Status

        private void LoginPage_Loaded(object sender, RoutedEventArgs e)
        {
            GetNetworkStatus();
            NetworkChange.NetworkAddressChanged += new
                NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
        }

        private void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
        {
            GetNetworkStatus();
        }

        private void GetNetworkStatus()
        {
            _dataContext.Online = NetworkInterface.GetIsNetworkAvailable();
            if (!_dataContext.Online)
            {
                //no internet connection
                _dataContext.Message = "Internet connection is not available";
            }
            else
            {
                //Load All user Data.
                _dataContext.LoadData();
            }
        }

        #endregion