How to get the data from api on bases of start date and end date in ReactNative? - api

how do I get a list of data from API according to start date and end date in react-native?
componentDidMount = async() => {
var token = await AsyncStorage.getItem('accessToken')
var response = await this.props.listData({'startDate':,'endDate':},accessToken)
if(!response.error){
this.setState({})
}
}

componentDidMount = async() => {
start = 0;
var today = new Date();
today.setHours(0,0,0,0);
var day = today.getDay() - start;
var date = today.getDate() - day;
var Start = new Date(today.setDate(date));
var End= new Date(today.setDate(date + 6));
var StartDate = new Date(Start);
var EndDate = new Date(End);
var startingDate = StartDate.getDate()+"-"+(new Date(Start).getMonth()+1)+"-
"+ new Date(Start).getFullYear();
var endingDate = EndDate.getDate()+"-"+(new Date(End).getMonth()+1)+"-"+ new
Date(End).getFullYear();
var token = await AsyncStorage.getItem('accesToken')
var response await = this.props.posthistory({'startDate':startingDate,'endDate':endingDate,'page':'1'},accesstoken)
if(!response.error){
this.setState({response})
}
}

Related

_userManager.ReplaceClaimAsync error Id = 414, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}"

In my controller asp.net core 6.0 I got this error when execute ReplaceClaimAsync:
Id = 414, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}"
var user11 = _userManager.FindByIdAsync(User.Id).Result;
user11.Email = user.Email;
var Result = _userManager.UpdateAsync(user11).Result;
if (!Result.Succeeded)
{
ModelState.AddModelError(Result.Errors.First().Code, Result.Errors.First().Description);
//throw new Exception(result.Errors.First().Description);
return BadRequest(ModelState);
}
var claimsOriginaux = _userManager.GetClaimsAsync(user11);
var claimOld = claimsOriginaux.Result.FirstOrDefault(r => r.Type == JwtClaimTypes.GivenName);
var claimNew = new Claim(JwtClaimTypes.GivenName, User.GivenName);
if (claimNew.Value != claimOld.Value)
{
var temp = _userManager.ReplaceClaimAsync(user11, claimOld, claimNew);
}
return NoContent(); //success
Any clue?
You are calling a bunch of async methods, and you are not using them the way you should.
You should await all async methods, instead of calling the .Result property.
Using await
var user11 = await _userManager.FindByIdAsync(User.Id);
user11.Email = user.Email;
var Result = await _userManager.UpdateAsync(user11);
if (!Result.Succeeded)
{
ModelState.AddModelError(Result.Errors.First().Code, Result.Errors.First().Description);
//throw new Exception(result.Errors.First().Description);
return BadRequest(ModelState);
}
var claimsOriginaux = await _userManager.GetClaimsAsync(user11);
var claimOld = claimsOriginaux.Result.FirstOrDefault(r => r.Type == JwtClaimTypes.GivenName);
var claimNew = new Claim(JwtClaimTypes.GivenName, User.GivenName);
if (claimNew.Value != claimOld.Value)
{
var temp = await _userManager.ReplaceClaimAsync(user11, claimOld, claimNew);
}
return NoContent(); //success
or
Using GetAwaiter()
var user11 = _userManager.FindByIdAsync(User.Id).GetAwaiter().GetResult();
user11.Email = user.Email;
var Result = _userManager.UpdateAsync(user11).GetAwaiter().GetResult();
if (!Result.Succeeded)
{
ModelState.AddModelError(Result.Errors.First().Code, Result.Errors.First().Description);
//throw new Exception(result.Errors.First().Description);
return BadRequest(ModelState);
}
var claimsOriginaux = _userManager.GetClaimsAsync(user11).GetAwaiter().GetResult();
var claimOld = claimsOriginaux.Result.FirstOrDefault(r => r.Type == JwtClaimTypes.GivenName);
var claimNew = new Claim(JwtClaimTypes.GivenName, User.GivenName);
if (claimNew.Value != claimOld.Value)
{
var temp = _userManager.ReplaceClaimAsync(user11, claimOld, claimNew).GetAwaiter().GetResult();
}
return NoContent(); //success

Calling multiple APIs slows down the app to load?

