err_connection_timed_out after some successful calls in angularjs - angularjs

I am using http service of AngularJs and it works successfully. But from last three months, I receive err_connection_timed_out after 1 or two successful calls. If I reload the page, then the error disappears.
I am using ASP.Net MVC as backend application and it uses Cookies for session management.
Anybody can help how to resolve this issue?
Global.asax.cs
protected void Application_BeginRequest(Object sender, EventArgs e)
{
HttpContext.Current.Items["dbkey"] = new DBEntities();
}
protected void Application_BeginRequest(Object sender, EventArgs e)
{
var entityContext = HttpContext.Current.Items["dbkey"] as DBEntities;
if (entityContext != null)
entityContext.Dispose();
}
LoginController
public JsonResult JsonLogin(string email, string password)
{
// Hashed ticket
string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);
cookie.Expires = expiryDate;
Response.Cookies.Add(cookie);
HttpCookie mycookie = new HttpCookie("cookieName");
HttpContext.Current.Response.Cookies.Set(mycookie);
}
StaffController
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies["cookieName"];
if (cookie == null || string.IsNullOrEmpty(User.Identity.Name))
{
filterContext.Result = new RedirectResult("/Login/Index");
}
base.OnActionExecuting(filterContext);
}
public JsonResult GetData()
{
var res = entityContext.StaffData.Where(...).ToList();
return Json(res, JsonRequestBehavior.AllowGet);
}
Data.js
var app = angular.module('StaffApp', []);
app.controller('StaffCtrl', function ($scope, $http) {
$scope.GetData = function () {
$http.get("/Staff/GetData")
.then(function (response) {
let data = response.data;
if (data.length > 0) {
angular.forEach(data, function (fm, key) {
$scope.Staffs.push(fm);
});
}
}, function (response) {
});
};

Related

Current request is not a multipart request Springboot+ angular js

I could not figure out the problem for days now. can any one help me? I think the problem is in the backend I also created a custom directive for the angular
this is springbot controller
#RequestMapping(value = "/add", method = RequestMethod.POST,consumes= {MediaType.APPLICATION_JSON_VALUE,MediaType.MULTIPART_FORM_DATA_VALUE} )
public ResponseEntity <AGPResponse>addArtist( #RequestParam("file") MultipartFile file, #RequestBody ArtistModel Ar ) {
try {
if (Ar.getId() == null) {
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File("-uploaded")));
stream.write(bytes);
stream.close();
service.addArtist(Ar);}
else {
service.updateArtist(Ar);
}
} catch (Exception e) {
return AGPResponse.error(getMessage("something went Wrong"), HttpStatus.UNPROCESSABLE_ENTITY);
}
return AGPResponse.success(getMessage("successful"));
}
this is angular js controller
APP.controller('ArtistController', artistcontroller);
function artistcontroller($rootScope, $scope, ArtistService, $routeParams,
$route) {
$scope.user={
name:"",
nickname:"",
file:[]
}
$scope.saveArtist=function(datas){
var data=new FormData();
data.append("name",$scope.user.name);
data.append("nickname",$scope.user.nickname);
for(i=0;i<$scope.user.file.length;i++){
data.append("file",$scope.user.file[i]);
}var config={
transformRequest:angular.identity,
transformResponse:angular.identity,
headers:{'Content-Type':undefined}
}
ArtistService.saveArtist.save(datas, sucess, error);
function sucess(obj) {
$scope.successMessage = "Saved!"
$scope.errors = null;
}
function error(obj) {
$scope.successMessage = null;
$scope.errors = obj;
}}}

Cant find why my return is being serialized twice

