Archive
Fix: “The Global element ‘xx’ has already been declared” warnings in config files after .NET framework upgrade in Visual Studio solution
Had just converted to target .NET framework 4.7.2 a Visual Studio solution full of 4.5 libraries, console apps and an MVC 5.0 (recently converted from 4.0) web app and all seemed to build fine, but then noticed that with web.config of the MVC web app open in the editor, it was showing lots of warnings of the form:
The Global element ‘xx‘ has already been declared in …
and marking them in the text with blue underscores under some whitespace
Seems others have had this issue too with configuration files (both ASP.net and Entity Framework ones) after changing target .NET framework:
Luckily the solution was hidden in that thread, just had to pick the best one (read on below)
– at https://stackoverflow.com/a/52274659/903783 one reads (see related screenshot there):
I noticed this issue with my VS2017.
Changing DotNetConfig.xsd to use "Automatic" solved the problem.
This doesn’t seem to work permanently (only worked once for a while for me)
– at https://stackoverflow.com/a/28114738/903783 is says:
With the symptoms as described in the question, and using Visual Studio 2013 (Update 4), I could see in the XML Schemas [sic] dialog that both
DotNetConfig.xsd
andDotNetConfig40.xsd
were selected for use.I’m using a .NET Framework 4.0 project.
The two XSD files conflict with each other, each defining the same elements, causing the warnings to be emitted.
These schema files are contained in the
%programfiles(x86)%\Microsoft Visual Studio 12.0\xml\Schemas\
folder.
DotNetConfig.xsd
is in the1033
sub-folder and appears to be the newer, more complete version.No matter what settings I selected in XML Schemas, I could not deselect, or remove DotNetConfig40 nor DotNetConfig. I tried "Remove", and changing the Use parameter from "Use this schema" to "Automatic" and then "Do not use this schema".
No matter what was selected, for either file, when I would return to the dialog, both would be selected for use. I also tried the trick of moving to another row before pressing "OK" to no avail.
Finally, I renamed the
DotNetConfig40.xsd
file toDotNetConfig40 DO NOT USE.xsd
to prevent it from being loaded. This immediately solved the problem.
This does work (adapting the path for VS2017), but one isn’t sure (unless they check the file dates maybe) which file to keep, in my case it was 1033/DotNetConfig.xsd and DotNetConfig45.xsd, nor are they sure this won’t cause any side-effects in other solutions/projects.
– Finally, at https://stackoverflow.com/a/33823331/903783 it read:
I struggled with this for a while as well. Turns out, my version of the problem originated from the hidden
{PROJECTNAME}.SUO
file created by Visual Studio.My guess is, VS will cache the XSD schema associations in this file. The warnings popped up after I changed the target framework, and they disappeared after I deleted the SUO file and restarted VS.
This fixed it permanently. Deletion of the .suo ended up with the DotNetConfig.xsd and removed the DotNetConfig45.xsd from the XML schemas list for the projects in the solution. In fact I deleted just a .suo file with no filename part, just a file extension, found by typing “.suo” at the search filter in the top-right of the solution’s folder window in Windows 10 File Explorer.
Getting resulting SQL string from parametric ADO.net SqlCommand
Microsoft is suggesting to always use Named parameters with SqlCommands for security reasons (to avoid SQL injection exploits), but they haven’t thought of providing a property at SqlCommand to give you back the result SQL so that you can have your app log it without resorting to SQL Server for that logging.
Found a solution at CommandAsSQL project on GitHub and the discussion that brought it to life at https://stackoverflow.com/questions/265192/get-the-generated-sql-statement-from-a-sqlcommand-object/
That solution was only for the case where the type of the SqlCommand was StoredProcedure, but needed to cover non-Stored procedures too (aka type Text of SqlCommand), so I augmented that library with this logic:
private static void CommandAsSql_Text(this SqlCommand command,
System.Text.StringBuilder sql)
{
string query = command.CommandText;
foreach (SqlParameter p in command.Parameters)
query = Regex.Replace(query,
"\\B" + p.ParameterName + "\\b", p.ParameterValueForSQL());
sql.AppendLine(query);
}
The pull request is at: https://github.com/jphellemons/CommandAsSql/pull/3/commits/527d696dc6055c5bcf858b9700b83dc863f04896
The Regex idea was based on @stambikk’s and EvZ’s comments at that StackOverflow thread and the "Update:" section of https://stackoverflow.com/a/2544661/903783 that mentions "negative look-behind assertion".
The use of \B instead of \b for word boundary detection at the start of the regular expression is because the p.parameterName will always start with a "@" which is not a word character.
Note that ParameterValueForSQL() is an extension method defined at the CommandAsSql library to handle issues like single-quoting string parameter values etc. It may have a bug with its date handling currently though, will submit an issue on that
Btw, other promising piece of code is at https://github.com/jeroenpot/SqlHelper/blob/master/Source/Mirabeau.MsSql.Library/SqlGenerator.cs (mentioned at an answer in this thread). Probably could merge code from CommandAsSql and SqlGenerator if one finds something not working at one or the other.
Difference between LocalizableAttribute and LocalizabilityAttribute in .NET
I’ve just updated an older answer of mine at:
In case you’re wondering too what’s the difference between Localizable and Localizability attributes in .NET, maybe this helps a bit:
https://msdn.microsoft.com/en-us/library/ms753944(v=vs.100).aspx
- LocalizableAttribute – Specifies whether a property should be localized
- LocalizabilityAttribute – Specifies the localization attributes for a binary XAML (BAML) class or class member
Seems the Localizability attribute is BAML-specific and makes sure localization-related comments (probably to make use by localization tools and show to the translators) are preserved/exposed when WPF XAML is compiled from text XML form into binary BAML.
Managed .NET Speech API links
(this is my answer at http://stackoverflow.com/questions/14771474/voice-recognition-in-windows)
I’m looking into adding speech recognition to my fork of Hotspotizer Kinect-based app (http://github.com/birbilis/hotspotizer)
After some search I see you can’t markup the actionable UI elements with related speech commands in order to simulate user actions on them as one would expect if Speech input was integrated in WPF. I’m thinking of making a XAML markup extension to do that, unless someone can point to pre-existing work on this that I could reuse…
The following links should be useful:
http://www.wpf-tutorial.com/audio-video/speech-recognition-making-wpf-listen/
http://www.c-sharpcorner.com/uploadfile/mahesh/programming-speech-in-wpf-speech-recognition/
https://msdn.microsoft.com/en-us/library/hh855387.aspx (make use of Kinect mic array audio input)
http://kin-educate.blogspot.gr/2012/06/speech-recognition-for-kinect-easy-way.html
https://channel9.msdn.com/Series/KinectQuickstart/Audio-Fundamentals
https://www.microsoft.com/en-us/download/details.aspx?id=27225
https://www.microsoft.com/en-us/download/details.aspx?id=27226
http://www.redmondpie.com/speech-recognition-in-a-c-wpf-application/
http://www.codeproject.com/Articles/55383/A-WPF-Voice-Commanded-Database-Management-Applicat
http://www.codeproject.com/Articles/483347/Speech-recognition-speech-to-text-text-to-speech-a
http://www.c-sharpcorner.com/uploadfile/nipuntomar/speech-to-text-in-wpf/
http://www.w3.org/TR/speech-grammar/
https://msdn.microsoft.com/en-us/library/hh361625(v=office.14).aspx
Structuring (physical) source and (virtual) solution folders for portability
Copying here those comments of mine at a discussion on the GraphX project:
https://github.com/panthernet/GraphX/issues/21
describing the source code (physical) folder structure and the Visual Studio solution (virtual) folder structure I’ve been using at ClipFlair and other multi-platform projects.
——
looking at the folders/projects/libraries/namespaces naming, I think it would be more appropriate to add the platform at the end of the name, say GraphX.somePart.PCL, GraphX.somePart.UWA (=Universal Windows Application model [aka Win10]) etc. Not sure how easy it will be though for contributors to merge pending changes via GitHub if you do such drastic changes (I’m still struggling with Git myself, prefer Mercurial)
…
Speaking of moving the platform to the end of the name (e.g. GraphX.Controls.WPF, GraphX.Controls.SL5 etc.), to do it on the folder names (apart from doing at the source code for packages, target assemblies etc.), I think one has to use some Version Control command to "move" (Git should have something like that) the files to the new folder, else other contributors may have issue merging their changes.
Despite the trouble to do it, I think it is better for the long run. Also, all GraphX.SomePart.* subfolders could then be grouped in a GraphX.SomePart folder as subfolders where a Source or Common subfolder would also exists that has all the common code those platform-specific versions of GraphX.SomePart share (via linked files to ..\Common\SomeFile, ..\Common\SomeFolder\SomeFile and ..\Common\SomeOtherFolder\SomeFile etc.)
This is the scheme I’ve been using (and I’m very satisfied with) at http://clipflair.codeplex.com and other projects (e.g. at the AmnesiaOfWho game [http://facebook.com/AmnesiaOfWho] that has separate versions for SL5, WP7 and WP8 and WPF version on the works, plus WRT (WinRT) and UWA [Universal Windows App] too coming in the near future, with all code and most XAML shared via linked files and UserControl[s])
…
I meant I’d expect GraphX.Common folder with GraphX.Common.PCL in it and GraphX.Common.WP7 etc. versions for example also in that folder since PCL is usually set at WP8 level. This is just an example.
What I’m saying is that the platform name is the last part of the specialization chain, so logically GraphX comes first then say comes Controls then comes WPF, SL5, WP8 etc. in the folder name.
Also would have 3 parent folders Controls, Common and Logic. The last two would just contain the respective .PCL subfolder for now, but I can contribute subfolders for specific platforms too, esp for those the common PCL profile doesn’t cover. Source would be at Controls\Source, Common\Source, Logic\Source and respective platform specific projects (even the pcl projects) would use linked files
aka
GraphX (contains GraphX.sln)
–\Controls
—-\Source
—-\GraphX.Controls.WP7
—-\GraphX.Controls.WP8
—-\GraphX.Controls.SL5 (contains GraphX.Controls.SL5.csproj)
—-\GraphX.Controls.WPF (contains GraphX.Controls.WPF.csproj)
—-\GraphX.Controls.WIN8
—-\GraphX.Controls.UWA
—- … (more platform specific versions)
–\Common
—-\Source
—-\GraphX.Common.PCL
—- … (platform specific versions, esp. those not covered by the settings chosen at the PCL)
–\Logic
—-\Source
—-\GraphX.Logic.PCL
—- … (platform specific versions, esp. those not covered by the settings chosen at the PCL)
The same structure would also be used at examples to cover the potential of porting some of them to more platforms:
–\Examples
—-\SomeExample
——\Source
——\SomeExample.WPF
——\SomeExample.SL5
—-\SomeOtherExample
——\Source
——\SomeOtherExample.WIN8
——\SomeOtherExample.UWA
etc.
Of course common code at each folder is at the Source subfolder of that folder, shared using linked files (e.g. at \Examples\SomeExample\Source) and platform specific code is inside the respective projects (e.g. at \Examples\SomeExample\SomeExample.WPF)
Similarly the GraphX.sln would contain solution folders "Controls", "Common" and "Examples", though it could also contain separate solution (virtual) folders per platform that have each one of them "Controls", "Common" and "Examples" in them. That is the solution’s folder structure is organized per-platform in such a case. This is mostly useful if you want to focus on a specific platform each time when developing. However since the solution folders are virtual, one could even go as far as having two solutions, one with the same structure as the filesystem folders I suggest and one with a per-platform/target structure.
I follow the per-platform virtual solution folders style at ClipFlair.sln in http://clipflair.codeplex.com, while the real folders are structured as I describe above (where each module has its own physical subfolders for the various platforms). In fact some module subfolders there (say Client\ZUI\ColorChooser) contain their own extra solution file when I want to be able to focus just on a certain module. That solution just includes the respective ColorChooser.WPF, ColorChooser.SL5 etc. subprojects from respective subfolders). Such solutions also contain virtual WPF, Silverlight etc. subfolders that has as children apart from the respective platform-specific project (say ColorChooser.WPF) any other platform-specific projects needed (e.g. ….\Helpers\Utils\Utils.WPF\Utils.WPF.csproj etc.) by that module to compile.
…
Speaking of Xamarin, adding support for that too could follow the same pattern as described above (PCL where possible and platform-specific versions for .XamarinIOS, .XamarinAndroid etc. where needed)
Source code analyzers for .NET porting & Portable Class Libraries (PCL)
- .NET Portability Analyzer extension
https://visualstudiogallery.msdn.microsoft.com/1177943e-cfb7-4822-a8a6-e56c7905292b - API Portability Analyzer – Alpha (command-line version)
http://www.microsoft.com/en-us/download/details.aspx?id=42678 - PLIB API XLS
https://onedrive.live.com/view.aspx?resid=8A7FB4A4B32FB2C9!180&app=Excel&authkey=!AHaBmLAhQ49YCI0 - Xamarin Scanner (How Mobile is your .NET code?)
http://scan.xamarin.com/
HowTo: Use MEF to implement import/export etc. plugin architecture
Copying here my comment at a discussion on the GraphX project:
https://github.com/panthernet/GraphX/pull/15
in case it helps somebody in using MEF (Managed Extensibility Framework) in their software’s architecture
——–
Using static classes instead of interfaces can mean though that you need to use reflection to call them (e.g. if you wan to have a list of export plugins).
Instead can keep interfaces and make use of MEF to locate import/export and other plugins (you can have some class attribute there that mark the class as a GraphXExporter and MEF can be asked then to give you interface instances from classes that have that attribute.)
see usage at
http://clipflair.codeplex.com/SourceControl/latest#Client/ClipFlair.Windows/ClipFlair.Windows.Map/MapWindowFactory.cs
//Project: ClipFlair (http://ClipFlair.codeplex.com)
//Filename: MapWindowFactory.cs
//Version: 20140318using System.ComponentModel.Composition;
namespace ClipFlair.Windows.Map
{//Supported views
[Export("ClipFlair.Windows.Views.MapView", typeof(IWindowFactory))]
//MEF creation policy
[PartCreationPolicy(CreationPolicy.Shared)]
public class MapWindowFactory : IWindowFactory
{
public BaseWindow CreateWindow()
{
return new MapWindow();
}
}}
//Project: ClipFlair (http://ClipFlair.codeplex.com)
//Filename: ImageWindowFactory.cs
//Version: 20140616using System.ComponentModel.Composition;
using System.IO;namespace ClipFlair.Windows.Image
{//Supported file extensions
[Export(".PNG", typeof(IFileWindowFactory))]
[Export(".JPG", typeof(IFileWindowFactory))]
//Supported views
[Export("ClipFlair.Windows.Views.ImageView", typeof(IWindowFactory))]
//MEF creation Policy
[PartCreationPolicy(CreationPolicy.Shared)]
public class ImageWindowFactory : IFileWindowFactory
{public const string LOAD_FILTER = "Image files (*.png, *.jpg)|*.png;*.jpg";
public static string[] SUPPORTED_FILE_EXTENSIONS = new string[] { ".PNG", ".JPG" };
public string[] SupportedFileExtensions()
{
return SUPPORTED_FILE_EXTENSIONS;
}public BaseWindow CreateWindow()
{
return new ImageWindow();
}}
}
to get the first plugin that supports some contract (I get that contract name from the serialization file [using DataContracts]) for a loaded view, or that supports some file extension for a file dropped inside a component, I do:
protected static IWindowFactory GetWindowFactory(string contract)
{
Lazy<IWindowFactory> win = mefContainer.GetExports<IWindowFactory>(contract).FirstOrDefault();
if (win == null)
throw new Exception(BaseWindowStrings.msgUnknownViewType + contract);
else
return win.Value;
}protected static IFileWindowFactory GetFileWindowFactory(string contract)
{
Lazy<IFileWindowFactory> win = mefContainer.GetExports<IFileWindowFactory>(contract).FirstOrDefault();
if (win != null)
return win.Value;
else
return null;
}
HowTo: Install .NET 3.5 component in Windows 8.1
I just installed .NET 3.5 on a Windows Enterprise 8.1 system that was failing to bring the needed files from the network
To do this I opened a command prompt with elevated rights and ran a single command, having the Windows DVD at drive F:
Dism /online /enable-feature /featurename:NetFx3 /All /Source:F:\sources\sxs /LimitAccess
as explained at this article:
http://www.askvg.com/how-to-install-microsoft-net-framework-3-5-offline-in-windows-8-without-internet-connection/
Notes:
1) if you have the Windows DVD in .ISO file, with a double click it mounts it to a virtual drive on Windows 8, so you can do similarly (you look at My Computer or the folder it opens after mounting to see what drive letter it used)
2) to run command prompt with elevated (administrator) rights, I searched for "cmd" (it is cmd.exe) and right click at the result found to then select "Run as administrator".
Gotcha: System.IO.GetInvalidPathChars result not guaranteed
at System.IO.Path.GetInvalidPathChars one reads:
The array returned from this method is not guaranteed to contain the complete set of characters that are invalid in file and directory names
note: can also call this method from non-trusted Silverlight app – not as Intellisense tooltip wrongly says in Visual Studio 2013 with Silverlight 5.1
I just found out about this the hard way (since DotNetZip library was failing at SelectFiles to open .zip files that it had before successfully saved with item filenames containing colons). So I had to update my ReplaceInvalidFileNameChars string extension method to also replace/remove invalid characters such as the colon, wildcard characters (* and ?) and double quote.
public static string ReplaceInvalidFileNameChars(
this string s,
string replacement = "") { return Regex.Replace(s, "[" + Regex.Escape( Path.VolumeSeparatorChar + Path.DirectorySeparatorChar + Path.AltDirectorySeparatorChar + ":" + //added to cover Windows & Mac in case code is run on UNIX "\\" + //added for future platforms "/" + //same as previous one "<" + ">" + "|" + "\b" + "" + "\t" + //based on characters not allowed on Windows new string(Path.GetInvalidPathChars()) + //seems to miss *, ? and " "*" + "?" + "\"" ) + "]", replacement, //can even use a replacement string of any length RegexOptions.IgnoreCase); //not using System.IO.Path.InvalidPathChars (deprecated insecure API) }
Useful to know:
System.IO.Path.VolumeSeparatorChar
slash ("/") on UNIX, and a backslash ("\") on the Windows and Macintosh operating systems
System.IO.Path.DirectorySeparatorChar
slash ("/") on UNIX, and a backslash ("\") on the Windows and Macintosh operating systems
System.IO.Path.AltDirectorySeparatorChar
backslash (‘\’) on UNIX, and a slash (‘/’) on Windows and Macintosh operating systems
More info on illegal characters at various operating systems can be found at:
Gotcha: .NET Point and PointConverter inconsistency in string format used
I have submitted the following issue to Microsoft Connect (product feedback center):
Point class issue with two-way databinding
In Silverlight, when using databinding code like the following:
<StackPanel Orientation="Vertical" Name="propPosition">
<sdk:Label Style="{StaticResource PropertyLabelStyle}" Content="Position:" Target="{Binding ElementName=edPosition}" />
<TextBox Name="edPosition" Text="{Binding Position, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=true}" />
</StackPanel>and binding (via DataContext) to a View that has the following property:
Point Position { get; set; }
then what you see on the UI is values like 500; 100
but when you try to edit the position and enter say 400; 100 it shows a red message that it is invalid format (caught an exception that is and showing on the UI automatically cause of ValidatesOnExceptions and NotifyOnValidationError being true)
if you enter 400, 100 it works ok (it moves a ClipFlair Studio [http://ClipFlair.net] window arround in my case), so it outputs the two numbers (X, Y) with a ";" but expects to get them separated with a "," (also wonder if it copes OK with numbers in say format used in Greece where decimal point separator is , instead of .)
I managed to reproduce the same behaviour in a .NET console program:
//Console program in C# to demonstrate Point.ToString and PointConverter (from string) inconsistency in string format
//(the former outputs X;Y, the later expects X,Y)
using System;
using System.Windows; //for "Point" class (needs WindowsBase.dll reference)
namespace ConsoleApplication1
{
class Program
{
static PointConverter conv = new PointConverter();
static void Main(string[] args)
{
Point p = new Point(10, 20);
Console.WriteLine(p); //outputs "10;20"
//——————
Point p1 = (Point)conv.ConvertFrom("10, 20");
Console.WriteLine(p1); //outputs "10;20"
//——————
Point p2 = (Point)conv.ConvertFrom("10; 20"); //unhandled exception "System.FormatException" in mscorlib.dll
Console.WriteLine(p2); //never reached cause of exception above
}
}
}