Proccess.Start in MVC4 project not working when published - c#

From My MVC4 page I need to call a Powershell script. I don't really need to return any result from it, just make sure the script runs.
When I Debug in my computer, it works fine, but when I try after publishing, it just doesn't do anything or show any error.
This is the code in my Controller:
using (new Impersonator(ConfigurationManager.AppSettings["ImpersonatorUser"],
ConfigurationManager.AppSettings["ImpersonatorDomain"],
ConfigurationManager.AppSettings["ImpersonatorPassword"]))
{
var scr = new PSScriptParam("\\\\SERVER\\...\\Script.ps1", Param);
scr.Run();
}
The class PSScriptParam is just this:
public class PSScriptParam
{
public string Script { get; set; }
public string Param { get; set; }
public PSScriptParam(string Path, string param)
{
Param = param;
Script = Path;
}
public void Run()
{
try
{
Process _Proc = Process.Start("Powershell.exe", Script + " '" + Param + "'");
}
catch (Exception err)
{
System.IO.File.WriteAllText("\\\\SERVER\\...\\Error.txt", err.Message.ToString());
}
}
}
The impersonator is using a domain admin account, and the execution policy is set as unrestricted in the server (there is no problem running the script from the cmd).
Can anyone help?
Thanks in advance!

This problem was solved after applying pending updates in the server... Even if I'm not sure why it didn't work, updating Windows solved the problem.

Related

How to schedule a job using FluentScheduler library with Web Api?

