Will increasing my RAM reduce the size of my w3wp.exe in memory - iis-7

I have a asp.net web site. I have an image being updated via a timer as many times as possible every second with an image the size of 720x576. I control when the image can be updated by initiating the next ashx page call to get my image after the img control has finished loading the previous image (I do this on the 'onload' event).
My w3wp.exe currently stands at 140,000k and it drops to 130,000. Frequently going up and down between these 2 values.
As i am testing with 1 User and as I am on a cheap VPS shared hosting environment my question is when I go Live will the w3wp.exe become uncontrollable or will the fact that by upgrading my server package (mainly increasing RAM) help to keep this all under control n a multi-user environment?
This is my Javascript:
var timer3;
var intervalLive = 50;
function play2() {
if (timer3) window.clearTimeout(timer3);
swapImages3();
}
function setImageSrc3(src) {
_imgLive.src = src;
timer3 = window.setTimeout(swapImages3, intervalLive);
}
function swapImages3() {
var imgCached = new Image();
imgCached.onload = function () {
setImageSrc3(imgCached.src);
};
imgCached.onerror = function () {
setImageSrc3("http://a URL/images/ERROR.jpg");
};
imgCached.onload = function () {
setImageSrc3(imgCached.src);
};
imgCached.src = null;
imgCached.src = 'http://A URL/Cloud/LiveXP.ashx?id=' + new Date().getTime() + '&Alias=' + alias;
}
And this is in my ashx page:
public class Live : IHttpHandler {
DAL dal = new DAL();
static byte[] StandardError = Shared.ERROR;
public void ProcessRequest(HttpContext context)
{
byte[] data = null;
context.Response.ContentType = "image/jpg";
try
{
if (context.Request.QueryString["Alias"] != null)
{
data = Shared.GetFrame(context.Request.QueryString["Alias"].ToString());
context.Response.BinaryWrite(data);
}
}
catch (Exception ex)
{
data = StandardError;
dal.AddError(ex.ToString());
}
finally
{
context.Response.BinaryWrite(data);
}
}
public bool IsReusable {
get {
return true;
}
}
}
thanks

Related

ASP .NET MVC - how to change view when thread will finished

I want to make ActionResult with run a thread. When thread are running I will return View with loading but when thread finished the ActionResult return the another View
My code look like:
private static void ExecuteScrapper()
{
ScriptEngine pythonEngine = IronPython.Hosting.Python.CreateEngine();
ScriptSource pythonScript = pythonEngine.CreateScriptSourceFromFile(HostingEnvironment.MapPath("/PythonScript/main.py"));
var searchPath = pythonEngine.GetSearchPaths();
searchPath.Add(HostingEnvironment.MapPath("/PythonScript/"));
searchPath.Add(HostingEnvironment.MapPath("/PythonScript/drivers/"));
pythonEngine.SetSearchPaths(searchPath);
var result = pythonScript.Execute();
}
private ScrapperEnum.ScrapperOperations scraperParam;
private Thread t = new Thread(new ThreadStart(ExecuteScrapper));
public ActionResult RunScrapper(ScrapperEnum.ScrapperOperations operation)
{
scraperParam = operation;
t.Start();
bool run = false;
while(t.IsAlive)
{
if(!run)
{
run = true;
return View("ScrapperLoadingView");
}
}
return RedirectToAction("Scrapper");
}
I don't know exactly how to do that, because when in this code I return ScrapperLoginView it will break while so the function don't switch the View
You just need to add an else if I'm correct
while(t.IsAlive)
{
if(!run)
{
run = true;
return View("ScrapperLoadingView");
}
else
{
return RedirectToAction("Scrapper");
}
}
}

Xamarin.Android - How to continue a process while app is minimized or screen is locked

