How can I launch an application through Microsoft Visual Studio? - visual-studio

I am still new to using Visual Studio, any windows programming really, and I am trying to make an application Launcher for Microsoft Office applications. I have already made the interface but dont know how to make the buttons actually launch the programs. Any help is appreciated.

You can add System.Diagnostics namespace to your project and use its Process.Start function to start an external application and for closing a process you can use Process.Close function, save your started process in a variable and close it when ever you want: like this:
static void Main()
{
// ... Open specified Word file.
OpenMicrosoftWord(#"C:\Users\Sam\Documents\Gears.docx");
}
public Process myProcess;
static void OpenMicrosoftWord(string file)
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "WINWORD.EXE";
//If skip this line, you'll have an open MS Word with no specific file loaded
startInfo.Arguments = file;
myProcess = Process.Start(startInfo);
}
static void CloseMicrosoftWord()
{
myProcess.Close();
}
for more information check below links
Process.Start Examples
Using Diagnostics.Process to start an external application
Process.Close Method

Related

Is it possible to read MSBuild macros of C/C++ project programatically outside of Visual Studio?

I am trying to do a mass edit on Visual Studio 2017 projects (.vcxproj). This edit depends conditionally on some project properties. Sadly it's more complicated than what could I do using shared .props file.
I could reimplement the functions needed to get the macros I want, such as $(TargetExt). But I was wondering if there is some Microsoft build tool that could print the required macro to stdout so that I could do:
getMacroValue.exe -project MyProject.vcxproj -value TargetExt
Is there anything like that, or some hack/trick that would lead to the same result? I don't mind dirty solution if it works, what I am doing is a one-time thing, but there are 50+ projects to edit with 5mins per edit so writing a script is worth it.
Maybe this sample(C# console app) could help you read the property value from proj file.
static void Main(string[] args)
{
if (args.Length < 2)
{
return;
}
string path = args[0];
string macro = args[1];
ProjectCollection collection = new ProjectCollection();
Project project = new Project(path, null, null, collection, ProjectLoadSettings.IgnoreMissingImports);
string val = project.GetPropertyValue(macro);
Console.WriteLine(val);
Console.ReadLine();
}

How to run a single class in a console inside my MS visual studio 2012

I have the following class:-
public Class test{
public void testmethod(int i)
{
i = 56789121;
//code ges here
Console.WriteLine(i);
} }
but i need to run this class an see the result of the Console.writeline,, but i am not sure how i can do this. i usually build a web application using MS visual studio and run the application by clicking on "start" button,, but i have never try to output the result using Console.writeline.
BR
Build a Console application instead.
File -> Add -> New Project... and select Console Application
Change the .cs file that VS produces to be something like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Test
{
public void MyMethod()
{
Console.WriteLine("Hello World!");
}
}
class Program
{
static void Main(string[] args)
{
new Test().MyMethod();
}
}
}
The usual way to do this, as Nigel suggested, is to make a Console App for testing stuff.
However, as you stated, you can't do this from VS Web. I personally have started using LINQPad for one-off testing of my objects:
http://www.linqpad.net/
Once you open it, switch the Language dropdown to "C# Statement(s)" or "C# Program". Hit F4, browse to and add a reference to your DLL and an Import for your namespace. Now you can dim your object and call its methods right from LINQPad. LINQPad will not lock any files, so if you rebuild from VS, you can Alt-Tab back to LINQPad and re-run, and it will use the copy of the library you just build.
I've switched almost exclusively to this, as LINQPad has a really nice interface for exploring objects and exceptions you've .Dump()'ed to the output window.
(No, I'm not affiliated with LINQPad, I'm just a really satisfied customer.)
Alternatively....
Since the C# compiler is part of the .Net framework, and not Visual Studio, you can compile programs on the command line.
For example take the standard HelloWorld program in C#
using System;
public class HelloWorld
{
public static void Main(string[] args)
{
Console.WriteLine("Hello world!");
}
}
Create this in notepad, and save as HelloWorld.cs,
Open a command prompt and add the .net framework folder to your path (if not already there):
C:\> PATH=%PATH%;C:\Windows\Microsoft.NET\Framework\v4.0.30319
(note your .net version above may vary)
Then compile using the following command:
C:\> csc HelloWorld.cs
to create HelloWorld.exe.