I am unable to get FluentScheduler working in .Net Framework 4.5.2 Web api. Few days ago, I asked a similar question about scheduling through Console application and could get it to work with help but unfortunately facing issues with Web Api now. Below is the code.
[HttpPost]
[Route("Schedule")]
public IHttpActionResult Schedule([FromBody] SchedulerModel schedulerModel)
{
var registry = new Registry();
registry.Schedule<MyJob>().ToRunNow();
JobManager.Initialize(registry);
JobManager.StopAndBlock();
return Json(new { success = true, message = "Scheduled!" });
}
Below is the job I want to schedule which for now is just writing text to a file
public class SampleJob: IJob, IRegisteredObject
{
private readonly object _lock = new object();
private bool _shuttingDown;
public SampleJob()
{
HostingEnvironment.RegisterObject(this);
}
public void Execute()
{
lock (_lock)
{
if (_shuttingDown)
return;
//Schedule writing to a text file
WriteToFile();
}
}
public void WriteToFile()
{
string text = "Random text";
File.WriteAllText(#"C:\Users\Public\TestFolder\WriteText.txt", text);
}
public void Stop(bool immediate)
{
lock (_lock)
{
_shuttingDown = true;
}
HostingEnvironment.UnregisterObject(this);
}
Got this resolved finally. It turns out the issue was with my Registry class. I had to change it as follows.
public class ScheduledJobRegistry: Registry
{
public ScheduledJobRegistry(DateTime appointment)
{
//Removed the following line and replaced with next two lines
//Schedule<SampleJob>().ToRunOnceIn(5).Seconds();
IJob job = new SampleJob();
JobManager.AddJob(job, s => s.ToRunOnceIn(5).Seconds());
}
}
[HttpPost]
[Route("Schedule")]
public IHttpActionResult Schedule([FromBody] SchedulerModel schedulerModel)
{
JobManager.Initialize(new ScheduledJobRegistry());
JobManager.StopAndBlock();
return Json(new { success = true, message = "Scheduled!" });
}
Another point to note: I could get this to work but hosting Api in IIS makes it tricky because we have to deal with App Pool recycles, idle time etc. But this looks like a good start.

Twilio Rest API Helper Library, v 5.0.1, C# - MessageResource.Create function call not returning properly

I am using the Twilio REST API helper library, v 5.0.1 in my C# ASP.NET MVC Web Application. I created the following helper class and function to send out text messages:
using MyApplication.Web.Helpers;
using System;
using System.Configuration;
using Twilio;
using Twilio.Exceptions;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
namespace MyApplication.Web.Services
{
public class TwilioSmsSender : ISmsSender
{
public string AccountSid { get; set; }
public string AuthToken { get; set; }
public string FromPhoneNumber { get; set; }
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public string SmsPrefix { get; set; }
public string SmsSuffix { get; set; }
public TwilioSmsSender()
{
//get our Twilio account info from the config file
AccountSid = ConfigurationManager.AppSettings["TwilioAccountSid"];
AuthToken = ConfigurationManager.AppSettings["TwilioAuthToken"];
FromPhoneNumber = ConfigurationManager.AppSettings["SmsService.FromPhoneNumber"];
SmsPrefix = ConfigurationManager.AppSettings["SmsPrefix"];
SmsSuffix = ConfigurationManager.AppSettings["SmsSuffix"];
if (FromPhoneNumber.Length == 10)
{
FromPhoneNumber = $"+1{FromPhoneNumber}";
}
TwilioClient.Init(AccountSid, AuthToken);
}
public INotificationResponse SendTextMessage(string phoneNumber, string message, bool useFormatting = true)
{
var resp = new TwilioSmsSenderResponse();
resp.Succeeded = false;
resp.AttemptDateTimeUtc = DateTime.UtcNow;
if (useFormatting)
{
message = $"{SmsPrefix}{message}{SmsSuffix}";
}
try
{
var msgResponse = MessageResource.Create(
to: new PhoneNumber($"+1{phoneNumber}"),
from: new PhoneNumber($"{FromPhoneNumber}"),
body: message);
//Previous line works (i.e, I get the text message that I'm sending out successfully).
//However, none of the following lines are running...
//As you see, this is in a try/catch block... and it doesn't go to the catch block either!
if (msgResponse.ErrorCode == null)
{
//successfully queued
resp.Succeeded = true;
resp.ReferenceId = msgResponse.Sid;
resp.AttemptDateTimeUtc = DateTime.UtcNow;
}
else
{
//Twilio sent an error back
log.Info($"Twilio sent an error back: {msgResponse}");
resp.Succeeded = false;
resp.Notes = $"ErrorCode: {msgResponse.ErrorCode}, ErrorMessage: {msgResponse.ErrorMessage}";
resp.AttemptDateTimeUtc = DateTime.UtcNow;
}
}
catch (Exception e)
{
resp.Succeeded = false;
resp.Notes = ExceptionsHelper.GetExceptionDetailsAsString(e);
resp.AttemptDateTimeUtc = DateTime.UtcNow;
log.Error($"Twilio Error: {resp.Notes}, to: {phoneNumber}, message: {message}");
}
return resp;
}
}
}
Unfortunately, my code is not behaving as I expected it would after the MessageResource.Create() call. That is, the text-message is sent out correctly and I receive the SMS on my phone. However, I expect the call to return control to my msgResponse variable and I expect the
if (msgResponse.ErrorCode == null) ...
line and subsequent lines to run but that is not happening. I can put a breakpoint on the var msgResponse line and it will run that just fine but it does not run any code lines after that. You’ll see that I have the call in a try/catch. I suspected there was an exception that was occurring but it doesn’t seem so because it doesn’t go to my catch block either! The text message is being sent successfully! All I want to do is to get an acknowledgement back so that I can properly log it and send that information back to the routines that are calling this function.
Any help would be greatly appreciated!
version 5.0.2 fixed this for me just update twilio to 5.0.2. they just added .ConfigureAwait(false); with CreateAsync

Microsoft.SharePoint.Client.ClientContext in UWP APP fails after reset

I am trying to connect to a SharePointOnline 2013.
In my C# Console Application everything works fine, but if I try (nearly) the same code in an Universal App, it is not possible to create multiple instances of a ClientContext nor setting the credentials multiple times.
Im using the Microsoft.SharepointOnline.CSOM Version: 16.1.4727.1204 (released on 11.12.2015)
class Program
{
static void Main(string[] args)
{
UseContextMultipleTime();
UseContextMultipleTime();
}
public static void UseContextMultipleTime()
{
using (var context = new ClientContext("https://something.sharepoint.com"))
{
var securePassword = new SecureString();
foreach (char c in "password".ToCharArray()) securePassword.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials("username", securePassword);
try
{
context.ExecuteQuery();
string status = "OK";
}
catch (Exception ex)
{
string test = ex.ToString();
}
}
}
}
Below the Universal App version, which crashes in the second method call:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
UseContextMultipleTime();
UseContextMultipleTime();
}
public void UseContextMultipleTime()
{
using (var context = new ClientContext("https://something.sharepoint.com"))
{
context.Credentials = new SharePointOnlineCredentials("username", "password");
try
{
context.ExecuteQueryAsync().Wait();
string status = "OK";
}
catch (Exception ex)
{
string test = ex.ToString();
}
}
}
}
When I set the credentials only once, it will work.
Does anybody know a solution for this problem? I will appreciate every kind of hints.
The Problem was solved in the latest CSOM update. Everything works fine now.