I've created a Xamarin app that checks the users current location every couple minutes. My problem is it doesn't work when I minimize the app or the screen locks. Is there a way for me to continue the process while minimized or when the phone is locked?
This function checks to see if the user is at the destination location.
public bool atLocation(decimal currentLat, decimal currentLong, decimal destLat, decimal destLong)
{
decimal GPSLatitudePadding = 0.001M;
decimal GPSLongitudePadding = 0.001M;
var totalLowerLatitude = Convert.ToDecimal((destLat - GPSLatitudePadding).ToString("#.####"));
var totalLowerLongitude = Convert.ToDecimal((destLong + GPSLongitudePadding).ToString("#.####"));
var totalUpperLatitude = Convert.ToDecimal((destLat + GPSLatitudePadding).ToString("#.####"));
var totalUpperLongitude = Convert.ToDecimal((destLong - GPSLongitudePadding).ToString("#.####"));
if ((Convert.ToDecimal(destLat) >= totalLowerLatitude) &&
(Convert.ToDecimal(destLat) <= totalUpperLatitude) &&
(Convert.ToDecimal(destLong) <= totalLowerLongitude) &&
(Convert.ToDecimal(destLong) >= totalUpperLongitude))
{
return true;
}
return false;
}
If the user is at the destination for 2 instances of 2 minutes the process is ended. This is where you could start a new process or update a database.
int intNumberOfTimesFoundAtLocation = 0;
void OnLocationResult(object sender, Android.Locations.Location location)
{
decimal currentLatitude = Convert.ToDecimal(location.Latitude);
decimal currentLongitude = Convert.ToDecimal(location.Longitude);
decimal destLatitude = Convert.ToDecimal(this.dblDestLatitude);
decimal destLongitude = Convert.ToDecimal(this.dblDestLongitude);
var atLocation = locationQ.atLocation(currentLatitude, currentLongitude, destLatitude, destLongitude);
if (ayLocation == true)
{
intNumberOfTimesFoundAtLocation = intNumberOfTimesFoundAtLocation + 1;
if(intNumberOfTimesFoundAtLocation == 2)
{
client.RemoveLocationUpdates(locationCallback);
}
}
}
I call this function to start the process
MyLocationCallback locationCallback;
FusedLocationProviderClient client;
public async void StartLocationUpdatesAsync()
{
// Create a callback that will get the location updates
if (locationCallback == null)
{
locationCallback = new MyLocationCallback();
locationCallback.LocationUpdated += OnLocationResult;
}
// Get the current client
if (client == null)
client = LocationServices.GetFusedLocationProviderClient(this);
try
{
locationRequest = new LocationRequest()
.SetInterval(120000)
.SetFastestInterval(120000)
.SetPriority(LocationRequest.PriorityHighAccuracy);
await client.RequestLocationUpdatesAsync(locationRequest, locationCallback);
}
catch (Exception ex)
{
//Handle exception here if failed to register
}
}
}
class MyLocationCallback : LocationCallback
{
public EventHandler<Android.Locations.Location> LocationUpdated;
public override void OnLocationResult(LocationResult result)
{
base.OnLocationResult(result);
LocationUpdated?.Invoke(this, result.LastLocation);
}
}
Create a foreground service.
Inside service call the following code to start the request updates.
locationLogger = new LocationLogger();
locationLogger.LogInterval = _currentInterval;
locationLogger.StopUpdates();
locationLogger.StartRequestionUpdates();
Check here for the code
Let me know if you need more help.

WebAPI call hangs when return a large amount of data