So I have made a News App using APIs available on the internet. So I had to use different API for each different Category. There are more than 9 categories, So this is making my app load very slow. So, what is the solution to this. How can I only call 2 APIs at the initial state and rest of the others after some time when the app has loaded.
See the code below:
class NewsCard extends StatefulWidget {
#override
_NewsCardState createState() => _NewsCardState();
}
class _NewsCardState extends State<NewsCard>
with SingleTickerProviderStateMixin {
TabController tabController;
static DateTime now = DateTime.now();
String formattedDate;
List newsData;
List topNews1;
List businessNews1;
List worldNews1;
List sportsNews1;
List entertainmentNews1;
List educationNews1;
List tvnews1;
List electionNews1;
List lifeNews1;
bool isLoading = true;
final String toi= "https://timesofindia.indiatimes.com/";
final String topNews =
"API url";
final String sportsNews =
"API url";
final String businessNews =
"API url";
final String worldNews =
"API url ";
final String entertainmentNews =
"API url ";
final String educationNews =
"API url";
final String tvNews =
"API url ";
final String electionNews =
"API url";
final String lifeNews =
"API url";
final String url =
"https://newsapi.org/v2/top-headlines?sources=google-news-in&apiKey=";
Future getData() async {
var response = await http.get(
Uri.encodeFull(url),
headers: {
HttpHeaders.authorizationHeader: ""
},
);
var response1 = await http.get(
Uri.encodeFull(topNews),
);
var response2 = await http.get(
Uri.encodeFull(businessNews),
);
var response3 = await http.get(
Uri.encodeFull(worldNews),
);
var response4 = await http.get(
Uri.encodeFull(sportsNews),
);
var response5 = await http.get(
Uri.encodeFull(entertainmentNews),
);
var response6 = await http.get(
Uri.encodeFull(tvNews),
);
var response7 = await http.get(
Uri.encodeFull(lifeNews),
);
var response8 = await http.get(
Uri.encodeFull(electionNews),
);
var response9 = await http.get(
Uri.encodeFull(educationNews),
);
List data = jsonDecode(response.body)['articles'];
List topNewsData = jsonDecode(response1.body)['stories'];
List businessNewsData = jsonDecode(response2.body)['items'][0]['stories'];
List worldNewsData = jsonDecode(response3.body)['items'][0]['stories'];
List sportsNewsData = jsonDecode(response4.body)['items'][0]['stories'];
List entertainmentNewsData = jsonDecode(response5.body)['items'][0]['stories'];
List tvNewsData = jsonDecode(response6.body)['items'][0]['stories'];
List lifeNewsData = jsonDecode(response7.body)['items'][0]['stories'];
List electionsNewsData = jsonDecode(response8.body)['items'][0]['stories'];
List educationNewsData = jsonDecode(response9.body)['items'][0]['stories'];
setState(() {
newsData = data;
topNews1 = topNewsData;
businessNews1 = businessNewsData;
worldNews1 = worldNewsData;
sportsNews1 = sportsNewsData;
entertainmentNews1 = entertainmentNewsData;
tvnews1 = tvNewsData;
lifeNews1=lifeNewsData;
electionNews1 = electionsNewsData;
educationNews1 = educationNewsData;
isLoading = false; //this is for the initial loading, this is taking too much of time.
});
}
#override
void initState() {
super.initState();
this.getData();
tabController = TabController(vsync: this, length: 9);
}
Inside the Scaffold
isLoading
?Column(....):Column(.....)
Do keep in Mind that i am a beginner in Flutter, So if my method of approach is wrong then kindly request me to do the perfect approach.
Since there is no dependency between different api calls (api call 1 need not wait for api call 0 to finish), better to start them all and await for the results at end. So don't use await for every api call. Instead use Future.wait to wait for all futures at the end. Something like:
Future getData() async {
List<Future> responseFutures = [
http.get(
Uri.encodeFull(url),
headers: {HttpHeaders.authorizationHeader: ""},
),
http.get(
Uri.encodeFull(topNews),
),
http.get(
Uri.encodeFull(businessNews),
),
http.get(
Uri.encodeFull(worldNews),
),
http.get(
Uri.encodeFull(sportsNews),
),
http.get(
Uri.encodeFull(entertainmentNews),
),
http.get(
Uri.encodeFull(tvNews),
),
http.get(
Uri.encodeFull(lifeNews),
),
http.get(
Uri.encodeFull(electionNews),
),
http.get(
Uri.encodeFull(educationNews),
),
];
List responses = await Future.wait(responseFutures);
List data = jsonDecode(responses[0].body)['articles'];
List topNewsData = jsonDecode(responses[1].body)['stories'];
List businessNewsData = jsonDecode(responses[2].body)['items'][0]['stories'];
List worldNewsData = jsonDecode(responses[3].body)['items'][0]['stories'];
List sportsNewsData = jsonDecode(responses[4].body)['items'][0]['stories'];
List entertainmentNewsData = jsonDecode(responses[5].body)['items'][0]['stories'];
List tvNewsData = jsonDecode(responses[6].body)['items'][0]['stories'];
List lifeNewsData = jsonDecode(responses[7].body)['items'][0]['stories'];
List electionsNewsData = jsonDecode(responses[8].body)['items'][0]['stories'];
List educationNewsData = jsonDecode(responses[9].body)['items'][0]['stories'];
setState(() {
newsData = data;
topNews1 = topNewsData;
businessNews1 = businessNewsData;
worldNews1 = worldNewsData;
sportsNews1 = sportsNewsData;
entertainmentNews1 = entertainmentNewsData;
tvnews1 = tvNewsData;
lifeNews1 = lifeNewsData;
electionNews1 = electionsNewsData;
educationNews1 = educationNewsData;
isLoading = false; //this is for the initial loading, this is taking too much of time.
});
}

IdentityServer4 client - Refreshing access tokens on CookieAuthenticationEvents

I am trying to use refresh token when the access token expires. A similar so question is answered here. And a sample code to renew token by an action
And i end up with the following code in the startup.cs
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "Cookies",
//ExpireTimeSpan = TimeSpan.FromSeconds(100),
AutomaticAuthenticate = true,
AutomaticChallenge = true,
Events = new CookieAuthenticationEvents()
{
OnValidatePrincipal = async x =>
{
if (x.Properties?.Items[".Token.expires_at"] == null) return;
var logger = loggerFactory.CreateLogger(this.GetType());
var now = DateTimeOffset.UtcNow;
var tokenExpireTime = DateTime.Parse(x.Properties.Items[".Token.expires_at"]).ToUniversalTime();
var timeElapsed = now.Subtract(x.Properties.IssuedUtc.Value);
var timeRemaining = tokenExpireTime.Subtract(now.DateTime);
if (timeElapsed > timeRemaining)
{
var httpContextAuthentication = x.HttpContext.Authentication;//Donot use the HttpContext.Authentication to retrieve anything, this cause recursive call to this event
var oldAccessToken = await httpContextAuthentication.GetTokenAsync("access_token");
var oldRefreshToken = await httpContextAuthentication.GetTokenAsync("refresh_token");
logger.LogInformation($"Refresh token :{oldRefreshToken}, old access token:{oldAccessToken}");
var disco = await DiscoveryClient.GetAsync(AuthorityServer);
if (disco.IsError) throw new Exception(disco.Error);
var tokenClient = new TokenClient(disco.TokenEndpoint, ApplicationId, "secret");
var tokenResult = await tokenClient.RequestRefreshTokenAsync(oldRefreshToken);
logger.LogInformation("Refresh token requested. " + tokenResult.ErrorDescription);
if (!tokenResult.IsError)
{
var oldIdToken = await httpContextAuthentication.GetTokenAsync("id_token");
var newAccessToken = tokenResult.AccessToken;
var newRefreshToken = tokenResult.RefreshToken;
var tokens = new List<AuthenticationToken>
{
new AuthenticationToken {Name = OpenIdConnectParameterNames.IdToken, Value = oldIdToken},
new AuthenticationToken {Name = OpenIdConnectParameterNames.AccessToken, Value = newAccessToken},
new AuthenticationToken {Name = OpenIdConnectParameterNames.RefreshToken, Value = newRefreshToken}
};
var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResult.ExpiresIn);
tokens.Add(new AuthenticationToken { Name = "expires_at", Value = expiresAt.ToString("o", CultureInfo.InvariantCulture) });
var info = await httpContextAuthentication.GetAuthenticateInfoAsync("Cookies");
info.Properties.StoreTokens(tokens);
await httpContextAuthentication.SignInAsync("Cookies", info.Principal, info.Properties);
}
x.ShouldRenew = true;
}
else
{
logger.LogInformation("Not expired");
}
}
}
});
The client setup is as follows
AllowAccessTokensViaBrowser = true,
RefreshTokenUsage = TokenUsage.ReUse,
RefreshTokenExpiration = TokenExpiration.Sliding,
AbsoluteRefreshTokenLifetime = 86400,
AccessTokenLifetime = 10,
AllowOfflineAccess = true,
AccessTokenType = AccessTokenType.Reference
After successfully login, i am getting a 401 for every other request. And the log says
[Identity Server]2017-07-04 10:15:58.819 +01:00 [Debug]
"TjpIkvHQi../cfivu6Nql5ADJJlZRuoJV1QI=" found in database: True
[Identity Server]2017-07-04 10:15:58.820 +01:00 [Debug]
"reference_token" grant with value:
"..9e64c1235c6675fcef617914911846fecd72f7b372" found in store, but has
expired.
[Identity Server]2017-07-04 10:15:58.821 +01:00 [Error] Invalid
reference token. "{ \"ValidateLifetime\": true,
\"AccessTokenType\": \"Reference\", \"TokenHandle\":
\"..9e64c1235c6675fcef617914911846fecd72f7b372\" }"
[Identity Server]2017-07-04 10:15:58.822 +01:00 [Debug] Token is
invalid.
[Identity Server]2017-07-04 10:15:58.822 +01:00 [Debug] Creating
introspection response for inactive token.
[Identity Server]2017-07-04 10:15:58.822 +01:00 [Information] Success
token introspection. Token status: "inactive", for API name: "api1"
Any help would by highly appreciated
UPDATE:
Basically, when the token expires i get a System.StackOverflowException on the following line
var tokenExpireTime = DateTime.Parse(x.Properties.Items[".Token.expires_at"]).ToUniversalTime();
UPDATE 2:
Do not use HttpContext.Authentication to retrieve anything. Check my answer below to find the working implementaion
I was working on this for last two days and could not make this work. Funnily, after posting the question here, within 2 hours I make it working :)
Events = new CookieAuthenticationEvents()
{
OnValidatePrincipal = async x =>
{
if (x.Properties?.Items[".Token.expires_at"] == null) return;
var now = DateTimeOffset.UtcNow;
var tokenExpireTime = DateTime.Parse(x.Properties.Items[".Token.expires_at"]).ToUniversalTime();
var timeElapsed = now.Subtract(x.Properties.IssuedUtc.Value);
var timeRemaining = tokenExpireTime.Subtract(now.DateTime);
WriteMessage($"{timeRemaining} and elapsed at {timeElapsed}");
if (timeElapsed > timeRemaining)
{
var oldAccessToken = x.Properties.Items[".Token.access_token"];
var oldRefreshToken = x.Properties.Items[".Token.refresh_token"];
WriteMessage($"Refresh token :{oldRefreshToken}, old access token {oldAccessToken}");
var disco = await DiscoveryClient.GetAsync(AuthorityServer);
if (disco.IsError) throw new Exception(disco.Error);
var tokenClient = new TokenClient(disco.TokenEndpoint, ApplicationId, "secret");
var tokenResult = await tokenClient.RequestRefreshTokenAsync(oldRefreshToken);
if (!tokenResult.IsError)
{
var oldIdToken = x.Properties.Items[".Token.id_token"];//tokenResult.IdentityToken
var newAccessToken = tokenResult.AccessToken;
var newRefreshToken = tokenResult.RefreshToken;
var tokens = new List<AuthenticationToken>
{
new AuthenticationToken {Name = OpenIdConnectParameterNames.IdToken, Value = oldIdToken},
new AuthenticationToken {Name = OpenIdConnectParameterNames.AccessToken, Value = newAccessToken},
new AuthenticationToken {Name = OpenIdConnectParameterNames.RefreshToken, Value = newRefreshToken}
};
var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResult.ExpiresIn);
tokens.Add(new AuthenticationToken { Name = "expires_at", Value = expiresAt.ToString("o", CultureInfo.InvariantCulture) });
x.Properties.StoreTokens(tokens);
WriteMessage($"oldAccessToken: {oldAccessToken}{Environment.NewLine} and new access token {newAccessToken}");
}
x.ShouldRenew = true;
}
}
}
Basically httpContextAuthentication.GetTokenAsync make this recursive, for that reason StackOverflowException occured.
Please let me know if this implementation has any issue