How do I start/stop IIS Express Server?

I have installed MS Visual Web Developer 2010 which includes IIS Express.
Before this, I had installed XAMPP server for my php applications.
I would like to know how can I stop IIS in order to be able to start XAMPP? It appears that they use the same port. I guess those could be changed, but I do not want to interfere with other programs, and more than that I think this should be simpler.
Thanks!
Closing IIS Express
By default Visual Studio places the IISExpress icon in your system tray at the lower right hand side of your screen, by the clock. You can right click it and choose exit. If you don't see the icon, try clicking the small arrow to view the full list of icons in the system tray.
then right click and choose Exit:
Changing the Port
Another option is to change the port by modifying the project properties. You'll need to do this for each web project in your solution.
Visual Studio > Solution Explorer
Right click the web project and choose Properties
Go to the Web tab
In the 'Servers' section, change the port in the Project URL box
Repeat for each web project in the solution
If All Else Fails
If that doesn't work, you can try to bring up Task Manager and close the IIS Express System Tray (32 bit) process and IIS Express Worker Process (32 bit).
If it still doesn't work, as ni5ni6 pointed out, there is a 'Web Deployment Agent Service' running on the port 80. Use this article to track down which process uses it, and turn it off:
https://sites.google.com/site/anashkb/port-80-in-use
An excellent answer given by msigman. I just want to add that in windows 10 you can find IIS Express System Tray (32 bit) process under Visual Studio process:
Open Task Manager and Kill both of these processes. They will autostart back up.
Then try debugging your project again.
I came across the same issue. My aim is to test PHP scripts with Oracle on Windows 7 Home and without thinking installed IIS7 express and as an afterthought considered Apache as a simpler approach. I will explore IIS express's capabilities seperately.
The challenge was after installing IIS7 express the Apache installation was playing second fiddle to IIS express and bringing up the Microsoft Homepage.
I resolved the port 80 issue by :-
Stopping Microsoft WedMatrix :- net stop was /y
Restarted the Apache Server
Verifying Apache now was listening on the port :- netstat -anop
Clearing out the Browsers caches - Firefox and IE
Running localhost
Here is a static class implementing Start(), Stop(), and IsStarted() for IISExpress. It is parametrized by hard-coded static properties and passes invocation information via the command-line arguments to IISExpress. It uses the Nuget package, MissingLinq.Linq2Management, which surprisingly provides information missing from System.Diagnostics.Process, specifically, the command-line arguments that can then be used to help disambiguate possible multiple instances of IISExpress processes, since I don't preserve the process Ids. I presume there is a way to accomplish the same thing with just System.Diagnostics.Process, but life is short. Enjoy.
using System.Diagnostics;
using System.IO;
using System.Threading;
using MissingLinq.Linq2Management.Context;
using MissingLinq.Linq2Management.Model.CIMv2;
public static class IisExpress
{
#region Parameters
public static string SiteFolder = #"C:\temp\UE_Soln_7\Spc.Frm.Imp";
public static uint Port = 3001;
public static int ProcessStateChangeDelay = 10 * 1000;
public static string IisExpressExe = #"C:\Program Files (x86)\IIS Express\iisexpress.exe";
#endregion
public static void Start()
{
Process.Start(InvocationInfo);
Thread.Sleep(ProcessStateChangeDelay);
}
public static void Stop()
{
var p = GetWin32Process();
if (p == null) return;
var pp = Process.GetProcessById((int)p.ProcessId);
if (pp == null) return;
pp.Kill();
Thread.Sleep(ProcessStateChangeDelay);
}
public static bool IsStarted()
{
var p = GetWin32Process();
return p != null;
}
static readonly string ProcessName = Path.GetFileName(IisExpressExe);
static string Quote(string value) { return "\"" + value.Trim() + "\""; }
static string CmdLine =
string.Format(
#"/path:{0} /port:{1}",
Quote(SiteFolder),
Port
);
static readonly ProcessStartInfo InvocationInfo =
new ProcessStartInfo()
{
FileName = IisExpressExe,
Arguments = CmdLine,
WorkingDirectory = SiteFolder,
CreateNoWindow = false,
UseShellExecute = true,
WindowStyle = ProcessWindowStyle.Minimized
};
static Win32Process GetWin32Process()
{
//the linq over ManagementObjectContext implementation is simplistic so we do foreach instead
using (var mo = new ManagementObjectContext())
foreach (var p in mo.CIMv2.Win32Processes)
if (p.Name == ProcessName && p.CommandLine.Contains(CmdLine))
return p;
return null;
}
}
You can stop any IIS Express application or you can stop all application. Right click on IIS express icon , which is located at right bottom corner of task bar. Then Select Show All Application
to stop IIS manually:
go to start menu
type in IIS
you get a search result for the manager (Internet Information Services (IIS) manager, on the right side of it there are restart/stop/start buttons.
If you don't want IIS to start on startup because its really annoying..:
go to start menu.
click control panel.
click programs.
turn windows features on or off
wait until the list is loaded
search for Internet Information Services (IIS).
uncheck the box.
Wait until it's done with the changes.
restart computer, but then again the info box will tell you to do that anyways (you can leave this for later if you want to).
oh and IIS and xampp basically do the same thing just in a bit different way. ANd if you have Xampp for your projects then its not really all that nessecary to leave it on if you don't ever use it anyways.

WPF Application crashes on WIndows 7 when command executable.Start() is run

I've got a tiny Portal I´m writing, and this portal is supposed to launch installers on button click. I´m developing on VS2010 on a WinXP SP3 station, and on this machine, even fter compilation and publishing, everything works as expected. However, when i run the compiled application in Windows 7, it crashes...The application work, it just crashes when i click a button for program installation.
The programming looks like this:
private void button_access_Click(object sender, RoutedEventArgs e)
{
Process executable = new Process();
string executablePath = "D:\\Visual Studio 2010\\SAFE_Portal1\\SAFE_Portal1\\Extra Programs\\AccessRT2003.exe";
executable.StartInfo.FileName = executablePath;
executable.Start();
}
It specifically crashes on thr button_access_Click procedure...
Any ideas as to why this could be? I`ve tried looking around here in Stackoverflow, and in other forums, but to no avail...
Any help or direction is ganz welcome!
Try this:
try
{
Process executable = new Process();
string executablePath = "D:\\Visual Studio 2010\\SAFE_Portal1\\SAFE_Portal1\\Extra Programs\\AccessRT2003.exe";
executable.StartInfo.FileName = executablePath;
executable.Start();
}
catch (Exception msg)
{
MessageBox.Show(msg.Message);
}
What message are you getting?
Are you sure you want to use fixed paths in your application? If so you should at least check if the file you try to start exists beforehand. Otherwise an exception will be thrown which could be the problem here.
if (File.Exists(executablePath))
{
...
}

Tools for previewing configuration file transformations

Are there any tools or Visual Studio 2010 extensions which allow me to view the output of a configuration file transformation short of having to publish the entire project? Is the process which performs the transformation directly invokable?
Edit
After a little more Googling I came across this:
Step 4: Generating a new transformed web.config file for “Staging” environment from command line
Open Visual Studio Command prompt by
going to Start --> Program Files –>
Visual Studio v10.0 –> Visual Studio
tools –> Visual Studio 10.0 Command
Prompt
Type “MSBuild “Path to Application
project file (.csproj/.vbproj) ”
/t:TransformWebConfig
/p:Configuration=Staging" and hit
enter as shown below:
Once the transformation is successful
the web.config for the “Staging”
configuration will be stored under obj
-->Staging folder under your project root (In solution explorer you can
access this folder by first un-hiding
the hidden files) :
In the solution explorer click the button to show hidden files
Open the Obj folder
Navigate to your Active configuration (in our current case it is “Staging”)
You can find the transformed web.config there
You can now verify that the new
staging web.config file generated has
the changed connection string section.
Source: Web Deployment: Web.Config Transformation
This isn't really a perfect solution for me as it still requires building the entire project- at least with the command he posted. If anyone knows of way to skip the build step with the MSBuild command that would be helpful (although that sounds somewhat unlikely).
Edit 2
I also found this Config Transformation Tool on CodePlex, which offers some nice functionality to extend the transformation process. This is tool is the closest thing I've seen for the functionality I'm seeking and would be a great starting point for developing an extension which creates previews. It uses the Microsoft.Web.Publishing.Tasks library to perform the transformation and does not depend on building an actual project.
The SlowCheetah VS add-in on the visualstudiogallery allows you to preview the transform results
You can transform a config file by using the same objects the MSBuild task uses, bypassing MSBuild altogether. Web config transform logic is contained in the Microsoft.Web.Publishing.Tasks library.
The following code snippet comes from a simple class library, referencing the Microsoft.Web.Publishing.Tasks library (which is installed on my machine at C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web).
The sample loads a source document and transform, applies the transform, and writes the results to a new file.
using System;
using Microsoft.Web.Publishing.Tasks;
// ...
var xmlTarget = new XmlTransformableDocument();
xmlTarget.PreserveWhitespace = true;
xmlTarget.Load("Web.config");
var xmlTransform = new XmlTransformation("Web.Release.config");
if (xmlTransform.Apply(xmlTarget))
xmlTarget.Save("Web.Transformed.config");
else
Console.WriteLine("Unable to apply transform.");
With a little creativity, this simple solution could be integrated into a Visual Studio plugin, perhaps as a context menu item on the web.config file. At the very least, you can make a console utility or script out of it to generate previews.
Good luck!
Old post, but thought I would share what I had found with a quick google (for those that may not have found it or tried here first):
Web.config Transformation Tester - By AppHarbor
Simply paste your original XML along with the transformation XML and see the result instantaneously.
Also, it's open source for anyone who's interested.
Just to extend on this a little.
I needed exactly what is discussed above. To be able to run the transform only.
Then hook that into my build process which happens to be TeamCity in my case.
You will need using Microsoft.Web.Publishing.Tasks, which you can just smash down with Nuget. Well, I was in VS2013 so I could. I'm sure you could acquire the dll otherwise.
Wrote a simple Console App. You may find it useful.
Program.cs
using System;
namespace WebConfigTransform
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 3)
{
Console.WriteLine("Config Gen ... usage -source -transform -destination");
Environment.Exit(-1);
}
Transform t = new Transform(args[0], args[1], args[2]);
t.Run();
}
}
}
Transform.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Security;
using System.Security.Permissions;
using Microsoft.Web.XmlTransform;
namespace WebConfigTransform
{
class Transform
{
private readonly string m_source;
private readonly string m_transform;
private readonly string m_destination;
public Transform(string source, string transform, string destination)
{
m_source = source;
m_transform = transform;
m_destination = destination;
}
private void TransformFiles()
{
var xmlTarget = new XmlTransformableDocument();
xmlTarget.PreserveWhitespace = true;
xmlTarget.Load(m_source);
var xmlTransform = new XmlTransformation(m_transform);
if (xmlTransform.Apply(xmlTarget))
xmlTarget.Save(m_destination);
else
{
Console.WriteLine("Unable to apply transform.");
Environment.Exit(-1);
}
}
private void CheckPermissions()
{
string directoryName = m_destination;
PermissionSet permissionSet = new PermissionSet(PermissionState.None);
FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, directoryName);
permissionSet.AddPermission(writePermission);
if (!(permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)))
{
Console.WriteLine("Cannot write to file : " + m_destination);
Environment.Exit(-1);
}
}
private void CheckFileExistance()
{
List<string> ls = new List<string>();
ls.Add(m_source);
ls.Add(m_transform);
foreach (string item in ls)
{
if (!File.Exists(item))
{
Console.WriteLine("Cannot locate file : " + item);
Environment.Exit(-1);
}
}
}
public void Run()
{
CheckFileExistance();
CheckPermissions();
TransformFiles();
}
}
}

Resources