I have a web api call that I recently added to my app. I returns a complete list of all countries, states and cities in the app (currently 486 rows) I perform this call when all of the reference data for my application loads (I have a base loading page and call the function in my startup class to load all the data there). The challenge is that the call to get all my countries.... hangs and eventually I get "The operation was canceled" error. If I modify my stored procedure that selects the data from the database on the server to only return say 20 rows, it runs fine. Any suggestions?
Below is the code from the startup class:
using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace GBarScene
{
class StartUpClass
{
public event GeneralDataLoad BaseDataLoadComplete;
public async Task<GBSStartUpEventArgs> ProcessStartup()
{
GBSStartUpEventArgs lobj_EventArgs;
lobj_EventArgs = new GBSStartUpEventArgs();
App.InStartUpDataLoad = true;
try
{
if (!App.IsGeolocationEnabled)
{
lobj_EventArgs.ErrorOccurred = true;
lobj_EventArgs.ShowRetry = true;
lobj_EventArgs.ShowWebSite = false;
lobj_EventArgs.ErrorMessage = resourcestrings.GetValue("NoLocationServicesMessage");
}
else if (!App.InternetIsAvailable)
{
lobj_EventArgs.ErrorOccurred = true;
lobj_EventArgs.ErrorMessage = resourcestrings.GetValue("NoInternetConnectionFound");
lobj_EventArgs.ShowRetry = true;
lobj_EventArgs.ShowWebSite = false;
}
else
{
Debug.WriteLine("Process StartUp");
await Task.Delay(500);
//Reset values
ViewModelObjects.DayOfWeek.DataLoadProcessed = false;
ViewModelObjects.Languages.DataLoadProcessed = false;
if (await ViewModelObjects.DayOfWeek.LoadData() == false)
// //try it once more
await ViewModelObjects.DayOfWeek.LoadData();
Debug.WriteLine("GBar After DayofWeek Load");
await ViewModelObjects.Languages.LoadData();
Debug.WriteLine("GBar After Languages Load");
if ((ge_AppMode)ViewModelObjects.AppSettings.AppMode == ge_AppMode.CitySelected)
{
//We need to reload the NearbyCities and set the selected one
await ViewModelObjects.NearbyCities.LoadData();
}
Debug.WriteLine("Before load of coutries");
await ViewModelObjects.CountryStateCity.LoadData();
Debug.WriteLine("After load of coutries");
Debug.WriteLine("Count: " + ViewModelObjects.CountryStateCity.CountryItems_ForList.Count.ToString());
ViewModelObjects.NumberOfResults.LoadData();
ViewModelObjects.Perspectives.LoadData();
ViewModelObjects.SearchRadiuses.LoadData();
ViewModelObjects.UseMetric.LoadData();
while (!ViewModelObjects.DayOfWeek.DataLoadProcessed && !ViewModelObjects.Languages.DataLoadProcessed && !App.IsGeolocationEnabled)
{
await Task.Delay(100);
}
if (App.BaseDataLoadError)
{
lobj_EventArgs.ErrorOccurred = true;
lobj_EventArgs.ShowRetry = true;
lobj_EventArgs.ShowWebSite = true;
lobj_EventArgs.ErrorMessage = resourcestrings.GetValue("ErrorLoadingReferenceData");
}
}
Debug.WriteLine("StartUp Process Ended");
BaseDataLoadComplete(this, lobj_EventArgs);
}
catch (Exception ex)
{
App.ProcessException(ex);
}
App.InStartUpDataLoad = false;
return lobj_EventArgs;
}
}
}
This is the helper class that makes all the WebAPI calls:
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace GBarScene
{
public class WebAPICaller: IDisposable
{
HttpClient iobj_HTTPClient = null;
public void Dispose()
{
if (iobj_HTTPClient != null)
iobj_HTTPClient.Dispose();
}
public async Task<string> HTTPGetWebServiceAsync(string ps_URI)
{
string ls_Response = "";
string ls_JSONData = "";
string ls_Prefix = "";
try
{
iobj_HTTPClient = await GetClient();
switch (Device.RuntimePlatform)
{
case Device.Android:
ls_Prefix = App.APIStandardPrefix;
break;
//case Device.Android:
// ls_Prefix = App.APISecurePrefix;
// break;
//case Device.Windows:
//case Device.WinPhone:
// ls_Prefix = App.APISecurePrefix;
// break;
default:
ls_Prefix = App.APISecurePrefix;
break;
}
Debug.WriteLine("before api call");
iobj_HTTPClient.BaseAddress = new Uri(ls_Prefix);
ls_JSONData = await iobj_HTTPClient.GetStringAsync(ps_URI);
Debug.WriteLine("after api call");
ls_Response = System.Net.WebUtility.HtmlDecode(ls_JSONData);
}
catch (Exception ex)
{
Debug.WriteLine("api call error");
App.ProcessException(ex);
}
return ls_Response;
}
public async Task<bool> HTTPPostWebService(string ps_URI, object pobj_BodyObject)
{
HttpResponseMessage lobj_HTTPResponse = null;
bool lb_Response = false;
HttpContent lobj_Content = null;
try
{
if (iobj_HTTPClient != null)
iobj_HTTPClient = await GetClient();
iobj_HTTPClient.BaseAddress = new Uri(App.APISecurePrefix);
lobj_Content = new StringContent(JsonConvert.SerializeObject(pobj_BodyObject == null ? "" : pobj_BodyObject));
lobj_Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
lobj_HTTPResponse = await iobj_HTTPClient.PostAsync(ps_URI, lobj_Content);
if (!lobj_HTTPResponse.IsSuccessStatusCode)
{
Exception lobj_Exception = new Exception(lobj_HTTPResponse.ToString());
lobj_Exception.Source = "HTTPGetWebService for: " + ps_URI;
App.ProcessException(lobj_Exception);
}
else
{
lb_Response = true;
}
}
catch (Exception ex)
{
App.ProcessException(ex);
}
finally
{
if (lobj_HTTPResponse != null)
{
lobj_HTTPResponse.Dispose();
}
//Debug.WriteLine("WebAPICaller-CallWebService-1: Done");
}
return lb_Response;
}
private async Task<HttpClient> GetClient()
{
HttpClient lobj_HTTPClient = null;
if (lobj_HTTPClient == null)
{
lobj_HTTPClient = new HttpClient();
lobj_HTTPClient.DefaultRequestHeaders.Add("Accept", "application/json");
lobj_HTTPClient.MaxResponseContentBufferSize = 2147483647;
lobj_HTTPClient.Timeout = new TimeSpan(0,0,0,0,60000);
}
return lobj_HTTPClient;
}
}
}
Sorry I forget to include the method in the CountryStateCity view model that calls the webapi helper class.
public async Task<bool> LoadData()
{
string ls_Response = "";
string ls_WorkURI = "";
WebAPICaller lobj_WebAPICaller = null;
bool lb_DataLoaded = false;
try
{
IsDataLoaded = false;
//Debug.WriteLine("City Data Load");
lobj_WebAPICaller = new WebAPICaller();
ls_WorkURI = ic_CoutryStateCityAPIUrl.Replace("{Language}", "EN");
ls_Response = await lobj_WebAPICaller.HTTPGetWebServiceAsync(ls_WorkURI);
if (ls_Response.Trim().Length == 0)
{
AddErrorEntry();
}
else
{
CountryItems_ForList = new ObservableCollection<GBSCountry_ForList>();
StateItems_ForList = new ObservableCollection<GBSState_ForList>();
CityItems_ForList = new ObservableCollection<GBSCity_ForList>();
iobj_CountryStateCity = JsonConvert.DeserializeObject<ObservableCollection<GBSCountryStateCity>>(ls_Response);
//Now load the display lists
CountryItems_ForList = new ObservableCollection<GBSCountry_ForList>(
(from lobj_Country in iobj_CountryStateCity
select new GBSCountry_ForList()
{
ID = lobj_Country.Country_Code,
Value = lobj_Country.Country_Name_Text
}).Distinct().ToList());
CountryItems_ForList.Insert(0, new GBSCountry_ForList
{
ID = "XX",
Value = "Base Value"
});
lb_DataLoaded = true;
}
}
catch (Exception ex)
{
AddErrorEntry();
App.ProcessException(ex);
}
finally
{
IsDataLoaded = true;
if (lobj_WebAPICaller != null)
lobj_WebAPICaller.Dispose();
}
return lb_DataLoaded;
}
So after much time, I believe I figured out what the problem is. The problem started to manifest itself again with smaller amounts of data and I could not figure out why. The problem appeared. The issue appears to be the IP address I was using. (I was using the IP address of the actual laptop I was hosting both the App and WebAPIs on.) It appears you have to use one of the other network adaptors for the emulator to have this work reliably.
Here are the steps I used to resolved this:
I launched my Windows 10 mobile emulator.
Click on the >> (Tools) icon in the tool bar of the emulator.
Click on the Network tab of the Additional Tools window.
Look in the list for the network adaptor labeled Desktop Adaptor #1 and copy the IP address.
Edit the Applicationhost.config file in the folder of the WebAPI project.
Find the entry in the file for site name="XXXXX" where XXXXX is the name of the Visual Studio project you are hosting your WebAPIs in.
Within the section of the entry for your WebAPI project, add a binding for the IP address you copied from in step 4. It should look something like this:
<binding protocol="http" bindingInformation="*:56952:169.254.69.220" />
Where 56952 is the port my IIS Express is hosting the WebAPIs on and 169.254.69.220 is the IP address I copied from step 4. After adding this, I was able to connect to locally hosted WebAPIs in IIS Express.
Hope this helps.