Cannot run a restfull server in a ASP.Net without MVC

I'm trying to run a simple restfull server in a simple asp.net application without the mvc(following this tutorial : http://www.codeproject.com/Articles/769671/Web-API-without-MVC
(which will trun into a online portal).
here is my class :
public class Foods
{
public string FoodName { get; set; }
public string Price { get; set; }
public string Type { get; set; }
public string Content { get; set; }
public Foods()
{
}
}
and here is my controller:
public class FoodController : ApiController
{
public List<Foods> _productList;
public List<Foods> GetProductList()
{
_productList = new List<Foods>{
new Foods{FoodName= "pizza",Content= "bread cheese",Type="Main",Price="100"},
new Foods{FoodName= "rice",Content= "rice and ...",Type="Main",Price="100"}
};
return _productList;
}
}
and here is my asp.net page code(it is simple nothing to show):
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var config = new HttpSelfHostConfiguration("http://localhost:8080/");
config.Routes.MapHttpRoute(
"API Default", "api/{controller}/{id}",
new { id = System.Web.Http.RouteParameter.Optional });
using (HttpSelfHostServer server = new HttpSelfHostServer(config))
{
server.OpenAsync().Wait();
}
}
}
when i run it there is no error and the blank page is shown
and here is the client which is a simple c# form with a list box and a button:
private void button1_Click(object sender, EventArgs e)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:8080/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
try
{
HttpResponseMessage response = client.GetAsync("api/foods").Result;
if (response.IsSuccessStatusCode)
{
// Parse the response body. Blocking!
var foods = response.Content.ReadAsAsync<IEnumerable<Foods>>().Result;
foreach (Foods food in foods)
{
string foodinfo = food.FoodName + " " + food.Content + " " + food.Type + " " + food.Price;
listBox1.Items.Add(foodinfo);
}
}
}
catch (Exception ex)
{
textBox1.Text = ex.ToString();
}
}
but when i run the client and click the button i get this error:
System.AggregateException: One or more errors occurred.
System.Net.Sockets.SocketException: No connection could be made
because the target machine actively refused it 127.0.0.1:8080
There could be one or more reason for it.
1) Make sure that the port 8080 is not consumed by other application, Try running on different port.
try client.BaseAddress = new Uri("http://localhost:9090/");
2) By default, listening at a particular HTTP address requires administrator privileges. When you run the application, therefore, you might get an error: "HTTP could not register URL http://+:8080/".To avoid this error, run Visual Studio with elevated administrator permissions.
3) Make sure that both projects are running parallelly. If not do it.
Go to Solution properties -> Common properties -> Startup Project and select Multiple startup projects

Adding config file for Cmdlet

I've made a powershell Cmdlet for creating an AppFabric a region, the code:
[Cmdlet(VerbsCommon.New, "CacheRegion")]
public class NewCacheRegion : Cmdlet {
[Parameter(Mandatory = true, Position = 1)]
public string Cache { get; set; }
[Parameter(Mandatory = true, Position = 2)]
public string Region { get; set; }
protected override void ProcessRecord() {
base.ProcessRecord();
DataCacheFactory factory = new DataCacheFactory(); // exception
DataCache cache = factory.GetCache(Cache);
try {
cache.CreateRegion(Region);
}
catch (DataCacheException ex) {}
}
}
It's installed with import-module appfabriccmdlet.dll and the code executes when running new-cacheregion.
but the line
DataCacheFactory factory = new DataCacheFactory();
throws an exception that server collection is empty which means that no dataCacheClient section is found in app.config. So I want to a client that but Im not sure in which config file to add the appfabric sections. I've tried finding out from what executable the cmdlet dll is running with
Assembly a = Assembly.GetEntryAssembly();
but that returns null.
So where do I need to put config sections that a cmdlet dll has access to?
never mind.
fixed it by programmatically adding the server without config
DataCacheServerEndpoint[] servers = new DataCacheServerEndpoint[1];
servers[0] = new DataCacheServerEndpoint("localhost", 22233);
DataCacheFactoryConfiguration conf = new DataCacheFactoryConfiguration();
conf.Servers = servers;
DataCacheFactory factory = new DataCacheFactory(conf);

Categories