set a value to the attribute at run time - c#

I have a namespace that contains some classes, one of the classes I'm working on contains properties, where each proprty has an attribute associated with it, as the follwing
namespace Local.Business
{
[DynamoDBTable("myTableName")]
public class Business
{
[DynamoDBHashKey("PK")]
public string MunId {get; set;}
[DynamoDBRangeKey("SK")]
public string Id {get; set;}
[DynamoDBProperty("Dba")]
public string Dba {get; set;}
}
}
the string "myTableName" need to be determined at runtime(by calling a function or reading it from other class's property)
How can I achieve that, please?

What you are trying to do is inherently flawed. You kinda can ish change attributes sort of, sometimes, but there's a good chance that whatever is consuming the attributes won't see the change, which makes it entirely pointless.
Basically: you need to find another way of reconfiguring DynamoDB at runtime. This isn't it.
For the "kinda can ish":
you can materialize attributes, and if they're mutable, change the copies you have; but when other code materializes the attributes, they'll get different unrelated versions, which will not have any changes you have made
there is an API that supports this concept (System.ComponentModel), but: most attribute consumers do not use that API - it is mostly just UI binding tools (think PropertyGrid, DataGridView, etc) that would take any notice of it - because they are expecting to work with things like DataTable that require a different approach to metadata and reflection

Set the table name value to empty string in the class file:
[DynamoDBTable("")]
During runtime, use the overloaded functions on DynamoDBMapper to pass DynamoDBMapperConfig configured with TableNameOverride

Actually I deleted the table property and I gave the table name in the query
dynamoDBOperationConfig = new DynamoDBOperationConfig();
dynamoDBOperationConfig.OverrideTableName = "tableName";
string munId = "1";
var search = dynamoDBcontext.QueryAsync<Business>(munId, dynamoDBOperationConfig);
and It works fine, thank you all guys for helping

Related

Dapper UpdateAsync ignore column

I am trying to update with Dapper.Contrib this table:
public class MyTable
{
public int ID { get; set; }
public int SomeColumn1 { get; set; }
public int SomeColumn2 { get; set; }
public int CreateUserID { get; set; }
public int UpdateUserID { get; set; }
}
I don't want to update the CreateUserID column because it is an update method so that I want to ignore this column while calling the Dapper - Update.Async(entity) method.
I tried using [NotMapped] and [UpdateIgnore] attributes but no help.
Note: I still want this column to be passed on insert operations, therefore, [Computed] and [Write(false)] is not appropriate.
Can someone help me figure out how to ignore this column when updating the table in the database?
Well, it's just not supported. Here is related issue, and solution is expected only in Dapper v2. You can also inspect source code (it's pretty simple) and see that updated properties are searched as follows:
var allProperties = TypePropertiesCache(type);
keyProperties.AddRange(explicitKeyProperties);
var computedProperties = ComputedPropertiesCache(type);
var nonIdProps = allProperties.Except(keyProperties.Union(computedProperties)).ToList();
So all properties not marked with Key\ExplicitKey\Computed and which are writable are included. The same happens for InsertAsync (except properties with ExplicitKey are also included in insert, but you cannot use this attribute in your situtaion, because your property is not key after all).
So you have to either wait for this to be implemented, fork and implement yourself, or just write your own UpdateAsync method. You can see from source code that it's very simple and is not hard to reimplement.
As #Evk already mentioned in his answer, there is no solution implemented yet. He have also mentioned the workarounds.
Apart from that, you can choose to use Dapper (IDbConnection.Execute(...)) directly bypassing Dapper.Contrib for this particular case.
I had a similar problem (with DapperExtensions though) with particular column update and other complex queries those DapperExtensions either cannot generate at all or need much work to make it happen with it.
I used Dapper directly instead of DapperExtensions for that particular case; other part of project still take benefit of DapperExtensions. This is like tread-off. Such cases are very limited. I found this is better solution instead of tweaking/forcing DapperExtensions for this. This also saved me on time and efforts.
I suggest using the [Computed] attribute.
[Computed] - this property is computed and should not be part of updates
But, It appears that the documentation for Dapper.Contrib is worded in a confusing manner. The [Computed] attribute appears to be ignored on inserts as well - this may or may not work for your use case.

Query with OData without exposing ORM models?

