Thursday, January 23, 2014

Silverlight DataGrid Scrolling Fix

<UserControl.Resources>          
<Style x:Key="ScrollViewerStyle1" TargetType="ScrollViewer">
<Setter Property="HorizontalContentAlignment" Value="Left"/>
<Setter Property="VerticalContentAlignment" Value="Top"/>
<Setter Property="VerticalScrollBarVisibility" Value="Visible"/>
<Setter Property="Padding" Value="4"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderBrush">
<Setter.Value>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFA3AEB9" Offset="0"/>
<GradientStop Color="#FF8399A9" Offset="0.375"/>
<GradientStop Color="#FF718597" Offset="0.375"/>
<GradientStop Color="#FF617584" Offset="1"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ScrollViewer">
<Border BorderBrush="{TemplateBinding BorderBrush}">
<Grid Background="{TemplateBinding Background}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ScrollContentPresenter x:Name="ScrollContentPresenter" Cursor="{TemplateBinding Cursor}" ContentTemplate="{TemplateBinding ContentTemplate}"/>
<Rectangle Grid.Column="1" Fill="#FFE9EEF4" Grid.Row="1"/>
<ScrollBar x:Name="VerticalScrollBar" Grid.Column="1" IsTabStop="False" Maximum="{TemplateBinding ScrollableHeight}" Margin="0,-1,-1,-1" Minimum="0" Orientation="Vertical" Grid.Row="0" Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}" Value="{TemplateBinding VerticalOffset}" ViewportSize="{TemplateBinding ViewportHeight}" Width="18"/>
<ScrollBar x:Name="HorizontalScrollBar" Grid.Column="0" Height="18" IsTabStop="False" Maximum="{TemplateBinding ScrollableWidth}" Margin="-1,0,-1,-1" Minimum="0" Orientation="Horizontal" Grid.Row="1" Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}" Value="{TemplateBinding HorizontalOffset}" ViewportSize="{TemplateBinding ViewportWidth}"/>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
        <Style x:Key="DataGridStyle2" TargetType="sdk:DataGrid">
            <Setter Property="RowBackground" Value="#AAEAEFF4"/>
            <Setter Property="AlternatingRowBackground" Value="#00FFFFFF"/>
            <Setter Property="Background" Value="#FFFFFFFF"/>
            <Setter Property="HeadersVisibility" Value="Column"/>
            <Setter Property="HorizontalScrollBarVisibility" Value="Auto"/>
            <Setter Property="VerticalScrollBarVisibility" Value="Auto"/>
            <Setter Property="SelectionMode" Value="Extended"/>
            <Setter Property="CanUserReorderColumns" Value="True"/>
            <Setter Property="CanUserResizeColumns" Value="True"/>
            <Setter Property="CanUserSortColumns" Value="True"/>
            <Setter Property="AutoGenerateColumns" Value="True"/>
            <Setter Property="RowDetailsVisibilityMode" Value="VisibleWhenSelected"/>
            <Setter Property="BorderBrush">
                <Setter.Value>
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                        <GradientStop Color="#FFA3AEB9" Offset="0"/>
                        <GradientStop Color="#FF8399A9" Offset="0.375"/>
                        <GradientStop Color="#FF718597" Offset="0.375"/>
                        <GradientStop Color="#FF617584" Offset="1"/>
                    </LinearGradientBrush>
                </Setter.Value>
            </Setter>
            <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="DragIndicatorStyle">
                <Setter.Value>
                    <Style TargetType="ContentControl">
                        <Setter Property="Foreground" Value="#7FFFFFFF"/>
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="ContentControl">
                                    <Grid>
                                        <VisualStateManager.VisualStateGroups>
                                            <VisualStateGroup x:Name="SortStates">
                                                <VisualState x:Name="Unsorted"/>
                                                <VisualState x:Name="SortAscending">
                                                    <Storyboard>
                                                        <DoubleAnimation Duration="0" To="1.0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="SortIcon"/>
                                                    </Storyboard>
                                                </VisualState>
                                                <VisualState x:Name="SortDescending">
                                                    <Storyboard>
                                                        <DoubleAnimation Duration="0" To="1.0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="SortIcon"/>
                                                        <DoubleAnimation Duration="0" To="-.9" Storyboard.TargetProperty="(RenderTransform).ScaleY" Storyboard.TargetName="SortIcon"/>
                                                    </Storyboard>
                                                </VisualState>
                                            </VisualStateGroup>
                                        </VisualStateManager.VisualStateGroups>
                                        <Rectangle x:Name="BackgroundRectangle" Grid.ColumnSpan="2" Fill="#66808080" Stretch="Fill"/>
                                        <Rectangle x:Name="BackgroundGradient" Grid.ColumnSpan="2" Opacity="0" Stretch="Fill">
                                            <Rectangle.Fill>
                                                <LinearGradientBrush EndPoint=".7,1" StartPoint=".7,0">
                                                    <GradientStop Color="#FFFFFFFF" Offset="0.015"/>
                                                    <GradientStop Color="#F9FFFFFF" Offset="0.375"/>
                                                    <GradientStop Color="#E5FFFFFF" Offset="0.6"/>
                                                    <GradientStop Color="#C6FFFFFF" Offset="1"/>
                                                </LinearGradientBrush>
                                            </Rectangle.Fill>
                                        </Rectangle>
                                        <Grid HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}">
                                            <Grid.ColumnDefinitions>
                                                <ColumnDefinition/>
                                                <ColumnDefinition Width="Auto"/>
                                            </Grid.ColumnDefinitions>
                                            <ContentPresenter Content="{TemplateBinding Content}"/>
                                            <Path x:Name="SortIcon" Grid.Column="1" Data="F1 M -5.215,6.099L 5.215,6.099L 0,0L -5.215,6.099 Z " Fill="#7FFFFFFF" HorizontalAlignment="Left" Margin="4,0,0,0" Opacity="0" RenderTransformOrigin=".5,.5" Stretch="Uniform" VerticalAlignment="Center" Width="8">
                                                <Path.RenderTransform>
                                                    <ScaleTransform ScaleY=".9" ScaleX=".9"/>
                                                </Path.RenderTransform>
                                            </Path>
                                        </Grid>
                                    </Grid>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </Setter.Value>
            </Setter>
            <Setter Property="DropLocationIndicatorStyle">
                <Setter.Value>
                    <Style TargetType="ContentControl">
                        <Setter Property="Background" Value="#FF3F4346"/>
                        <Setter Property="Width" Value="2"/>
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="ContentControl">
                                    <Rectangle Fill="{TemplateBinding Background}" Height="{TemplateBinding Height}" Width="{TemplateBinding Width}"/>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </Setter.Value>
            </Setter>
            <Setter Property="GridLinesVisibility" Value="Vertical"/>
            <Setter Property="HorizontalGridLinesBrush" Value="#FFC9CACA"/>
            <Setter Property="IsTabStop" Value="True"/>
            <Setter Property="VerticalGridLinesBrush" Value="#FFC9CACA"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="sdk:DataGrid">
                        <Grid>
                            <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup x:Name="CommonStates">
                                    <VisualState x:Name="Normal"/>
                                    <VisualState x:Name="Disabled">
                                        <Storyboard>
                                            <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="DisabledVisualElement"/>
                                        </Storyboard>
                                    </VisualState>
                                </VisualStateGroup>
                            </VisualStateManager.VisualStateGroups>
                            <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="2">
                                <Grid x:Name="Root" Background="{TemplateBinding Background}">
                                    <Grid.Resources>
                                        <ControlTemplate x:Key="TopLeftHeaderTemplate" TargetType="sdk:DataGridColumnHeader">
                                            <Grid x:Name="Root">
                                                <Grid.RowDefinitions>
                                                    <RowDefinition/>
                                                    <RowDefinition/>
                                                    <RowDefinition Height="Auto"/>
                                                </Grid.RowDefinitions>
                                                <Border BorderBrush="#FFC9CACA" BorderThickness="0,0,1,0" Background="#FF1F3B53" Grid.RowSpan="2">
                                                    <Rectangle Stretch="Fill" StrokeThickness="1">
                                                        <Rectangle.Fill>
                                                            <LinearGradientBrush EndPoint=".7,1" StartPoint=".7,0">
                                                                <GradientStop Color="#FCFFFFFF" Offset="0.015"/>
                                                                <GradientStop Color="#F7FFFFFF" Offset="0.375"/>
                                                                <GradientStop Color="#E5FFFFFF" Offset="0.6"/>
                                                                <GradientStop Color="#D1FFFFFF" Offset="1"/>
                                                            </LinearGradientBrush>
                                                        </Rectangle.Fill>
                                                    </Rectangle>
                                                </Border>
                                                <Rectangle Fill="#FFDBDCDC" Height="1" Grid.RowSpan="2" StrokeThickness="1" VerticalAlignment="Bottom" Width="Auto"/>
                                            </Grid>
                                        </ControlTemplate>
                                        <ControlTemplate x:Key="TopRightHeaderTemplate" TargetType="sdk:DataGridColumnHeader">
                                            <Grid x:Name="RootElement">
                                                <Grid.RowDefinitions>
                                                    <RowDefinition/>
                                                    <RowDefinition/>
                                                    <RowDefinition Height="Auto"/>
                                                </Grid.RowDefinitions>
                                                <Border BorderBrush="#FFC9CACA" BorderThickness="1,0,0,0" Background="#FF1F3B53" Grid.RowSpan="2">
                                                    <Rectangle Stretch="Fill">
                                                        <Rectangle.Fill>
                                                            <LinearGradientBrush EndPoint=".7,1" StartPoint=".7,0">
                                                                <GradientStop Color="#FCFFFFFF" Offset="0.015"/>
                                                                <GradientStop Color="#F7FFFFFF" Offset="0.375"/>
                                                                <GradientStop Color="#E5FFFFFF" Offset="0.6"/>
                                                                <GradientStop Color="#D1FFFFFF" Offset="1"/>
                                                            </LinearGradientBrush>
                                                        </Rectangle.Fill>
                                                    </Rectangle>
                                                </Border>
                                            </Grid>
                                        </ControlTemplate>
                                    </Grid.Resources>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="Auto"/>
                                        <ColumnDefinition/>
                                        <ColumnDefinition Width="Auto"/>
                                    </Grid.ColumnDefinitions>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition/>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="Auto"/>
                                    </Grid.RowDefinitions>
                                    <sdk:DataGridColumnHeader x:Name="TopLeftCornerHeader" Template="{StaticResource TopLeftHeaderTemplate}" Width="22"/>
                                    <sdk:DataGridColumnHeadersPresenter x:Name="ColumnHeadersPresenter" Grid.Column="1"/>
                                    <sdk:DataGridColumnHeader x:Name="TopRightCornerHeader" Grid.Column="2" Template="{StaticResource TopRightHeaderTemplate}"/>
                                    <Rectangle x:Name="ColumnHeadersAndRowsSeparator" Grid.ColumnSpan="3" Fill="#FFC9CACA" Height="1" StrokeThickness="1" VerticalAlignment="Bottom" Width="Auto"/>
                                    <ScrollViewer Grid.ColumnSpan="2" Grid.Row="1" Style="{StaticResource ScrollViewerStyle1}">
                                        <sdk:DataGridRowsPresenter x:Name="RowsPresenter" />
                                    </ScrollViewer>                                                                    
                                    <Rectangle x:Name="BottomRightCorner" Grid.Column="2" Fill="#FFE9EEF4" Grid.Row="2"/>
                                    <Rectangle x:Name="BottomLeftCorner" Grid.ColumnSpan="2" Fill="#FFE9EEF4" Grid.Row="2"/>
                                    <ScrollBar x:Name="VerticalScrollbar" Grid.Column="2" Margin="0,-1,-1,-1" Orientation="Vertical" Grid.Row="1" Width="18"/>
                                    <Grid Grid.Column="1" Grid.Row="2">
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="Auto"/>
                                            <ColumnDefinition/>
                                        </Grid.ColumnDefinitions>
                                        <Rectangle x:Name="FrozenColumnScrollBarSpacer"/>
                                        <ScrollBar x:Name="HorizontalScrollbar" Grid.Column="1" Height="18" Margin="-1,0,-1,-1" Orientation="Horizontal"/>
                                    </Grid>
                                    <sdk:ValidationSummary x:Name="ValidationSummary" Grid.ColumnSpan="3" MaxHeight="90" Grid.Row="3"/>
                                </Grid>
                            </Border>
                            <Border x:Name="DisabledVisualElement" Background="#8CFFFFFF" CornerRadius="2" HorizontalAlignment="Stretch" Height="Auto" IsHitTestVisible="False" Opacity="0" VerticalAlignment="Stretch" Width="Auto"/>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </UserControl.Resources>

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'