How to detect broken WPF Data binding? - wpf

While trying to answer a question in the vicinity 'Unit Testing WPF Bindings' I had the following niggling question..
What's the best way to find if you have WPF Data Binding wiring setup incorrectly (or you just broke something that was wired up correctly) ?
Although the unit-testing approach seems to be like Joel's 'ripping off your arm to remove a splinter'.. I am looking around for easier less Overhead ways to detect this.
Everyone seems to have committed themselves to data binding in a big way with WPF.. and it does have its merits.

In .NET 3.5 it was introduced a new way to specifically output tracing information about specific data bindings.
This is done through the new System.Diagnostics.PresentationTraceSources.TraceLevel attached property that you can apply to any binding or data provider. Here is an example:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
Title="Debug Binding Sample"
Height="300"
Width="300">
<StackPanel>
<TextBox Name="txtInput" />
<Label>
<Label.Content>
<Binding ElementName="txtInput"
Path="Text"
diag:PresentationTraceSources.TraceLevel="High" />
</Label.Content>
</Label>
</StackPanel>
</Window>
This will put trace information for just that particular binding in Visual Studio's Output Window, without any tracing configuration required.

Best I could find...
How can I debug WPF Bindings? by Beatriz Stollnitz
Since everyone can't always keep one eye on the Output Window looking for Binding errors, I loved Option#2. Which is add this to your App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.diagnostics>
<sources>
<source name="System.Windows.Data" switchName="SourceSwitch" >
<listeners>
<add name="textListener" />
</listeners>
</source>
</sources>
<switches>
<add name="SourceSwitch" value="All" />
</switches>
<sharedListeners>
<add name="textListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="GraveOfBindErrors.txt" />
</sharedListeners>
<trace autoflush="true" indentsize="4"></trace>
</system.diagnostics>
</configuration>
Pair that up with a good regex scan script to extract out relevant info, that you can run occasionally on the GraveOfBindErrors.txt in your output folder
System.Windows.Data Error: 35 : BindingExpression path error: 'MyProperty' property not found on 'object' ''MyWindow' (Name='')'. BindingExpression:Path=MyProperty; DataItem='MyWindow' (Name=''); target element is 'TextBox' (Name='txtValue2'); target property is 'Text' (type 'String')

I use the solution presented here to turn binding errors into native Exceptions: http://www.jasonbock.net/jb/Default.aspx?blog=entry.0f221e047de740ee90722b248933a28d
However, a normal scenario in WPF bindings is to throw exceptions in case the user input cannot be converted to the target type (for instance, a TextBox bound to a integer field; the input of a non-numeric string results in a FormatException, the input of number that is too large results in an OverflowException). A similar case is when the Setter of the source property throws an exception.
The WPF way of handling this is via ValidatesOnExceptions=true and ValidationExceptionRule to signal the user the supplied input is not correct (using the exception message).
However, these exception are also send to the output window and thus 'caught' by the BindingListener, resulting in an error...clearly not the behaviour you'd want.
Therefore, I expanded the BindingListener class to NOT throw an Exception in these cases:
private static readonly IList<string> m_MessagesToIgnore =
new List<String>()
{
//Windows.Data.Error 7
//Binding transfer from target to source failed because of an exception
//Normal WPF Scenario, requires ValidatesOnExceptions / ExceptionValidationRule
//To cope with these kind of errors
"ConvertBack cannot convert value",
//Windows.Data.Error 8
//Binding transfer from target to source failed because of an exception
//Normal WPF Scenario, requires ValidatesOnExceptions / ExceptionValidationRule
//To cope with these kind of errors
"Cannot save value from target back to source"
};
Modified lines in public override void WriteLine(string message):
....
if (this.InformationPropertyCount == 0)
{
//Only treat message as an exception if it is not to be ignored
if (!m_MessagesToIgnore.Any(
x => this.Message.StartsWith(x, StringComparison.InvariantCultureIgnoreCase)))
{
PresentationTraceSources.DataBindingSource.Listeners.Remove(this);
throw new BindingException(this.Message,
new BindingExceptionInformation(this.Callstack,
System.DateTime.Parse(this.DateTime),
this.LogicalOperationStack, int.Parse(this.ProcessId),
int.Parse(this.ThreadId), long.Parse(this.Timestamp)));
}
else
{
//Ignore message, reset values
this.IsFirstWrite = true;
this.DetermineInformationPropertyCount();
}
}
}

