waitInterval configuration on msdeploy DeploymentProviderOptions - msdeploy

As part of our build and deploy code, we have timeout issues related to stopping and starting a service.
Here is the code that stops the service
public DeploymentChangeSummary StopService(WebPublisherParameters parameters)
{
var sourceOptions = new DeploymentBaseOptions();
var destinationEndpointOptions = new DeploymentBaseOptions()
{
ComputerName = parameters.DestinationComputer
};
var destProviderOptions = new DeploymentProviderOptions(DeploymentWellKnownProvider.RunCommand)
{
Path = "Net Stop " + parameters.DestinationName
};
using (var sourceObj =
DeploymentManager.CreateObject(new DeploymentProviderOptions(DeploymentWellKnownProvider.RunCommand), sourceOptions))
{
return sourceObj.SyncTo(destProviderOptions, destinationEndpointOptions, new DeploymentSyncOptions());
}
}
We are having timeout issues and ulitmately a failed build because the service does not stop in time.
We tried configuring the waitInterval like this
destProviderOptions.ProviderSettings["waitInterval"] = 20000;
but realised that it was a read only configuration, so I was wondering if anyone could point us in the right direction to do this programmatically rather than using the command line option.
Thanks
Tapashya

You need to set RetryInterval of DeploymentBaseOptions object. Edited code from the question.
public DeploymentChangeSummary StopService(WebPublisherParameters parameters)
{
var sourceOptions = new DeploymentBaseOptions();
var destinationEndpointOptions = new DeploymentBaseOptions()
{
ComputerName = parameters.DestinationComputer
};
var destProviderOptions = new DeploymentProviderOptions(DeploymentWellKnownProvider.RunCommand)
{
Path = "Net Stop " + parameters.DestinationName
};
using (var sourceObj =
DeploymentManager.CreateObject(new DeploymentProviderOptions(DeploymentWellKnownProvider.RunCommand), sourceOptions))
{
destinationEndpointOptions.RetryInterval = 2 * 1000; // Set wait interval to 2 minutes
return sourceObj.SyncTo(destProviderOptions, destinationEndpointOptions, new DeploymentSyncOptions());
}
}

Related

Getting error when a method is made for post request

When made I post request is made its giving internal server. Is the implementation of Flurl is fine or I am doing something wrong.
try
{
Models.PaymentPost paymentPost = new Models.PaymentPost();
paymentPost.Parts = new Models.Parts();
paymentPost.Parts.Specification = new Models.Specification();
paymentPost.Parts.Specification.CharacteristicsValue = new List<Models.CharacteristicsValue>();
paymentPost.Parts.Specification.CharacteristicsValue.Add(new Models.CharacteristicsValue { CharacteristicName = "Amount", Value = amount });
paymentPost.Parts.Specification.CharacteristicsValue.Add(new Models.CharacteristicsValue { CharacteristicName = "AccountReference", Value = accountId });
foreach (var item in extraParameters)
{
paymentPost.Parts.Specification.CharacteristicsValue.Add(new Models.CharacteristicsValue {
CharacteristicName = item.Key, Value = item.Value });
}
var paymentInJson = JsonConvert.SerializeObject(paymentPost);
var selfCareUrl = "http://svdt5kubmas01.safari/auth/processPaymentAPI/v1/processPayment";
var fUrl = new Flurl.Url(selfCareUrl);
fUrl.WithBasicAuth("***", "********");
fUrl.WithHeader("X-Source-System", "POS");
fUrl.WithHeader("X-Route-ID", "STKPush");
fUrl.WithHeader("Content-Type", "application/json");
fUrl.WithHeader("X-Correlation-ConversationID", "87646eaa-2605-405e-967c-56e8002b5");
fUrl.WithHeader("X-Route-Timestamp", "150935");
fUrl.WithHeader("X-Source-Operator", " ");
var response = await clientFactory.Get(fUrl).Request().PostJsonAsync(paymentInJson).ReceiveJson<IEnumerable<IF.Models.PaymentPost>>();
return response;
}
catch (FlurlHttpException ex)
{
dynamic d = ex.GetResponseJsonAsync();
//string s = ex.GetResponseStringAsync();
return d;
}
You don't need to do this:
var paymentInJson = JsonConvert.SerializeObject(paymentPost);
PostJsonAsync just takes a regular object and serializes it to JSON for you. Here you're effectively double-serializing it and the server is probably confused by that format.
You're also doing a lot of other things that Flurl can do for you, such as creating those Url and client objects explicitly. Although that's not causing errors, this is how Flurl is typically used:
var response = await selfCareUrl
.WithBasicAuth(...)
.WithHeader(...)
...
.PostJsonAsync(paymentPost)
.ReceiveJson<List<IF.Models.PaymentPost>>();

Why does R.NET work locally but stop working in IIS?

