I have this code snippet
Task.Run(async () =>
{
stream = await DependencyService.Get<IPicturePicker>().GetImageStreamAsync();
if (stream != null)
{
Device.BeginInvokeOnMainThread(() =>
{
ImageOne.Source = ImageSource.FromStream(() => stream);
ImageTwo.Source = ImageSource.FromStream(() => stream);
});
}
}
The problem with the code is that only ImageTwo.Source gets set (because it is the last one). How do I set both ImageOne and ImageTwo with the same stream? Is there a better way to do this then what i am doing?
Here is what you can do:
Device.BeginInvokeOnMainThread(async () =>
{
Stream stream = await DependencyService.Get<IPicturePicker>().GetImageStreamAsync();
var memoryStream = new MemoryStream();
await stream.CopyToAsync(memoryStream);
image1.Source = ImageSource.FromStream(() => { return new MemoryStream(memoryStream.ToArray()); });
image2.Source = ImageSource.FromStream(() => { return new MemoryStream(memoryStream.ToArray()); });
});
Maybe you can get it doing this way:
Task.Run(async () =>
{
stream = await DependencyService.Get<IPicturePicker().GetImageStreamAsync();
if (stream != null)
{
Device.BeginInvokeOnMainThread(() =>
{
var source = ImageSource.FromStream(() => stream);
ImageOne.Source = source;
ImageTwo.Source = source;
});
}
}
You should test, I don't have tried it.
Related
I am facing issue in ionic 4 . Induction variable gives undefined but there is data when i run sql query ..Help me Please
following is my code
try {
let induction= await this.sql.dbInstance.executeSql('Select * FROM SurveyResponse where ADDData != ""')
.then(async res => {
let severity = [];
for (var i = 0; i < res.rows.length; i++) {
severity.push(res.rows.item(i));
alert("loop");
alert(induction);
}
var loc= severity;
return await loc;
})
.catch(e=>{
console.log(e);
})
return new Promise((resolve) => {
alert("Induction");
alert(induction);
let obj = { Success: true, result: induction };
resolve(obj);
});
} catch (error) {
alert("error");;
alert(error);
}
Help Me Please
i am trying to display server side errors on login form.
i am trying to change state when data is avaliable.
but its not working. can anybody help
or is there any better way to do it.
Future<dynamic> apiRequest(map) async {
String url = 'https://localhost/api/login';
var response = await http.post(Uri.encodeFull(url),
body: map, headers: {"Accept": "application/json"});
var res = json.decode(response.body);
return res;
}
void _submit() async {
if (this._formKey.currentState.validate()) {
_formKey.currentState.save(); // Save our form now.
var map = {
'email_id': '',
'password': '',
};
var hello = await apiRequest(map);
setState(() {
email_id_error = hello["errors"]["email_id"];
});
} else {
setState(() {
_autovalidate = true;
});
}
}
new Text(email_id_error),
response from server
{status_code: 4003, errors: {password: [can't be blank], email_id: [can't be blank]}}
you can try this
void _submit() async {
if (this._formKey.currentState.validate()) {
_formKey.currentState.save(); // Save our form now.
var map = {
'email_id': '',
'password': '',
};
var hello = await apiRequest(map);
if(hello.statusCode ==4003){
setState(() {
email_id_error = hello.responseBody["errors"]["email_id"];
});
}
} else {
setState(() {
_autovalidate = true;
});
}
}
Hi i am using nightmare for scrape data from website and also course details. I occur a issue :-
err: { message: 'navigation error',
code: 0,
details: 'OK',
url: 'https://www.myskills.gov.au/courses/details?Code=CHC14015' }
on each url traversal. Please suggest me to resolve this:
var Nightmare = require('nightmare')
var vo = require('vo')
var fs = require('fs')
var filesystem = require('file-system')
// var nightmare = Nightmare({show:true});
var sleep = require('sleep');
vo(run)(function(err, result) {
if (err) throw err
console.log("Hi");
})
function *run() {
var nightmare = Nightmare({show:true});
console.log("1st step *run");
yield nightmare
.goto('https://www.myskills.gov.au/courses/search/')
.wait(12000)
//.click('#select3 value="100")
.evaluate(function () {
var hrefs = [];
$('.search-result h4 a').each(function()
{
var course = new Object();
course.title = $(this).html();
course.link = $(this).attr('href');
course.code = $('.search-result .col-md-2.text-small
span').html();
hrefs.push(course);
});
return hrefs;
})
.then(function(str){
console.log("2nd step evaluate then on page load");
console.log(str);
for(var i=0; i< 8; i++)
{
console.log(i);
sleep.sleep(1);
var link = "https://www.myskills.gov.au";
var coursetitle = str[i].title
var courselink = link +str[i].link+"\n";
var coursesinglelink = link +str[i].link;
var courseData = coursetitle+"\n"+str[i].code+"\n"+courselink;
fs.appendFile('getcourselink.txt', courseData, function (err) {
if(err) console.log(err);
});
vo(run1)(function(err, result) {
if (err) console.log ("err: ",err);
console.log("Hi in run1");
//console.log(result);
});
function *run1() {
console.log("I 2nd time:-"+i);
console.log(coursesinglelink);
sleep.sleep(2);
var nightmare1 = Nightmare({show:true});
yield nightmare1
.goto(coursesinglelink)
.wait(9000)
.evaluate(function () {
var str="Hi";
var CourseDetails = $('#details #courseStructureDiv
#packagingrules').text();
str = str+"\n"+CourseDetails;
return str;
})
.then(function(str){
console.log("Run inner then",str);
fs.appendFile('getcourselink.txt', str, function (err) {
if(err) console.log(err);
});
// nightmare1.end();
});
}
//nightmare.end();
// nightmare.proc.disconnect();
// nightmare.proc.kill();
// nightmare.ended = true;
// nightmare = null;
}
});
}
In MVC 6 RCP 6 using Microsoft.AspNet.Security I was able to use a custom SecurityTokenValidator.
In RC Microsoft.AspNet.Security didn't exist in Beta4 so I changed my code to use Microsoft.AspNet.Authentication see below: (Compiles and runs but SecurityTokenValidator never fires.
services.Configure<ExternalAuthenticationOptions>(options =>
{
options.SignInScheme = OAuthBearerAuthenticationDefaults.AuthenticationScheme;
});
app.UseOAuthBearerAuthentication(options =>
{
options.TokenValidationParameters.ValidateAudience = true;
options.TokenValidationParameters.ValidateIssuer = true;
options.TokenValidationParameters.RequireSignedTokens = false;
options.AuthenticationScheme = OAuthBearerAuthenticationDefaults.AuthenticationScheme;
options.AutomaticAuthentication = true;
options.SecurityTokenValidators = new List<ISecurityTokenValidator> { validator };
});
Replace the app.UseOAuthBearerAuthentication code with
app.UseMiddleware<OAuthBearerAuthenticationMiddleware>(new ConfigureOptions<OAuthBearerAuthenticationOptions>(options =>
{
options.AutomaticAuthentication = true;
options.SecurityTokenValidators = new List<ISecurityTokenValidator> { validator };
}));
You got it?
Today occours that CustomSecurityValidationToken not fires because inner exception was throw (a inner validation occurs based in params in my case).
Try to debug Notifications and if it fires 'AuthenticationFailed', you will find in 'context' variable a Property named 'Exception' if any.
app.UseOAuthBearerAuthentication(bearer =>
{
bearer.SecurityTokenValidators = new List<ISecurityTokenValidator>() { new CustomSecurityValidationToken() };
bearer.AutomaticAuthentication = true;
bearer.Notifications = new OAuthBearerAuthenticationNotifications()
{
SecurityTokenReceived = context =>
{
return Task.FromResult(0);
},
MessageReceived = context =>
{
return Task.FromResult(0);
},
SecurityTokenValidated = context =>
{
return Task.FromResult(0);
},
AuthenticationFailed = context =>
{
context.Response.Redirect("Home/Error?message=" + context.Exception.Message);
return Task.FromResult(0);
}
};
});
I am beginner in using nopCommerce 2.30 (MVC 3 Razor) and Telerik().Grid. I am currently working
on Nop.Admin project.I try to create a Html.Telerik().Grid in my form, with many features.
Please see my grid image below.
These are the features.
grid data should be filter the selected value of the dropdownlist.
all grid columns are enable sorting.
in first column header contains a checkbox,for multiselect.
grid view must enable a column context menu.
Please see my code below.
My .cshtml file
<td>
#(Html.Telerik().Grid<NotificationMailReminderModel>()
.Name("productvariants-grid")
.DataKeys(keys =>
{
keys.Add(pv => pv.Username);
})
.DataBinding(dataBinding =>
dataBinding.Ajax()
.Select("EmailReminderByEvent", "Customer")
)
.Columns(columns =>
{
columns.Bound(pv => pv.IsSelected)
.ClientTemplate("<input type='checkbox' name='Id' value='<#= Id #>' />")
.HeaderTemplate(#<text><input type="checkbox" title="check all records" id="checkAllRecords" /></text>)
.Width(50)
.HeaderHtmlAttributes(new { style = "text-align:center" })
.HtmlAttributes(new { style = "text-align:center" });
columns.Bound(pv => pv.Username).ReadOnly().Width(250);
columns.Bound(pv => pv.Firstname).ReadOnly();
columns.Bound(pv => pv.Lastname).ReadOnly();
})
.ClientEvents(events => events.OnDataBinding("Grid_onDataBinding").OnError("Grid_onError").OnSubmitChanges("Grid_onSubmitChanges")
.OnRowDataBound("onRowDataBound"))
.Editable(editing => editing.Mode(GridEditMode.InCell))
.Pageable(settings => settings.PageSize(2).Position(GridPagerPosition.Both))
.Sortable(sorting => sorting.Enabled(true))
)
<script type="text/javascript">
$(document).ready(function () {
$('#search-products').click(function () {
var grid = $('#productvariants-grid').data('tGrid');
grid.currentPage = 1; //new search. Set page size to 1
grid.ajaxRequest();
return false;
});
$('#send-mail-reminder').click(function () {
var grid = $('#productvariants-grid').data('tGrid');
grid.ajaxRequest();
return false;
});
$('#grdCustomerEventRoleData #productvariants-grid table thead #checkAllRecords').click(function () {
$("#grdCustomerEventRoleData #productvariants-grid table tbody input:checkbox").attr("checked", this.checked);
});
});
function Grid_onError(args) {
if (args.textStatus == "modelstateerror" && args.modelState) {
var message = "Errors:\n";
$.each(args.modelState, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function () {
message += this + "\n";
});
}
});
args.preventDefault();
alert(message);
}
}
function Grid_onDataBinding(e) {
var loadData = true;
var grid = $(this).data('tGrid');
if (loadData) {
var searchModel = {
Event: $('#select-event').val()
};
e.data = searchModel;
}
}
function Grid_onSubmitChanges(e) {
//TODO pass current search parameters
//we can't pass search parameters in submit changes
//that's why let's just clear search params
//$('##Html.FieldIdFor(model => model.Event)').val('');
//$('#SearchCategoryId').val('0');
//$('#SearchManufacturerId').val('0');
}
</script>
</td>
My Controller actions
public ActionResult EmailReminder()
{
if (!_permissionService.Authorize(StandardPermissionProvider.ManageCustomers))
return AccessDeniedView();
var model = new NotificationMailReminderModels();
model.Event = 0;
List<Nop.Core.Domain.Catalog.Product> products = _productRepository.Table.Where(p => p.EventDate != null && p.EventDate >= DateTime.MinValue).OrderBy(o => o.Name).ToList();
model.Events = products.Select(p => new System.Web.Mvc.SelectListItem
{
Text = p.Name.Trim(),
Value = p.Id.ToString()
}).ToList();
return View(model);
}
[HttpPost, GridAction(EnableCustomBinding = true)]
public ActionResult EmailReminderByEvent(int[] Id, GridCommand command, NotificationMailReminderModels model)
{
if (!_permissionService.Authorize(StandardPermissionProvider.ManageCustomers))
return AccessDeniedView();
var gridModel = new GridModel();
string vwSlEv = ViewBag.SelectedEvent;
int selevent = 0;
if (!string.IsNullOrEmpty(vwSlEv))
{
Int32.TryParse(vwSlEv, out selevent);
}
else
{
selevent = model.Event;
}
var csts = _customerEventRoleRepository.Table.Where(e => e.EventId == selevent).Select(cs => cs.CustomerId).Distinct().ToArray();
var customers = _customerRepository.Table.Where(c => !string.IsNullOrEmpty(c.Username) && !string.IsNullOrEmpty(c.Email) && csts.Contains(c.Id)).ToList();
var gridmodel = customers.Select(x =>
{
NotificationMailReminderModel not = new NotificationMailReminderModel();
not.Id = x.Id;
not.Username = x.Username;
not.Firstname = x.CustomerAttributes.FirstName;
not.Lastname = x.CustomerAttributes.LastName;
return not;
});
var grddata = new PagedList<NotificationMailReminderModel>(gridmodel.ToList(), command.Page - 1, command.PageSize);
gridModel.Data = grddata;
gridModel.Total = grddata.TotalCount;
return new JsonResult
{
Data = gridModel
};
}
data grid sorting and filtering works fine in my grid. But i can't get the ContextMenu
function in the Razor intellisence.
I want to passing the selected rows to the Controller POST function.
But, How to pass the selected rows in to the controller function.
please help.
But, How to pass the selected rows in to the controller function.
JQuery (Sample Code)
var MyConnectionList = {
ColorList: []
};
function SendStream() {
debugger;
MyConnectionList.ColorList.push({
"Name": 'Test1',
"Color": 'red'
});
MyConnectionList.ColorList.push({
"Name": 'Test2',
"Color": 'Green'
});
$.ajax({
url: "Ur url",
data: JSON.stringify(MyConnectionList),
type: 'POST',
contentType: 'application/json',
dataType: 'json',
success: function (data) { }
});
}
Action Method
public ActionResult SendStream(List<Sample> ColorList)
{
}