In my web api 2 project, if I want to use OData library (which looks awesome and very tempting) for queries over some properties, that would force the client side to know the exact properties of my database models. Is this a good practice? Is there a way to avoid this decouple?
For the following models:
public class LetterEntity
{
public int Id {get; set;}
public string Title {get; set;}
public string Content {get; set;}
public string Source {get; set;}
public DateTime SendingTime {get; set;}
public string AnotherWierdString {get; set;
...
}
public class LetterDTO
{
public int Id {get; set;}
public string Title {get; set;}
public string LetterContent {get; set;}
public string Source {get; set;}
public DateTime SendingTime {get; set;}
}
public class LetterInsideFolderDTO
{
public string Title {get; set;}
public string Source {get; set;}
}
public class LettersController : ApiController
{
// In this approach method, I hate the fact that a LetterEntity must be used for the query.
[HttpGet]
[Route("api/letters")]
[EnableQuery]
public IQueryable<LetterInsideFolderDTO> Get(ODataQueryOptions<LetterEntity> query)
{
IQueryable<Letter> letters = db.Letters;
var afterQuery = query.ApplyTo(letters)
IQueryable<LetterInsideFolderDTO> dtos = afterQuery.ProjectTo<LetterInsideFolderDTO>(afterQuery)
return dtos;
}
// Is there a way to do something like the following?:
[HttpGet]
[Route("api/letters")]
[EnableQuery]
public IQueryable<LetterInsideFolderDTO> Get(ODataQueryOptions<LetterDTO> query)
{
IQueryable<Letter> letters = db.Letters;
// Convert the query to work on the entities somehow? Should I use a mapping between LetterDTO to LetterEntity?
// I only have a map from LetterEntity to LetterDTO
var afterQuery = query.ApplyTo(letters)
IQueryable<LetterInsideFolderDTO> dtos = afterQuery.ProjectTo<LetterInsideFolderDTO>(afterQuery)
return dtos;
}
}
Because of the fact that at the moment I take Entity model directly in the clients query, there is a strong coupling between clients and server.
For example if i want to query and get all the letters that has "abc" inside the Content field, I need to route to the following:
api/letters/?$filter=contains(Content,'abc')
If tomorrow I decide to change that property from "Content" to "LetterContent" all clients code will be broken.
How can I surpass it?
Thanks!
EDIT:
Please give me a concrete example,
I don't understand yet what HATEOAS are (if that helps me solve this issue),
How can documentation service help me? It'll still force clients to change their code if I decide to change my EDM models?
I do believe that exposing your entities directly is a bad practice in most cases. I'd recommend DTOs in almost every case. It allows you to evolve your database and business logic without breaking the API. There are some great use cases for OData for example open data initiatives where the government publishes data as it is.
I had to built an app that was essentially grids over data with all the filtering and sorting options. I wanted to use OData but I did not find a way to do queries over entities but project to DTOs so I built my own library to convert jqgrid filters to IQueryable queries - https://github.com/KodarLtd/WebApiJQGridFilters Note that I do not recommend using this code as it is not full featured library and is not documented at all. I just provide it as evidence how firmly I believe in the DTO approach.
I would like to be proven wrong so I can use OData but return DTOs for my next project.
if I want to use OData library (which looks awesome and very tempting) for queries over some properties, that would force the client side to know the exact properties of my database models. Is this a good practice?
It depends on what do you mean by "would force the client side to know the exact properties". There are two ways:
Use auto-generated proxies made by datasvcutil. Indeed, that would force the client side to know the exact properties since they are hard-coded in client-side. When server side is changed client would be broken - client/server are tightly coupled. In general it's bad, but usually if you need smth to get done quickly - datasvcutil is your tool.
Learn your client to read service document, so that he could dynamically decide what resources he may query. You have everything for it - service document, metadata.
Remember that OData is built on REST architecture which has a set of advantages that are achieved via set of constraints. Several of constraints are Addressability and HATEOAS.
Addressability means that each resource must have its address.
HATEOAS means that in any given moment, client, based on hypermedia in representation of current resource, must have all the information he needs to decide where to transit next.
In order to know where to transit client must
Know how to find resources(URL's) in the stream of data where he may transit. Like you get data with text and URL's - client must know how to find URL's. URL may have different meanings - like several URL's for CRUD operations.
Get that data with resources. In general client must know how to start querying service
First point is resolved via profiles. Profile - allows clients to learn about additional semantic associated with the resource representation (https://www.rfc-editor.org/rfc/rfc6906). Consider it OData documentation. In case of OData your client must know that data in OData is represented via Atom or Json formats. Client must know principles of constructing queries to OData service, of getting specific record and so forth.
If client calls OData root address - smth like ...OData.svc, he would get list of all resources that he can query(service document). That is how second point is resolved.
You may come further and get metadata via $metadata suffix. That would give you all properties of resources.

How to use XmlAttributeOverrides with WCF

I have a WCF service using basicHttpBinding. On a service method I have a class that is returned, for this class I need to dynamically / programmatically exclude properties and change property names for the XML. This needs to be done both in the WSDL and when the service method is called.
I have searched for the best solution and it seems that I will need to (1) use the XmlAttributeOverrides with the XmlSerializer or (2) implement the IXmlSerializable on the class that needs to be customized. Or there may be a better solution altogether. I know that Property Name + "Specified" can be added to the class and then those properties can be excluded. However, this does not exclude in the WSDL and this doesn't solve the property renaming issue.
Why do I want this? Because of globalization and customization of our application. There are many properties that are built into our application that may be renamed or hidden entirely from users of the application.
After MUCH research I the best option is to swap out the WCF serializer with my own custom serializer. However, I never found good examples of how to do this for a custom class that would use the XmlSerializer. Also I'm not sure how I would pass in the XmlAttributeOverrides for a specific class.
Also, this might not be the case for others who want this same functionality but in my application I only need to initialize the values once for the lifetime of the app. Too bad C# doesn't allow static readonly variables to be used with attributes.
Here is an simple example of a class:
public Customer
{
public string Address1
{
get;
set;
}
public string Address2
{
get;
set;
}
public string Zipcode
{
get;
set;
}
}
In this example I would like to for certain installations of the application use PostalCode instead of Zipcode and hide the Address2 property.
Your help is very much appreciated.
Thanks,
Tyler
There are many properties that are built into our application that may be renamed or hidden entirely from users of the application.
A standard approach is to create a special Data Transfer Object (DTO). Or several.
I know this seems like a bit of a cop out, but since your object property names are dynamic why not just use property bagging instead of doing this XMLSerializer shuffle?

What ways can I ensure that a string property is of a particular length?

I've created some classes that will be used to provide data to stored procedures in my database. The varchar parameters in the stored procs have length specifications (e.g. varchar(6) and I'd like to validate the length of all string properties before passing them on to the stored procedures.
Is there a simple, declarative way to do this?
I have two conceptual ideas so far:
Attributes
public class MyDataClass
{
[MaxStringLength = 50]
public string CompanyName { get; set; }
}
I'm not sure what assemblies/namespaces I would need to use to implement this kind of declarative markup. I think this already exists, but I'm not sure where and if it's the best way to go.
Validation in Properties
public class MyDataClass
{
private string _CompanyName;
public string CompanyName
{
get {return _CompanyName;}
set
{
if (value.Length > 50)
throw new InvalidOperationException();
_CompanyName = value;
}
}
}
This seems like a lot of work and will really make my currently-simple classes look pretty ugly, but I suppose it will get the job done. It will also take a lot of copying and pasting to get this right.
I'll post this as a different answer, because it is characteristically different than Code Contracts.
One approach you can use to have declarative validation is to use a dictionary or hash table as the property store, and share a utility method to perform validation.
For example:
// Example attribute class for MaxStringLength
public class MaxStringLengthAttribute : Attribute
{
public int MaxLength { get; set; }
public MaxStringLengthAttribute(int length) { this.MaxLength = length; }
}
// Class using the dictionary store and shared validation routine.
public class MyDataClass
{
private Hashtable properties = new Hashtable();
public string CompanyName
{
get { return GetValue<string>("CompanyName"); }
[MaxStringLength(50)]
set { SetValue<string>("CompanyName", value); }
}
public TResult GetValue<TResult>(string key)
{
return (TResult)(properties[key] ?? default(TResult));
}
public void SetValue<TValue>(string key, TValue value)
{
// Example retrieving attribute:
var attributes = new StackTrace()
.GetFrame(1)
.GetMethod()
.GetCustomAttributes(typeof(MaxStringLengthAttribute), true);
// With the attribute in hand, perform validation here...
properties[key] = value;
}
}
You can get at the calling property using reflection by working up your stack trace as demonstrated here. Reflect the property attributes, run your validation, and voila! One-liner getter/setters that share a common validation routine.
On an aside, this pattern is also convenient because you can design a class to use alternative dictionary-like property stores, such as ViewState or Session (in ASP.NET), by updating only GetValue and SetValue.
One additional note is, should you use this approach, you might consider refactoring validation logic into a validation utility class for shared use among all your types. That should help prevent your data class from getting too bulky in the SetValue method.
Well, whatever way you go, what's executed is going to look like your second method. So the trick is getting your first method to act your second.
First of all, It would need to be [MaxStringLength(50)]. Next, all that's doing is adding some data to the Type object for this class. You still need a way of putting that data to use.
One way would be a binary re-writer. After compilation (but before execution), the rewriter would read the assembly, looking for that Attribute, and when finding it, add in the code for the check. The retail product PostSharp was designed to do exactly that type of thing.
Alternately, you could trigger it at run-time. SOmething like:
public class MyDataClass
{
private string _CompanyName;
[MaxStringLength(50)]
public string CompanyName
{
get {return _CompanyName;}
set
{
ProcessValidation()
_CompanyName = value;
}
}
}
That's still quite ugly, but it's a bit better if you have a number of validation attributes.
The first method using attribute sounds good.
Implement your attribute by inherit from the System.Attribute class and mark your class with AttributeUsage attribute to let your attribute being set on a field.
Then, using reflection, check for presence and value of the attribute before sending the value to the SP.
Thats provide you with lot more flexibility than the second method. If tomorow you decide to let your SP receive the first N chars of a too lengthly string, you won't have to modify all your code but only the one that interpret the attribute.
There are indeed some validation attribute in the framework but I wouldn't use those one because you could implies some behaviour you don't expect and because you won't be able to modify then in any way (liek if you want something like [MaxLength(50, true)] to specify that using the first 5O chars is OK.
It sounds like a business rule. So I would put it in a Company class (Since it is CompanyName), and do the validation there. I don't see why it would require copying and pasting if you have it encapsulated.
Either an attribute or your second example should be fine. The attribute allows for reuse in other classes with string length constraints, however.
Though not exactly the same thing, I recently became aware of .NET 4 Code Contracts in an MSDN article. They provide a convenient and elegant way of encoding and analyzing code assumptions. It's worth taking a look at.

When to use Properties and Methods?

I'm new to the .NET world having come from C++ and I'm trying to better understand properties. I noticed in the .NET framework Microsoft uses properties all over the place. Is there an advantage for using properties rather than creating get/set methods? Is there a general guideline (as well as naming convention) for when one should use properties?
It is pure syntactic sugar. On the back end, it is compiled into plain get and set methods.
Use it because of convention, and that it looks nicer.
Some guidelines are that when it has a high risk of throwing Exceptions or going wrong, don't use properties but explicit getters/setters. But generally even then they are used.
Properties are get/set methods; simply, it formalises them into a single concept (for read and write), allowing (for example) metadata against the property, rather than individual members. For example:
[XmlAttribute("foo")]
public string Name {get;set;}
This is a get/set pair of methods, but the additional metadata applies to both. It also, IMO, simply makes it easier to use:
someObj.Name = "Fred"; // clearly a "set"
DateTime dob = someObj.DateOfBirth; // clearly a "get"
We haven't duplicated the fact that we're doing a get/set.
Another nice thing is that it allows simple two-way data-binding against the property ("Name" above), without relying on any magic patterns (except those guaranteed by the compiler).
There is an entire book dedicated to answering these sorts of questions: Framework Design Guidelines from Addison-Wesley. See section 5.1.3 for advice on when to choose a property vs a method.
Much of the content of this book is available on MSDN as well, but I find it handy to have it on my desk.
Consider reading Choosing Between Properties and Methods. It has a lot of information on .NET design guidelines.
properties are get/set methods
Properties are set and get methods as people around here have explained, but the idea of having them is making those methods the only ones playing with the private values (for instance, to handle validations).
The whole other logic should be done against the properties, but it's always easier mentally to work with something you can handle as a value on the left and right side of operations (properties) and not having to even think it is a method.
I personally think that's the main idea behind properties.
I always think that properties are the nouns of a class, where as methods are the verbs...
First of all, the naming convention is: use PascalCase for the property name, just like with methods. Also, properties should not contain very complex operations. These should be done kept in methods.
In OOP, you would describe an object as having attributes and functionality. You do that when designing a class. Consider designing a car. Examples for functionality could be the ability to move somewhere or activate the wipers. Within your class, these would be methods. An attribute would be the number of passengers within the car at a given moment. Without properties, you would have two ways to implement the attribute:
Make a variable public:
// class Car
public int passengerCount = 4;
// calling code
int count = myCar.passengerCount;
This has several problems. First of all, it is not really an attribute of the vehicle. You have to update the value from inside the Car class to have it represent the vehicles true state. Second, the variable is public and could also be written to.
The second variant is one widley used, e. g. in Java, where you do not have properties like in c#:
Use a method to encapsulate the value and maybe perform a few operations first.
// class Car
public int GetPassengerCount()
{
// perform some operation
int result = CountAllPassengers();
// return the result
return result;
}
// calling code
int count = myCar.GetPassengerCount();
This way you manage to get around the problems with a public variable. By asking for the number of passengers, you can be sure to get the most recent result since you recount before answering. Also, you cannot change the value since the method does not allow it. The problem is, though, that you actually wanted the amount of passengers to be an attribute, not a function of your car.
The second approach is not necessarily wrong, it just does not read quite right. That's why some languages include ways of making attributes look like variables, even though they work like methods behind the scenes. Actionscript for example also includes syntax to define methods that will be accessed in a variable-style from within the calling code.
Keep in mind that this also brings responsibility. The calling user will expect it to behave like an attribute, not a function. so if just asking a car how many passengers it has takes 20 seconds to load, then you probably should pack that in a real method, since the caller will expect functions to take longer than accessing an attribute.
EDIT:
I almost forgot to mention this: The ability to actually perform certain checks before letting a variable be set. By just using a public variable, you could basically write anything into it. The setter method or property give you a chance to check it before actually saving it.
Properties simply save you some time from writing the boilerplate that goes along with get/set methods.
That being said, a lot of .NET stuff handles properties differently- for example, a Grid will automatically display properties but won't display a function that does the equivalent.
This is handy, because you can make get/set methods for things that you don't want displayed, and properties for those you do want displayed.
The compiler actually emits get_MyProperty and set_MyProperty methods for each property you define.
Although it is not a hard and fast rule and, as others have pointed out, Properties are implemented as Get/Set pairs 'behind the scenes' - typically Properties surface encapsulated/protected state data whereas Methods (aka Procedures or Functions) do work and yield the result of that work.
As such Methods will take often arguments that they might merely consume but also may return in an altered state or may produce a new object or value as a result of the work done.
Generally speaking - if you need a way of controlling access to data or state then Properties allow the implementation that access in a defined, validatable and optimised way (allowing access restriction, range & error-checking, creation of backing-store on demand and a way of avoiding redundant setting calls).
In contrast, methods transform state and give rise to new values internally and externally without necessarily repeatable results.
Certainly if you find yourself writing procedural or transformative code in a property, you are probably really writing a method.
Also note that properties are available via reflection. While methods are, too, properties represent "something interesting" about the object. If you are trying to display a grid of properties of an object-- say, something like the Visual Studio form designer-- then you can use reflection to query the properties of a class, iterate through each property, and interrogate the object for its value.
Think of it this way, Properties encapsulate your fields (commoningly marked private) while at the same time provides your fellow developers to either set or get the field value. You can even perform routine validation in the property's set method should you desire.
Properties are not just syntactic sugar - they are important if you need to create object-relational mappings (Linq2Sql or Linq2Entities), because they behave just like variables while it is possible to hide the implementation details of the object-relational mapping (persistance). It is also possible to validate a value being assigned to it in the getter of the property and protect it against assigning unwanted values.
You can't do this with the same elegance with methods. I think it is best to demonstrate this with a practical example.
In one of his articles, Scott Gu creates classes which are mapped to the Northwind database using the "code first" approach. One short example taken from Scott's blog (with a little modification, the full article can be read at Scott Gu's blog here):
public class Product
{
[Key]
public int ProductID { get; set; }
public string ProductName { get; set; }
public Decimal? UnitPrice { get; set; }
public bool Discontinued { get; set; }
public virtual Category category { get; set; }
}
// class Category omitted in this example
public class Northwind : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
}
You can use entity sets Products, Categories and the related classes Product and Category just as if they were normal objects containing variables: You can read and write them and they behave just like normal variables. But you can also use them in Linq queries, persist them (store them in the database and retrieve them).
Note also how easy it is to use annotations (C# attributes) to define the primary key (in this example ProductID is the primary key for Product).
While the properties are used to define a representation of the data stored in the database, there are some methods defined in the entity set class which control the persistence: For example, the method Remove() marks a given entity as deleted, while Add() adds a given entity, SaveChanges() makes the changes permanent. You can consider the methods as actions (i.e. you control what you want to do with the data).
Finally I give you an example how naturally you can use those classes:
// instantiate the database as object
var nw = new NorthWind();
// select product
var product = nw.Products.Single(p => p.ProductName == "Chai");
// 1. modify the price
product.UnitPrice = 2.33M;
// 2. store a new category
var c = new Category();
c.Category = "Example category";
c.Description = "Show how to persist data";
nw.Categories.Add(c);
// Save changes (1. and 2.) to the Northwind database
nw.SaveChanges();

Categories

Resources