I've recently been re-factoring my code to move from inproc to Session State. I've created a new class that I built from the start to be serializable. I'm currently getting the 'Unable to serialize the session state.' error. However, I am able to serialize the class using JsonConvert (newtonsoft).
Are methods not allowed or something?
This is what it looks like:
[Serializable()]
public class SessionStateObject
{
public int CurrentSessionId { get; set; }
public int CurrentAssessmentId { get; set; }
public int CurrentAssessmentElementId { get; set; }
public int CurrentUserId { get; set; }
public Dictionary<string, int> AssessmentItemsIds { get; set; }
public Dictionary<string, int> SessionResponseIds { get; set; }
public List<string> AdministeredItemOrderByName;
public string LastVisitedItem;
public int? TotalAssessmentCurrentItemOrder;
public RenderablePersistanceObject RenderablePersistance;
#region formula engine section variables
public string BranchingResult { get; set; }
public string ContentOutput { get; set; }
public int CurrentItemId { get; set; }
public int VirtualWorkingItemId { get; set; }
public bool isCloneItem { get; set; }
public bool wasPreFormulaRun;
public bool wasContentOutput;
public bool wasPrefillReached;
public bool isVirtual;
public List<string> FormulaStack { get; set; }
public List<string> ItemNameTokens { get; set; }
public string serializedJSContext { get; set; }
public string CloneSourceItem { get; set; }
public int itemsAbletoFastForwardThrough { get; set; }
#endregion
private Dictionary<int, int> itemIdByMultiGroupId; //key is itemId, val is groupId
private Dictionary<int, List<int>> MultiGroupIdByItemIds; //key is groupId, val is itemId
public SessionStateObject()
{
RenderablePersistance = new RenderablePersistanceObject();
AssessmentItemsIds = new Dictionary<string, int>();
SessionResponseIds = new Dictionary<string, int>();
AdministeredItemOrderByName = new List<string>();
FormulaStack = new List<string>();
ItemNameTokens = new List<string>();
itemIdByMultiGroupId = new Dictionary<int, int>();
MultiGroupIdByItemIds = new Dictionary<int, List<int>>();
}
public void initMultiItemGroups(Assessment assessment, NetScidDbContainer dbContext)
{
List<MultiItem> assessmentMultiItems = (from multi in dbContext.MultiItems
where multi.AssessmentId == assessment.Id
select multi).ToList();
List<int> uniqueGroupIds = new List<int>();
foreach (MultiItem mItem in assessmentMultiItems)
{
itemIdByMultiGroupId.Add(mItem.ItemId, mItem.GroupId);
if (!uniqueGroupIds.Contains(mItem.GroupId))
{
uniqueGroupIds.Add(mItem.GroupId);
}
}
foreach (int groupId in uniqueGroupIds)
{
List<int> ItemIds = (from itemGroup in assessmentMultiItems
where itemGroup.GroupId == groupId
orderby itemGroup.Id ascending
select itemGroup.ItemId).ToList();
MultiGroupIdByItemIds.Add(groupId, ItemIds);
}
}
public List<int> GetItemIdsFromSingleItemId(int itemId)
{
List<int> foundItemIDs = new List<int>();
int foundGroupId = -1;
if (this.itemIdByMultiGroupId.ContainsKey(itemId))
{
foundGroupId = this.itemIdByMultiGroupId[itemId];
}
if (this.MultiGroupIdByItemIds.ContainsKey(foundGroupId))
{
foundItemIDs = this.MultiGroupIdByItemIds[foundGroupId];
}
return foundItemIDs;
}
public void nullifyRenderable()
{
this.RenderablePersistance = null;
}
public void PersistRenderable(IRenderable renderable)
{
this.RenderablePersistance = new RenderablePersistanceObject();
if (renderable is MultiItemRenderable)
{
//get list of item IDs from the multi-item lookup
this.RenderablePersistance.isMultiItem = true;
this.RenderablePersistance.primaryItemId = ((Item)((MultiItemRenderable)renderable).IndexedItems.Last()).Id;
}
else //regular renderable
{
this.RenderablePersistance.isMultiItem = false;
this.RenderablePersistance.primaryItemId = ((Item)renderable).Id;
}
}
public AssessmentRuntime StartAdministrativeSession(NetScidDbContainer dataContext, Assessment assessment, User currentUser, string pid = "1")
{
AssessmentRuntime newRuntime = new AssessmentRuntime(this, dataContext);
Session newSession = new Session();
assessment.PrepElements();
PermissionEntity rootPE = new PermissionEntity();
if (currentUser != null)
{
rootPE = PermissionEntityHelper.GetRootPermissionEnity(dataContext, currentUser);
}
else
{
rootPE = (from adminpe in dataContext.PermissionEntities
where adminpe.Name == "TelesageAdmin"
select adminpe
).FirstOrDefault();
}
newSession.Participant = (from pids in dataContext.ParticipantIdAliasLookups
where pid == pids.AliasId && pids.RootPermissionEntity.Id == rootPE.Id
select pids.Participant).FirstOrDefault();
if (newSession.Participant == null)
{
Participant newParticipant = new Participant();
ParticipantIdAliasLookup newPidAlias = new ParticipantIdAliasLookup();
newParticipant.ParticipantDataJSON = "";
newPidAlias.AliasId = pid;
newPidAlias.RootPermissionEntity = rootPE;
newParticipant.AliasLookup = newPidAlias;
newParticipant.PermissionEntities.Add(currentUser.PermissionEntity);
newParticipant.PermissionEntities.Add(rootPE);
newSession.Participant = newParticipant;
dataContext.Participants.AddObject(newParticipant);
dataContext.ParticipantIdAliasLookups.AddObject(newPidAlias);
}
newSession.Assessment = assessment;
newSession.User = currentUser;
newSession.StartTime = DateTime.Now;
newSession.PermissionEntity = currentUser.PermissionEntity;
newSession.SetSessionData("engineversion", typeof(SmartQWeb.MvcApplication).Assembly.GetName().Version.ToString());
newSession.SetSessionData("assessmentname", newSession.Assessment.Name);
newSession.SetSessionData("assessmentversion", newSession.Assessment.Version);
newSession.SetSessionData("computername", Environment.MachineName);
newSession.SetSessionData("username", currentUser.Name);
dataContext.Sessions.AddObject(newSession);
newSession.SetSessionData("dxdata", JsonConvert.SerializeObject(newRuntime.RenderedDiagnoses));
newRuntime.formulaEngine = new FixedLengthFormulaEngine(newRuntime);
SessionLog newSessionLog = new SessionLog();
dataContext.SessionLogs.AddObject(newSessionLog);
newSession.SessionLog = newSessionLog;
dataContext.SaveChanges();
initMultiItemGroups(assessment, dataContext);
this.CurrentSessionId = newSession.Id;
this.CurrentUserId = currentUser.Id;
this.CurrentAssessmentId = assessment.Id;
newRuntime.Context = new RuntimeContext(this, dataContext);
this.GetAssessmentItems(assessment); //to populate the items dict
newRuntime.formulaEngine.InitializeContext(this.AssessmentItemsIds.Keys.ToList());
newRuntime.RenderedDiagnoses = new RenderedDiagnosisModel(newRuntime.Context.AdministeredItemOrderByName);
newRuntime.Context.Logger.WriteLog("Session started with assessment: " + newRuntime.Context.Assessment.Name + " with version: " + newRuntime.Context.Assessment.Version);
newRuntime.Context.Logger.WriteLog("Session started by user: " + newRuntime.Context.CurrentUser.Name + "for participant ID: " + newSession.ParticipantId);
return newRuntime;
}
//start from a previous existing session
public AssessmentRuntime StartAdministrativeSession(NetScidDbContainer dataContext, Assessment assessment, Session previousSession, User currentUser, string pid = "", string resumefromlatest = "false")
{
AssessmentRuntime newRuntime = new AssessmentRuntime(this, dataContext);
Session newSession = new Session();
Assessment sessionAssessment = assessment;
newSession.ParticipantId = previousSession.ParticipantId;
//THE OTHER ENTITIES BESIDES THE SESSION NEED TO BE DETATCHED AND RE-ATTACHED (BY BEING ADDED TO THE NEW SESSION)
assessment.PrepElements();
newRuntime.RenderedDiagnoses = new RenderedDiagnosisModel(newRuntime.Context.AdministeredItemOrderByName);
List<Response> prevresponses = previousSession.Responses.ToList();
if (sessionAssessment == assessment)
{
foreach (Response prevresponse in prevresponses)
{
newRuntime.Context.CachedAssessmentResponses.Add(prevresponse.Item.ItemName, prevresponse);
dataContext.Detach(prevresponse);
newSession.Responses.Add(prevresponse);
}
}
else
{
//the sessionAssessment is now the more up-to-date one so the responses pulled will have to be mapped, not just detatched and copied
foreach (Response prevresponse in prevresponses)
{
Dictionary<string, FixedLengthItem> newAssessmentItemNames = AssessmentHelper.GetAssessmentItems(sessionAssessment);
if (!newAssessmentItemNames.ContainsKey(prevresponse.Item.ItemName))
continue;
Response newResponse = new Response
{
NumericValue = prevresponse.NumericValue,
Item = newAssessmentItemNames[prevresponse.Item.ItemName],
ItemName = prevresponse.Item.ItemName,
AdministeredOrder = -1,
Value = prevresponse.Value
};
newRuntime.Context.CachedAssessmentResponses.Add(newResponse.Item.ItemName, newResponse);
newSession.Responses.Add(newResponse);
}
}
newSession.SessionDataJSON = previousSession.SessionDataJSON;
//DxData
newRuntime.RenderedDiagnoses =
JsonConvert.DeserializeObject<RenderedDiagnosisModel>(newSession.GetSessionData("dxdata"));
//inc session is =2 when the the session has been resumed by
previousSession.IncSession = 2;
newSession.SetSessionData("previoussession", previousSession.Id.ToString());
newSession.Participant = previousSession.Participant;
newSession.Assessment = sessionAssessment;
newSession.User = currentUser;
newSession.PermissionEntity = currentUser.PermissionEntity;
newSession.StartTime = DateTime.Now;
dataContext.Sessions.AddObject(newSession);
dataContext.SaveChanges();
newRuntime.formulaEngine = new FixedLengthFormulaEngine(newRuntime);
initMultiItemGroups(assessment, dataContext);
newSession.SetSessionData("continuedsession", newSession.Id.ToString());
this.CurrentSessionId = newSession.Id;
this.CurrentUserId = currentUser.Id;
this.CurrentAssessmentId = assessment.Id;
this.GetAssessmentItems(assessment); //to populate the items dict
this.SetUpPreviousResponses(newSession); //populates SSO responses
newRuntime.Context = new RuntimeContext(this, dataContext);
if (newRuntime.RenderedDiagnoses != null)
newRuntime.RenderedDiagnoses.reInitAdminOrder(newRuntime.Context.AdministeredItemOrderByName);
newRuntime.formulaEngine.InitializeContext(this.AssessmentItemsIds.Keys.ToList());
return newRuntime;
}
//start from the SSO
public AssessmentRuntime ResumeSessionFromState(NetScidDbContainer dataContext)
{
AssessmentRuntime newRuntime = new AssessmentRuntime(this, dataContext);
newRuntime.formulaEngine = new FixedLengthFormulaEngine(newRuntime);
newRuntime.formulaEngine.InitializeSerializedContext(serializedJSContext);
newRuntime.Context = new RuntimeContext(this, dataContext);
if (this.CurrentAssessmentElementId != 0)
{
newRuntime.CurrentAssessmentElement = (from ae in dataContext.AssessmentElements
where ae.Id == this.CurrentAssessmentElementId
select ae).FirstOrDefault();
newRuntime.CurrentAssessmentElement.GetNewRuntime(newRuntime.Context);
}
return newRuntime;
}
private void GetAssessmentItems(Assessment assessment)
{
var fixedLengthElements = (from elements in assessment.AssessmentElements
where elements is FixedLengthBlock
select elements);
foreach (FixedLengthBlock elemblock in fixedLengthElements)
{
foreach (FixedLengthItem item in elemblock.ItemBank.Items)
{
item.aeRef = elemblock;
AssessmentItemsIds.Add(item.ItemName, item.Id);
}
}
}
private void SetUpPreviousResponses(Session newSession)
{
//put response IDs by itemname into this dictionary
SessionResponseIds = (from response in newSession.Responses
select response).ToDictionary(key => key.ItemName, value => value.Id);
}
}
And the RenderablePersistanceObject looks like this:
public class RenderablePersistanceObject
{
public int primaryItemId;
public int MultiItemGroupId;
public bool isMultiItem;
}
You can't serialize a straight Dictionary like that. You can take a look at this MSDN article for suggestions on implementing. If you don't truly need a Dictionary, perhaps List> might work better?
As Erik pointed out, it was the lack of the adorner [Serializable()] on that other object that caused the problem. Adding it solved my issue.
Related
I'm Having a problem with my query
HighScoreGrammarI
-- getting data from sqlite
private void GetGrammarIScore()
{
highScores.Clear();
using (IDbConnection dbConnection = new SqliteConnection(Connection))
{
dbConnection.Open();
using (IDbCommand dbCmd = dbConnection.CreateCommand())
{
string select = String.Format("Select Hs_date, Hs_answer, Hs_score from Highscores_data where Hs_stage = 'GrammarI' and Hs_name = (\"{0}\")", Username.text);
dbCmd.CommandText = select;
using (IDataReader reader = dbCmd.ExecuteReader())
{
while (reader.Read())
{
highScores.Add(new HighScore(reader.GetDateTime(0), reader.GetInt32(1), reader.GetInt32(2)));
}
}
}
}
}
-- showing data using the get data void
private void showGrammarI()
{
GetGrammarIScore();
for (int i = 0; i < highScores.Count; i++)
{
GameObject tmpobjec = Instantiate(ScorePrefab);
HighScore tmpScore = highScores[i];
tmpobjec.GetComponent<HighscoreScript>().SetScore(tmpScore.Date.ToString(), tmpScore.CorrectAnswer.ToString(), tmpScore.Score.ToString());
}
}
HighscoreScript
public GameObject Date;
public GameObject CorrectAnswer;
public GameObject Score;
public void SetScore(string date, string correctanswer, string score)
{
this.Date.GetComponent<Text>().text = date;
this.CorrectAnswer.GetComponent<Text>().text = correctanswer;
this.Score.GetComponent<Text>().text = score;
}
HighScore
public DateTime Date { get; set; }
public int CorrectAnswer { get; set; }
public int Score { get; set; }
public HighScore(DateTime date, int correctanswer, int score)
{
this.Date = date;
this.CorrectAnswer = correctanswer;
this.Score = score;
}
THE ERROR IS HERE:
InvalidCastException: Cannot cast from source type to destination type.
Mono.Data.Sqlite.SqliteDataReader.VerifyType (Int32 i, DbType typ)
Mono.Data.Sqlite.SqliteDataReader.GetDateTime (Int32 i)HighScoreGrammarI.GetGrammarIScore () (at Assets/Script/HighScoreGrammarI.cs:73) >> this line is inside the while query in HighscoreGrammarI
So, I recently found quite an issue with my site: when it first loads, a section of the website is missing. After some tests, I found that this line was sometimes false: #if (Model != null && Model.Any()). After a test using a single Modal == null, I found that yes, the issue is that it's sometimes null. Also, I found that the best way for me to reproduce the issue (no error messages) is to restart visual studio. CTRL + F5 does not make it be null. Any ideas why is that ?
Here's the Model and the part of cshtml:
public class BlogModel
{
public int Id { get; set; }
public bool AfficheAuteur { get; set; }
public string Alias { get; set; }
public string Sujet { get; set; }
public string Auteur { get; set; }
public string Photo { get; set; }
public int? Ordre { get; set; }
public PostModel Post { get; set; }
}
public class PostModel
{
public int Id { get; set; }
public string Alias { get; set; }
public string Nom { get; set; }
}
//.cshtml:
#model IList<Project.Models.Shared.BlogModel>
//...
#if (Model != null && Model.Any())
//...
Note that I'm using asp.net Core MVC with razor.
Edit:
public static IList<BlogModel> GetBlogs()
{
var _lock = new object();
var strKey = string.Format("Home-Blogs-{0}", Site.Id);
var blogs = (IList<BlogModel>)CacheManager.Get(strKey);
if (blogs == null)
{
lock (_lock)
{
blogs = (IList<BlogModel>)CacheManager.Get(strKey);
if (blogs == null)
{
using (var context = new DB())
{
context.Configuration.LazyLoadingEnabled = false;
var nIdSite = Site.Id;
var bl = (from b in context.Blog
where b.Actif &&
(b.IdsSite.Contains("," + nIdSite + ",")) &&
b.Posts.Any(y => y.Publier)
orderby b.Ordre
select new BlogModel()
{
Id = b.Id,
AfficheAuteur = b.AfficherAuteur,
Alias = b.Alias,
Sujet = b.Sujet,
Photo = b.Image,
Auteur = b.User.Profile.FirstName + " " + b.User.Profile.LastName,
Ordre = b.Ordre,
Post = (from p in context.BlogPost
where p.Publier &&
p.IdBlog == b.Id &&
p.DateAffichage <= DateTime.Now
orderby p.DateAffichage descending
select new PostModel()
{
Id = p.Id,
Alias = p.Alias,
Nom = p.Nom
}).FirstOrDefault()
}).ToList();
CacheManager.Insert(strKey, bl, null, 10800, Cache.NoSlidingExpiration, CacheItemPriority.High, null);
return blogs;
}
}
}
}
return blogs;
}
public ActionResult Index(GridSettings settings, string strQuery)
{
var model = new IndexBlogViewModel(settings, blogService, strQuery);
ViewBag.FilAriane.Add(new KeyValuePair<string, string>(Url.Action("Index", "Home"), "Accueil"));
ViewBag.FilAriane.Add(new KeyValuePair<string, string>("", "Blogs"));
return View(model);
}
[HttpGet]
public ActionResult Create()
{
var model = new BlogFormViewModel { Blog = new Entitie.Blog { IdSite = IdSite } };
var lstUser = new List<User>();
var cfUserProvider = new CFUserProvider();
foreach (var mu in cfUserProvider.GetAllUsers().Cast<MembershipUser>())
{
var r = new CFRoleProvider();
if (r.IsUserInRole(mu.UserName, "Bloggeur"))
{
var u = new User { Username = mu.UserName, Id = Convert.ToInt32(mu.ProviderUserKey) };
lstUser.Add(u);
}
}
model.User = lstUser.Select(x => new SelectListItem
{
Text = x.Username,
Value = x.Id.ToString()
});
model.Sites = siteService.GetAll(x => x.IdEntreprise == IdEntreprise)
.Select(x => new CheckBoxListItem
{
Id = x.Id,
Display = x.Nom,
IsChecked = false
}).ToList();
ViewBag.FilAriane.Add(new KeyValuePair<string, string>(Url.Action("Index", "Home"), "Accueil"));
ViewBag.FilAriane.Add(new KeyValuePair<string, string>("", "Blog"));
return View(model);
}
Found it... It was checking for null and if it was, was adding it to cache but still returning the non-updated variable. Simply had to update it before returning...
Added:
blogs = (IList<BlogModel>)CacheManager.Get(strKey);
before returning.
I have a List<Semesters> Object and Semesters class has Semester as String[] type. Below is my code which has error where Semester[1]= item.Semester. What is the correct syntax?
public class CourseList
{
public int? Prog_id { get; set; }
public List<Semesters> Series{ get; set; }
}
public class Semesters
{
public string[] Semester { get; set; }
public string Subject { get; set; }
public int Credit {get; set;}
}
[HttpGet]
[AllowAnonymous]
public CourseList GetCourseList(int Progid)
{
using (var context = new DataContext())
{
CourseList Obj = new CourseList();
List<Semesters> CObj = new List<Semesters>();
var qry = (from a in context.Courses
where a.Prog_id == Progid
orderby a.Semester
select a).ToList();
foreach (var item in qry)
{
Obj.Prog_id = item.Prog_id;
if (item.Semester.ToString() == "1st Semester")
{
CObj.Add(new Semesters {Semester[1]=item.Semester, Subject = item.Subject.ToString(), Coursetitle= item.Coursetitle });
}
if (item.Semester.ToString() == "2nd Semester")
{
CObj.Add(new Semesters { Semester[2] = item.Semester, Subject = item.Subject.ToString(), Coursetitle = item.Coursetitle });
}
Obj.Series = CObj;
}
return Obj;
}
You say Semester is an array of strings, so in this statement
Semester[1] = item.Semester
Semester is an array and item.Semester is an array.
Semester[1] should be assigned a string, but you are assigning it an array. You'll need to change it to (possibly...)
// assign a value from the item.Semester array.
Semester[1] = item.Semester[n]
That's one possibility w/o more info.
Dears,
I am implementing load more items to listview without a button.
My code:
public partial class DashBoardPage : ContentPage
{
ObservableCollection<string> Items;
bool isLoading;
public DashBoardPage()
{
InitializeComponent();
Items = new ObservableCollection<string>();
var listview = new ListView();
listview.ItemsSource = Items;
listview.ItemAppearing += (sender, e) =>
{
if (isLoading || Items.Count == 0)
return;
//hit bottom!
if (e.Item.ToString() == Items[Items.Count - 1])
{
LoadItems();
}
};
LoadItems();
}
public async void LoadItems()
{
isLoading = true;
HttpClient client = new HttpClient();
var response = await client.GetAsync("My Url");
string tweetJson = await response.Content.ReadAsStringAsync();
UserTweetResponse userTweetResponse = new UserTweetResponse();
if (tweetJson != "")
{
userTweetResponse = JsonConvert.DeserializeObject<UserTweetResponse>(tweetJson.ToString());
foreach (var tweet in userTweetResponse.userTweetsList)
{
Items.Add(tweet.ToString());
}
}
ListView1.ItemsSource = userTweetResponse.userTweetsList;
isLoading = false;
}
}
I refer the following link and confused with the for loop inside LoadItems():
https://montemagno.com/load-more-items-at-end-of-listview-in/
for (int i = 0; i < 20; i++)
{
Items.Add (string.Format("Item {0}", Items.Count));
}
In my case I am using itemSource property to bind the response to list view.
My model class:
public class UserTweetResponse
{
public List<UserTweetsList> userTweetsList { get; set; }
}
public class UserTweetsList
{
public int tweetId { get; set; }
public string tweetData { get; set; }
public string createdTime { get; set; }
public int commentCount { get; set; }
public int likeCount { get; set; }
public int flagCount { get; set; }
public string mediaUrl { get; set; }
public string tweetUser { get; set; }
public bool userLiked { get; set; }
public bool userFlagged { get; set; }
public bool isMediaUrlNull { get { return string.IsNullOrEmpty(mediaUrl); } }
}
How can I fix this?
Thanks in advance
You need to add your new tweets to your Items collection
public async void LoadItems()
{
isLoading = true;
HttpClient client = new HttpClient();
var response = await client.GetAsync("My Url");
string tweetJson = await response.Content.ReadAsStringAsync();
UserTweetResponse userTweetResponse = new UserTweetResponse();
if (tweetJson != "")
{
userTweetResponse = JsonConvert.DeserializeObject<UserTweetResponse>(tweetJson.ToString());
foreach (var tweet in userTweetResponse.userTweetsList)
{
Items.Add(tweet);
}
}
isLoading = false;
}
because the Observable collection is the ListView item source the new items will appear in the list.
Pasete this whole:
using System;
using System.Diagnostics;
using System.Net.Http;
using Newtonsoft.Json;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
namespace SmartTweet
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class DashBoardPage : ContentPage
{
int i = 1;
bool loadMore;
ObservableCollection<UserTweetsList> Items =new ObservableCollection<SmartTweet.UserTweetsList>();
bool isLoading;
UserTweetResponse userTweetResponse;
public DashBoardPage()
{
InitializeComponent();
ListView1.ItemAppearing += (sender, e) =>
{
if (isLoading || Items!=null && Items.Count == 0)
return;
//hit bottom
if (userTweetResponse.userTweetsList!=null && userTweetResponse.userTweetsList.Count>0)
{
UserTweetsList item = userTweetResponse.userTweetsList[userTweetResponse.userTweetsList.Count - 1];
if ((e.Item as UserTweetsList).tweetId.ToString() == item.tweetId.ToString())
{
Debug.WriteLine("Enter bottom");
loadMore = true;
UserTweetsList();
}
}
};
}
protected async override void OnAppearing()
{
await UserTweetsList();
base.OnAppearing();
}
async void ButtonClicked(Object sender, EventArgs e)
{
loadMore = true;
// await UserTweetsList();
}
public async Task UserTweetsList()
{
isLoading = true;
if (loadMore)
{
i = i + 1;
}
int countInInt = i * 3;
try
{
string applicationId = "1";
string siteId = "5";
string userId = "225";
string ownedBy = "me";
string period = "before";
string count = countInInt.ToString();
DateTime dt = DateTime.Now.ToLocalTime();
string date = dt.Year.ToString() + "-" + dt.Month.ToString() + "-" + dt.Day.ToString() + " " + dt.Hour.ToString() + ":" + dt.Minute.ToString() + ":" + dt.Second.ToString() + "." + dt.Millisecond.ToString();
HttpClient client = new HttpClient();
var response = await client.GetAsync("web service url");
string tweetJson = await response.Content.ReadAsStringAsync();
Debug.WriteLine("tweetList:>" + tweetJson);
userTweetResponse = new UserTweetResponse();
if (tweetJson != "")
{
userTweetResponse = JsonConvert.DeserializeObject<UserTweetResponse>(tweetJson.ToString());
foreach (var tweet in userTweetResponse.userTweetsList)
{
if (!Items.Contains(tweet))
{
Items.Add(tweet);
}
//Items.Add(tweet.ToString());
}
}
ListView1.ItemsSource = userTweetResponse.userTweetsList;
isLoading = false;
if (userTweetResponse.userTweetsList.Count == 0)
{
//loadMoreButton.IsVisible = false;
blue_holo_circle.IsVisible = false;
blueLine.IsVisible = false;
}
else
{
//loadMoreButton.IsVisible = true;
blue_holo_circle.IsVisible = true;
blueLine.IsVisible = true;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception:>" + ex);
}
}
}
}
This is my first time creating a web service. I am not sure if my implementation is incorrect, but I am trying to use much like a class. The problem is that when I am trying to consume I am getting confused and not being able to set the values of the properties.
here is the web service.
public class Service1 : System.Web.Services.WebService
{
private bool _isUserActive { get; set; }
private bool _isCredentialValid { get; set; }
public string email { get; set; }
public string pass { get; set; }
public int customerID { get; set; }
[WebMethod]
public bool VerifyUserCredential()
{
bool result = false;
PURLDataContext purl = new PURLDataContext();
try
{
var res = purl.Sel_User(email.ToLower(), pass);
if (res != null)
result = true;
_isUserActive = true;
_isCredentialValid = true;
}
catch (Exception ex)
{
if (ex.Message == "Account is inactive, please contact your administrator!")
{
_isUserActive = false;
_isCredentialValid = false;
}
else
_isCredentialValid = false;
//Invalid credentials.
}
return result;
}
[WebMethod]
public ArrayList retrieveCustomerInfo()
{
ArrayList customerInfo = new ArrayList();
string validate = "Please Validate";
if (_isCredentialValid)
{
PURLDataContext purl = new PURLDataContext();
var customer = purl.Sel_Recipient(customerID);
foreach (var c in customer)
{
customerInfo.Add(c);
}
}
else
customerInfo.Add(validate);
return customerInfo;
}
}
Here is what I am trying to do to consume.
PURLServices.Service1SoapClient webserv = new Service1SoapClient();
bool result;
ArrayOfAnyType array = new ArrayOfAnyType();
webserv.email = "email#email.com";
webserv.pass = "pass";
webserv.customerID = 12345;
result = webserv.VerifyUserCredential();
array = webserv.retrieveCustomerInfo();
Thank you for any help/
You do not want to try to use properties like this. Your method should look more like this:
public bool VerifyUserCredential(string userName, string password)
{
// method body here
}
Probably you would want to return an access token of some sort that the server will cache. This can then be passed into other methods to show that the user is valid.