I am calling a custom Web API from my Angular app, and I need to JSON.parse() my response twice in order to access the properties. I am not sure why this is happening.
/// <summary>
/// Gets list of printers
/// </summary>
[HttpGet]
public IHttpActionResult GetPrinterList()
{
try
{
List<Printer> pl = new List<Printer>();
// List the print server's queues
PrintQueueCollection myPrintQueues = new PrintServer(#"\\LPH-Printers").GetPrintQueues();
foreach (PrintQueue pq in myPrintQueues)
{
Printer p = new Printer();
p.Name = pq.FullName;
pl.Add(p);
}
return Ok(JsonConvert.SerializeObject(pl));
}
catch (Exception e)
{
return BadRequest(e.ToString());
}
}
This is the method in my API, and below is how I am calling it in Angular
'use strict';
app.factory('printerService', ['$http', 'ngAuthSettings', function ($http, ngAuthSettings) {
var serviceBase = ngAuthSettings.apiServiceBaseUri;
var printerServiceFactory = {};
var _DefaultPrinter = function (val) {
return $http.get(serviceBase + 'api/LibertyMobile/GetUserDefaultPrinter', {
params: { 'username': val }
})
};
var _SetDefaultPrinter = function (userName, DefaultPrinter) {
return $http({
url: serviceBase + "api/LibertyMobile/SaveUserDefaultPrinter",
method: "POST",
params: { 'username': userName, 'printer': DefaultPrinter }
});
}
var _GetPrinterList = function () {
return $http.get(serviceBase + 'api/LibertyMobile/GetPrinterList');
}
printerServiceFactory.DefaultPrinter = _DefaultPrinter;
printerServiceFactory.SetDefaultPrinter = _SetDefaultPrinter;
printerServiceFactory.GetPrinterList = _GetPrinterList;
return printerServiceFactory;
}]);
Any help would be greatly appreciated.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
//config.Routes.MapHttpRoute(
// name: "DefaultApi",
// routeTemplate: "api/{controller}/{id}",
// defaults: new { id = RouteParameter.Optional }
//);
//config.Routes.MapHttpRoute(
// name: "GetPartNumbers",
// routeTemplate: "api/Inventory/GetPartNumbers/{partnum}/{user}",
// defaults: new { controller = "Inventory" }
//);
config.Routes.MapHttpRoute(
name: "ApiByAction",
routeTemplate: "api/{controller}/{action}",
defaults: new { controller = "Inventory", action = RouteParameter.Optional }
);
}
}
Above is my WebApiConfig.cs code.
This
return Ok(JsonConvert.SerializeObject(pl));
The framework will serialize the value passed for you but you are also serializing it using JsonConvert.SerializeObject before passing it to the action result, hence the double serialization.
Just pass the value back
/// <summary>
/// Gets list of printers
/// </summary>
[HttpGet]
public IHttpActionResult GetPrinterList() {
try {
List<Printer> pl = new List<Printer>();
// List the print server's queues
PrintQueueCollection myPrintQueues = new PrintServer(#"\\LPH-Printers").GetPrintQueues();
foreach (PrintQueue pq in myPrintQueues) {
Printer p = new Printer();
p.Name = pq.FullName;
pl.Add(p);
}
return Ok(pl);
} catch (Exception e) {
return BadRequest(e.ToString());
}
}
And let the framework do its thing.

Breakpoints not being hit or methods not being called when using $http.get to call methods in APIController

When I call $http.get('/api/calendarevent/getall') in my Angular code, the breakpoints for the method in my API Controller that matches that route are not being hit. I don't know if that means the methods in the controller aren't being called or if it's bypassing the breakpoints set in the method. In the IE Developer tools, I receive a 500 error code. So the method is being found but I'm not sure if it's being executed since I would have received some kind of 400 error if it wasn't being found. Below, I've included the necessary code, can anyone see where I might be going wrong?
Angular Code:
function () {
var deferred = $q.defer();
$http.get('/api/calendarevent/getall').success(function (data) {
deferred.resolve(data);
});
return deferred.promise;
}
Global.asax.cs:
protected void Application_Start(object sender, EventArgs e)
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "Default",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional });
}
APIController:
public class CalendarEventController : ApiController
{
[HttpGet]
[ActionName("all")]
public object GetAll()
{
using (var entity = new RPOEntities())
{
CalendarEventViewModel returnModel = new CalendarEventViewModel();
var events = entity.CalendarEvents.Where(e => !e.Deleted);
var eventList = events.ToList();
var calendarEvents = eventList.Select(e => new
{
id = e.CalendarEventId,
title = e.Title,
start = e.StartDate,
end = e.EndDate,
url = "details/" + e.CalendarEventId.ToString(),
contact = e.Contact,
location = e.Location,
property = e.AllProperties ? "All Properties" : e.Property != null ?
e.Property.PropertyName : "",
active = e.Active,
canEdit = Helper.IsRPOAdmin || Helper.IsCorporateAdmin || (e.PropertyStaffId.HasValue && e.PropertyStaffId.Value == Helper.CurrentUserId)
}).ToList();
return new {
events = calendarEvents,
color = "",
textColor = "" };
}
}

How do I update the UI from a HttpWebRequest?

In my Mainpage.xaml.cs file I have a function that creates an instance of another class and tries to download a webpage using a HttpWebRequest from that instance. The problem is, once I've managed to download the webpage I can't send it back to the main UI thread. I've tried using Deployment.Current.Dispatcher.BeginInvoke to send the webpage back to a TextBlock I have waiting, but when I try I get an error telling me that I can't access the TextBlock from the other class. Is there any way to pass data between two threads without using LocalStorage?
EDIT: code below:
MainPage:
private void button1_Click(object sender, RoutedEventArgs e)
{
Member m = new Member(name, id);
}
Member class:
public Member(String Member, String API)
{
APIKey = API;
MemberName = Member;
this.super = super;
DoSend(method, string, "", null);
}
public void DoSend(string method, string url, string body, string mimetype)
{
if (WebRequest.RegisterPrefix("https://",System.Net.Browser.WebRequestCreator.ClientHttp)) {
HttpWebRequest request = WebRequest.Create(makeURI(url)) as HttpWebRequest;
request.Method = method;
request.Headers["X-NFSN-Authentication"] = MakeAuthHeader(url,body);
if (body != "")
{
byte[] bodyData = Encoding.UTF8.GetBytes(body);
request.ContentType = mimetype;
//Stuff Should Happen Here
}
else
doStuff(request);
}
public void doStuff(HttpWebRequest httpReq)
{
httpReq.BeginGetResponse(r =>
{
var httpRequest = (HttpWebRequest)r.AsyncState;
var httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(r);
using (var reader = new StreamReader(httpResponse.GetResponseStream()))
{
var response = reader.ReadToEnd();
ResponseBlock.Text = response; //Invalid cross-thread reference
}
}, httpReq);
}
MainPage:
customClass.DownloadPage((result) =>
{
textBlock.Text = result;
},
(exception) =>
{
MessageBox.Show(exception.Message);
});
CustomClass:
public void DownloadPage(Action<string> callback, Action<Exception> exception)
{
WebClient webClient = new WebClient();
webClient.DonwloadStringCompleted += (s, e) =>
{
if (e.Error == null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
callback(e.Result);
});
}
else
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
exception(e.Error);
});
}
};
webClient.DonwloadStringAsync();
}

