Detect and install framework 4.5 when program execute - c#

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

Related

Using ToastNotificationManager in .Net5.0

I was using the following code to show a Windows 10 Toast notifications from a .NetCore 3.1 console application, where I was using objects from the following namespaces: Windows.UI.Notifications & Windows.Data.Xml.Dom, in .Net5.0 these namespaces seem to be moved to somewhere else.
public void GenerateToast(string appid, string imageFullPath, string h1, string h2, string p1)
{
try
{
var template = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText04);
var textNodes = template.GetElementsByTagName("text");
textNodes[0].AppendChild(template.CreateTextNode(h1));
textNodes[1].AppendChild(template.CreateTextNode(h2));
textNodes[2].AppendChild(template.CreateTextNode(p1));
if (File.Exists(imageFullPath))
{
XmlNodeList toastImageElements = template.GetElementsByTagName("image");
((XmlElement)toastImageElements[0]).SetAttribute("src", imageFullPath);
}
IXmlNode toastNode = template.SelectSingleNode("/toast");
((XmlElement)toastNode).SetAttribute("duration", "long");
var notifier = ToastNotificationManager.CreateToastNotifier(appid);
var notification = new ToastNotification(template);
notifier.Show(notification);
}
catch (Exception)
{
// Ignore
}
}
How to get back these namespaces?
Solution found Here:
This option is only supported in projects that use .NET 5 (or a later release) and target Windows 10, version 1809 or a later OS release. For more background info about this scenario, see this blog post.
With your project open in Visual Studio, right-click your project in
Solution Explorer and choose Edit Project File. Your project file
should look similar to this.
WinExe
net5.0
true
Replace the value of the TargetFramework element with one of the
following strings:
net5.0-windows10.0.17763.0: Use this value if your app targets
Windows 10, version 1809. net5.0-windows10.0.18362.0: Use this value
if your app targets Windows 10, version 1903.
net5.0-windows10.0.19041.0: Use this value if your app targets
Windows 10, version 2004.
For example, the following element is for a project that targets
Windows 10, version 2004.
net5.0-windows10.0.19041.0
Save your changes and close the project file.

Excel interop MissingMethodException on some systems

In my C# program, I am using Microsoft.Office.Interop.Excel. With this i am reading & writing data to excel file. On one machine, even though it has Office 2007, there are seeing below exception, raises at GetComponentPath() method call.
Unhandled Exception: System.MissingMethodException: Method not found: 'System.Type System.Runtime.InteropServices.Marshal.GetTypeFromCLSID(System.GUID)'.
Here is my code:
public static string GetComponentPath(OfficeComponent _component)
{
string toReturn = string.Empty;
string _key = string.Empty;
try
{
Microsoft.Office.Interop.Excel.Application _excelApp = null;
_excelApp = new Microsoft.Office.Interop.Excel.Application();
if (_excelApp != null)
{
Console.WriteLine("Excel is installed");
}
else
{
Console.WriteLine("Excel not found.");
}
}
catch (Exception ex)
{
Console.WriteLine("Error \n" + ex.ToString());
}
return toReturn;
}
public enum OfficeComponent
{
Word,
Excel,
PowerPoint,
Outlook
}
Problem : you have developed your application in your local machine with heigher version of .NET Framework and running the same on remote pc having Lower Version of.NET Framework.
Note : if you target your application to run on Heigher Version of .NET Framework it wont run on lower versions.
Solution : you need to target it to .NET Framework Lower Version available on your remote PC to run on remote pc.
Step 1: right click on project - select properties
Step 2: change the Target Framework from .NET Framework x.x to .NET Framework x.y.
Note : where x.x is heigher and x.y is lower version available on remote pc or any lower version.

Recommended way to test for iOS Version specific feature at runtime

I'm targetting IOS 4.3 and 5.0 with an app built against the 5.0 SDK and would like to add support for the Twitter functionality introduced in iOS5 only when the app runs on a iOS5 device. What is the recommended way to reliably test for the availability of these OS features at runtime without having your app crash?
I know you do this using respondsToSelector in Objective-C but how is it done in C#?
With recent MonoTouch versions you can use the following code:
if (UIDevice.CurrentDevice.CheckSystemVersion (5, 0)) {
window.RootViewController = navigation;
} else {
window.AddSubview (navigation.View);
}
Otherwise you can get a string from UIDevice.CurrentDevice.SystemVersion and do some checks with your own code.
Follow up to comments, including mine...
If you want to check by feature you can do something like:
MonoTouch.Twitter.TWRequest req = new MonoTouch.Twitter.TWRequest ();
if (req.Handle == IntPtr.Zero) {
Console.WriteLine ("No Twitter support before iOS5");
}
What happens is that the selector to create the TWRequest instance will return null and the .NET object will be created in an invalid (unusable) state that you can query with the Handle property. Again YMMV, testing is key :-)

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?

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

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.

Categories

Resources