I'm trying to store an entity called Tshirt into a Windows Azure table storage along with a Blob on Windows Azure Blob storage.
That entity Tshirt contains a field called Image (byte[]) but I don't want to save that in my table.
How can I indicate in my class that I don't want to save that field?
public class Tshirt : TableServiceEntity
{
public Tshirt(string partitionKey, string rowKey, string name)
{
this.PartitionKey = partitionKey;
this.RowKey = rowKey;
this.Name = name;
this.ImageName = new Guid();
}
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
private string _color { get; set; }
public string Color
{
get { return _color; }
set { _color = value; }
}
private int _amount { get; set; }
public int Amount
{
get { return _amount; }
set { _amount = value; }
}
[NonSerialized]
private byte[] _image;
public byte[] Image
{
get { return _image; }
set { _image = value; }
}
private Guid _imageName;
public Guid ImageName
{
get { return _imageName; }
set { _imageName = value; }
}
}
The easy way is to expose the field as a pair of methods rather than an actual property:
public byte[] GetImage()
{
return _image;
}
public void SetImage(byte[] image)
{
_image = image;
}
If that's not an option, then you can remove the Image property when you're storing the entity by handling the WritingEntity event. (Credit to Neil Mackenzie)
public void AddTshirt(Tshirt tshirt)
{
var context = new TableServiceContext(_baseAddress, _credentials);
context.WritingEntity += new EventHandler<ReadingWritingEntityEventArgs>(RemoveImage);
context.AddObject("Tshirt", tshirt);
context.SaveChanges();
}
private void RemoveImage(object sender, ReadingWritingEntityEventArgs args)
{
XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";
XElement imageElement = args.Data.Descendants(d + "Image").First();
imageElement.Remove();
}
Related
I have this database structure:
public class QRDatabase
{
readonly SQLiteAsyncConnection _database;
public QRDatabase(string dbPath)
{
_database = new SQLiteAsyncConnection(dbPath);
_database.CreateTableAsync<db_QRCODE_Type>().Wait();
}
public Task<List<db_QRCODE_Type>> GetQRCode()
{
return _database.Table<db_QRCODE_Type>().ToListAsync();
}
public Task<int> SaveQRCode(db_QRCODE_Type note)
{
if (note.ID != 0)
{
return _database.UpdateAsync(note);
}
else
{
return _database.InsertAsync(note);
}
}
public Task<int> DelteQRCode(db_QRCODE_Type note)
{
return _database.DeleteAsync(note);
}
}
This uses this type:
public class db_QRCODE_Type
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; } // Identificator of column
public string firstName { get; set; } // firstname
public string lastName { get; set; } // firstname
public byte[] qrBytes { get; set; } //qr code in bytes
}
Then, in the class where I need the DB I am doing this from the tutorial here:
https://learn.microsoft.com/de-de/xamarin/get-started/quickstarts/database?pivots=windows
static QRDatabase database;
static string nameOfDB = "01db_qrs_q2go.db3";
public static QRDatabase Database
{
get
{
if (database == null)
{
database = new QRDatabase(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), nameOfDB));
}
return database;
}
}
However, I am not quite sure how this works since I am never calling "Database" even though this is where the database is supposed to be initiliased.
Now, when I try to write to the database:
db_QRCODE_Type entry = new db_QRCODE_Type();
entry.firstName = entry_firstname.Text;
entry.lastName = entry_lastname.Text;
entry.qrBytes = qrCodeBytes;
try
{
await database.SaveQRCode(entry);
}
catch
{
DependencyService.Get<IMessage>().LongAlert("Etwas hat nicht funktioniert, bitte versuche es noch einmal. Fehlercode: DB_665h");
}
It fails saying it is not set reference to an instance and goes into the catch block. I am doing everything as in the tutorial. Why is this happening?
Thank you!
I am trying to make a custom file validation for my project which is based on .net core 2.
I want to validate file size and also file extension in order to prevent users from uploading large files and for example .png files.
I have searched a lot but I could not find anything that works.
Here is my file validation class :
public class FileTypeAttribute : ValidationAttribute, IClientModelValidator
{
private const int MaxSize = 1048576;
private const string _DefaultErrorMessage = "Only the following file types are allowed: {0}";
private IEnumerable<string> _ValidTypes { get; set; }
public string ValidTypes { get; set; }
public string ErrorMessageExtension { get; set; }
public string ErrorMessageSize { get; set; }
public FileTypeAttribute(string errorExtension, string errorSize, string vt)
{
ErrorMessageExtension = errorExtension;
ErrorMessageSize = errorSize;
_ValidTypes = vt.Split(',');
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
IFormFile file = value as IFormFile;
if (file != null)
{
if (!_ValidTypes.Any(e => file.FileName.EndsWith(e)))
{
return new ValidationResult(ErrorMessageExtension);
}
if (file.Length > MaxSize)
{
return new ValidationResult(ErrorMessageSize);
}
}
return ValidationResult.Success;
}
public void AddValidation(ClientModelValidationContext context)
{
MergeAttribute(context.Attributes, "data-val", "true");
var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
MergeAttribute(context.Attributes, "data-val-fileextensions", ErrorMessageExtension);
MergeAttribute(context.Attributes, "data-val-maxfilesize", ErrorMessageSize);
}
private bool MergeAttribute(
IDictionary<string, string> attributes, string key, string value)
{
if (attributes.ContainsKey(key))
{
return false;
}
attributes.Add(key, value);
return true;
}
}
and here is the javascript code in my view:
$.validator.addMethod("FileType",
function (value, element, param) {
for (var i = 0; i < element.files.length; i++) {
var extension = getFileExtension(element.files[0].name);
if ($.inArray(extension, param.validtypes) === -1) {
return false;
}
}
return true;
});
$.validator.unobtrusive.adapters.add('FileType', ['validtypes'], function (options) {
console.log("value:");
options.rules.cannotbered = {};
options.messages["FileType"] = options.message;
});
function getFileExtension(fileName) {
if (/[.]/.exec(fileName)) {
return /[^.]+$/.exec(fileName)[0].toLowerCase();
}
return null;
}
and here is the entity class code in my project:
public class MyEntityClass
{
public int MyEntityClassId { get; set; }
[FileType("invalid format", "invalid size", "jpg,png,gif")]
public IFormFile Photo { get; set; }
}
Can anyone help me to know where the problem is?
Thanks in advance.
I'm designing a profile page for users where they can edit their personal info. I'm using a PersonViewModel (which contains the current signed in person) to display the current info about the User. The fields to edit the user's info are bound to a validation model. After pressing the 'execute changes' button and I get a response of the server (HTTPStatusCode Ok + the altered user object), I alter the fields of the existing object according to the changes. Then I used setter injection to update my PersonViewModel... When debugging, I can see that my objects are all up-to-date but my view is still displaying the old info... What am I doing wrong?`
This is the code that get's executed when I press the button to execute my changes:
private async void ChangeInfoButton(object sender, RoutedEventArgs e)
{
User user;
List<ErrorInfo> errors;
if (_profileInformationValidationModel.TryGetUser(out user, out errors))
{
var response = await Session.Instance.DataProvider.UpdaterUserInfo(user);
if (response.IsSuccess)
{
/*SignedInUserInfo = AlteredUserInfo*/
Session.Instance.User.Information = user.Information;
_personViewModel.SetPerson(user.Information);
var d1 = new MessageDialog("Uw gegevens werden succesvol gewijzigd.");
d1.ShowAsync();
AnnulInfoButton(sender, e);
}
`
And this is the PersonViewModel:
public class PersonViewModel
{
private Person _person;
public void SetPerson(Person p)
{
_person = p;
}
public PersonViewModel(Person person)
{
_person = person;
}
public string Street
{
get { return _person.Street; }
}
public string HouseNumber
{
get { return _person.HouseNumber; }
}
public string Bus
{
get { return _person.Bus; }
}
public string Email
{
get { return _person.Email; }
}
Your view model should implement the INotifyPropertyChanged interface.
Look into using a framework like MVVM Light which does most of this work for you.
You can add it to your project using NuGet.
This is how your model and view-model should look:
public class Person
{
public string Street { get; set; }
public string HouseNumber { get; set; }
public string Bus { get; set; }
public string Email { get; set; }
}
public class PersonViewModel : System.ComponentModel.INotifyPropertyChanged
{
private Person _person;
public void SetPerson(Person person)
{
_person = person;
Street = person.Street;
HouseNumber = person.HouseNumber;
Bus = person.Bus;
Email = person.Email;
}
public PersonViewModel(Person person)
{
SetPerson(person);
}
#region Street (INotifyPropertyChanged Property)
private string _street;
public string Street
{
get { return _street; }
set
{
if (_street != value)
{
_street = value;
RaisePropertyChanged("Street");
}
}
}
#endregion
#region HouseNumber (INotifyPropertyChanged Property)
private string _houseNumber;
public string HouseNumber
{
get { return _houseNumber; }
set
{
if (_houseNumber != value)
{
_houseNumber = value;
RaisePropertyChanged("HouseNumber");
}
}
}
#endregion
#region Bus (INotifyPropertyChanged Property)
private string _bus;
public string Bus
{
get { return _bus; }
set
{
if (_bus != value)
{
_bus = value;
RaisePropertyChanged("Bus");
}
}
}
#endregion
#region Email (INotifyPropertyChanged Property)
private string _email;
public string Email
{
get { return _email; }
set
{
if (_email != value)
{
_email = value;
RaisePropertyChanged("Email");
}
}
}
#endregion
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string p)
{
var propertyChanged = PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(p));
}
}
}
There are so many question about that but there is no solution for my problem. I want to return a custom class which has datacontract key and it's members have datamember key. I am getting this error while I testing it;
When I call it from my windows phone application, it returns "The remote server not found"
It returns not found but it runs methods that return types are void, bool, list.
[OperationContract]
BaseModel Login(string userName, string password);
[DataContract]
public class UserModel
{
private int userID;
[DataMember]
public int UserID
{
get { return userID; }
set { userID = value; }
}
private string userName;
[DataMember]
public string UserName
{
get { return userName; }
set { userName = value; }
}
private string password;
[DataMember]
public string Password
{
get { return password; }
set { password = value; }
}
private string email;
[DataMember]
public string Email
{
get { return email; }
set { email = value; }
}
private int securityQuestionID;
[DataMember]
public int SecurityQuestionID
{
get { return securityQuestionID; }
set { securityQuestionID = value; }
}
private string securityQuestionAnswer;
[DataMember]
public string SecurityQuestionAnswer
{
get { return securityQuestionAnswer; }
set { securityQuestionAnswer = value; }
}
private string sex;
[DataMember]
public string Sex
{
get { return sex; }
set { sex = value; }
}
private string gsmNo;
[DataMember]
public string GSMNo
{
get { return gsmNo; }
set { gsmNo = value; }
}
private DateTime birthDate;
[DataMember]
public DateTime BirthDate
{
get { return birthDate; }
set { birthDate = value; }
}
private string registeredDeviceUniqueID;
[DataMember]
public string RegisteredDeviceUniqueID
{
get { return registeredDeviceUniqueID; }
set { registeredDeviceUniqueID = value; }
}
private string registrationType;
[DataMember]
public string RegistrationType
{
get { return registrationType; }
set { registrationType = value; }
}
private string registeredDeviceType;
[DataMember]
public string RegisteredDeviceType
{
get { return registeredDeviceType; }
set { registeredDeviceType = value; }
}
private string registeredApplication;
[DataMember]
public string RegisteredApplication
{
get { return registeredApplication; }
set { registeredApplication = value; }
}
private DateTime registeredDate;
[DataMember]
public DateTime RegisteredDate
{
get { return registeredDate; }
set { registeredDate = value; }
}
private string registeredGSM;
[DataMember]
public string RegisteredGSM
{
get { return registeredGSM; }
set { registeredGSM = value; }
}
private string profilePictureURL;
[DataMember]
public string ProfilePictureURL
{
get { return profilePictureURL; }
set { profilePictureURL = value; }
}
}
[DataContract]
public class BaseModel
{
private string errorMessage;
[DataMember]
public string ErrorMessage
{
get { return errorMessage; }
set { errorMessage = value; }
}
private string informationMessage;
[DataMember]
public string InformationMessage
{
get { return informationMessage; }
set { informationMessage = value; }
}
private string warningMessage;
[DataMember]
public string WarningMessage
{
get { return warningMessage; }
set { warningMessage = value; }
}
private string succeedMessage;
[DataMember]
public string SucceedMessage
{
get { return succeedMessage; }
set { succeedMessage = value; }
}
private object returnObject;
[DataMember]
public object ReturnObject
{
get { return returnObject; }
set { returnObject = value; }
}
private bool isSucceed;
[DataMember]
public bool IsSucceed
{
get { return isSucceed; }
set { isSucceed = value; }
}
}
And the method is;
public BaseModel Login(string userName, string password)
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT * FROM UserBaseInformations WITH (NOLOCK) Where UserName=#userName", connection))
{
command.Parameters.Add(new SqlParameter("#userName", userName));
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
DataTable dt = new DataTable();
adapter.Fill(dt);
DataSet ds = new DataSet();
ds.Tables.Add(dt);
connection.Close();
if (dt.Rows.Count == 0)
return new BaseModel() { IsSucceed = false, ErrorMessage = "Geçersiz bir kullanıcı adı girdiniz." };
else if (!dt.Rows[0]["Password"].ToString().Equals(password))
return new BaseModel() { IsSucceed = false, ErrorMessage = "Şifrenizi yanlış girdiniz." };
else
return new BaseModel()
{
IsSucceed = true,
ReturnObject = new UserModel()
{
Email = dt.Rows[0]["Email"].ToString(),
Password = dt.Rows[0]["Password"].ToString(),
UserID = (int)dt.Rows[0]["UserID"],
UserName = dt.Rows[0]["UserName"].ToString(),
SecurityQuestionID = (int)dt.Rows[0]["SecurityQuestionID"],
SecurityQuestionAnswer = dt.Rows[0]["SecurityQuestionAnswer"].ToString()
}
};
}
}
}
I have found solution.
Returning an object type can be problem in WCF so I changed it to a base class for returning my classes and added KnownType attribute to BaseModel.
I have an object which has a property on it that has then has collections which i would like to not load in a couple situations. 98% of the time i want those collections fetched but in the one instance i do not. Here is the code I have... Why does it not set the fetch mode on the properties collections?
[DataContract(Name = "ThemingJob", Namespace = "")]
[Serializable]
public class ThemingJob : ServiceJob
{
[DataMember]
public virtual Query Query { get; set; }
[DataMember]
public string Results { get; set; }
}
[DataContract(Name = "Query", Namespace = "")]
[Serializable]
public class Query : LookupEntity<Query>, DAC.US.Search.Models.IQueryEntity
{
[DataMember]
public string QueryResult { get; set; }
private IList<Asset> _Assets = new List<Asset>();
[IgnoreDataMember]
[System.Xml.Serialization.XmlIgnore]
public IList<Asset> Assets { get { return _Assets; } set { _Assets = value; } }
private IList<Theme> _Themes = new List<Theme>();
[IgnoreDataMember]
[System.Xml.Serialization.XmlIgnore]
public IList<Theme> Themes { get { return _Themes; } set { _Themes = value; } }
private IList<Affinity> _Affinity = new List<Affinity>();
[IgnoreDataMember]
[System.Xml.Serialization.XmlIgnore]
public IList<Affinity> Affinity { get { return _Affinity; } set { _Affinity = value; } }
private IList<Word> _Words = new List<Word>();
[IgnoreDataMember]
[System.Xml.Serialization.XmlIgnore]
public IList<Word> Words { get { return _Words; } set { _Words = value; } }
}
using (global::NHibernate.ISession session = NHibernateApplication.GetCurrentSession())
{
global::NHibernate.ICriteria criteria = session.CreateCriteria(typeof(ThemingJob));
global::NHibernate.ICriteria countCriteria = session.CreateCriteria(typeof(ThemingJob));
criteria.AddOrder(global::NHibernate.Criterion.Order.Desc("Id"));
var qc = criteria.CreateCriteria("Query");
qc.SetFetchMode("Assets", global::NHibernate.FetchMode.Lazy);
qc.SetFetchMode("Themes", global::NHibernate.FetchMode.Lazy);
qc.SetFetchMode("Affinity", global::NHibernate.FetchMode.Lazy);
qc.SetFetchMode("Words", global::NHibernate.FetchMode.Lazy);
pageIndex = Convert.ToInt32(pageIndex) - 1; // convert to 0 based paging index
criteria.SetMaxResults(pageSize);
criteria.SetFirstResult(pageIndex * pageSize);
countCriteria.SetProjection(global::NHibernate.Criterion.Projections.RowCount());
int totalRecords = (int)countCriteria.List()[0];
return criteria.List<ThemingJob>().ToPagedList<ThemingJob>(pageIndex, pageSize, totalRecords);
}