Google OAuth2.0 - Windows phone 7

Experts,
I'm new to OAuth,
I'm writing an small App in windows Phone 7, I'm using OAuth2 for google contacts, I need to get the initial URL API (1) to get the Token
1) https://accounts.google.com/o/oauth2/auth?response_type=code&scope=https://www.google.com/m8/feeds/&redirect_uri=REDIRECT_URI&client_id=CLIENT_ID&hl=en-US&from_login=1&as=NEW_AS&pli=1
I got the success code, and when I'm trying to use this
https://www.google.com/m8/feeds/contacts/default/full?access_token=TOKEN_CODE
but I'm getting 401 error back,
Can you please advice, what mistake i'm going.
I've taken Twitter OAuth example as base, and doing modifications.
CODE
var uri = new Uri(url);
var request = BuildOAuthWebRequest(url, null);
MakeGetRequest(callback, request);
private static HttpWebRequest BuildOAuthWebRequest( string url, string realm)
{
var header = new StringBuilder();
var request = (HttpWebRequest)WebRequest.Create(url);
return request;
}
private static void MakeGetRequest(EventHandler<OAuthEventArgs> callback, HttpWebRequest request)
{
var asyncState = request.BeginGetResponse(new AsyncCallback((asyncRes) =>
{
HttpWebResponse response = null;
try
{
//request has returned
response = (HttpWebResponse)request.EndGetResponse(asyncRes);
if (response.StatusCode == HttpStatusCode.OK)
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
var token = sr.ReadToEnd();
callback(null, new OAuthEventArgs() { Response = token });
}
}
}
catch (WebException we)
{
string t = new StreamReader(we.Response.GetResponseStream()).ReadToEnd();
callback(null, new OAuthEventArgs() { Error = we, ErrorMessage = t, IsError = true });
}
catch (Exception e)
{
callback(null, new OAuthEventArgs() { Error = e, ErrorMessage = e.Message, IsError = true });
}
finally
{
if (response != null)
response.Close();
}
}), null);
}

Resources