GridControl (GridView) returns no rows - c#

EDIT: Fixed.. I believe the problem was fixed by going to Add New Item -> Persistent Classes 11.2 and adding a new persistent class through the wizard. Then I just copied the code from that and put it in my Form1 code. Works!
I was following this page very closely: http://documentation.devexpress.com/#WindowsForms/CustomDocument3265
I tried both ways of getting a gridcontrol setup to show records from a SQL Server database, neither worked. Both (when I ran the program) returned the columns but no rows. I am positive I have the correct SQL server name, database name and table name. Searching Google seems to return "how to get the program to show a message that says 'no rows found'" i.e. nothing useful. Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Xpo;
using DevExpress.Xpo.DB;
using DevExpress.Xpo.Metadata;
using DevExpress.XtraGrid;
namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Generate the connection string to the AdventureWorks database on local SQL Server.
XpoDefault.ConnectionString =
MSSqlConnectionProvider.GetConnectionString("dsd-sql3", "PH");
// Create a Session object.
Session session1 = new Session(XpoDefault.GetDataLayer(XpoDefault.ConnectionString, AutoCreateOption.None));
// Create an XPClassInfo object corresponding to the Person_Contact class.
XPClassInfo classInfo = session1.GetClassInfo(typeof(Call));
// Create an XPServerCollectionSource object.
XPServerCollectionSource xpServerCollectionSource1 =
new XPServerCollectionSource(session1, classInfo);
xpServerCollectionSource1.Reload();
// Create a grid control.
GridControl gridControl1 = new GridControl();
gridControl1.Dock = DockStyle.Fill;
this.Controls.Add(gridControl1);
// Enable server mode.
gridControl1.ServerMode = true;
// Bind the grid control to the data source.
gridControl1.DataSource = xpServerCollectionSource1;
}
}
[Persistent("dbo.CallLog")]
public class Call : XPLiteObject
{
public Call(Session session) : base(session) { }
[Key, DevExpress.Xpo.DisplayName("Oid")]
public string Oid;
//public string Title;
[DevExpress.Xpo.DisplayName("FirstName")]
public string FirstName;
[DevExpress.Xpo.DisplayName("MiddleName")]
public string MiddleName;
[DevExpress.Xpo.DisplayName("LastName")]
public string LastName;
[DevExpress.Xpo.DisplayName("Email")]
public string Email;
//public string Phone;
}
}
My coworker said that its possible the data is being loaded from the DB but not linked, and he wasn't sure how to fix it...
Any help is greatly appreciated. Thanks.

Related

Directory Not Found in creating json file Unity3D

I have a problem with Unity3D. In particular, I am trying to collect data during a game session, and then save them inside a .json file, to be stored at a specific location. The code to store the file is the following:
using System;
using System.IO;
public class ManageJSON : MonoBehaviour
{
private string _jsonPath;
private JsonObject _jsonObject;
private string _filename = "output.json";
void Start()
{
_jsonPath = Application.dataPath + "/json/";
if (!Directory.Exists(_jsonPath))
{
Directory.CreateDirectory(_jsonPath);
}
_sessionCode = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");
_jsonPath = Path.Combine(_jsonPath, _sessionCode + "-" + _filename);
WriteJsonFile();
}
public void WriteJsonFile()
{
string json = JsonUtility.ToJson(_jsonObject);
using (StreamWriter writer = File.CreateText(_jsonPath))
{
writer.Write(json);
}
}
}
The class JsonObject is the class that generates the json content. As an example it could be like this:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class JsonObject
{
public List<PotionData> potionData = new List<PotionData>();
}
[Serializable]
public class PotionData
{
public string potionName;
public int value;
public List<Effect> effect = new List<Effect>();
}
[Serializable]
public class Effect
{
public string name;
public string descr;
}
However, when I try to write the file, I receive this error:
DirectoryNotFoundException: Could not find a part of the path "C:\Users\username\Documents\Unity Projects\ProjectName\Assets\json\2022-05-27T10:32:13-output.json".
However, the folder is correctly created, and I cannot understand what is the problem. Can anybody help me?
I have already tried in both using Application.persistentDataPath instead of Application.dataPath, and also in not using any different location to create the file in the general project folder, but I always have the same error.
The problem was in the creation of the path: in Windows paths cannot have : inside them. Correcting the creation of the session code solved this issue

C# ASP.NET | Is there any point in me using a model class when saving data to MongoDB?

