Welcome to David Sandor Sign in | Join | Help
in Search

Professional Software Architecture

  • SOLVED: You must install SQL Server 2005 Analysis Services with Service Pack 2 or higher before installing the Analysis extensions.

    Situation:  Windows Server 2008 with SQL Server 2008 Reporting Services and SQL Server 2008 Analysis Services SP 1, Microsoft Dynamics Axapta 2009 with Service Pack 1 and KB 959494 will not allow AX Analysis Extensions to install with the error message: You must install SQL Server 2005 Analysis Services with Service Pack 2 or higher before installing the Analysis extensions.

    As a new DAX-er, welcome to the hell that is DAX 2009 installer.  To be kind, the setup for Ax 2009 needs a great deal of work.

    Microsoft suggests applying KB 959494 which is of no use for SSAS 2008 SP1.

     

    ssas-ax-02

    After applying the KB article SSAS Extensions still will not install.  Further research seems to indicate that the problem might be with some 9.0 SSAS assemblies in the GAC.

    Setup does not recognize that SQL Server 2008 Analysis Services is
    installed If you have SQL Server 2008 Analysis Services installed and you are
    installing the analysis extensions, you might receive an error that says you
    must install SQL Server 2005 Analysis Services with Service Pack 2. This
    error message indicates that there is an Analysis Services 2005 version of
    the Microsoft.AnalysisServices.dll file in the Global Assembly Cache.
    Microsoft Dynamics AX does not support running Analysis Services 2005 and
    Analysis Services 2008 on the same computer. To resolve this issue, uninstall
    the Microsoft.AnalysisServices.dll file that has a version number of 9.0 from
    the Global Assembly Cache (typically located at C:\Windows\assembly).
    Important: Be sure that you do not uninstall the
    Microsoft.AnalysisServices.dll file that has a version number of 10.0

    ssas-ax-01

    I checked and sure enough there were.  So I looked and found SQL Server 2005 Express installed on the machine, not sure why.

    Anyway, I uninstalled SQL Server 2005 Express and also the SQL Server 2005 Analysis Services ADOMD assemblies.

    ssas-ax-03

    I checked the GAC after uninstalling the 2005 components and I had a clean GAC, only 10.0 references.

    ssas-ax-04

    On to install again…and the Analysis Extensions can now be installed!

     

    ssas-ax-05

    Oh how beautiful it is:

    ssas-ax-06

  • Validating properties of a class in .NET 3.5

    A few years ago (5 I believe) I was in the process of building an API / Framework for this.  ASP.NET Dynamic Data supports the RegularExpressionAttribute class.  Cool!

     

    http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.regularexpressionattribute.aspx

  • The InnerException message was 'Type 'System.DelegateSerializationHolder+DelegateEntry' with data contract name 'DelegateSerializationHolder.DelegateEntry:http://schemas.datacontract.org/2004/07/System' is not expected.

    In .NET 4.0 / Visual Studio 2010 I was working with a WPF application who’s ViewModel was sending a Model (Data) object back to a WCF service for processing.  In previous versions of the framework and WCF I could simply send any serializable object down the wire.  In .NET 4.0 apparently I need to do some further class decorating.

    I needed to include the namespace:

    using System.Runtime.Serialization;

    My class that I was sending needed to be decorated with:

    [DataContract]

    and the properties I wanted to send down the wire via WCF needed to have:

    [DataMember]

    After decorating the Class and it’s properties with DataContract and DataMethod everything worked like a charm.

     

    Below are some of the debugger data that helped troubleshoot the problem.

    error

     

    The InnerException message was 'Type 'System.DelegateSerializationHolder+DelegateEntry' with data contract name 'DelegateSerializationHolder.DelegateEntry:http://schemas.datacontract.org/2004/07/System' is not expected.

    System.ServiceModel.CommunicationException was unhandled
      Message=There was an error while trying to serialize parameter http://tempuri.org/:receipts. The InnerException message was 'Type 'System.DelegateSerializationHolder+DelegateEntry' with data contract name 'DelegateSerializationHolder.DelegateEntry:http://schemas.datacontract.org/2004/07/System' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'.  Please see InnerException for more details.
      Source=mscorlib
      StackTrace:
        Server stack trace:
           at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameterPart(XmlDictionaryWriter writer, PartInfo part, Object graph)
           at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameter(XmlDictionaryWriter writer, PartInfo part, Object graph)
           at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameters(XmlDictionaryWriter writer, PartInfo[] parts, Object[] parameters)
           at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeBody(XmlDictionaryWriter writer, MessageVersion version, String action, MessageDescription messageDescription, Object returnValue, Object[] parameters, Boolean isRequest)
           at System.ServiceModel.Dispatcher.OperationFormatter.SerializeBodyContents(XmlDictionaryWriter writer, MessageVersion version, Object[] parameters, Object returnValue, Boolean isRequest)
           at System.ServiceModel.Dispatcher.OperationFormatter.OperationFormatterMessage.OperationFormatterBodyWriter.OnWriteBodyContents(XmlDictionaryWriter writer)
           at System.ServiceModel.Channels.BodyWriter.WriteBodyContents(XmlDictionaryWriter writer)
           at System.ServiceModel.Security.SecurityAppliedMessage.WriteBodyToSignThenEncryptWithFragments(Stream stream, Boolean includeComments, String[] inclusivePrefixes, EncryptedData encryptedData, SymmetricAlgorithm algorithm, XmlDictionaryWriter writer)
           at System.ServiceModel.Security.WSSecurityOneDotZeroSendSecurityHeader.ApplyBodySecurity(XmlDictionaryWriter writer, IPrefixGenerator prefixGenerator)
           at System.ServiceModel.Security.SecurityAppliedMessage.OnWriteMessage(XmlDictionaryWriter writer)
           at System.ServiceModel.Channels.BufferedMessageWriter.WriteMessage(Message message, BufferManager bufferManager, Int32 initialOffset, Int32 maxSizeQuota)
           at System.ServiceModel.Channels.TextMessageEncoderFactory.TextMessageEncoder.WriteMessage(Message message, Int32 maxMessageSize, BufferManager bufferManager, Int32 messageOffset)
           at System.ServiceModel.Channels.HttpOutput.SerializeBufferedMessage(Message message)
           at System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout)
           at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.SendRequest(Message message, TimeSpan timeout)
           at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
           at System.ServiceModel.Channels.ClientReliableChannelBinder`1.RequestClientReliableChannelBinder`1.OnRequest(TRequestChannel channel, Message message, TimeSpan timeout, MaskingMode maskingMode)
           at System.ServiceModel.Channels.ClientReliableChannelBinder`1.Request(Message message, TimeSpan timeout, MaskingMode maskingMode)
           at System.ServiceModel.Channels.ClientReliableChannelBinder`1.Request(Message message, TimeSpan timeout)
           at System.ServiceModel.Security.SecuritySessionClientSettings`1.SecurityRequestSessionChannel.Request(Message message, TimeSpan timeout)
           at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
           at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
           at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
           at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
        Exception rethrown at [0]:
           at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
           at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
           at Warehouse.ViewModel.Services.SyncService.ISync.SendNewReceipts(SendNewReceiptsRequest request)
           at Warehouse.ViewModel.Services.SyncService.SyncClient.SendNewReceipts(SendNewReceiptsRequest request) in d:\Projects\Warehouse.2010\Warehouse.ViewModel\Service References\Services.SyncService\Reference.cs:line 75
           at Warehouse.ViewModel.SyncData.PerformSync() in d:\Projects\Warehouse.2010\Warehouse.ViewModel\SyncData.cs:line 60
           at Warehouse.Window1.btnBackup_Click(Object sender, RoutedEventArgs e) in d:\Projects\Warehouse.2010\Warehouse\Window1.xaml.cs:line 196
           at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
           at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
           at System.Windows.Controls.Button.OnClick()
           at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
           at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
           at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
           at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
           at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
           at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
           at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
           at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
           at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
           at System.Windows.Input.InputManager.ProcessStagingArea()
           at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
           at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
           at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
           at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
           at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
           at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
           at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
           at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
           at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
           at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
           at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
           at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
           at System.Windows.Threading.Dispatcher.TranslateAndDispatchMessage(MSG& msg)
           at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
           at System.Windows.Application.RunInternal(Window window)
           at Warehouse.App.Main() in d:\Projects\Warehouse.2010\Warehouse\obj\Debug\App.g.cs:line 0
           at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
           at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart()
      InnerException: System.Runtime.Serialization.SerializationException
           Message=Type 'System.DelegateSerializationHolder+DelegateEntry' with data contract name 'DelegateSerializationHolder.DelegateEntry:http://schemas.datacontract.org/2004/07/System' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
           Source=System.Runtime.Serialization
           StackTrace:
                at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, Boolean verifyKnownType, RuntimeTypeHandle declaredTypeHandle)
                at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiType(XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
                at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
                at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerializeReference(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
                at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteSerializationInfo(XmlWriterDelegator xmlWriter, Type objType, SerializationInfo serInfo)
                at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteISerializable(XmlWriterDelegator xmlWriter, ISerializable obj)
                at System.Runtime.Serialization.ClassDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
                at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
                at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerializeReference(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
                at WriteDockReceiptToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , ClassDataContract )
                at System.Runtime.Serialization.ClassDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
                at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
                at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerializeReference(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
                at WriteArrayOfDockReceiptToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , CollectionDataContract )
                at System.Runtime.Serialization.CollectionDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
                at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph)
                at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph)
                at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph)
                at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameterPart(XmlDictionaryWriter writer, PartInfo part, Object graph)
           InnerException:

     

     

  • Bug with Visual Studio 2010 and DBML designer – Changes not causing regeneration of DataContext code.

    Vote for this bug if you encounter this problem.  Basically in 2010, if you regen the DBML file outside of VS the underlying DataContext code does not get regenerated.  This is bad because changes outside of VS 2010 to your DBML will not get ‘picked up’ when you rebuild.

    https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=474117

  • Great troubleshooting resource for Microsoft Dynamics AX 2009 installations.

    This has actually been updated to reflect a lot of Server 2008 / SQL 2008 issues.  One thing I learned that has not yet been resolved:  Install Enterprise Portal, SSRS and SSAS all on the same machine.  Otherwise you will have great big problems!  As of this writing it is still an issue, mainly an OLAP problem / Kerberos issues.  So take my advice and install all 3 on the same machine!

    http://technet.microsoft.com/en-us/library/aa497072.aspx

  • CK Wanted me to post this speed test, so here it is..

  • WPF: How to bind to an enum in XAML.

    Finally found a great article on this after some searching and finding really outdated articles!

    http://msdn.microsoft.com/en-us/library/bb613576.aspx

    <Window
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:sys="clr-namespace:System;assembly=mscorlib" 
      SizeToContent="WidthAndHeight" 
      Title="Show Enums in a ListBox using Binding">
     
      <Window.Resources>
        <ObjectDataProvider MethodName="GetValues"
                            ObjectType="{x:Type sys:Enum}"
                            x:Key="AlignmentValues">
          <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="HorizontalAlignment" />
          </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
      </Window.Resources>
     
      <Border Margin="10" BorderBrush="Aqua"
              BorderThickness="3" Padding="8">
        <StackPanel Width="300">
          <TextBlock>Choose the HorizontalAlignment value of the Button:</TextBlock>
          <ListBox Name="myComboBox" SelectedIndex="0" Margin="8"
                   ItemsSource="{Binding Source={StaticResource AlignmentValues}}"/>
          <Button Content="Click Me!"
                  HorizontalAlignment="{Binding ElementName=myComboBox,
                                                Path=SelectedItem}"/>
        </StackPanel>
      </Border>
    </Window>

     

    Something that might not be readily apparent to you is the use of the <x:Type /> markup extension.  Documented here.  I needed to figure this one out because I was binding my own enum instead of simply a CLR enum.  The thing to know is that you must include the namespace for your assembly that contains your enum in the XAML markup:

    xmlns:warehouse="clr-namespace:Warehouse.Model;assembly=Warehouse.Model"

    I named my namespace ‘warehouse’ here and referenced the assembly and namespace that contains my enum.

    Next, you must reference the type with namespace prefix like so:

    <x:Type TypeName="warehouse:DockReceiptTypeEnum" />

    Now the beginning of my XAML looks like this and it works great!

    <Window x:Class="Warehouse.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib" 
        xmlns:warehouse="clr-namespace:Warehouse.Model;assembly=Warehouse.Model"
        Title="Dock Receipts" Height="478" Width="957" xmlns:my="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.GridView">
        <Window.Resources>
            <ObjectDataProvider MethodName="GetValues"
                            ObjectType="{x:Type sys:Enum}"
                            x:Key="ReceiptTypeEnum">
                <ObjectDataProvider.MethodParameters>
                    <x:Type TypeName="warehouse:DockReceiptTypeEnum" />
                </ObjectDataProvider.MethodParameters>
            </ObjectDataProvider>
        </Window.Resources>
  • Visual Studio 2010: Debug annotations (sticky notes) for debugging / Quick Watch

    Two really cool features in Visual Studio 2010 for C# developers. 

    1) Sticky Notes Quick Watch with annotations.  You may say, huh?  What are you talking about?  Well, look at the screen cap below.

    quick watch sticky notes-vs2010

    This is by far one of the coolest features I have seen so far (apart from the awesome XAML / WPF designer).  When debugging you can save a quick watch as a sticky note in your code (the note disappears when you exit debug mode).  You can even add notes to the watches so that next time you debug you can know what the values are supposed to be.  Instead of leaving bookmarks all over your code you can add a sticky note! 

    2) Highlight to debug.  You can now highlight a section of code (including casts) to view the properties and values.  This was available in VB for some time but finally is working correctly in C#.

  • AG_E_UNKNOWN_ERROR inside Silverlight/WPF project

    I encountered the infamous AG_E_UNKNOWN yesterday.  I was actually using Silverlight controls from Telerik.  I dragged the RadGridView control inside my XAML and thats where the problem manifested.  Apparently the drag/drop operation did not add all the References that I needed in order to use the Telerik controls. 

    If you have the same problem, make sure all the references and dependencies are referenced in your project’s References section.  I had to add Telerik.Windows.Controls and Telerik.Windows.Controls.Data to get my RadGrid error in my XAML to go away.

  • How to bind the value of a slider control to another control’s property in WPF/Silverlight.

    This should work for WPF and Silverlight.  This is a SUPER simple example.  I find it hard to locate really good clean examples in WPF / Silverlight.  People tend to do a lot of Control Templating and Style-izing which clouds the code.  I am starting a ‘Clean and Simple’ set of blog entries to show SIMPLE and CLEAN examples.

    sliders

    In this code (there is no code behind other than that which is generated by Visual Studio) all we do is bind the Value of the slider to the Content of the label. 

    <Window x:Class="WpfToolbox.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="153" Width="300">
        <Grid>
     
            <StackPanel Height="115" VerticalAlignment="Top">
                <Label Content="{Binding ElementName=slider1, Path=Value}" />
                <Slider Height="22"  Name="slider1" VerticalAlignment="Top" Minimum="0" Maximum="99" />
                <Label Content="{Binding ElementName=slider2, Path=Value}" />
                <Slider Height="22"  Name="slider2" VerticalAlignment="Top"  Minimum="99" Maximum="199" />
            </StackPanel>
        </Grid>
    </Window>

    So in the XAML above you will see that the labels are not even named.  All I did was use a binding expression to bind the ElementName to the Name of the slider control.  The Path is simply the property name who’s value is to be bound.  So the slider1.Value is bound to the Content of the first label.

  • Custom configuration settings and persisting data to XML… the right way.

    At my wits end with some seriously lame code I stumbled upon today.  Believe it or not, I actually saw a developer use a dead open source .ini reader/writer to read and write ONE setting in a config file.  The best part is the open source project they used was not originally intended to be used that way.  It was originally used to read/write settings in a .INI file.  Once again… Carpenter.. Hammer.. used on everything.  My sincerest apologies to the carpenters.

    Problem:  I want to read, write and store data on disk.  .NET since 1.0 has had facilities built in to serialize classes to XML (and other medium).  This works out well if you for example have an ‘order’ class that contains a customer’s order.  That order class would have properties containing order data and possibly a List<> of OrderedItems which in turn would have it’s own set of properties.  So you want to persist this Order to disk?  Serialize it and write it. 

    Solution:  Serialize the data to XML and write it to disk.  I will provide clear cut examples of this in part 2 of this post.  For now, I wanted to post a base class I use that I wrote long ago that lets you Load, Save and Enqueue an object to Disk or to an MSMQ Message Queue.  I find it very useful in storing configuration settings and for sending MSMQ Messages.

    First is the interface: ILoadableSavableQueueable

    using System;
    namespace ConfigHelper
    {
        interface ILoadableSaveableQueueable
        {
            void Enqueue(string msmqDestinationPath);
            void SaveToXML(string filename);
            string ToString();
        }
    }

    Second is the class implementation: LoadableSavableQueueable

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Messaging;
    using System.Reflection;
    using System.Xml.Serialization;
    using System.IO;
     
    namespace ConfigHelper
    {
        public class LoadableSaveableQueueable<T> : ILoadableSaveableQueueable
        {
            public static T LoadFromXML(string filePath)
            {
     
                XmlSerializer xer = new XmlSerializer(typeof(T));
                StreamReader sr = File.OpenText(filePath);
                T config = (T)xer.Deserialize(sr);
     
                sr.Close();
                sr.Dispose();
     
                return config;
            }
     
            public void SaveToXML(string filename)
            {
                if (!Directory.Exists(Path.GetDirectoryName(filename)))
                    Directory.CreateDirectory(Path.GetDirectoryName(filename));
     
                XmlSerializer xer = new XmlSerializer(typeof(T));
     
                if (File.Exists(filename))
                    File.Delete(filename);
     
                using (FileStream fs = File.Create(filename))
                {
                    xer.Serialize(fs, this);
                }
     
            }
     
            public override string ToString()
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("--] {0}", this.GetType().Name);
     
                foreach (PropertyInfo pi in this.GetType().GetProperties())
                {
                    sb.AppendFormat("{0}: '{1}'\r\n", pi.Name, pi.GetValue(this, null));
                }
                return sb.ToString();
            }
     
            public void Enqueue(string msmqDestinationPath)
            {
                using (MessageQueue q = new MessageQueue(msmqDestinationPath))
                {
                    Message msg = new Message(this);
                    msg.Recoverable = true;
     
                    q.Send(msg);
                    msg.Dispose();
                }
     
            }
        }
    }

     

    Simple example:

    You have a class that you want to read and write to XML to disk.  That class is called ConfigSettings and contains a property called ProgramName.

    [Serializable]
    public class ConfigSettings : LoadableSavableQueueable<ConfigSettings>
    {
       public ConfigSettings() {}
     
       private string _ProgramName;
       public string ProgramName
       {
        get { return _ProgramName; }
        set { _ProgramName = value; }
       }
     
    }

     

    Now you can use the LoadFromXML and SaveToXML methods to read and write this class to XML file on disk.

    Again, a better example is to follow.

  • Code Snippet for Dependency Property (WPF/SL)

    I am writing some User Controls for a WPF application and needed a quick way to create my Dependency Properties for my control.

    Below is the code snippet.

    First element is the type, next the Property Name, then the Containing Class name (you need this for the Dependency Property Registration call.

    <?xml version="1.0" encoding="utf-8" ?>
    <CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
        <CodeSnippet Format="1.0.0">
            <Header>
                <Title>Dependency Property</Title>
                <Shortcut>dp</Shortcut>
                <Description>Code snippet for dependency property</Description>
                <Author>David Sandor</Author>
                <SnippetTypes>
                    <SnippetType>Expansion</SnippetType>
                </SnippetTypes>
            </Header>
            <Snippet>
                <Declarations>
                    <Literal>
                        <ID>type</ID>
                        <ToolTip>Property type</ToolTip>
                        <Default>int</Default>
                    </Literal>
                    <Literal>
                        <ID>property</ID>
                        <ToolTip>Property name (name of the CLR property).</ToolTip>
                        <Default>MyProperty</Default>
                    </Literal>
                    <Literal>
                        <ID>className</ID>
                        <ToolTip>Name of the class that contains this DP.</ToolTip>
                        <Default>MyClass</Default>
                    </Literal>
                </Declarations>
                <Code Language="csharp"><![CDATA[
            public $type$ $property$
            {
                get { return ($type$)this.GetValue($property$Property); }
                set { this.SetValue($property$Property,value); }
            }
            public static readonly DependencyProperty $property$Property =
             DependencyProperty.Register(
                "$property$", typeof($type$), typeof($className$));
    $end$]]>
                </Code>
            </Snippet>
        </CodeSnippet>
    </CodeSnippets>

    The snippet will generate out code like this:

    public string AddressLine1
    {
        get { return (string)this.GetValue(AddressLine1Property); }
        set { this.SetValue(AddressLine1Property, value); }
    }
    public static readonly DependencyProperty AddressLine1Property =
     DependencyProperty.Register(
        "AddressLine1", typeof(string), typeof(Address));

    Here is the snippet file click here to download.

  • Blog Header Silverlight application code (moving image).

    This blog entry, when complete, will discuss the Silverlight application I created for the header of my blog.  It is a simple little application that I created to explore some Silverlight functionality for another project.  What I learned here I applied to a work-project.

  • How do I add an image to a Telerik R.A.D. Expander control in WPF.

    It turns out to be quite simple.

    Add the expander to your WPF control surface:

    <telerik:RadExpander Height="24" Name="radExpander2" Width="170" />

     

    Specifically set the Header property in the XAML like so:

                <telerik:RadExpander Height="24" Name="radExpander1" Width="170">
                    <telerik:RadExpander.Header>
                        <Image Height="20" Source="Gfx/Alerts.ico"/>
                    </telerik:RadExpander.Header>
                </telerik:RadExpander>
     

    This code assumes that you have a graphics file in a folder named ‘Gfx’ in your solution.

  • Solved: Connection String does not show up when editing the connection property of a DBML file.

    The DBML editor in Visual Studio 2008 tends to create a nasty name in the settings file for your database connection string.  We have our databases named with the associated environment e.g. Product_dev or Product_test.  When the DBML editor saves the connection string you get a nasty name such as: ClassLibrary1.Properties.Settings.Product_devConnectionString.

    This is fixed by creating the setting for the connection string first and giving it a pleasant name such as: ProductDb. 

     

    Make sure you create the setting of type (Connection String) and save the settings.  After this you will need to edit your .config file and assign a providerName attribute to the connection string that was created.

    providerName="System.Data.SqlClient"

     

    After this, open your DBML file and your ProductDb connection string will show in the dropdown.

More Posts Next page »

This Blog

Syndication

Powered by Community Server (Personal Edition), by Telligent Systems