Json request error instead of regular error - websocket

Trying to connect to https://www.xbtce.com via WebSocket (WebSocketSharp)
enter link description here
Here is the login json model
{
"Id": <some unique Id>,
"Request": "Login",
"Params": {
"AuthType": "HMAC",
"WebApiId": <Web API Id>,
"WebApiKey": <Web API Key>,
"Timestamp": <timestamp (e.g. Date.now())>,
"Signature": <signature>,
"DeviceId": <Device Id>
}
}
Here's my code which always gives
{
"Response": "Error",
"Error": "Cannot parse JSON request!"
}
instead of normal response
{
"Id": <your unique Id>,
"Response": "Error",
"Error": <error description from TickTrader Server>
}
My code
private static WebSocket socket = new WebSocket("wss://cryptottlivewebapi.xbtce.net:3020");
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
socket.OnMessage += Socket_OnMessage;
socket.OnOpen += socket_Opened;
socket.OnError += socket_Error;
socket.Connect();
socket.OnClose += socket_Closed;
}
private void Socket_OnMessage(object sender, MessageEventArgs e)
{
if (e.IsText)
{
MessageBox.Show(e.Data.ToString());
}
else
{
MessageBox.Show(e.RawData.ToString());
}
}
private void socket_Closed(object sender, EventArgs e)
{
throw new NotImplementedException();
}
private void socket_Error(object sender, ErrorEventArgs e)
{
MessageBox.Show(e.Exception.ToString());
}
private void socket_Opened(object sender, EventArgs e)
{
string jsonSerialized = JsonConvert.SerializeObject(GetLogin()).ToString() ;
MessageBox.Show(jsonSerialized);
socket.Send(jsonSerialized);
}
LoginParams GetLogin()
{
return new LoginParams
{
Id = Guid.NewGuid().ToString(),
Request = "Login",
Params = new Parameters
{
AuthType = "HMAC",
WebApiId = "my id",
WebApiKey = "my api key",
Timestamp = ((Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds).ToString(),
Signature = Hmac.CreateToken(((Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds).ToString(), "2058e846-0a32-49b9-bc8f-4e28afd0aa9c", "my id", "my key").ToString(),
DeviceId = "WebBrowser"
}
};
}
public static double DateTimeToUnixTimestamp(DateTime dateTime)
{
return (TimeZoneInfo.ConvertTimeToUtc(dateTime) -
new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;
}
}
public static class Hmac
{
public static string CreateToken(string timestamp, string id , string key, string secret)
{
string message = timestamp + id + key;
secret = secret ?? "";
var encoding = new System.Text.ASCIIEncoding();
byte[] keyByte = encoding.GetBytes(secret);
byte[] messageBytes = encoding.GetBytes(message);
using (var hmacsha256 = new HMACSHA256(keyByte))
{
byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
return Convert.ToBase64String(hashmessage);
}
}
}
public class LoginParams
{
public string Id { get; set; }
public string Request { get; set; }
public Parameters Params { get; set; }
}
public class Parameters
{
public string AuthType {
get; set; }
public string WebApiId { get; set; }
public string WebApiKey { get; set; }
public string Timestamp {
get; set; }
public string Signature { get; set; }
public string DeviceId { get; set; }
}
Json serialization output
{
"Id": "be078b3d-2eb8-475a-97fb-89aedf775b78",
"Request": "Login",
"Params": {
"AuthType": "HMAC",
"WebApiId": "myid",
"WebApiKey": "mykey",
"Timestamp": "1467486605",
"Signature": "NbREH0HkPadfuDESuGEHho/FwX+DFdIoCV/D5aW/gv8=",
"DeviceId": "WebBrowser"
}
}
Thanks in advance

Finally found the problem it seems that the time stamp should not be a string but a long
LoginParams GetLogin()
{
return new LoginParams
{
Id = Guid.NewGuid().ToString(),
Request = "Login",
Params = new Parameters
{
AuthType = "HMAC",
WebApiId = "my id",
WebApiKey = "my api key",
Timestamp = ((long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds).ToString(),
Signature = Hmac.CreateToken(((long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds), "2058e846-0a32-49b9-bc8f-4e28afd0aa9c", "my id", "my key").ToString(),
DeviceId = "WebBrowser"
}
};
}

Related

Cannot deserialize the current JSON object into type ObservableCollection because the type requires a JSON array

I'm trying to display a search result API in a ListView.
This is the model which I want to display in the ListView:
public class Video
{
[Key]
public int VideoId { get; set; }
public string Exercice { get; set; }
public string Titre { get; set; }
public int Sexe{ get; set; }
public int Categorie { get; set; }
public int Level { get; set; }
public string FilePath { get; set; }
public DateTime DateUpload { get; set; } = DateTime.Now;
[ForeignKey("Machine")]
public int Machine_Qr { get; set; }
}
This is the get method:
public async Task<ObservableCollection<Video>> search(string qr)
{
string url = Base_url + "machines/" +qr;
try
{
HttpClient client = new HttpClient();
HttpResponseMessage responseMessage = await client.GetAsync(url);
var result = await responseMessage.Content.ReadAsStringAsync();
var json = JsonConvert.DeserializeObject<ObservableCollection<Video>>(result);
return json;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return null;
}
the result json value:
[
{
"videoId": 7,
"exercice": "string",
"titre": "string",
"sexe": 0,
"categorie": 0,
"level": 0,
"filePath": "string",
"dateUpload": "2022-07-07T13:13:39.725",
"machine_Qr": 7895,
"machine": null
}
]
This is the View.cs
public partial class SearchResult : INotifyPropertyChanged
{
IMachineService _rest = DependencyService.Get<IMachineService>();
public SearchResult(string value)
{
InitializeComponent();
qr.Text = value;
GetVideos();
}
public async void GetVideos()
{
string value = qr.Text;
var result = await _rest.search(value);
if (result != null)
{
Videos = result;
}
}
public ObservableCollection<Video> videos;
public ObservableCollection<Video> Videos
{
get { return videos; }
set
{
videos = value;
}
}
but I got an exception while debugging this line in the service
HttpResponseMessage responseMessage = await client.GetAsync(url);
and this is the detailed exception:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.ObjectModel.ObservableCollection`1[App5.Models.Video]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'type', line 1, position 8.
Do this as a test:
public ObservableCollection<Video> search(string qr)
{
try
{
var result = "[ { \"videoId\": 7, \"exercice\": \"string\", \"titre\": \"string\","
+ " \"sexe\": 0, \"categorie\": 0, \"level\": 0, \"filePath\": \"string\","
+ " \"dateUpload\": \"2022-07-07T13:13:39.725\", \"machine_Qr\": 7895, \"machine\": null } ]";
var json = JsonConvert.DeserializeObject<ObservableCollection<Video>>(result);
return json;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return null;
}
Put breakpoint on both return statements. To make sure this really is the code that is giving the error. Which breakpoint does it hit now? Does it print the same exception message?

How to get Auth code in api call post on ruby on rails app from wix api website?

I'm trying to developing a dashboard website for a wix application and I need to connect the website to the wix application.
I have a problem with an api (post) call. I have to fill in several information including the auth code that I don't know where to find.
Here is an image to illustrate the process :
I don't really know what is the wix app marker install, but for the authorization request I did this
$url_oauth = "https://www.wix.com/oauth/access"
response = RestClient::Request.execute(url: $url_oauth, method: :post, body:{grant_type: "authorization_code",client_id:"APP_ID", client_secret:"Secret_key", code:"{Can not find what is this value}"})
#data = JSON.parse(response)
render json: response
Here is the documentation :
Could you help how and where to find this Auth code ?
You will need to make an intermediate web service that will accept webhooks from WIX.
I'll show you the example of C# ASP.Net Core.
STEP 1:
We are waiting for a token from WIX and if it is received, we make a redirect.
private const string AppID = "";
private const string ApiKey = "";
private const string UrlAccess = "https://www.wix.com/oauth/access";
HttpGet("WaitToken")]
public ActionResult GetToken([FromQuery] string token = "")
{
try
{
if (string.IsNullOrWhiteSpace(token))
{
string message = "Your message";
ModelState.AddModelError("TokenNotCorrect", message);
return BadRequest(ModelState);
}
string paramUrl = #"https://your web service/OAuth/api/check/WaitAuthCode";
string urlRedirect = $#"https://www.wix.com/installer/install?token={token}&appId={AppID}&redirectUrl={paramUrl}";
return RedirectPermanent(urlRedirect);
}
catch (WebException ex)
{
ModelState.AddModelError("GetTokenException", ex.Message);
return BadRequest(ModelState);
}
}
STEP 2:
We are waiting for the Auth Code to be received, provided that the user has confirmed the installation of the application.
[HttpGet("WaitAuthCode")]
public async Task<ActionResult> GetAuthCodeAsync([FromQuery] string code = "", string state = "", string instanceId = "")
{
try
{
if (string.IsNullOrWhiteSpace(code))
{
string message = "your message";
ModelState.AddModelError("AuthCodeNotCorrect", message);
return BadRequest(ModelState);
}
var token = new Token(code);
if (!GetAccessToken(ref token))
return BadRequest("your message RefreshToken");
var tokenBase = new TokenBase
{
AppID = instanceId,
Token = token.RefreshToken
};
db.Tokens.Add(tokenBase);
if(await db.SaveChangesAsync() == 0)
return BadRequest("your message");
string urlRedirect = $"https://www.wix.com/installer/token-received?access_token={token.AccessToken}";
return RedirectPermanent(urlRedirect);
}
catch (WebException ex)
{
ModelState.AddModelError("GetAuthCodeException", ex.Message);
return BadRequest(ModelState);
}
}
The AuthCode is valid for 10 minutes, we send a request to receive a Refresh Token. This token must be kept at home, as it will be required in the future to obtain an Access Token.
private bool GetAccessToken(ref Token token)
{
try
{
string json = JsonConvert.SerializeObject(token, Formatting.Indented);
var client = new RestClient(UrlAccess);
var request = new RestRequest();
request.Method = Method.POST;
request.AddHeader("Content-Type", "application/json");
request.AddParameter(string.Empty, json, "application/json", ParameterType.RequestBody);
var response = client.Post(request);
if (response == null)
return false;
token = JsonConvert.DeserializeObject<Token>(response.Content);
if (string.IsNullOrWhiteSpace(token.RefreshToken))
return false;
return !string.IsNullOrWhiteSpace(token.AccessToken);
}
catch (Exception ex)
{
return false;
}
}
Getting an Access Token from a client application:
[HttpGet("WaitAccessToken")]
public async Task<ActionResult<string>> GetAccessToken([FromQuery] string instance = "", string apiKey = "")
{
string message;
var tokenBase = await db.Tokens.FirstOrDefaultAsync(x => x.AppID == instance);
if (tokenBase == null)
{
message = "Your message";
ModelState.AddModelError("AppIdNotFound", message);
return NotFound(ModelState);
}
var token = new Token
{
GrantType = "refresh_token",
RefreshToken = tokenBase.Token
};
if (!GetAccessToken(ref token))
{
message = $"Your message";
ModelState.AddModelError("NotCorrectAccessToken", message);
return BadRequest(ModelState);
}
return new ObjectResult(token.AccessToken);
}
Model Token:
public class Token
{
public Token() { }
public Token(string code) { Code = code; }
[JsonProperty("grant_type")]
public string GrantType { get; set; } = "authorization_code";
[JsonProperty("client_id")]
public string ClientID { get; set; } = "";
[JsonProperty("client_secret")]
public string ClientSecret { get; set; } = "";
[JsonProperty("code")]
public string Code { get; set; }
[JsonProperty("refresh_token", NullValueHandling = NullValueHandling.Ignore)]
public string RefreshToken { get; set; }
[JsonProperty("access_token", NullValueHandling = NullValueHandling.Ignore)]
public string AccessToken { get; set; }
}
Model Instance:
public class Instance
{
[JsonProperty("instanceId")]
public string InstanceId { get; set; }
[JsonProperty("appDefId")]
public string AppDefId { get; set; }
[JsonProperty("signDate")]
public DateTime SignDate { get; set; }
[JsonProperty("uid")]
public string Uid { get; set; }
[JsonProperty("permissions")]
public string Permissions { get; set; }
[JsonProperty("demoMode")]
public bool DemoMode { get; set; }
[JsonProperty("siteOwnerId")]
public string SiteOwnerId { get; set; }
[JsonProperty("siteMemberId")]
public string SiteMemberId { get; set; }
[JsonProperty("expirationDate")]
public DateTime ExpirationDate { get; set; }
[JsonProperty("loginAccountId")]
public string LoginAccountId { get; set; }
}
Don't forget that to get an Access Token, you will need the application ID on the site where it is installed.
[HttpGet("WixInfo")]
public ActionResult GetWixInfo([FromQuery] string instance = "")
{
try
{
string message;
var base64 = instance.Split(".");
if (base64.Length != 2)
{
message = "Your message";
ModelState.AddModelError("InstanceNotCorrect", message);
return BadRequest(ModelState);
}
var base64EncodedBytes = Convert.FromBase64String(base64[1]);
string json = Encoding.Default.GetString(base64EncodedBytes);
var info = JsonConvert.DeserializeObject<Instance>(json);
message = $"Your message.AppID: {info.InstanceId}";
return Ok(message);
}
catch (Exception ex)
{
ModelState.AddModelError("GetWixInfoException", ex.Message);
return BadRequest(ModelState);
}
}
When a WIX application is launched by a user, you can get the ID of the running application.

Xamarin Forms consuming Web Service

I'm new in mobile apps and now developing an app with xamarin forms. There is a website which i developed with django (sqlite3 db), and now i'am trying to consume data from it and display in my mobile app in listvew. Any thoughts how to achieve it. I've tried this but it doesn't work. Should i use rest api?
public class LandingViewModel : INotifyPropertyChanged
{
private List<Dishes> _menuList { set; get; }
public List<Dishes> MenuList
{
get
{
return _menuList;
}
set
{
if(value != _menuList)
{
_menuList = value;
NotifyPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public LandingViewModel()
{
GetDataAsync();
}
private async void GetDataAsync()
{
HttpClient client = new HttpClient();
var response = await client.GetAsync("https://mysite.ru/project/");
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var menu = JsonConvert.DeserializeObject<List<Dishes>>(content);
MenuList = new List<Dishes>(menu);
}
}
models:
public class Dishes
{
public int id { get; set; }
public string description { get; set; }
public string image { get; set; }
public DateTime published { get; set; }
}
my database in django:
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('description', models.TextField(blank=True)),
('image', models.ImageField(blank=True, upload_to='pictures/')),
('published', models.DateTimeField(verbose_name='publishing date')),
],
),
]
i solved the problem
in postgresql database allowed remote connection: in postgresql.conf replaced line listen_addresses = 'localhost' with listen_addresses = '*'
allowed tcp\ip connection on port 5432
in my web api established connection width db
NpgsqlConnection connection;
public string _name;
public string _description;
public string _image;
private readonly MenuContext _context;
public MenuController(MenuContext context)
{
_context = context;
string connectionString = "Server=server; Port=5432; User Id=user;
Password=password; Database=database";
try
{
connection = new NpgsqlConnection(connectionString);
connection.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
NpgsqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM table";
try
{
NpgsqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
_name = reader[1].ToString();
_image = reader[2].ToString();
_description = reader[3].ToString();
_context.Menus.Add(new Menu { name = _name, description =
_description, image = "https://mysite.ru/media/" + _image });
_context.SaveChanges();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
// GET: api/Menu
[HttpGet]
public async Task<ActionResult<IEnumerable<Menu>>> GetMenus()
{
return await _context.Menus.ToListAsync();
}
code in my app:
private async void GetDataAsync()
{
HttpClient httpClient = new HttpClient();
var content = await httpClient.GetStringAsync("https://locahost/api/Menu");
var menu = JsonConvert.DeserializeObject<List<Dishes>>(content);
MenuList = new ObservableCollection<Dishes>(menu);
}
and then displayed it in listview

How to get associated name of linked resources in HAL

I am creating an API for project tasks. It has a TasksController as listed below. I am generating hypermedia using WebApi.Hal and the service supports hal+json and hal+xml media types also.
Following is the response I currently have for the GET request http://localhost:51910/api/tasks/1. In the response there is a list of links for priorities – but they don’t have associated name in the response (to show in the UI – like Low, Medium, High, etc.).
What is the best HAL approach for getting name of the priorities also, using WebApi.HAL?
Note: The list of priorities can be enhanced in the future.
Priority
public class Priority
{
public int PriorityID { get; set; }
public string PriorityName { get; set; }
public string Revision { get; set; }
public DateTime ApprovalDate { get; set; }
}
Controller
public class TasksController : ApiController
{
// GET api/values/5
[HttpGet]
public TaskRepresentation Get(int id)
{
Task selectedTask = TasksHelper.GetTask(id);
TaskRepresentation taskRepresentation = new TaskRepresentation(selectedTask);
return taskRepresentation;
}
//PUT For Setting Priority
[HttpPut]
[Route("api/tasks/{taskID}/priorities/{priorityID}")]
public TaskRepresentation PutSetPriority(int taskID, int priorityID)
{
Task selectedTask = TasksHelper.GetTask(taskID);
Priority selectedPriority = null;
List<Priority> allPriorities = TasksPrioritiesHelper.GetAllPriorities();
foreach (Priority p in allPriorities)
{
if (p.PriorityID == priorityID)
{
selectedPriority = p;
}
}
//Update Task
if (selectedPriority != null)
{
selectedTask.CurrentPriority = selectedPriority.PriorityName;
}
else
{
throw new Exception("Not available");
}
TaskRepresentation taskRepresentation = new TaskRepresentation(selectedTask);
return taskRepresentation;
}
[HttpGet]
[Route("api/tasks/{taskID}/priorities/{priorityID}")]
public Priority Get(int taskID, int priorityID)
{
Priority selectedPriority = null;
List<Priority> allPriorities = TasksPrioritiesHelper.GetAllPriorities();
foreach (Priority p in allPriorities)
{
if (p.PriorityID == priorityID)
{
selectedPriority = p;
}
}
return selectedPriority;
}
}
HAL Generation Related Classes
public static class LinkTemplates
{
public static class TaskLinks
{
public static Link TaskEntry { get { return new Link("self", "~/api/tasks/{taskID}"); } }
public static Link PriorityLink { get { return new Link("priorities", "~/api/tasks/{taskID}/priorities/{priorityID}"); } }
}
}
public class TaskRepresentation : Representation
{
Task theTask;
public int TaskID{get{return theTask.TaskID;}}
public string TaskName{get{return theTask.Name;}}
public string CurrentPriority{get{return theTask.CurrentPriority;}}
public string Category{get{return theTask.Category;}}
public TaskRepresentation(Task t)
{
theTask = t;
}
public override string Rel
{
get { return LinkTemplates.TaskLinks.TaskEntry.Rel; }
set { }
}
public override string Href
{
get { return LinkTemplates.TaskLinks.TaskEntry.CreateLink(new { taskID = theTask.TaskID }).Href; }
set { }
}
protected override void CreateHypermedia()
{
foreach (Priority p in theTask.PossiblePriorities)
{
Links.Add(LinkTemplates.TaskLinks.PriorityLink.CreateLink(new { taskID = theTask.TaskID, priorityID = p.PriorityID }));
}
}
}
HAL Specification mentions title - this will meet the requirement.
Following is the updated response.
{
"TaskID": 1,
"TaskName": "Task1",
"CurrentPriority": "Medium",
"Category": "IT",
"_links": {
"self": {
"href": "/api/tasks/1"
},
"priorities": [
{
"href": "/api/tasks/1/priorities/101",
"title": "Low"
},
{
"href": "/api/tasks/1/priorities/103",
"title": "High"
},
{
"href": "/api/tasks/1/priorities/104",
"title": "Critical"
}
]
}
}
WebAPI.HAL changes
protected override void CreateHypermedia()
{
foreach (Priority p in theTask.PossiblePriorities)
{
Link lnk = LinkTemplates.TaskLinks.PriorityLink.CreateLink(new { taskID = theTask.TaskID, priorityID = p.PriorityID });
lnk.Title = p.PriorityName;
Links.Add(lnk);
}
}
Code
public static class LinkTemplates
{
public static class TaskLinks
{
public static Link TaskEntry { get { return new Link("self", "~/api/tasks/{taskID}"); } }
//public static Link PriorityLink { get { return new Link("priorities", "~/api/tasks/{taskID}/priorities/{priorityID}"); } }
public static Link PriorityLink
{
get
{
Link l = new Link("priorities", "~/api/tasks/{taskID}/priorities/{priorityID}");
return l;
}
}
}
}
public class TasksController : ApiController
{
// GET api/values/5
[HttpGet]
public TaskRepresentation Get(int id)
{
Task selectedTask = TasksHelper.GetTask(id);
TaskRepresentation taskRepresentation = new TaskRepresentation(selectedTask);
return taskRepresentation;
}
//PUT For Setting Priority
[HttpPut]
[Route("api/tasks/{taskID}/priorities/{priorityID}")]
public TaskRepresentation PutSetPriority(int taskID, int priorityID)
{
Task selectedTask = TasksHelper.GetTask(taskID);
Priority selectedPriority = null;
List<Priority> allPriorities = TasksPrioritiesHelper.GetAllPriorities();
foreach (Priority p in allPriorities)
{
if (p.PriorityID == priorityID)
{
selectedPriority = p;
}
}
//Update Task
if (selectedPriority != null)
{
selectedTask.CurrentPriority = selectedPriority.PriorityName;
}
else
{
throw new Exception("Not available");
}
TaskRepresentation taskRepresentation = new TaskRepresentation(selectedTask);
return taskRepresentation;
}
[HttpGet]
[Route("api/tasks/{taskID}/priorities/{priorityID}")]
public Priority Get(int taskID, int priorityID)
{
Priority selectedPriority = null;
List<Priority> allPriorities = TasksPrioritiesHelper.GetAllPriorities();
foreach (Priority p in allPriorities)
{
if (p.PriorityID == priorityID)
{
selectedPriority = p;
}
}
return selectedPriority;
}
}
public class TaskRepresentation : Representation
{
Task theTask;
public int TaskID{get{return theTask.TaskID;}}
public string TaskName{get{return theTask.Name;}}
public string CurrentPriority{get{return theTask.CurrentPriority;}}
public string Category{get{return theTask.Category;}}
public TaskRepresentation(Task t)
{
theTask = t;
}
public override string Rel
{
get { return LinkTemplates.TaskLinks.TaskEntry.Rel; }
set { }
}
public override string Href
{
get { return LinkTemplates.TaskLinks.TaskEntry.CreateLink(new { taskID = theTask.TaskID }).Href; }
set { }
}
protected override void CreateHypermedia()
{
foreach (Priority p in theTask.PossiblePriorities)
{
Link lnk = LinkTemplates.TaskLinks.PriorityLink.CreateLink(new { taskID = theTask.TaskID, priorityID = p.PriorityID });
lnk.Title = p.PriorityName;
Links.Add(lnk);
}
}
}
public class Task
{
public string Name { get; set; }
public int TaskID { get; set; }
public string Category { get; set; }
public string CurrentPriority { get; set; }
public List<Priority> PossiblePriorities { get; set; }
}
public class Priority
{
public int PriorityID { get; set; }
public string PriorityName { get; set; }
public string Revision { get; set; }
public DateTime ApprovalDate { get; set; }
}
public static class TasksPrioritiesHelper
{
public static List<Priority> GetAllPriorities()
{
List<Priority> possiblePriorities = new List<Priority>();
Priority pLow = new Priority { PriorityID = 101, PriorityName = "Low" };
Priority pMedium = new Priority { PriorityID = 102, PriorityName = "Medium" };
Priority pHigh = new Priority { PriorityID = 103, PriorityName = "High" };
Priority pCritical = new Priority { PriorityID = 104, PriorityName = "Critical" };
possiblePriorities.Add(pLow);
possiblePriorities.Add(pMedium);
possiblePriorities.Add(pHigh);
possiblePriorities.Add(pCritical);
return possiblePriorities;
}
public static List<Priority> GetAdministrativePriorities()
{
List<Priority> possiblePriorities = new List<Priority>();
Priority pLow = new Priority { PriorityID = 101, PriorityName = "Low" };
Priority pHigh = new Priority { PriorityID = 103, PriorityName = "High" };
possiblePriorities.Add(pLow);
possiblePriorities.Add(pHigh);
return possiblePriorities;
}
public static List<Priority> GetPossiblePrioritiesForTask(Task t)
{
List<Priority> possibleTaskPriorities = new List<Priority>();
if (String.Equals(t.Category, "IT"))
{
possibleTaskPriorities = GetAllPriorities();
}
else
{
possibleTaskPriorities = GetAdministrativePriorities();
}
Priority currentTaskPriority = null;
foreach(Priority p in possibleTaskPriorities )
{
if(String.Equals(t.CurrentPriority,p.PriorityName ))
{
currentTaskPriority=p;
}
}
if(currentTaskPriority!=null)
{
possibleTaskPriorities.Remove(currentTaskPriority);
}
return possibleTaskPriorities;
}
}
public static class TasksHelper
{
public static Task GetTask(int id)
{
Task selectedTask = null;
List<Task> tasks = GetAllTasks();
foreach (Task t in tasks)
{
if(t.TaskID==id)
{
selectedTask = t;
}
}
return selectedTask;
}
public static List<Task> GetAllTasks()
{
List<Task> tasks;
tasks = new List<Task>();
Task t1 = new Task{Category = "IT",CurrentPriority = "Medium",Name = "Task1",TaskID = 1};
t1.PossiblePriorities = TasksPrioritiesHelper.GetPossiblePrioritiesForTask(t1);
tasks.Add(t1);
return tasks;
}
}

Object reference not set to an instance of an object in view model

I get this error:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 251: ManageAccount.Instance.GetUserAccounts(username), "accountID", "name", accountFrom);
Line 252:
Line 253: Currencies = new SelectList(
Line 254: ManageCurrency.Instance.getCurrencies(), "id", "name",_Account.currency1.id);
Line 255:
It gives the error in this viewModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using Common;
using Business;
using System.Web.Mvc;
using System.Web.Security;
using System.Runtime.Remoting.Contexts;
namespace internetBankingApplication.ViewModel
{
public class NewFixedAccountViewModel
{
private account _Account { get; set; }
private fixedAccount _FixedAccount { get; set; }
public SelectList AccountTypes { get; set; }
public SelectList Durations { get; set; }
public SelectList AccountFromList { get; set; }
public SelectList Currencies { get; set; }
public int ID
{
get
{
return _Account.accountID;
}
}
[Required]
[Display(Name = "Account Name")]
public string Name
{
get
{
return _Account.name;
}
set
{
_Account.name = value;
}
}
[Required]
[Display(Name = "Account From")]
public int accountFrom { get;set;}
public string AccountFromName
{
get
{
string result = string.Empty;
try
{
result = ManageAccount.Instance.GetAccountBYID(accountFrom).name;
}
catch { }
return result;
}
}
[Required]
[Display(Name = "Duration")]
public int duration
{
get
{
return _FixedAccount.duration;
}
set
{
_FixedAccount.duration = value;
}
}
public string durationName
{
get
{
string result = string.Empty;
try
{
result = ManageDuration.Instance.GetDurationById(_FixedAccount.duration).duration1;
}
catch { }
return result;
}
}
[Required]
[Display(Name = "Available Balance")]
public decimal AvailableBalance
{
get
{
return _Account.availableBalance;
}
set
{
_Account.availableBalance = value;
}
}
[Required]
[Display(Name = "Currency")]
public int currency
{
get
{
return _Account.currency;
}
set
{
_Account.currency = value;
}
}
public string CurrencyName
{
get
{
string result = string.Empty;
try
{
result = ManageCurrency.Instance.getTypesByID(_Account.currency).name;
}
catch { }
return result;
}
}
[Required]
[Display(Name = "Account Description")]
public string Description
{
get
{
return _Account.description;
}
set
{
_Account.description = value;
}
}
[Required]
[Display(Name = "Account Renew")]
public bool renew
{
get
{
if (_FixedAccount.renew == 0)
{
return false;
}
return true;
}
set
{
if (value == false)
{
_FixedAccount.renew = 0;
}
else
{
_FixedAccount.renew = 1;
}
}
}
public NewFixedAccountViewModel()
{
// AccountTypes = new SelectList(
//ManageAccountType.Instance.getTypes(), "id", "type", _Account.typeID);
string username = HttpContext.Current.User.Identity.Name.ToString();
AccountFromList = new SelectList(
ManageAccount.Instance.GetUserAccounts(username), "accountID", "name", accountFrom);
**Currencies = new SelectList(
ManageCurrency.Instance.getCurrencies(), "id", "name",_Account.currency1.id);** //Giving the error
Durations = new SelectList(
ManageDuration.Instance.GetAllDurations(), "id", "duration", _FixedAccount.duration);
}
public NewFixedAccountViewModel(string username)
{
AccountTypes = new SelectList(
ManageAccountType.Instance.getTypes(), "id", "type", _Account.typeID);
AccountFromList = new SelectList(
ManageAccount.Instance.GetUserAccounts(username), "accountID", "name", accountFrom);
Currencies = new SelectList(
ManageCurrency.Instance.getCurrencies(), "id", "name", _Account.currency);
Durations = new SelectList(
ManageDuration.Instance.GetAllDurations(), "id", "duration", _FixedAccount.duration);
}
public NewFixedAccountViewModel(int accountID, string username)
{
_Account = ManageAccount.Instance.GetAccountBYID(accountID);
_FixedAccount = ManageFixedAccount.Instance.GetFixedAccountByID(accountID);
AccountFromList = new SelectList(
ManageAccount.Instance.GetUserAccounts(username), "accountID", "name", accountFrom);
AccountTypes = new SelectList(
ManageAccountType.Instance.getTypes(), "id", "type", _Account.accountType);
Currencies = new SelectList(
ManageCurrency.Instance.getCurrencies(), "id", "name", _Account.currency);
Durations = new SelectList(
ManageDuration.Instance.GetAllDurations(), "id", "duration", _FixedAccount.duration);
}
}
}
The error message you are getting means that you are trying to call a method or property on a null value - which you can't do.
From what I can see, either ManageCurrency is null or ManageCurrency.Instance is null.
If ManageCurrency is null the call to the Property Instance fails, as null objects have no methods or properties. Similarly, if ManageCurrency.Instance is null, the call to the Method getCurrencies fails for the same reason.
In any case - this is not too hard to debug. As skumar suggests, set a breakpoint on that line, run in debug mode, and see where the null value is, and then work backwards to discover why the value is null.
The username you are passing in the following code could be Empty or Invalid. That is why it returns NULL and above exception occurs.
AccountFromList = new SelectList(
ManageAccount.Instance.GetUserAccounts(username), "accountID", "name", accountFrom);

Resources