You can use the trigger debugging feature of WPF Inspector. Just download the tool from codeplex and attach it to your running app. It also shows binding errors on the bottom of the window.
Very useful tool!

Here's a useful technique for debugging/tracing triggers effectively. It allows you to log all trigger actions along with the element being acted upon:
http://www.wpfmentor.com/2009/01/how-to-debug-triggers-using-trigger.html

This was very helpful to us but I wanted to add to those who find this useful that there is a utility that Microsoft provides with the sdk to read this file.
Found here: http://msdn.microsoft.com/en-us/library/ms732023.aspx
To open a trace file
1.Start Service Trace Viewer by using a command window to navigate to your
WCF installation location (C:\Program
Files\Microsoft
SDKs\Windows\v6.0\Bin), and then type
SvcTraceViewer.exe. (although we found ours in \v7.0\Bin)
Note: The Service Trace Viewer tool
can associate with two file types:
.svclog and .stvproj. You can use two
parameters in command line to register
and unregister the file extensions.
/register: register the association of
file extensions ".svclog" and
".stvproj" with SvcTraceViewer.exe
/unregister: unregister the
association of file extensions
".svclog" and ".stvproj" with
SvcTraceViewer.exe
1.When Service Trace Viewer starts, click File and then point to Open.
Navigate to the location where your
trace files are stored.
2.Double-click the trace file that you want to open.
Note: Press SHIFT while clicking
multiple trace files to select and
open them simultaneously. Service
Trace Viewer merges the content of all
files and presents one view. For
example, you can open trace files of
both client and service. This is
useful when you have enabled message
logging and activity propagation in
configuration. In this way, you can
examine message exchange between
client and service. You can also drag
multiple files into the viewer, or use
the Project tab. See the Managing
Project section for more details.
3.To add additional trace files to the collection that is open, click File
and then point to Add. In the window
that opens, navigate to the location
of the trace files and double-click
the file you want to add.
Also, as for the filtering of the log file, we found these this link extremely helpful:
http://msdn.microsoft.com/en-us/library/ms751526.aspx

For anyone like me looking for a pure programmatic way of enabling all WPF Tracing at a given Trace Level, here is a piece of code that does it. For reference, it's based on this article: Trace sources in WPF.
It doesn't requires a change in the app.config file, and it does not require to change the registry either.
This is how I use it, in some startup place (App, etc.):
....
#if DEBUG
WpfUtilities.SetTracing();
#endif
....
And here is the utility code (by default it sends all Warning to the Default Trace Listener):
public static void SetTracing()
{
SetTracing(SourceLevels.Warning, null);
}
public static void SetTracing(SourceLevels levels, TraceListener listener)
{
if (listener == null)
{
listener = new DefaultTraceListener();
}
// enable WPF tracing
PresentationTraceSources.Refresh();
// enable all WPF Trace sources (change this if you only want DataBindingSource)
foreach (PropertyInfo pi in typeof(PresentationTraceSources).GetProperties(BindingFlags.Static | BindingFlags.Public))
{
if (typeof(TraceSource).IsAssignableFrom(pi.PropertyType))
{
TraceSource ts = (TraceSource)pi.GetValue(null, null);
ts.Listeners.Add(listener);
ts.Switch.Level = levels;
}
}
}

My suggestion at 2021:
The Best way is to use Benoit Blanchon small library from Nuget
His original post at here: https://stackoverflow.com/a/19610384/6296708
His GitHub link and more info about how to use it + Nuget command: https://github.com/bblanchon/WpfBindingErrors
Its features (until now!):
throw exception on binding errors (+ line number)
If source Variable throw any exceptions, this library will catch it and show it.
Unit Test supports too!
Happy Coding!

Related

Must add reference to WindowsBase.dll to use RenderTargetBitmap.Render method?