Directory levels Quotas on remote shared folder

I have 2 servers in AD (2008R2)
On one of them I have shared folder (c:\Shared\dirForUserAAA ==> \DC1\dir1)
On other one I have c# program that must manage folder quota on \DC1\dir1
Is it possible and how it can be done?
I try to use this piece of code, but it works only on local paths :(
public static void SetQuotaToFolder(string UNCPathForQuota, int quotaLimitBytes)
{
if (!Directory.Exists(UNCPathForQuota))
{
Directory.CreateDirectory(UNCPathForQuota);
}
// Create our interface
IFsrmQuotaManager FSRMQuotaManager = new FsrmQuotaManagerClass();
IFsrmQuota Quota = null;
try
{
// First we need to see if there is already a quota on the directory.
Quota = FSRMQuotaManager.GetQuota(UNCPathForQuota);
// If there is quota then we just set it to our new size
Quota.QuotaLimit = quotaLimitBytes;
}
catch (COMException e)
{
unchecked
{
if (e.ErrorCode == (int)0x80045301)
{
// There is no quota on this directory so we need to create it.
Quota = FSRMQuotaManager.CreateQuota(UNCPathForQuota);
// And then set our desired quota
Quota.QuotaLimit = quotaLimitBytes;
}
else
{
// some other COM exception occured so we return the error
Console.WriteLine(e);
return;
}
}
}
catch (Exception e)
{
// Generic error handling would go here
Console.WriteLine(e);
return;
}
// and finally we commit our changes.
Quota.Commit();
}
}
Old Question, but if someone needs a hint:
Open a RemotePowershell on the server where your folders are saved. Then use the Cmdlets from here
Some code snippets:
Open Runspace:
public static Runspace CreateAndOpen(string domain, string username, string password, string computername)
{
string userName = username + "#" + domain;
var securePassword = password.ToSecureString();
PSCredential credential = new PSCredential(username, securePassword);
var connectionInfo = new WSManConnectionInfo(false, computername, 5985, "/wsman", shellUri, credential);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Default;
connectionInfo.OpenTimeout = 2 * 60 * 1000; // 2 minutes
Runspace powershellRunspace = RunspaceFactory.CreateRunspace(connectionInfo);
powershellRunspace.Open();
return powershellRunspace;
}
Set a quota on a path
public void SetQuotaTemplateOnPath(Runspace runspace, string path, string template)
{
using (var pipe = runspace.CreatePipeline())
{
var newFsrmQuotaCommand = new Command("New-FsrmQuota");
newFsrmQuotaCommand.Parameters.Add("Path", path);
newFsrmQuotaCommand.Parameters.Add("Template", template);
newFsrmQuotaCommand.Parameters.Add("Confirm", false);
pipe.Commands.Add(newFsrmQuotaCommand);
var results = pipe.Invoke();
if (pipe.Error.Count > 0)
{
//Handle error
}
}
}

