i want to get data from web api in listview with paging. What i have done so far i dont see any problem in my code but i am getting null values in Handle_OnDemandLoading
private FeaturedItemList products = new FeaturedItemList();
protected async void FeaturedList()
{
var httpClient = new HttpClient();
var json = await httpClient.GetStringAsync("http://orangepotato.rjcpacking.com/index.php?route=api/login/getFeaturedProducts");
products = JsonConvert.DeserializeObject<FeaturedItemList>(json);
dataPager.Source = products.products;
}
void Handle_OnDemandLoading(object sender, Syncfusion.SfDataGrid.XForms.DataPager.OnDemandLoadingEventArgs e)
{
var source= products.products.Skip(e.StartIndex).Take(e.PageSize);
FeaturedlistView.ItemsSource = source.AsEnumerable();// here is i am getting null values but i am getting values in datapager.source
}
Related
So I need to get the userinfo so that I can retrieve the uniqueID object.
The sample code I found are always two steps, send a request to get the code, and then use the code and the appID and appSecret to get the token, along with the userInfo object. Can this process be simplied to be one step? Perhaps just request the id-token using the openID connect, without needing to get the code first?
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Params["code"] != null)
{
var code = Request.Params["code"];
AuthenticationContext ac = new AuthenticationContext(MicrosoftAuthBaseURL);
ClientCredential clcred = new ClientCredential(MicrosoftAppId, MicrosoftAppSecret);
AuthenticationResult acResult = ac.AcquireTokenByAuthorizationCodeAsync(code, new Uri(RedirectURI), clcred).Result;
SignInUser(acResult.UserInfo.UniqueId); var accesstoken = AcquireTokenWithResource(resource: "https://graph.microsoft.com/");
Response.Write(accesstoken);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
GetAuthorizationCode();
}
public void GetAuthorizationCode()
{
JObject response = new JObject();
var parameters = new Dictionary<string, string>
{
{ "response_type", "code" },
{ "client_id", "clientid" },
{ "redirect_uri", "http://localhost:8099/WebForm1.aspx" },
{ "prompt", "none"},
{ "scope", "openid"}
};
var requestUrl = string.Format("{0}/authorize?{1}", EndPointUrl, BuildQueryString(parameters));
Response.Redirect(requestUrl);
}
public string AcquireTokenWithResource(string resource)
{
var code = Request.Params["code"];
AuthenticationContext ac =
new AuthenticationContext(string.Format("https://login.microsoftonline.com/{0}", "tenantID"
));
ClientCredential clcred =
new ClientCredential("clientID", "clientSecret");
var token =
ac.AcquireTokenByAuthorizationCodeAsync(code,
new Uri("http://localhost:8099/WebForm1.aspx"), clcred,resource).Result.AccessToken;
return token;
}
private string BuildQueryString(IDictionary<string, string> parameters)
{
var list = new List<string>();
foreach (var parameter in parameters)
{
list.Add(string.Format("{0}={1}", parameter.Key, HttpUtility.UrlEncode(parameter.Value)));
}
return string.Join("&", list);
}
protected string EndPointUrl
{
get
{
return string.Format("{0}/{1}/{2}", "https://login.microsoftonline.com", "tenantID", #"oauth2/");
}
}
You can use id_token to get some user's information. For more details, please refer to https://learn.microsoft.com/en-us/azure/active-directory/develop/id-tokens.
Besides, if you want to get id_token, you can use the API as below
GET https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
client_id=<you app id> // Your registered Application ID
&response_type=id_tokene
&redirect_uri=<> // Your registered redirect URI, URL encoded
&response_mode=fragment // 'form_post' or 'fragment'
&scope=openid profile email // Include both 'openid' and scopes
&state=12345 // Any value, provided by your app
&nonce=678910 // Any value, provided by your app
For more details, please refer to the document
I have a search bar with list. The list will display all the suggestions from the database. The problem my search query is not working. I am getting zero count. I am not sure if my query has a correct syntax.
private void NameSearch_SearchButtonPressed(object sender, EventArgs e)
{
var keyword = NameSearch.Text;
var db = DependencyService.Get<ISQLiteDB>();
var conn = db.GetConnection();
var getCaf = conn.QueryAsync<ContactsTable>("SELECT FileAS FROM tblContacts WHERE FileAs LIKE '%?%'", keyword);
var resultCount = getCaf.Result.Count;
if (resultCount > 0)
{
var result = getCaf.Result;
lstName.ItemsSource = result;
}
}
In your Query, it contains "FileAS" and "FileAs" case sensitivity issue. Make sure they both are same and exactly like the column name.
Change your Query to:
conn.QueryAsync<ContactsTable>($"SELECT FileAS FROM tblContacts WHERE FileAS LIKE '%{ keyword }%'").ToList();
OR
To reduce spelling mistakes you can try following Lambda Expression as Query:
conn.Table<ContactsTable>().Where(x => x.FileAS.Contains(keyword)).ToList();
So, Your Final Code should look like:
private void NameSearch_SearchButtonPressed(object sender, EventArgs e)
{
var keyword = NameSearch.Text;
var db = DependencyService.Get<ISQLiteDB>();
var conn = db.GetConnection();
var getCaf = conn.Table<ContactsTable>().Where(x => x.FileAS.Contains(keyword)).ToList();
var resultCount = getCaf.Count();
if (resultCount > 0)
{
lstName.ItemsSource = getCaf;
}
}
Hope this will solve your issue.
OK...
I was finally making some headway with creating a User Management page using Identity 2 in Web Forms.
It was mostly moving along just fine. When suddenly I run into this issue, and it makes no sense to me.
I have an AS form with a dropdown list of Roles. That list is populated using
roleMgr.Roles.ToList();
Works Great
I use the user being edited Role to set the current selected value.
ddlUserType.SelectedValue = user.Roles.FirstOrDefault().ToString();
This WAS working like dynamite
Last week...
Now all of a sudden user.Roles.FirstOrDefault().ToString(); is returning
"System.Data.Entity.DynamicProxies.IdentityUserRole_FDDE5D267CF62D86904A3BC925D70DC410F12D5BE8313308EC89AC8537DC6375"
What he heck, man?
So I tried user.Roles.Take(1).ToString();
That returns
"System.Linq.Enumerable+d__24`1[Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole]"
I have to presume I Broke, Something...
But What?
Nothing in this code page changed at all between when it worked and then didn't.
The only thing I did related to Identity at all was Migrate a couple of fields into AspNetUsers (another whole ballgame, migrations...) which also worked like dynamite BTW.
I even went to the extreme of wiping out my Migrations and AspNet user tables entirely, and re-initializing it all.
Any suggestions ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Sperry_Parts.Models;
using Sperry_Parts.Logic;
using Microsoft.AspNet.Identity.Owin;
using Owin;
namespace Parts.Admin
{
public partial class CreateEditUser : System.Web.UI.Page
{
private bool NewUser
{
get { return ViewState["NewUser"] != null ? (bool)ViewState["NewUser"] : false; }
set { ViewState["NewUser"] = value; }
}
private string EditUser
{
get { return (string)ViewState["EditUser"]; }
set { ViewState["EditUser"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
EditUser = Session["Edit_User"].ToString();
// Access the application context and create result variables.
Models.ApplicationDbContext context = new ApplicationDbContext();
RoleActions roleAction = new RoleActions();
// Create a RoleStore object by using the ApplicationDbContext object.
var roleStore = new RoleStore<IdentityRole>(context);
// Create a RoleManager object that is only allowed to contain IdentityRole objects.
var roleMgr = new RoleManager<IdentityRole>(roleStore);
// Load the DDL of Roles
var roles = roleMgr.Roles.ToList();
ddlUserType.DataTextField = "Name";
ddlUserType.DataValueField = "Id";
ddlUserType.DataSource = roles;
ddlUserType.DataBind();
if (EditUser == "")
{
txtUserName.Enabled = true;
txtUserName.Focus();
NewUser = true;
} // End New User
else
{
// User part
var userMgr = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
txtUserName.Enabled = false;
txtFullName.Focus();
var user = userMgr.FindByName(EditUser);
if (user != null)
{
txtUserName.Text = user.UserName;
txtUserEmail.Text = user.Email;
txtFullName.Text = user.FullName;
var hisroles = user.Roles.ToList(); // properly returns 1 item
// this is where it went off the rails - these 4 lines are debugging code
string xrole = user.Roles.FirstOrDefault().ToString();
string role2 = user.Roles.Take(1).ToString();
string trythis = xrole.ToString();
string trythis2 = role2.ToString();
// I swear, this worked last week...
ddlUserType.SelectedValue = user.Roles.FirstOrDefault().ToString();
}
} // End Editing User
} // End if (!IsPostBack)
} // End Page Load
protected void CreateUser()
{
// removed as non-relevant to question
} // End CreateUser
protected void UpdateUser()
{
// removed as non-relevant to question
} // End UpdateUser
protected void btnSave_Click(object sender, EventArgs e)
{
// removed as non-relevant to question
} // End btnSave
protected void btnCancel_Click(object sender, EventArgs e)
{
Response.Redirect("~/ManageUsers");
} // End btnCancel
} // End Class CreateEditUser
}
I ran into the same problem trying to set the value of a "Roles" DropDownList inside a GridView Control. I solved it by using:
user.Roles.First().RoleId
It just happens that my RoleId is also my role name.
I want to show a list on an .aspx site. Therefore I have to use the SP client object model.
I found the following tutorial, but this doesn't use the client libraries:
http://social.technet.microsoft.com/wiki/contents/articles/30287.binding-gridview-with-sharepoint-list.aspx
My code so far looks the following:
ClientContext clientContext = GetContext(accessToken);
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();
// Get the email input list.
List inboxList = web.Lists.GetByTitle("InboxList");
Microsoft.SharePoint.Client.ListItemCollection items = inboxList.GetItems(new CamlQuery());
clientContext.Load(inboxList);
clientContext.Load(items, ic => ic.Include(i => i["DisplayName"], i => i["Client_Title"], i => i["HasUniqueRoleAssignments"]));
clientContext.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem i in items)
{
clientContext.Load(i);
}
clientContext.ExecuteQuery();
oGrid.DataSource = items;
oGrid.DataBind();
But this shows only some "meta data" of the list item collection, see screenshot:
If I use oGrid.DataSource = inboxList; I get an InvalidOperationException because the data source isn't type of IListSource, IEnumerable nor IDataSource.
If I use oGrid.DataSource = inboxList.DataSource; I get an PropertyOrFieldNotInitializedException, but I don't know how to load this attribute (via clientContext.Load it didn't work)?!
I got it - works with following code:
protected void Page_Load(object sender, EventArgs e)
{
...
ClientContext clientContext = GetContext(accessToken);
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();
// Get the email input list.
List inboxList = web.Lists.GetByTitle("InboxList");
Microsoft.SharePoint.Client.ListItemCollection items = inboxList.GetItems(new CamlQuery());
clientContext.Load(inboxList);
clientContext.Load(items);
clientContext.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem i in items)
{
clientContext.Load(i);
}
clientContext.ExecuteQuery();
oGrid.DataSource = GetInboxListData(inboxList, items);
oGrid.DataBind();
}
else if (!IsPostBack)
{
Response.Write("Could not find a context token.");
return;
}
}
private DataTable GetInboxListData(List inboxList, Microsoft.SharePoint.Client.ListItemCollection items)
{
DataTable dt = new DataTable();
dt.Columns.Add("From");
dt.Columns.Add("To");
dt.Columns.Add("Subject");
dt.Columns.Add("Body");
dt.Columns.Add("Attachments");
dt.Columns.Add("Sent");
DataRow row;
foreach(Microsoft.SharePoint.Client.ListItem item in items)
{
row = dt.Rows.Add();
row["From"] = item["From1"].ToString();
row["To"] = item["To"].ToString();
row["Subject"] = item["Subject1"].ToString();
row["Body"] = item["Body1"].ToString();
row["Attachments"] = item["Attachments"].ToString();
row["Sent"] = item["Sent"].ToString();
}
return dt;
}
This is similar to Retrieve the values from a list to Gridview in SharePoint Webpart? but with client object model methods & objects.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I read lots of about Web Api. For example i understand Web Service is a kind of Web Api or Web Api is more flexible.
But i didn't get that: Is Web Api future of Web Service?
For example one of our client needs data from our main database. Normally i use a Web Service for this -simple- purpose but this time i created a Web Api project. I got and service data plus i figured out how it works with Entity or Identity etc. But it's not simple as a web service. I think our client will think same thing also because of identity thing. So why should i prefer Web Api vs Web Service or should i prefer Web Api in this -simple- case?
This kind of depends what you mean by 'web service', but for now I'm going to assume you mean the old .net SOAP services.
If you are building something new today (September 2015) you are almost certainly better off using an asp.net web API. This is a standard REST-style service which can be called by almost any HTTP enabled client with no requirements for local software or understanding of how the service works, this is the whole point of the REST architectural style. I blogged a little about web API and REST here: http://blogs.msdn.com/b/martinkearn/archive/2015/01/05/introduction-to-rest-and-net-web-api.aspx
In your case of a simple service that adds CRUD operations to a database using entity framework. This can be very easily achieved with Web API. You can actually scaffold this whole thing based on a simple model.
To answer your specific question, Yes I believe that in eth asp.net world at least, web API is the future of web services. In fact web services have now been dropped in favour of web API.
Web API supports the .net identity model (I blogged on this here: http://blogs.msdn.com/b/martinkearn/archive/2015/03/25/securing-and-working-securely-with-web-api.aspx) and entity framework.
Hope this helps, if it does please mark as an answer or let me know of any more details you need.
public class Service1 : System.Web.Services.WebService
{
private List<string> GetLines(string filename) {
List<string> lines = new List<string>();
//filename: ime fajla (valute.txt) SA EXT
using (StreamReader sr = new StreamReader(Server.MapPath("podaci/" + filename))) {
string line;
while ((line = sr.ReadLine()) != null) {
lines.Add(line);
}
}
return lines;
}
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public double ProcitajKursNaDan(DateTime datum, string valuta) {
List<string> podaci = GetLines("valute.txt");
double kurs = 0.0;
// Pronalazenje upisa
for (int i = 0; i < podaci.Count; i++) {
string[] linija = podaci[i].Split('|');
/* Датум[0] | Oznaka valute[1] | Kurs[2] */
string dat = linija[0];
string val = linija[1];
string vrednost = linija[2];
// Uklanjanje viska
dat = dat.Trim();
val = val.Trim();
vrednost = vrednost.Trim();
// Konverzija:
DateTime datIzFajla = DateTime.ParseExact(dat, "d/M/yyyy", null);
double kursIzFajla = Convert.ToDouble(vrednost);
if (DateTime.Compare(datIzFajla, datum) == 0 && val == valuta)
kurs = kursIzFajla;
}
return kurs;
}
[WebMethod]
public bool UpisiKursNaDan(DateTime datum, string valuta, double Kurs) {
string date = datum.ToString("d/M/yyyy");
string linijaZaUpis = date + " | " + valuta + " | " + Kurs.ToString();
bool success = false;
try
{
StreamWriter sw = new StreamWriter(Server.MapPath("podaci/valute.txt"), true);
sw.WriteLine(linijaZaUpis);
sw.Close();
success = true;
}
catch {
success = false;
}
return success;
}
[WebMethod]
public List<string> ProcitajSveValute() {
List<string> linije = GetLines("valute.txt");
List<string> ValuteIzFajla = new List<string>();
for (int i = 0; i < linije.Count; i++) {
string linija = linije[i];
string valuta = linija.Split('|')[1];
valuta = valuta.Trim();
ValuteIzFajla.Add(valuta);
}
List<string> ValuteKraj = ValuteIzFajla.Distinct().ToList();
return ValuteKraj;
}
}
}
//using A10App.localhost;
//namespace A10App
//{
// public partial class pregledkursa : System.Web.UI.Page
// {
// protected void Page_Load(object sender, EventArgs e)
// {
// if (!this.IsPostBack) {
// Service1 servis = new Service1();
// List<string> valute = servis.ProcitajSveValute().ToList();
// for (int i = 0; i < valute.Count; i++)
// DropDownList1.Items.Add(valute[i]);
// }
// }
// protected void Button1_Click(object sender, EventArgs e)
// {
// string datum = TextBox1.Text;
// string valuta = DropDownList1.Text;
// Service1 servis = new Service1();
// double kurs = servis.ProcitajKursNaDan(DateTime.ParseExact(datum, "d/M/yyyy", null), valuta);
// if (kurs != 0.0)
// Label2.Text = kurs.ToString();
// else
// Label2.Text = "Nije pronadjen kurs";
// }
// }
//}
//namespace A10App
//{
// public partial class azuriranjeliste : System.Web.UI.Page
// {
// protected void Page_Load(object sender, EventArgs e)
// {
// if (!this.IsPostBack)
// {
// Service1 servis = new Service1();
// List<string> valute = servis.ProcitajSveValute().ToList();
// for (int i = 0; i < valute.Count; i++)
// DropDownList1.Items.Add(valute[i]);
// }
// }
// protected void Button1_Click(object sender, EventArgs e)
// {
// string datum = TextBox1.Text;
// string valuta = DropDownList1.Text;
// string kurs = TextBox2.Text;
// Service1 servis = new Service1();
// servis.UpisiKursNaDan(DateTime.ParseExact(datum, "d/M/yyyy", null), valuta, Convert.ToDouble(kurs));
// }
// }
//}