I have an ASP.NET MVC application that sends parameters to an R script, the R script then generates a file and puts it in a folder locally. The process works perfectly on my local machine through Visual Studio but goes in and out after I publish and use IIS. Below is how I am initializing R.NET and getting these values from my view via AJAX.
I also have placed both of these PATHs in my system environment variables.
If anyone knows why IIS only works right after I restart my OS and then stops working shortly after I would greatly appreciate it. Seems odd that I have no problems in Visual Studio that I face in IIS.
[HttpGet]
public JsonResult Index1(string modelTypes = null, string fileNames = null, string[] locations = null, string lowerLimits = null, string upperLimits = null, string areas = null, string productivities = null, string[] fobs = null)
{
#ViewBag.UserName = System.Environment.UserName;
string userName = #ViewBag.UserName;
//Declare field parameters
var strModelTypeValue = modelTypes;
string strFileName = fileNames;
var strLocationValue = locations;
var strLowerLimitValue = lowerLimits;
var strUpperLimitValue = upperLimits;
string strAreaValue = areas;
string strProductivityValue = productivities;
string strFobValue = fobs.ToString();
var libraryLocation = "C:/Users/" + userName + "/Documents/R/win-library/3.2";
string rPath = #"C:\Program Files\R\R-3.3.2\bin\x64";
string rHome = #"C:\Program Files\R\R-3.3.2";
//Initialize REngine
REngine.SetEnvironmentVariables(rPath, rHome);
REngine engine = REngine.GetInstance();
engine.Initialize();
if (fobs.Length > 1)
{
strFobValue = string.Join(" ", fobs);
}
else
{
strFobValue = "ALL";
}
//Declare R Script path
var rScriptPath = "C:/Users/" + userName + "/Documents/R/RWDir/Loop_Optimization.R";
//Check to see if there was more than one location selected
if (strLocationValue.Length > 1)
{
foreach (var item in strLocationValue)
{
//Set string location to each location value in loop
var strlocation = item;
//Add values to parameter list
var myParams = new List<string>
{
strModelTypeValue,
strFileName,
strlocation,
strLowerLimitValue,
strUpperLimitValue,
strAreaValue,
strProductivityValue,
strFobValue,
libraryLocation
};
//Set myParams as arguments to be sent to r script
engine.SetCommandLineArguments(myParams.ToArray());
engine.Evaluate("source('" + rScriptPath + "')");
}
}
//Only one location specified, no need to loop
else
{
foreach (var item in strLocationValue)
{
//Set string location to each location value in loop
var strlocation = item;
var myParams = new List<string>
{
strModelTypeValue,
strFileName,
strlocation,
strLowerLimitValue,
strUpperLimitValue,
strAreaValue,
strProductivityValue,
strFobValue,
libraryLocation
};
engine.SetCommandLineArguments(myParams.ToArray());
engine.Evaluate("source('" + rScriptPath + "')");
}
}
//engine.Evaluate("source('" + rScriptPath + "')");
//engine.Dispose();
return Json("success", JsonRequestBehavior.AllowGet);
}
have you done any debugging by attaching process .

Set a job to failed using Hangfire with ASP.NET?