Sometimes Image is not displaying for only one user

I am having ASP.NET MVC application in which i am using HTTP handler ashx file to get the image on the page . This image is uploaded by user by scanning the document.
Now my problem is for every user its displaying except one , User is reporting he is not able to see the image even though it was loaded sucessfully , when i checked the logs it shown that server got image.
No exception was logged at the server while converting image too :(
One more thing this is happening frequently , 70% times user is not able to see the image in the page. 30% time he managed to see the image ...
Strange issue
Please advice what could be the issue ?
Below is my code
public class GetImage : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
public GetImage()
{
}
public void ProcessRequest(HttpContext context)
{
if (context != null)
{
if (!string.IsNullOrEmpty(context.Request.Params["side"]))
{
bool isFront = false;
if (context.Request.Params["side"].Equals("Front"))
{
isFront = true;
}
else
{
isFront = false;
}
ICache Cache = CacheManager.SessionCache;
DepositState depState = (DepositState)Cache[Constants.DepositSession];
if (depState != null)
{
byte[] imageByteArray = null;
System.IO.MemoryStream imageMemoryStream = null;
try
{
if (isFront)
{
imageByteArray = System.Convert.FromBase64String(depState.FrontJpegBase64);
}
else
{
imageByteArray = System.Convert.FromBase64String(depState.BackJpegBase64);
}
imageMemoryStream = new System.IO.MemoryStream(imageByteArray);
using (System.Drawing.Image img = System.Drawing.Image.FromStream(imageMemoryStream))
{
img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
catch(Exception ex)
{
Log.Error(Constants.DefaultErrorCode, "Exception occured while converting image to Base 64 in GetImage.ashx.cs" + ex);
}
imageMemoryStream.Close();
context.Response.Flush();
}
else
{
Log.Error(Constants.DefaultErrorCode, " Deposit State object is nullin GetImage.ashx ");
}
}
}
else
{
Log.Error(Constants.DefaultErrorCode, "Context is null in the Process Request ");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
I don't see where you are setting the context.Response.ContentType. I haven't tested this, but I wonder if the missing header would cause unpredictable browser behavior.

Resources