how to add button to reduce and to increase the spped of interval in action script 2.0

I have a code with which i can fetch image through internet ... I have completed it. I have to add to button , one to increase and one to reduce the interval ... in action script 2.0
import mx.transitions.*;
import mx.transitions.easing.*;
my_pb.mode = "manual";
this.createEmptyMovieClip("img_mc", 999);
var my_mcl:MovieClipLoader = new MovieClipLoader();
var mclListenerbject = new Object();
mclListener.onLoadStart = function(target_mc:MovieClip) {
my_pb.label = "loading: "+target_mc._name;
};
mclListener.onLoadProgress = function(target_mc:MovieClip, numBytesLoaded:Number, numBytesTotal:Number) {
var pctLoaded:Number = Math.ceil(100*(numBytesLoaded/numBytesTotal));
my_pb.setProgress(numBytesLoaded, numBytesTotal);
};
var number:Number = 2000;
var myInterval = setInterval(testInterval, number); //
function testInterval() {
my_mcl.addListener(mclListener);
my_mcl.loadClip("http://google.com/l5", img_mc);
}
i can create 2 button but there are some error...
If you want change the interval of the setInterval function, you have to clear it and then use the function with the new interval value, like this :
var delay:Number = 2000;
var interval = setInterval(on_repeat, delay);
function on_repeat() {
// instructions
}
fast.onPress = function(){
clearInterval(interval);
interval = setInterval(on_repeat, delay - 1000);
}
slow.onPress = function(){
clearInterval(interval);
interval = setInterval(on_repeat, delay + 1000);
}
But, as #Raptor has said, I recommend you to use ActionScript 3 instead of the old ActionScript 2.
For example, the code above can simply be replaced by a Timer object like this :
var delay:int = 2000;
var timer:Timer = new Timer(delay);
timer.addEventListener(TimerEvent.TIMER, function(e:TimerEvent):void {
// instructions
})
timer.start();
fast.addEventListener(MouseEvent.CLICK, function(e:MouseEvent):void {
timer.delay = delay - 1000;
})
slow.addEventListener(MouseEvent.CLICK, function(e:MouseEvent):void {
timer.delay = delay + 1000;
})
Hope that can help.
var current_loader:Number = 1;
var current_img:Number = 0;
this.createEmptyMovieClip('img_01', 999);
this.createEmptyMovieClip('img_02', 998);
img_01._x = img_01._y=img_02._x=img_02._y=20;
var loader:MovieClipLoader = new MovieClipLoader();
var listener:Object = new Object();
listener.onLoadStart = function(target_mc:MovieClip) {
};
listener.onLoadProgress = function(target_mc:MovieClip, numBytesLoaded:Number, numBytesTotal:Number) {
};
listener.onLoadComplete = function(target_mc:MovieClip) {
if (target_mc._name == 'img_01') {
img_02._visible = false;
} else {
img_01._visible = false;
}
};
var delay:Number = 2000;
var interval = setInterval(load_image, delay);
function load_image() {
loader.addListener(listener);
loader.loadClip("http://google.com/latimage.php?", _root['img_0'+current_loader]);
current_loader = current_loader == 1 ? 2 : 1;
current_img = current_img == images.length-1 ? 0 : current_img+1;
}
slow.onRelease = function() {
interval = setInterval(load_image, delay+1000);
trace(interval);
};
fast.onRelease = function() {
clearInterval(interval);
interval = setInterval(load_image, delay-1000);
trace(interval);
};
image_load();