I'm currently working on a WPF application that uses a plotting library called Live Charts for WPF. I want to save a PNG of my graph, which is described on their github page Save Plot Example also discussed at this stackoverflow question here. The problem is adding a reference to the windows base assembly.
`
private void SaveToPng(FrameworkElement visual, string filename)
{
var encoder = new PngBitmapEncoder();
EncodeVisual(visual, filename, encoder);
}
private static void EncodeVisual(FrameworkElement visual, string fileName, BitmapEncoder encoder)
{
var bitmap = new RenderTargetBitmap((int)visual.ActualWidth, (int)visual.ActualHeight, 96, 96, PixelFormats.Pbgra32);
//bitmap.Render();
bitmap.Render(visual);
var frame = BitmapFrame.Create(bitmap);
encoder.Frames.Add(frame);
using (var stream = File.Create(fileName)) encoder.Save(stream);
}
`
I have tried to add this dll as a reference which is located at C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.0, but when I do this it does not work. It is actually implicitly included in the project, so that may be why I can add it explicitly like I did with the PresentationCore.dll and PresentationFramework.dll which were also required and solved a few errors. The error states: the type 'System.Windows.Freezable' is defined in an assembly that is not referenced. You must add a reference to assembly 'WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. This is shown by hovering over the call to bitmap.Render(visual), and when hovering over encoder.Save(stream) as shown in the picture and in the above code. I believe resolving this dependency would fix the problem, but I cannot figure out how. Thank you.
Picture of Project
Discovered what I believe is the answer to the problem. I was creating the SaveToPNG and EncodeVisual methods inside of a class library which would be used in the WPF project. The class library is unable to accept WindowsBase as an explicit reference, but the WPF project itself can. It will take some restructuring of the code to implement this in the WPF project itself, but it seems to be the way to resolve this problem.
I am using .NET 6. Here is the contents of my csproj file in my class library:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
<ItemGroup>
<Compile Update="Core Library\Port.cs">
<SubType>Component</SubType>
</Compile>
</ItemGroup>
</Project>
I did not see the attributes that you spoke of, and autocomplete could not reference them in this file. Inside of the IDE (Rider) I was able to target net6.0-windows in the properties menu of the project. I then reinserted the code into the class library, but the same error still occurred. I agree with you that it shouldn't be necessary to reference WindowsBase, which isn't necessary when placing the code in the wpf project itself, but in the class library I also had to reference PresentationCore and PresentationFramework, which did take care of multiple errors.

How to use ReactiveUI with WinForms