I have begun writing an ASP.NET Web API for an app that I am building. I have set up a MongoCRUD.cs class to save data from POST requests made by the app to a MongoDB database (and other CRUD actions).
I (following a beginner tutorial), also set up a Submission.cs model class to act as a blueprint for the objects I wanted to save to the database. However, now that I have implemented the InsertRecord() method in MongoCRUD.cs, I cannot see a use for this model.
MongoCRUD.cs:
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebAPI.Services
{
public class MongoCRUD
{
private IMongoDatabase db;
public MongoCRUD(string database)
{
var client = new MongoClient();
db = client.GetDatabase(database);
}
public void InsertRecord<T>(string table, T record)
{
var collection = db.GetCollection<T>(table);
collection.InsertOne(record);
}
}
}
Submission.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Web;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace WebAPI.Models
{
public class Submission
{
[BsonId]
public string SubId { get; set; }
public string Url { get; set; }
public string Text { get; set; }
}
}
SubmissionsController.cs:
using WebAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebAPI.Services;
using System.IO;
using System.Web.Script.Serialization;
namespace WebAPI.Controllers
{
public class SubmissionsController : ApiController
{
MongoCRUD db = new MongoCRUD("myDb");
Submission[] submission = new Submission[] {
new Submission { SubId = "test", Url = "test", Text = "test" };
};
public IEnumerable<Submission> GetAllSubmissions()
{
//add MongoCRUD functionality for load record
return submission;
}
public IHttpActionResult GetSubmission(string id)
{
//add MongoCRUD functionality for load record
return Ok();
}
public IHttpActionResult PostSubmission(object body)
{
//validate body
db.InsertRecord("Submissions", body);
return Ok();
}
}
}
As you can see at PostSubmission(), the body of the POST request can be saved to the database directly, so my question is what is the benefit of using a model such as Submission.cs instead of just using the object type?
I'm having some trouble traversing the body object to access its values (for carrying out validation etc), so my only guess is that using a model makes it easier to access values?
object is the base type for all classes (See - https://learn.microsoft.com/en-us/dotnet/api/system.object?view=netcore-3.1).
C# is an object-orientated language so we try to model classes based on our business domain, this makes it easier to reason about the code.
Like you said you can have models that can be used to validate the incoming data into the controller, also you might want to add extra methods on the models that related to your business domain.
For example
class CreditCard
{
string CardNumber { get;set; }
string Csv { get;set; }
bool ValidateChecksum()
{ }
}

How can I pass DataTable to view as JSON/XML code?

I am new to the .NET environment and trying to write a simple MVC application to read student data and display it to the end user. I have connected to a database using SQLOLEDB, the code of which I have pasted below. The data obtained from the query was stored in a variable of the type DataTable. Now I want to see the content of the query result in the form of a JSON output for which I have a faintest idea that I have to create a new controller. But I am not able to proceed beyond this point.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
namespace Database.model
{
public class student
{
public int id { get; set; }
public string name { get; set; }
private string age { get; set; }
public DataTable GETSQLServerData()
{
//Connect
var _connectionobject = new SqlConnection();
_connectionobject.ConnectionString = #"Provider=SQLOLEDB;Data Source=PHYSICS\SQLEXPRESS;Persist Security Info=true;Initial Catalog=master;Integrated Security=True; provider = SQLOLEDB;";
_connectionobject.Open();
//Command
var _commandObject = new SqlCommand();
_commandObject.CommandText = "select * from dbo.tblStudent";
//Execute
_commandObject.ExecuteReader();
//Data
var _dataReader = _commandObject.ExecuteReader();
DataTable obj2 = new DataTable();
obj2.Load(_dataReader);
_connectionobject.Close();
return obj2;
}
}
}
I would be really grateful if anyone could help me in this regard
You can convert the datatable object into a POCO object
How do I convert a datatable into a POCO object in Asp.Net MVC?
then return that POCO object back to the browser.
The best practice would be to create a class that will hold the student data and return that class object instead of the data table like so.
// you student model class
public class Student
{
// public properties of student...
}
In your data access class populate this student object list and return to the MVC action method.
//then in your MVC action method
IEnumerable<Student> students = GETSQLServerData();
return this.Json(students , JsonRequestBehavior.AllowGet);
A few points about your code:
1- Avoid using sql statement in your C# code, switch to stored
procedure.
2- Use Data Model layer and create Student class to define student
model.
3- Use Data acccess layer to call SQL Stored proc
4- Inject dependencies to avoid tightly coupled classes.
Hope this helps!

How To Filter AutocompleteBox Input from Another Column in Lightswitch 2013

I want to provide users with autocompletebox input control with items taken from database.
However, I'm stuck with how to change the strings filter to be referred from another column, instead of primary key.
The image below shows an example where I can filter input with primary key, but unable to do so using device name.
Users rarely filter primary key. They will likely search device names since it's easier.
Thank you so much for your help.
--
Here's the behind code of the screen
using System;
using System.Linq;
using System.IO;
using System.IO.IsolatedStorage;
using System.Collections.Generic;
using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Framework.Client;
using Microsoft.LightSwitch.Presentation;
using Microsoft.LightSwitch.Presentation.Extensions;
using System.Windows.Controls;
namespace LightSwitchApplication
{
public partial class FormDeviceLending
{
private ModalWindowHelper modalAddLendingWindowHelper;
private ModalWindowHelper modalEditLendingWindowHelper;
partial void FormDeviceLending_InitializeDataWorkspace(System.Collections.Generic.List<Microsoft.LightSwitch.IDataService> saveChangesTo)
{
modalAddLendingWindowHelper = new ModalWindowHelper(this.DeviceLendings, "ModalAddLending");
modalEditLendingWindowHelper = new ModalWindowHelper(this.DeviceLendings, "ModalEditLending");
}
partial void FormDeviceLending_Created()
{
modalAddLendingWindowHelper.Initialise();
modalEditLendingWindowHelper.Initialise();
}
partial void DeviceLendingsAddAndEditNew_Execute()
{
modalAddLendingWindowHelper.AddEntity();
}
partial void AddLendingOK_Execute()
{
modalAddLendingWindowHelper.DialogOk();
}
partial void AddLendingCancel_Execute()
{
modalAddLendingWindowHelper.DialogCancel();
}
partial void EditLendingOK_Execute()
{
modalEditLendingWindowHelper.DialogOk();
}
partial void EditLendingCancel_Execute()
{
modalEditLendingWindowHelper.DialogCancel();
}
partial void DeviceLendingsEditSelected_Execute()
{
modalEditLendingWindowHelper.ViewEntity();
}
}
}

Querying AspNet Identity tables in Code First MVC application

Is it possible to Query the AspNetUsers table based on the keyword using N-Tier design modeled after:
Implementing a generic data access layer using Entity Framework
I created the following Interfaces in my DAL:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Library.Model;
namespace Library.DataAccessLayer
{
...
public interface IAspNetUserRepository : IGenericDataRepository<ApplicationUser>
{
}
public class AspNetUserRepository : GenericDataRepository<ApplicationUser>, IAspNetUserRepository
{
}
}
And the Following BLL entry:
using System;
using System.Collections.Generic;
using System.Linq;
using Library.DataAccessLayer;
using Library.Model;
namespace Library.BusinessLogicLayer
{
public interface IBusinessLogicLayer_AspNetUser
{
ApplicationUser GetAspNetUserByAspNetUserID(string _UserID);
}
public class BusinessLogicLayer_AspNetUser : IBusinessLogicLayer_AspNetUser
{
private readonly IAspNetUserRepository _AspNetUserRepository;
public BusinessLogicLayer_AspNetUser()
{
_AspNetUserRepository = new AspNetUserRepository();
}
public BusinessLogicLayer_AspNetUser(IAspNetUserRepository AspNetUserRepository)
{
_AspNetUserRepository = AspNetUserRepository;
}
public ApplicationUser GetAspNetUserByAspNetUserID(string _UserID)
{
return _AspNetUserRepository.GetSingle(u => u.Id.Equals(_UserID));
}
}
}
Now in the BLL file, the only Lambda expression does not contain Td so it errors out.
What is the correct model to use. The only information I can find is that ApplicationUser inherits Identity User.
What needs to be done or changed so I can get these fields added to the ApplicationUser model without it affecting the Code First portion for the database?
I finally found the answer. It was actually staring me right in the face.
simply use the following code to get the user(s) object:
var context = new ApplicationDbContext();
var user = context.Users.{Methods and Lambda expressions};
for example, say you need the existing KNOWN active user's UserName, use User.Identity.Name. And to get the active User's AspNetUsers database record:
var context = new ApplicationDbContext();
var user = context.Users.SingleOrDefault(u => u.UserName == User.Identity.Name);

Categories