I have an ASP.NET app which sends emails whenever the user signs up in the web site. I'm using hangfire in order to manage the jobs and postal in order to send emails.
It all works great, but here's the thing:
I want the superuser to change how many times the APP can send the email before deleting the job.
Here's my code
public static void WelcomeUser(DBContexts.Notifications not)
{
try{
var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(#"~/Views/Emails"));
var engines = new ViewEngineCollection();
engines.Add(new FileSystemRazorViewEngine(viewsPath));
Postal.EmailService service = new Postal.EmailService(engines);
WelcomeUserMail welcomeUserMail = new WelcomeUserMail();
welcomeUserMail.To = not.ReceiverEmail;
welcomeUserMail.UserEmail = not.ReceiverEmail;
welcomeUserMail.From = BaseNotification.GetEmailFrom();
service.Send(welcomeUserMail);
}
catch(Exception e)
{
DBContexts.DBModel dbModel = new DBModel();
DBContexts.Notifications notificacionBD = dbModel.Notifications.Find(not.NotificationID);
notificacionBD.Status = false;
notificacionBD.Timestamp = DateTime.Now;
notificacionBD.Error = e.Message;
int numberOfRetriesAllowed = ParameterHelper.getNumberOfRetriesAllowed();
if (notificacionBD.Retries > numberOfRetriesAllowed)
{
//In this case Hangfire won't put this job in the failed section but rather in the processed section.
dbModel.SaveChanges();
}
else
{
notificacionBD.Retries++;
dbModel.SaveChanges();
throw new Exception(e.Message);
}
}
}
Why not just add attributes to handle it automatically?
[AutomaticRetry(Attempts = 10, LogEvents = true, OnAttemptsExceeded = AttemptsExceededAction.Delete)]
public void MyTask(){
//doing stuff
}
Or you could just make your own attribute that mimics the AutommaticRetryAttribute class but you handle it how you want?
https://github.com/HangfireIO/Hangfire/blob/a5761072f18ff4caa80910cda4652970cf52e693/src/Hangfire.Core/AutomaticRetryAttribute.cs

Change this from sync to async webrequests

I ahve been diggin the net for some time now, not finding code examples that help me through my problem.. I have looked at example code but I'm still not "getting" it...
I have read up on,
http://msdn.microsoft.com/en-us/library/aa480507.aspx and
http://msdn.microsoft.com/en-us/library/dd781401.aspx
But I cant seem to get it to work..
Im using HTMLAGILITYPACK
Today I make up to 20 webrequests,
After a request has finished, result is added to dictionary, after that a method searches it for the information, if found the code exits if not it makes another webrequest , until it caps at 20. I need to be able to exit all threads async calls when everything is found.
It goes like this
public void FetchAndParseAllPages()
{
PageFetcher fetcher = new PageFetcher();
for (int i = 0; i < _maxSearchDepth; i += _searchIncrement)
{
string keywordNsearch = _keyword + i;
ParseHtmldocuments(fetcher.GetWebpage(keywordNsearch));
//this checks if the information was found or not, if
//found stop exit and add to database
if (GetPostion() != 201)
{ //ADD DATA TO DATABASE
InsertRankingData(DocParser.GetSearchResults(), _theSearchedKeyword);
return;
}
}
}
This is inside the class that fetches the page
public HtmlDocument GetWebpage(string urlToParse)
{
System.Net.ServicePointManager.Expect100Continue = false;
HtmlWeb htmlweb = new HtmlWeb();
htmlweb.PreRequest = new HtmlAgilityPack.HtmlWeb.PreRequestHandler(OnPreRequest);
HtmlDocument htmldoc = htmlweb.Load(#"urlToParse", "38.69.197.71", 45623, "PORXYUSER", "PROXYPASSWORD");
return htmldoc;
}
public bool OnPreRequest(HttpWebRequest request)
{
// request.UserAgent = RandomUseragent();
request.KeepAlive = false;
request.Timeout = 100000;
request.ReadWriteTimeout = 1000000;
request.ProtocolVersion = HttpVersion.Version10;
return true; // ok, go on
}
How can I make this async and make it really quick with threads? Or should i even use threads when doing it async?
Okay I solved it! At least I think so! Execution time went down to around seven seconds. It took me about 30 secs to do that without async.
Here my code for future reference. EDIT I used a console project to test the code. Also I'm using html agilitypack. This is my way of doing it, any tips on how to further optimize this would be cool to see.
public delegate HtmlDocument FetchPageDelegate(string url);
static void Main(string[] args)
{
System.Net.ServicePointManager.DefaultConnectionLimit = 10;
FetchPageDelegate del = new FetchPageDelegate(FetchPage);
List<HtmlDocument> htmllist = new List<HtmlDocument>();
List<IAsyncResult> results = new List<IAsyncResult>();
List<WaitHandle> waitHandles = new List<WaitHandle>();
DateTime start = DateTime.Now;
for(int i = 0; i < 200; i += 10)
{
string url = #"URLSTOPARSE YOU CHANGE IT HERE READ FROM LIST OR ANYTHING";
IAsyncResult result = del.BeginInvoke(url, null, null);
results.Add(result);
waitHandles.Add(result.AsyncWaitHandle);
}
WaitHandle.WaitAll(waitHandles.ToArray());
foreach (IAsyncResult async in results)
{
FetchPageDelegate delle = (async as AsyncResult).AsyncDelegate as FetchPageDelegate;
htmllist.Add(delle.EndInvoke(async));
}
Console.ReadLine();
}
static HtmlDocument FetchPage(string url)
{
HtmlWeb htmlweb = new HtmlWeb();
HtmlDocument htmldoc = htmlweb.Load(url);
return htmldoc;
}

Problem uploading Excel-document. What's wrong?

For some reason, not all of Excel-documents can be upload from my computer. In half the cases get the error ".. no!! error:" from a block of try-catch .. What is wrong?
private function importXLS(e:MouseEvent):void {
fr = new FileReference();
var fileFilter:FileFilter = new FileFilter("Excel (.xls)", "*.xls");
fr.addEventListener(Event.SELECT,selectXLS);
fr.browse([fileFilter]);
statusLabel.text = "selecting...";
}
private function selectXLS(e:Event):void {
fr = FileReference(e.target);
fr.addEventListener(Event.COMPLETE, fileIn);
fr.load();
statusLabel.text = "loading...";
}
private function fileIn(e:Event):void {
ba = new ByteArray();
ba = fr.data;
xls = new ExcelFile();
var flag:Boolean = false;
try{
xls.loadFromByteArray(ba);
flag = true;
}catch(error:Error){
Alert.show("no!! error: " + error.getStackTrace());
}
if (flag == true) {
statusLabel.text = "XlS loaded.";
} else {
statusLabel.text = "XlS didn't load.";
}
}
You are reading the entire file into memory. If a user tries to upload too big a file, their browser will crash. Is there a reason you doing this? Are you using the bytes in the client or just passing them to the server. If you are passing them to the server, you want to just not use the fr.load method that you call in selectXLS(). Instead use fr.upload and avoid your whole problem.

Resources