i have a web page written in vb, i need to start a windows service that will be installed in the server.
You first need to add a reference to the System.ServiceProcess assembly. The following code gives you roughly what you want to do (I am using a Label control called messageLabel in the following):
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class StartService : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string serviceName = "Remote Registry";
try
{
StartServiceByName(serviceName);
}
catch (Exception ex)
{
messageLabel.Text = ex.ToString().Replace("\r\n", "<BR>");
return;
}
messageLabel.Text = String.Format("Service {0} started.", serviceName);
}
private void StartServiceByName(string serviceName)
{
ServiceController serviceController = new ServiceController(serviceName);
serviceController.Start();
}
}
However, there is a further thing - you need to have the web server have permission to change this service - which is something that normally can be only done with Administration rights.
haven't tested.
pleas try if works or not. you could add following code in btn click event.
dim controller as new ServiceController
controller.MachineName = "." //try the machine name
controller.ServiceName = "service name"
dim status as string = controller.Status.ToString
' Stop the service
controller.Stop()
' Start the service
controller.Start()
Depending on the permissions that the web site account has, you can start / stop services.
In addition to what others have answered, you can shell out NET START with the appropriate parameters.
You can also do this for remote computers as long as the permissions are granted (I think it has to be a domain account for this).
Related
We deployed on a existing server that was already setup and configured with another asp.net application. This isn't something we normally do, as we setup on a new server and configure everything. We also have this same ASP.NET application running on several other servers with no problems.
The application is MVC3 running on ASP.NET 4
The app uses controllers to create a simple RPC type of API.
Example: (Send) /Services/LMS/GetCourses (Returns) XML document
Once we deployed the asp.net application and had everything setup in IIS we ran into an issue we never seen before.
The application will send a NullReferenceException on the line below.
DbProviderFactories.GetFactory(ConfigurationManager.ConnectionStrings["LMS"].ProviderName);
But only if the http request is a POST. If we send a GET request, it works.
I guessing this is some configuration conflict. Is there something in a config file that could limit our application from reading our Web.config settings on a POST?
To provide more context based on comments:
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Configuration;
using Services.Models;
public class DBConnection
{
protected DbProviderFactory factory;
protected string connectionString;
protected char paramChar; // could be ':' or '#' depending on database
public DBConnection(string db) // db is equal to "LMS"
{
try
{
factory = DbProviderFactories.GetFactory(ConfigurationManager.ConnectionStrings[db].ProviderName); // the exception stack points to this line having NullReferenceException
connectionString = ConfigurationManager.ConnectionStrings[db].ConnectionString;
paramChar = DbUtil.GetParamChar(ConfigurationManager.ConnectionStrings[db].ProviderName);
}
catch (ConfigurationErrorsException)
{
throw new ConfigurationErrorsException("The database " + db + " has not been defined in the web.config file.");
}
}
}
Hi is there any way to create my own page in my web server so that i can ping it from external application to get the WAN ip from where the application is hosted? Something like whatismyip but on my own server.
What about next code:
using System;
using System.Web;
namespace WebApplication1
{
public class Global : HttpApplication
{
protected void Application_BeginRequest(object sender,
EventArgs e)
{
// Get request.
HttpRequest request = base.Request;
// Get UserHostAddress property.
string address = request.UserHostAddress;
// Write to response.
base.Response.Write(address);
// Done.
base.CompleteRequest();
}
}
}
I've just deployed WCF web service that includes WebAPI as well. Everything works fine until I add my own Filter Query Validator to my project. Then the role keeps recycling and restarting. It's a very strange issue, I am unable to determine what is the cause of this. Thank you for any help.
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.OData.Query;
using System.Web.Http.OData.Query.Validators;
using EMP.WebServices.api.Providers;
using Microsoft.Data.Edm.Library;
using Microsoft.Data.OData.Query.SemanticAst;
namespace EMP.WebServices.api.Validators
{
public class EntityFilterByQueryValidator : FilterQueryValidator
{
public override void ValidateSingleValuePropertyAccessNode(SingleValuePropertyAccessNode propertyAccessNode, ODataValidationSettings settings)
{
var declaringType = propertyAccessNode.Property.DeclaringType;
var edmEntityType = declaringType as EdmEntityType;
var allowedProperties = TableStorageProvider.GetMetadataPropertyNames(edmEntityType.Name,
Constants.WebApi.V1).ToList();
// Validate if we are accessing some sensitive property of WorkItem, such as Votes
if (!allowedProperties.Contains(propertyAccessNode.Property.Name))
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(string.Format("{0} is an invalid filter property. {1}You can filter by these properties:{1}{2}.", propertyAccessNode.Property.Name, Environment.NewLine, string.Join(", " + Environment.NewLine, allowedProperties))),
ReasonPhrase = "Invalid Filter Property",
StatusCode = HttpStatusCode.BadRequest
});
}
base.ValidateSingleValuePropertyAccessNode(propertyAccessNode, settings);
}
}
}
I see from the ODataQueryableSample (http://www.asp.net/web-api/samples) that throwing an ODataException seems to be the preferred technique. I recommend you try that.
If you believe there is a bug here, I recommend you report a new bug at http://aspnetwebstack.codeplex.com/workitem/list/basic .
I am trying to connect my silverlight application with Sql server 2005 for login purpose. I am totally new to silverlight and want to build my own website in Silverlight. Please suggest useful sites for referance. Thanx in advance.
This may help you
http://www.codeproject.com/Articles/37522/7-Simple-Steps-to-Connect-SQL-Server-using-WCF-fro
You have to use a Web Service example WCF.
1)Add a WCF to your project.
//This is your interface Class.
namespace SilverlightApplication1.Web
{
[ServiceContract]
public interface IService1
{
[OperationContract]
bool UserLogin(string email, string password);
}
}
//This is your service code behind class
namespace SilverlightApplication1.Web
{
public class Service1 : IService1
{
public bool UserLogin(string email,string password)
{
// Your logic here to verify user name and password
}
}
}
//After creating the service. Add a reference to your application.**
2) Add the Service Reference to your Silverlight application.
Right click on your project, Select the web references option and add the service to your project. Now if you have a button control on your form which will submit the data to your wcf service. Add the following code in its click event.
Service1Client proxy ;
private void button1_Click(object sender, RoutedEventArgs e)
{
proxy.UserLogin += new EventHandler<InsertDataCompletedEventArgs>(proxy_UserLogin);
proxy.UserLogin(txtEmail.Text, "Password");
}
void proxy_UserLogin(object sender, InsertDataCompletedEventArgs e)
{
if (e.Result == true)
{
lblMesg.Content = "User Login successfully";
}
else
{
lblMesg.Content = "User record not found";
}
}
In the button Click event call that service.
If you want a SQL Server connection for logging on, you can create a Silverlight Business Application project. It has user logon built in. This way, you can concentrate on the rest of your Silverlight application's features.
I have an ASP.net project which involves using a custom IHttpModule. This module will sit in the pipeline and when certain criteria match up, it should invoke a method on a WCF service hosted in a simple C# console application on the same machine.
The code for the module is below:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.SessionState;
using System.Web;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Configuration;
using System.ServiceModel;
using SimpleFarmStateServer;
namespace SimpleFarm
{
public class SimpleFarmModuleSS : IHttpModule, IRequiresSessionState
{
protected string cache_directory = "";
// WCF
ChannelFactory<IStateServer> factory;
IStateServer channel;
public void Dispose() { }
public void Init(System.Web.HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
setupFactory();
}
void setupFactory()
{
factory = new ChannelFactory<IStateServer>(
new NetNamedPipeBinding(),
"net.pipe://localhost/StateServer");
}
void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
try
{
if (factory.State != CommunicationState.Opened)
setupFactory();
channel = factory.CreateChannel();
channel.LogAccess("Hello World!");
}
catch (Exception ex)
{
}
finally
{
factory.Close();
}
}
}
}
My problem is that this runs the first time, but then subsequent attempts cause this error message
The communication object,
System.ServiceModel.Channels.ServiceChannel,
cannot be used for communication
because it is in the Faulted state.
It seems as if I am doing something wrong, and I am new to WCF in general so this is very likely.
I think the issue is surrounding the ChannelFactory being recreated, and this causes the faulted state.
The specific error probably means the factory faulted, threw an exception (which you're swallowing) and then when the finally block executes, the factory.Close() call fails because the factory is faulted (if a WCF object is faulted, you need to call Abort() on it, not Close()).