C# Regex Compatibility Issue (.NET 3.5 vs .Net 2.0) - c#

I have the following regex expression on a dev machine that is running .NET 3.5 and it works as designed. However when it is deployed to our test environment (which is running .NET 2.0) it doesn't work right and always seems to return false. Does anyone know what the culprit may be? Thanks
using System.Text.RegularExpressions;
protected void emailContactCheck(object source, ServerValidateEventArgs args)
{
string[] allContacts = this.Contacts.InnerText.ToString().Split(";,".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
Regex rx = new Regex(#"^(([^<>()[\]\\.,;:\s#\""]+"
+ #"(\.[^<>()[\]\\.,;:\s#\""]+)*)|(\"".+\""))#"
+ #"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
+ #"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
+ #"[a-zA-Z]{2,}))$", RegexOptions.IgnoreCase);
foreach (String contact in allContacts)
{
if (!rx.IsMatch(contact.Trim()))
{
args.IsValid = false;
return;
}
}
args.IsValid = true;
}

According to regular-expressions.info, there are no differences in regex support between .NET 2.0 and 3.x, so the problem is probably not with the regex engine.

I would try to set the .Net version of your dev machine to .Net 2.0 too. Can be done on the project build properties. You should always use the same version as on your test/production system.
Then you can try to check whether you can reproduce the problem also on your dev machine running .Net 2.0.

Related

How to use OpenHardwareMonitor .dll?

I'm trying to get status data of my processor on the local machine. I found several tutorials online, but no one of them covers the error I'm getting.
This is my code:
UpdateVisitor visitor = new UpdateVisitor();
Computer computer = new Computer();
computer.Open();
computer.CPUEnabled = true;
computer.Accept(visitor);
It throws an Exception when calling computer.Open() and this is the exception message:
What am i doing wrong? If i can provide some more detail, please let me know.
I'm referencing the library in a .NET Standard 2.0 project.
Solved the problem by referencing the library in a .NET Framework 4.7.1 project, instead that in a .NET Standard 2.0 project. I post this answer just to warn other people trying to achieve this that this library is not fully compatible with .NET Standard code.
I stole this WMI Answer from this question: C# CPU and GPU Temp.
Just install System.Management and start VS in Admin mode, and you can access the sensors.
using System;
using System.Diagnostics;
using System.Management;
class Program
{
static void Main(string[] args)
{
Double CPUtprt = 0;
System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(#"root\WMI", "Select * From MSAcpi_ThermalZoneTemperature");
foreach (System.Management.ManagementObject mo in mos.Get())
{
CPUtprt = Convert.ToDouble(Convert.ToDouble(mo.GetPropertyValue("CurrentTemperature").ToString()) - 2732) / 10;
Console.WriteLine("CPU temp : " + CPUtprt.ToString() + " °C");
}
}
}

Detect and install framework 4.5 when program execute

I have VS2013 EE WinForms application with target .net 4.5.
When I try to execute my app under Win7 without 4.5 framework installed exception window appears (0xc000007b).
What should I set in my app settings for showing a good info window with download framework option?
I don't want to publish installation file, just want exe with dll-s so publish is not my target.
try:
http://thecodeventures.blogspot.com/2012/12/c-how-to-check-if-specific-version-of.html
reffers to msdn
http://msdn.microsoft.com/en-us/library/hh925568.aspx
private static void Get45or451FromRegistry()
{
using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\")) {
int releaseKey = Convert.ToInt32(ndpKey.GetValue("Release"));
if (true) {
Console.WriteLine("Version: " + CheckFor45DotVersion(releaseKey));
}
}
}
// Checking the version using >= will enable forward compatibility,
// however you should always compile your code on newer versions of
// the framework to ensure your app works the same.
private static string CheckFor45DotVersion(int releaseKey){
if ((releaseKey >= 379893)) {
return "4.5.2 or later";
}
if ((releaseKey >= 379675)) {
return "4.5.1 or later";
}
if ((releaseKey >= 378389)) {
return "4.5 or later";
}
// This line should never execute. A non-null release key should mean
// that 4.5 or later is installed.
return "No 4.5 or later version detected";
}
kind regards
you can check in registry which framework is installed ? If VS version is below to 4.5 give a message window to download that version.
you can easily find out how to check VS version installed ?
here is the link http://www.mztools.com/articles/2008/MZ2008003.aspx

c# Covert.ToDecimal difference in the 3.5 and 4.5 framework and xp machine

I need help with this.
The following code runs fine on Win7/Win8 machine with both 3.5 and 4.5 .NET Framework installed.
CultureInfo info = CultureInfo.CreateSpecificCulture("hr-HR");
string ui = txtUkupanIznos.Text.Trim();
decimal pvalue;
if (decimal.TryParse(ui, NumberStyles.Any, info, out pvalue))
{
decimal poreznaStopa = 0.00m;
decimal ukupanIznos = 0.00m;
try
{
poreznaStopa = Convert.ToDecimal(txtstopa.Text.Replace(".", ","), info);
ukupanIznos = Convert.ToDecimal(ui.Replace(".", ","), info);
}
...
But on XP machine with .NET Framework 3.5 SP1 installed, this throws a FormatException so I need to remove Replace(".", ",")
Why?
My guess is that the regional settings defined for Croatia may have changed between these Windows versions. If you run the sample code in MSDN to output the settings on the three different PCs, what do you see for number format?
The culture wasn't defined pre Windows Vista more than likely. I'm guessing hr-HR may not have any meaning in the older OS's.

Future-proofing the .NET version detection

Not to beat the dead horse, however, I am looking for a way to detect the installed .NET frameworks. It seems like the provided solutions (in the links) are all good up until the point a new version of the framework is released and then all bets are off. The reason for this is that the detection relies on the registry keys and it seems that v4 of the framework has broken the convention and one now has to take extra steps to detect v4.
Is there a way to detect the .NET framework that will also work when .NET v5 appears.
EDIT: Ok, for future generations of frustrated .NET Version seekers, here is the code to make it happen:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Diagnostics;
using Microsoft.Win32;
private List<string> GetInstalledDotNetFrameworks()
{
string key = string.Empty;
string version = string.Empty;
List<string> frameworks = new List<string>();
var matches = Registry.LocalMachine
.OpenSubKey(#"SOFTWARE\Microsoft\NET Framework Setup\NDP")
.GetSubKeyNames().Where(keyname => Regex.IsMatch(keyname, #"^v\d"));
// special handling for v4.0 (deprecated) and v4 (has subkeys with info)
foreach (var item in matches)
{
switch (item)
{
case "v4.0": // deprecated - ignore
break;
case "v4":// get more info from subkeys
key = #"SOFTWARE\Microsoft\NET Framework Setup\NDP\" + item;
string[] subkeys = Registry.LocalMachine
.OpenSubKey(key)
.GetSubKeyNames();
foreach (var subkey in subkeys)
{
key = #"SOFTWARE\Microsoft\NET Framework Setup\NDP\" + item + #"\" + subkey;
version = Registry.LocalMachine
.OpenSubKey(key)
.GetValue("Version").ToString();
version = string.Format("{0} ({1})", version, subkey);
frameworks.Add(version);
}
break;
case "v1.1.4322": // special case, as the framework does not follow convention
frameworks.Add(item);
break;
default:
try
{
// get the Version value
key = #"SOFTWARE\Microsoft\NET Framework Setup\NDP\" + item;
version = Registry.LocalMachine
.OpenSubKey(key)
.GetValue("Version").ToString();
frameworks.Add(version);
}
catch
{
// most likely new .NET Framework got introduced and broke the convention
}
break;
}
}
// sort the list, just in case the registry was not sorted
frameworks.Sort();
return frameworks;
}
In short, you can use this approximately (see below for more complete solution):
Microsoft.Win32.Registry.LocalMachine
.OpenSubKey(#"SOFTWARE\Microsoft\NET Framework Setup\NDP")
.GetSubKeyNames().Where(keyname=>Regex.IsMatch(keyname,#"^v\d"))
On my machine, this returns: v2.0.50727, v3.0, v3.5, v4, v4.0. Subkeys could be used to detect service packs (which are probably relevant). Also, using the key SOFTWARE\Microsoft\.NETFramework returns v2.0.50727, v3.0 and v4.0.30319 - ehhh, lovely, slightly different!
There's no guarantee this pattern will hold, but it's a pretty reasonable bet :-). http://support.microsoft.com/kb/318785 has some more info on the details of the registry describing the versioning, and in particular, you may need to check for Install - but that's tricky as v4.0 demonstrates.
Edit: I've extended this to detect arbitrary sub-key's of the registry that include installation info so as to detect v4 Client and Full profiles correctly. Also, the RegistryKey type is IDisposable, and it looks like the Dispose method is indeed doing something (registry key unlocking).
var versionList = new List<string>();
using(var ndpKey=Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\NET Framework Setup\NDP")) {
Action<RegistryKey, Action<RegistryKey,string>> processKids = (node, action) => {
foreach(var childname in node.GetSubKeyNames())
using(var child = node.OpenSubKey(childname))
action(child,childname);
};
Action<RegistryKey, Func<RegistryKey, bool>> visitDescendants = null;
visitDescendants = (regkey, isDone) => {
if(!isDone(regkey))
processKids(regkey, (subkey, subkeyname)=>visitDescendants(subkey,isDone));
};
processKids(ndpKey, (versionKey, versionKeyName) => {
if(Regex.IsMatch(versionKeyName,#"^v\d")) {
visitDescendants(versionKey, key => {
bool isInstallationNode = Equals(key.GetValue("Install"), 1) && key.GetValue("Version") != null;
if(isInstallationNode)
versionList.Add(
key.Name.Substring(ndpKey.Name.Length+1)
+ (key.GetValue("SP")!=null ? ", service pack "+ key.GetValue("SP"):"")
+ " ("+key.GetValue("Version") +") "
);
return isInstallationNode;
});
}
});
}
versionList then contains:
v2.0.50727, service pack 2 (2.0.50727.4927)
v3.0, service pack 2 (3.0.30729.4926)
v3.5, service pack 1 (3.5.30729.4926)
v4\Client (4.0.30319)
v4\Full (4.0.30319)
Do you expect we can tell you the future? :) Why do you need that in the first place? I mean, if you write an app for v4, what difference does it make if v5 is installed or not? You can specify in the app.config what versions you support, but you can't know in advance what the next version will be, or even if your app will run on that. Whenever a new framework comes out, you'll have to test your app, and decide if you want to migrate or not. If you migrate, then you make changes to the app.config and possibly the code, too, and release a new version. If you don't, then you'll still require that an older framework version be installed. It's not like v5 comes out and people will start uninstalling all the previous frameworks. I still have v1.1 and v2 on my machine and I guess they'll stick around for a while.
I am in agreement with fejesjoco. Why do you even want to detect a future version that your code has not been compiled against?
If you look in the Framework folder (C:\Windows\Microsoft.NET\Framework) you will see that all previous versions of the Framework are install along with the most recent version. If your code is compiled against 4.0 and 5.0 comes out it will still have a folder for 4.0.
If you could give us a bit more context as to why you want to detect future versions we may be able to help you better.
Include an auto-update feature in the detection tool?

Enable ASP.NET in IIS6 Programmatically

Is there a way to enable the ASP.NET Web Service Extension in IIS6 via C#? I'm trying to simplify a website setup program for people who haven't used IIS before.
C# NET. Framework usage:
Process.Start(#"C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis", "-i -enable");
CMD usage:
C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -i -enable
It's useful.
Source: https://serverfault.com/questions/1649/why-does-iis-refuse-to-serve-asp-net-content
You could call out to WMI easily enough (System.Management namespace, IIRC) and I believe you can set it from there. However, it may well be much simpler to set it manually, you can't do it from within an ASP.NET site since your server won't be able to run it until it is set...
Principles of doing something similar may be found here
Looking around all the examples of this are written in vbscript. So I cheated and came up with this function:
static void EnableASPNET()
{
var file = "wmi.vbs";
using (var writer = new StreamWriter(file))
{
writer.WriteLine("Set webServiceObject = GetObject(\"IIS://localhost/W3SVC\")");
writer.WriteLine("webServiceObject.EnableWebServiceExtension \"ASP.NET v2.0.50727\"");
writer.WriteLine("webServiceObject.SetInfo");
}
var process = Process.Start("cscript", file);
process.WaitForExit();
File.Delete(file);
}
// if windows 2003
if (Environment.OSVersion.Version.Major == 5 &&
Environment.OSVersion.Version.Minor == 2)
{
DirectoryEntry folderRoot = new DirectoryEntry("IIS://localhost/W3SVC");
folderRoot.Invoke("EnableWebServiceExtension", "ASP.NET v2.0.50727");
}
Copied from: http://lastdon.blogspot.com/2006/12/setup-web-application-on-windows-2003.html
I believe you can also run the following command line:
C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -s W3SVC
And this will recursively enable the AND.NET framework v2.0.50727 for all configured websites.

Categories

Resources