I have decided to learn ReactiveUI after seeing what can be done with it, but my enthusiasm has been broken at the first attempt to run a simple project. I have recreated the example from this article, using reactiveui-winforms.Net40 version 6.5.0 from NuGet. Everything compiles ok, but i get an exception during runtime at the following line
var OKCmdObs = this.WhenAny(vm => vm.EnteredText,
s => !string.IsNullOrWhiteSpace(s.Value));
System.InvalidOperationException occurred
HResult=-2146233079
Message=The current thread has no Dispatcher associated with it.
Source=System.Reactive.Windows.Threading
StackTrace:
at System.Reactive.Concurrency.DispatcherScheduler.get_Current()
at ReactiveUI.PlatformRegistrations.<>c.<Register>b__0_7() in C:\workspace\git-perso\ReactiveUI\ReactiveUI\Platform\Registrations.cs:line 75
InnerException:
Does anyone have any idea of what's happening ?
The mentioned article does not have the compiled project available for download, and i didn't find any complete "Hello-World" project for reactiveui-winforms.
My test project can be downloaded here.
In Visual Studio, if i Continue(F5), another exception occures :
System.NullReferenceException occurred
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=ReactiveUI
StackTrace:
at ReactiveUI.IROObservableForProperty.<>c__DisplayClass1_0.<GetNotificationForProperty>b__6(IReactivePropertyChangedEventArgs`1 x) in C:\workspace\git-perso\ReactiveUI\ReactiveUI\IROObservableForProperty.cs:line 44
InnerException:
If i continue to hit F5 i get :
System.Exception was unhandled by user code
HResult=-2146233088
Message=An OnError occurred on an object (usually ObservableAsPropertyHelper) that would break a binding or command. To prevent this, Subscribe to the ThrownExceptions property of your objects
Source=ReactiveUI
This exception is caused because RxUI always tries to initialize for WPF, even though (because you're also using the winforms package) it'll override this setting with a Winforms-based scheduler right after.
It should be harmless though, as it's catched and ignored. You're probably hitting it within VS ?

Debug and Fixing ObjectDisposedException in Visual Studio 2010

When editing a XAML file I noticed the following error:
System.ObjectDisposedException occurred
Message=Cannot access a disposed object.
Object name: 'FileCodeModel'.
To debug this I ran another instance of Visual Studios and "Debug-> Attach to Process" to the instance of visual studio where the exception was shown.
I was able to catch the exception in the new Instances that started that is attached to the process. I catch the following exception:
System.ObjectDisposedException occurred
Message=Cannot access a disposed object.
Object name: 'FileCodeModel'.
Source=Microsoft.VisualStudio.CSharp.Services.Language
ObjectName=FileCodeModel
StackTrace:
at Microsoft.VisualStudio.CSharp.Services.Language.CodeModel.CFileCodeModel.GetCompilation(Boolean fBlockForParses)
at Microsoft.VisualStudio.CSharp.Services.Language.CodeModel.CPartialTypeCollection.EnumerateParts()
at Microsoft.VisualStudio.CSharp.Services.Language.CodeModel.CPartialTypeCollection.get_Count()
at Microsoft.VisualStudio.CSharp.Services.Language.CodeModel.CSlowSnapshot..ctor(CodeElements collection)
at Microsoft.VisualStudio.CSharp.Services.Language.CodeModel.CPartialTypeCollection.CreateSnapshot()
at Microsoft.VisualStudio.CSharp.Services.Language.CodeModel.CCollectionBase.GetEnumerator()
at EnvDTE.CodeElements.GetEnumerator()
at MS.Internal.VSSymbols.SymbolProvider.GetProperties(String fullName, Boolean isTypeDefinition, Boolean useCodeModel)
at Microsoft.Xaml.Symbols.IXamlSymbols.GetProperties(String typeName, Boolean isTypeDefinition, Boolean useCodeModel)
at MS.Internal.Design.Markup.HostedType.BuildProperties(Boolean useCodeModel)
InnerException:
Anybody ever run into this exception in your XAML, and what do you do to fix it.
Are you running a XAML beautifier? - I've had something similar with an extension that cleans XAML up.
This happened to me when I manually grouped a .xaml.cs and .xaml file by editing the .csproj file. To fix this I:
Moved .xaml file to different folder.
Opened up solution.
Removed .xaml from project.
Re-created .xaml file in Visual Studio.
Copied the contents of my original .xaml into the newly created .xaml.
After following these steps I no longer got that error message.

Can I force the installer project to use the .config file from the built solution instead of the original one?

I am using the solution to this question in order to apply configuration changes to App.config in a Winforms project. I also have an installer project for the project that creates an installable *.msi file. The problem is, the config file bundled in the installers is the original, un-transformed config file. So we're not getting the production connection strings in the production installer even though the config file for the built winforms project has all the correct transformations applied.
Is there any way to force the installer project to use the output of project build?
First of all: it is impossible to make the Setup Project point to another app.config file by using the Primary output option. So my solution is going to be a work around. I hope you find it useful in your situation.
Overview:
The basic idea is:
Remove the forced app.config from the Setup Project;
Add a file pointing to the app.config, manually;
Use MSBuild to get into the vdproj file, and change it to match the real output of the transformed app.config.
Some drawbacks are:
The setup project only gets updated, if the project it deploys build. ahhh... not a real drawback!
You need MSBuild 4.0... this can also be worked around!
Need a custom Task, called FileUpdate... it is open source and has installer.
Lets Work:
1) Go to your Setup Project, and select the Primary Output object, right click and go to Properties. There you will find the Exclude Filter... add a filter for *.config, so it will remove the hard-coded app.config.
2) Right click your Setup Project in the Solution Explorer -> Add -> File... select any file that ends with .config.
3) Download MSBuild Community Tasks Project, I recomend the msi installer.
4) Unload your project (the csproj) and replace the code from the other question with this one:
Code:
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets" />
<Target Name="AfterCompile" Condition="exists('app.$(Configuration).config')">
<!-- Generate transformed app config in the intermediate directory -->
<TransformXml Source="app.config" Destination="$(IntermediateOutputPath)$(TargetFileName).config" Transform="app.$(Configuration).config" />
<!-- Force build process to use the transformed configuration file from now on. -->
<ItemGroup>
<AppConfigWithTargetPath Remove="app.config" />
<AppConfigWithTargetPath Include="$(IntermediateOutputPath)$(TargetFileName).config">
<TargetPath>$(TargetFileName).config</TargetPath>
</AppConfigWithTargetPath>
</ItemGroup>
<PropertyGroup>
<SetupProjectPath>$(MSBuildProjectDirectory)\$(IntermediateOutputPath)$(TargetFileName).config</SetupProjectPath>
</PropertyGroup>
<!-- Change the following so that this Task can find your vdproj file -->
<FileUpdate Files="$(MSBuildProjectDirectory)\..\Setup1\Setup1.vdproj"
Regex="(.SourcePath. = .8:).*\.config(.)"
ReplacementText="$1$(SetupProjectPath.Replace(`\`,`\\`))$2" />
<FileUpdate Files="$(MSBuildProjectDirectory)\..\Setup1\Setup1.vdproj"
Regex="(.TargetName. = .8:).*\.config(.)"
ReplacementText="$1$(TargetFileName).config$2" />
</Target>
5) The previous code must be changed, so that it can find your vdproj file. I have placed a comment in the code, indicating where you need to make the change.
Now, everytime you build your main project, the MSBuild will change the Setup project, so that it uses the correct app.config file. It may have drawbacks, but this solution can be polished and become better. If you need leave a comment, and I'll try to respond ASAP.
Resources I Used
MSBuild 4.0 is needed because I need to use String's Replace function, to replace single "\" to double "\" in the path. See
MSBuild Property Functions for details about using function in MSBuild.
I learned about the FileUpdate Task in this other question. The official project is MSBuild Community Tasks Project.
These two topics were important to my findings:
Trying to include configuration specific app.config files in a setup project
Problems with setup project - am I thick?
Another solution I've found is not to use the transformations but just have a separate config file, e.g. app.Release.config. Then add this line to your csproj file.
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<AppConfig>App.Release.config</AppConfig>
</PropertyGroup>
This will force the deployment project to use the correct config file when packaging.
I combined the best of the following answers to get a fully working solution without using any external tools at all:
1. Setup App.Config transformations
Source: https://stackoverflow.com/a/5109530
In short:
Manually add additional .config files for each build configuration and edit the raw project file to include them similar to this:
<Content Include="App.config" />
<Content Include="App.Debug.config" >
<DependentUpon>App.config</DependentUpon>
</Content>
<Content Include="App.Release.config" >
<DependentUpon>App.config</DependentUpon>
</Content>
Then include the following XML at the end of the project file, just before the closing </project> tag:
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="AfterCompile" Condition="exists('app.$(Configuration).config')">
<TransformXml Source="app.config" Destination="$(IntermediateOutputPath)$(TargetFileName).config" Transform="app.$(Configuration).config" />
<ItemGroup>
<AppConfigWithTargetPath Remove="app.config" />
<AppConfigWithTargetPath Include="$(IntermediateOutputPath)$(TargetFileName).config">
<TargetPath>$(TargetFileName).config</TargetPath>
</AppConfigWithTargetPath>
</ItemGroup>
</Target>
Finally edit the additional .config files to include the respective transformations for each build configuration:
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<!-- transformations here-->
</configuration>
2. Include the appropriate .config in the setup project
First, add a command in the postbuild event of your main project to move the appropriate transformed .config file to a neutral location (e.g. the main bin\ directory):
copy /y "$(TargetDir)$(TargetFileName).config" "$(ProjectDir)bin\$(TargetFileName).config"
(Source: https://stackoverflow.com/a/26521986)
Open the setup project and click the "Primary output..." node to display the properties window. There, add an ExludeFilter "*.config" to exclude the default (untransformed) .config file.
(Source: https://stackoverflow.com/a/6908477)
Finally add the transformed .config file (from the postbuild event) to the setup project (Add > File).
Done.
You can now freely add build configurations and corresponding config transforms and your setup project will always include the appropriate .config for the active configuration.
I accomplished this in a different manner with no external tools:
I added a post-build event that copied the target files to a 'neutral' directory (the root of the /bin folder in the project) and then added this file to the .vdproj. The deployment project now picks up whatever the latest built version is:
Post Build Command:
copy /y "$(TargetDir)$(TargetFileName).config" "$(ProjectDir)bin\$(TargetFileName).config"
This worked for what I needed without any external tools, and works nicely with SlowCheetah transformations.
Based off Alec's answer, here is a similar element that you can use along with the transformations and still get their full benefit:
<ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<Content Include="$(OutputPath)$(AssemblyName).dll.config">
<InProject>false</InProject>
<Link>$(AssemblyName).dll.config</Link>
</Content>
</ItemGroup>
This way, you can use the SlowCheetah transforms or the built-in ones to transform your .config file, and then go into your Visual Studio Deployment Project (or other) and include the Content from the affected project in your Add -> Project Output... page easily, with minimal changes.
None of the above solutions or any articles worked for me in deployment/setup project. Spent many days to figure out the right solution. Finally this approach worked for me.
Pre requisites
I've used utility called cct.exe to transform file explicitly. You can download from here
http://ctt.codeplex.com/
I've used custom installer in setup project to capture installation events.
Follow these steps to achieve app config transformation
1) Add your desired config files to your project and modify your .csproj file like these
<Content Include="app.uat.config">
<DependentUpon>app.config</DependentUpon>
</Content>
<Content Include="app.training.config">
<DependentUpon>app.config</DependentUpon>
</Content>
<Content Include="app.live.config">
<DependentUpon>app.config</DependentUpon>
</Content>
I've added them as content so that they can be copied to output directory.
2) Add cct.exe to your project which you downloaded.
3) Add custom installer to your project which should look like this
[RunInstaller(true)]
public partial class CustomInstaller : System.Configuration.Install.Installer
{
string currentLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string[] transformationfiles = Directory.GetFiles(Path.GetDirectoryNam(Assembly.GetExecutingAssembly().Location), "app.*.config");
public CustomInstaller()
{
InitializeComponent();
// Attach the 'Committed' event.
this.Committed += new InstallEventHandler(MyInstaller_Committed);
this.AfterInstall += new InstallEventHandler(CustomInstaller_AfterInstall);
}
void CustomInstaller_AfterInstall(object sender, InstallEventArgs e)
{
try
{
Directory.SetCurrentDirectory(currentLocation);
var environment = Context.Parameters["Environment"];
var currentconfig = transformationfiles.Where(x => x.Contains(environment)).First();
if (currentconfig != null)
{
FileInfo finfo = new FileInfo(currentconfig);
if (finfo != null)
{
var commands = string.Format(#"/C ctt.exe s:yourexename.exe.config t:{0} d:yourexename.exe.config ", finfo.Name);
using (System.Diagnostics.Process execute = new System.Diagnostics.Process())
{
execute.StartInfo.FileName = "cmd.exe";
execute.StartInfo.RedirectStandardError = true;
execute.StartInfo.RedirectStandardInput = true;
execute.StartInfo.RedirectStandardOutput = true;
execute.StartInfo.UseShellExecute = false;
execute.StartInfo.CreateNoWindow = true;
execute.StartInfo.Arguments = commands;
execute.Start();
}
}
}
}
catch
{
// Do nothing...
}
}
// Event handler for 'Committed' event.
private void MyInstaller_Committed(object sender, InstallEventArgs e)
{
XmlDocument doc = new XmlDocument();
var execonfigPath = currentLocation + #"\yourexe.exe.config";
var file = File.OpenText(execonfigPath);
var xml = file.ReadToEnd();
file.Close();
doc.LoadXml(FormatXmlString(xml));
doc.Save(execonfigPath);
foreach (var filename in transformationfiles)
File.Delete(filename);
}
private static string FormatXmlString(string xmlString)
{
System.Xml.Linq.XElement element = System.Xml.Linq.XElement.Parse(xmlString);
return element.ToString();
}
}
Here I am using two event handlers CustomInstaller_AfterInstall in which I am loading correct config file and transforming .
In MyInstaller_Committed I am deleting transformation files which we don't need on client machine once we apply has been applied. I am also indenting transformed file because cct simply transforms elements were aligned ugly.
4) Open your setup project and add project output content file so that setup can copy config files like app.uat.config,app.live.config etc into client machine.
In previous step this snippet will load all available config files but we need supply right transform file
string[] transformationfiles = Directory.GetFiles(Path.GetDirectoryNam
(Assembly.GetExecutingAssembly().Location), "app.*.config");
For that I've added UI dialog on setup project to get the current config. The dialog gives options for user to select environment like "Live" "UAT" "Test" etc .
Now pass the selected environment to your custom installer and filter them.
It will become lengthy article if I explain on how to add dialog,how to set up params etc so please google them. But idea is to transform user selected environment.
The advantage of this approach is you can use same setup file for any environment.
Here is the summary:
Add config files
Add cct exe file
Add custom installer
Apply transformation on exe.config under after install event
Delete transformation files from client's machine
Modify setup project in such a way that
set up should copy all config files(project output content) and cct.exe into output directory
configure UI dialog with radio buttons (Test,Live,UAT..)
pass the selected value to custom installer
Solution might look lengthy but have no choice because MSI always copy app.config and doesn't care about project build events and transformations. slowcheetah works only with clickonce not setup project
The question is old, but the following could still help many folks out there.
I would simply use Wix WiFile.exe to replace the concerned file in the msi this way (for the sake of this example, we call your msi yourPackage.msi):
Step 1. From command prompt run: WiFile.exe "yourPackage.msi" /x "app.exe.config."
The above will extract the "wrong" app.exe.config file from the msi and place it the same directory as your msi;
Step 2. Place the new (prod) config file (must have the same name as the extracted file: app.exe.config) in same location as your msi;
This means that you are overwritting the app.exe.config that has just been extracted in step 1 above, with your new (production config file);
Step 3. From command prompt run: WiFile.exe "yourPackage.msi" /u "app.exe.config."
THAT'S ALL!
The above can be done in a few seconds. You could automate the task if you wanted, for instance, by running it as batch or else.
After running step 3 above, your msi will contain the new config file, which will now be installed at your clients' when they run the setup.

Silverlight 4: How to reference class from another assembly

In XAML-file of the SquadView page (VfmElitaSilverlightClientView.Pages.SquadView) I am using custom value converter. XAML-file is in "VfmElitaSilverlightClientView" namespace. Separate folder was created for converter and it is in "VfmElitaSilverlightClientView.Converter" namespace (in the same assembly). To use converter following code is used in XAML:
xmlns:Converter="clr-namespace:VfmElitaSilverlightClientView.Converter"
...
<NavigationControls:Page.Resources>
<Converter:BooleanToVisibilityConverter x:Key="resourceBooleanToVisibilityConverter" />
</NavigationControls:Page.Resources>
All works fine. Here I want to move converter class into a custom separate assembly "SilverlightCommonView" and class himself will be in "SilverlightCommonView.Converter" namespace. The XAML code is changed to the following:
xmlns:Converter="clr-namespace:SilverlightCommonView.Converter;assembly=SilverlightCommonView"
...
<NavigationControls:Page.Resources>
<Converter:BooleanToVisibilityConverter x:Key="resourceBooleanToVisibilityConverter" />
</NavigationControls:Page.Resources>
In this case when application throws following exception:
An unhandled exception ('Unhandled
Error in Silverlight Application...
Code: 4004 Category:
ManagedRuntimeError Message:
Microsoft.Practices.Unity.ResolutionFailedException:
Resolution of dependency failed, type="VfmElitaSilverlightClientView.Pages.SquadView",
name="(none)".
Exception occurred while: Calling constructor
VfmElitaSilverlightClientView.Pages.SquadView(). Exception is: XamlParseException -
The type 'BooleanToVisibilityConverter' was not found because
'cl...:SilverlightCommonView.Converter;assembly=SilverlightCommonView'
is an unknown namespace.
It's unclear why specified namespace is unknown (those assembly is referenced by the current one).
Please advise.
Any thoughts are welcome.
I'd bet you do not have an assembly reference to your shared/common project from your application project.

Resources