google maps api v2 map.removeOverlay() marker array issue

To start off with, I would like to say that I have been looking on the internet for a really long time and have been unable to find the answer, hence my question here.
My latest school project is to create an admin page for adding articles to a database, the articles are connected to a point on a google map. The requirement for adding the point on the map is that the user is able to click the map once and the marker is produced, if the map is clicked a second time the first marker is moved to the second location. (this is what I am struggling with.)
The problem is, as the code is now, I get the error that markersArray is undefined. If I place the var markersArray = new Array; underneath the eventListener then I get an error that there is something wrong the main.js (googles file) and markersArray[0] is undefined in the second if.
By the way, I have to use google maps API v2, even though it is old.
<script type="text/javascript">
//<![CDATA[
var map;
var markers = new Array;
function load() {
if (GBrowserIsCompatible()) {
this.counter = 0;
this.map = new GMap2(document.getElementById("map"));
this.map.addControl(new GSmallMapControl());
this.map.addControl(new GMapTypeControl());
this.map.setCenter(new GLatLng(57.668911, 15.203247), 7);
GDownloadUrl("genxml.php", function(data) {
var xml = GXml.parse(data);
var Articles = xml.documentElement.getElementsByTagName("article");
for (var i = 0; i < Articles.length; i++) {
var id = Articles[i].getAttribute("id");
var title = Articles[i].getAttribute("title");
var text = Articles[i].getAttribute("text");
var searchWord = Articles[i].getAttribute("searchWord");
var point = new GLatLng(parseFloat(Articles[i].getAttribute("lat")),
parseFloat(Articles[i].getAttribute("lng")));
var article = createMarker(point, id, title, text);
this.map.addOverlay(article);
}
});
}
var myEventListener = GEvent.bind(this.map,"click", this, function(overlay, latlng) {
if (this.counter == 0) {
if (latlng) {
var marker = new GMarker(latlng);
latlng1 = latlng;
this.map.addOverlay(marker);
this.counter++;
markers.push(marker); //This is where I get the error that markersArray is undefined.
}
}
else if (this.counter == 1) {
if (latlng){
alert (markers[0]);
this.map.removeOverlay(markers[0]);
var markers = [];
this.map.addOverlay(marker);
this.counter++;
}
}
});
}
function createMarker(point, id, title, text) {
var article = new GMarker(point);
var html = "<b>" + title + "</b> <br/>"
GEvent.addListener(article, 'click', function() {
window.location = "article.php?id=" + id;
});
return article;
}
I solved the problem. I'm not exactly sure why it worked but this is what it looks like now:
var markersArray = [];
function load() {
if (GBrowserIsCompatible()) {
this.counter = 0;
this.map = new GMap2(document.getElementById("map"));
this.map.addControl(new GSmallMapControl());
this.map.addControl(new GMapTypeControl());
this.map.setCenter(new GLatLng(57.668911, 15.203247), 7);
GDownloadUrl("genxml.php", function(data) {
var xml = GXml.parse(data);
var Articles = xml.documentElement.getElementsByTagName("article");
for (var i = 0; i < Articles.length; i++) {
var id = Articles[i].getAttribute("id");
var title = Articles[i].getAttribute("title");
var text = Articles[i].getAttribute("text");
var searchWord = Articles[i].getAttribute("searchWord");
var type = Articles[i].getAttribute("type");
var point = new GLatLng(parseFloat(Articles[i].getAttribute("lat")),
parseFloat(Articles[i].getAttribute("lng")));
var article = createMarker(point, id, title, text);
this.map.addOverlay(article);
}
});
}
var myEventListener = GEvent.bind(this.map,"click", this, function(overlay, latlng) {
var marker = new GMarker(latlng);
if (this.counter == 0) {
if (latlng) {
latlng1 = latlng;
this.map.addOverlay(marker);
markersArray.push(marker);
this.counter++;
}
}
else if (this.counter == 1) {
if (latlng){
this.map.removeOverlay(markersArray[0]);
this.map.addOverlay(marker);
this.counter++;
}
}
});
}
function createMarker(point, id, title, text) {
var article = new GMarker(point);
var html = "<b>" + title + "</b> <br/>"
GEvent.addListener(article, 'click', function() {
window.location = "article.php?id=" + id;
});
return article;
}