How to inherit System.Data.SQLite in C# - c#

I use System.Data.SQLite and C# for accesing SQLite databases/tables. For lazy and fast development reasons, I created my own library of classes to encapsulate some of System.Data.SQLite methods in one method, and to create many common database routines (methods) that let me reduce my work when accessing to data.
If I would inherit System.Data.SQLite library instead of referencing it would help me to optimize my work, ¿is this possible? ¿may you give an example, please?

It's possible to inherit from SQLite and make additions to some of the classes, particularly SQLiteConnection. However, you won't be able to use your own classes everywhere as SQLite will internally create a lot of classes like SQLiteCommand and SQLiteParameter and you don't have an option to tell SQLite to use your custom versions. There is a SQLiteFactory, but this is used for ADO.NET data provider integration and is not used internally by SQLite.
You're much better off keeping your methods separate. If you want them to feel like they're part of the library you can use Extension Methods

This is a great question and I didn't find much in the way of answers 7-years later! I just had to do a simple inherit and found it a little tricky (because I wasn't completely familiar with constraining a generic type). But here's what I ended up with that worked.
using SQLite; // Here using sqlite-net-pcl
using System.Collections.Generic;
namespace SQLiteEx
{
class SQLiteConnection : SQLite.SQLiteConnection
{
// Must provide a constructor with at least 1 argument
public SQLiteConnection(string path)
: base(path)
{
}
// With this class, you can automatically append
// some kind of global filter like LIMIT 1000
string mGlobalFilter = "";
public string GlobalFilter
{
set { mGlobalFilter = value; }
get { return string.IsNullOrWhiteSpace(mGlobalFilter) ? "" : " " + mGlobalFilter; }
}
// You MUST constrain the generic type with "where T : new()"
// OTHERWISE feel the wrath of:
// ===================================================================
// 'T' must be a non-abstract type with a public parameterless
// constructor in order to use it as parameter 'T' in the generic
// type or method 'SQLiteConnection.Query<T>(string, params object[])'
// ===================================================================
public List<T> Query<T>(string sql) where T : new()
{
return base.Query<T>(sql + GlobalFilter);
}
}
}

Related

How can I create an alias for a class, globally, in Unity?

Right now, I am using "string" to enumerate a list of equipment slots on a character.
I am also using "string" to enumerate the class type that the item can be equipped on.
This makes all my methods where I get, remove, generate, etc. items involve having two string parameters that is an equipment slot and class type.
What I really would like is to use 2 classes so that I have 2 strongly typed concepts for the slot and class_type.
The problem is that string is a sealed class and thus I cannot extend it!
A solution I conceived is to use "using SlotType = string;" as alias but I don't know how to have this work GLOBALLY.
How do you define a global alias for a class?
In C# you can create a type alias using "using". Because obviously that term needed a 3rd meanings in C# ;) However 'the scope of a using directive is limited to the file in which it appears.', so it would not apply globally.
There is another option - create a subclass. For example,
public class ListOfIntegers : List<int>{
//Nothing to do here.
}
would give you a sort-off-alias for List<int> that applies everywhere ListOfIntegers is given as Project Reference.
As for not being able to extend something: Just encapsulate it instead.
public class TypedString1 {
public value;
}
public class TypedString2 {
public value;
}
But you may want to set it up so that string overloads are used for stuff like Equality and ToString calls. Also propably a implicit cast to string to make it easier to use.

Is it possible get around C# function parameter strong typing?

I have a C# application using ADO.Net access to a particular type of database (VistaDB) which I need to extend to optionally use a second type of database (SQL Server).
I'm unable to use Vista Entity Framework data access (which can support multiple database types) as this requires a higher version of the .NET framework than is available to most of my users. My data access functions take VistaDBConnection as ref arguments and whilst I can overload the functions to provide SqlConnection argument support, this will mean replicating a large number of data access functions.
I was wondering if it was possible to define function arguments to be either VistaDBConnection or SqlConnection types and then test for which type has been passed and provide options inside the data access routine to use either. I can do this by passing both VistaConnection and SqlConnection arguments to the data access functions but passing a single argument or variable type would be neater. However, this does break the strong typing feature of C#.
The best would be either to create an interface or a base class. Then have two concrete classes that implement this interface, one for VistaDB and one for SQL Server. You can then use some kind of factory (or Dependency Injection) to instantiate the correct class at runtime. The methods in question would then take an instance of the interface/base class and does not need to know any of the specific inner workings. For example:
interface IApplicationDatabase
{
Foo GetFoo(int id);
}
class VistaDatabase : IApplicationDatabase
{
public Foo GetFoo(int id)
{
//do VistaDB-specific things to get the Foo
}
}
class SqlServerDatabase : IApplicationDatabase
{
public Foo GetFoo(int id)
{
//do SQL Server-specific things to get the Foo
}
}
class Demo
{
public Foo GetFooFromStorage(int id, IApplicationDatabase storage)
{
//notice here we don't need any separate code depending on the
//concrete type of database
return storage.GetFoo(id);
}
}
You just need to define more generic type or we can say parent type of the both connection SQL as well as VistaDB connection like following. and then use as operator to cast and check against null to check whether cast was successful or not.
public void Connect(DbConnection dbConnection)
{
var sqlDbCon = dbConnection as SQLConnection;
if(con != null)
{
//process here for SQLConnection
}
var vistaDbCon = dbConnection as VistaDbConnection;
if(con != null)
{
//process here for VistaDbConnection
}
}
You don't need to do separate implementation in if else if all you want is available in a parent class like in this case if you just want to call connect method then you can do it like below because it does have connect method in IDbConnection.
public void Connect(IDbConnection dbConnection)
{
dbConnection.Open();
}
It would work in both the case with sql server and vistadb.
The idea is, Instead of using a class as type for the parameter, use interface as type for the parameter.
This interface will be defined by you and implemented individually for each type of connection.
Now when you pass instance of any classes implementing the interface, your code will work.
Use Interface function to call provider specific functions.
Previous two code samples added by other contributors is the correct example for that, Use any of them.

C# class instance attribute mechanism

Is there a sane way in C# to achieve the following construct (in pseudocode):
void Method(MyClass<Attribute1, Attribute2, ...> foo)
{
// here I am guaranteed that foo has the specified attributes
}
Where Attribute* are, for example, enum values, such that only instances of MyClass instantiated with the attributes required by the method can be passed to the method (and otherwise fail to compile)?
I tried looking at generics since I know that C++ templates can make this work so it seemed like a logical starting point, but I couldn't get it working elegantly (I tried using interfaces to constrain the types of the parameter in this fashion but it was very bulky and frankly unusable since I have at least 4 attributes).
I want to do this to avoid having lots of annoying checks at the beginning of each method. I am doing DirectX 11 graphics development so I am kind of constrained by the API which does not make it particularly easy to pass objects around in this "type-safe" manner (in DirectX every resource has a large "Description" structure which contains information about what the resource can and cannot do, is and is not, etc.. and is tedious and error-prone to parse, so I am trying to write a wrapper around it for my and my users' convenience).
I also cannot have different class types for every case because there are a lot of combinations, so this seems like the most comfortable way to write code like this, and I am hoping C# makes this possible.
I'm sure there is a name for this kind of language feature (if you know it please let me know, I would have googled but this is kind of hard to search for when you don't know the proper keywords...)
Generic type parameters in .NET must be types themselves. You can't create a generic type/method that is specific to a particular value of the Generic type parameter only.
If you do not want or cannot create a type that represents the attribute values you want your method being restricted to, you will have to do sanity checks in your method to ensure that the proper attribute values are used in the provided "foo" object.
Using specific types as representation of specific attribute values might be an answer for the problem you asked about, but it has the disadvantage of not supporting switch-case statements (see further below). Please also read the final note at the end of my answer.
Say, you want a type that represents textures. Textures can have different number of channels, and different bit depths. You could then declare a generic texture type like this:
class Texture<TChannels, TBPC>
where TChannels : INumOfChannels,new()
where TBPC : IBitsPerChannel,new()
INumOfChannels and IBitsPerChannel are just interfaces and can be empty.
The new() constraint prevents creation of a concrete Texture type by using the interfaces themselves.
For different channels and different BPCs, you will create empty types extending from the respective base interfaces, for example:
class FourChannels : INumOfChannels {};
class ThreeChannels : INumOfChannels {};
class BitsPerChannel_24 : IBitsPerChannel {};
class BitsPerChannel_32 : IBitsPerChannel {};
Using this, you can restrict your generic method to certain attribute combinations. In case your method should only deal with 4-channel and 32bpc textures:
void MyMethod<TChannels, TBPC>(Texture<TChannels, TBPC> foo)
where TChannels : FourChannels
where TBPC : BitsPerChannel_32
Now, every good thing also has dark sides. How would you do something like this (written as pseudo-code)?
switch (NumOfChannelsAttribute)
{
case FourChannels:
// do something
break;
case ThreeChannels:
// do something else
break;
}
You can't, at least not in an easy and simple way, because "FourChannel" and "ThreeChannel" are types, not integral values.
Of course, you can still use if constructs. For this to work you would need to implement a property in the generic texture type which provides the used attributes:
class Texture<TChannels, TBPC> where TChannels : INumOfChannels,new() where TBPC : IBitsPerChannel,new()
{
public Type ChannelsAttribute
{
get { return typeof(TChannels); }
}
public Type BitsPerChannelAttribute
{
get { return typeof(TBPC); }
}
}
In an if construct, you could utilize this as follows:
var myTex = new Texture<FourChannels, BitsPerChannel_32>();
if (myTex.ChannelsAttribute == typeof(FourChannels))
{
... do something with 4 channels
}
else
{
... though luck, only 4 channels are supported...
}
A final note and advice:
While this might work for your problem, resorting to these kind of 'tricks' usually is an indication of a flawed design. I think it is well-invested time if you revisit the design choices you made in your code, so you don't need to rely on crutches like this.
C# doesn't have such a feature. You mention you have tried using interfaces, but don't specify how. The way I'd suggest you try using them is by using generics with multiple constraints, eg
void Method(T foo) where T : IAttribute1, IAttribute2, IAttribute3, IAttribute4
{
}
Let's say one such attribute class is then ICpuMappable, then you can constrain types that can be used with Method1 with:
void Method1(T foo) where T : ICpuMappable
{
}
and you can know any foo passed to Method1 is CPU mappable.
You'll likely end up with lots of interfaces, but as many will be treated as "flags", they shouldn't be too difficult to maintain.

value of generic class?

I couldn't find the need of a generic class other than situations like collection of classes. Items like stack and linked list.
I can see people use it in other places also.
What do we gain using a generic class?
Well let's say you have a class that repersents a database table, you would need methods like Save(), Delete() - which work on any database table entity, and regardless of the type, they all operate the same way (a generic way).
So to solve that you could use a generic class like so:
public class BaseEntityModel<T> where T : IEntity2 // We use llblgen here
{
// ... code
// T is a generic type parameter which has to implement IEntity2.
// But we don't care what type it is.
public T Entity { get; set; }
public void Save()
{
Entity.Save(); // Save is from IEntity2
}
// ... code
}
Then for a Customer class we could go like this
public class Customer : BaseEntityModel<CustomerEntity>
{
public void Method()
{
// Entity is of type Customer entity
Entity.CustomerName = "Bob";
base.Save();
}
}
and then one for Company
public class Company : BaseEntityModel<CompanyEntity>
{
public void Method()
{
// Entity is of type Company entity
Entity.CompanyName = "My Company";
base.Save(); // Save is declared in the base class for a generic type (in this case company)
}
}
So is this code example it allows the same generic code to be used on different types of objects, and can be constrained to certain types of objects (using where T : IMyInterface)
There are more ways to constrain the type of object that can me used on. This information is on MSDN
MSDN has a pretty comprehensive article on the Advantages and Limitations of Generics. Basically, when you use generics you decrease the headache of type-checking to ensure type safety, type compatibility, etc. It's all handled for you at compile time.
They can help you to avoid code duplication -- for example, rather than writing FooMethod(int arg), FooMethod(string arg) etc., you can just write FooMethod<T>(T arg), which is cleaner and much more maintainable.
Also note that you can add constraints on generic type parameters using the where keyword. This is useful in making sure that a generic type parameter implements a certain interface, or has a default parameterless constructor, etc.
You gain code reuse - the same source code and logic, instantiated using and operating on different concrete types or combination of types. Leverage.
Generics allow you to implement type-safe routines that will work on any type that supports the operations performed in the routine. This way you don't have to define the same class or function multiple times to handle different types even though all the types would be handled exactly the same way in the source.
You are more-or-less right: apart from very weird places, you mainly use them in collections. But you use collections everywhere, so generics are a godsend.

Extension interface patterns

The new extensions in .Net 3.5 allow functionality to be split out from interfaces.
For instance in .Net 2.0
public interface IHaveChildren {
string ParentType { get; }
int ParentId { get; }
List<IChild> GetChildren()
}
Can (in 3.5) become:
public interface IHaveChildren {
string ParentType { get; }
int ParentId { get; }
}
public static class HaveChildrenExtension {
public static List<IChild> GetChildren( this IHaveChildren ) {
//logic to get children by parent type and id
//shared for all classes implementing IHaveChildren
}
}
This seems to me to be a better mechanism for many interfaces. They no longer need an abstract base to share this code, and functionally the code works the same. This could make the code more maintainable and easier to test.
The only disadvantage being that an abstract bases implementation can be virtual, but can that be worked around (would an instance method hide an extension method with the same name? would it be confusing code to do so?)
Any other reasons not to regularly use this pattern?
Clarification:
Yeah, I see the tendency with extension methods is to end up with them everywhere. I'd be particularly careful having any on .Net value types without a great deal of peer review (I think the only one we have on a string is a .SplitToDictionary() - similar to .Split() but taking a key-value delimiter too)
I think there's a whole best practice debate there ;-)
(Incidentally: DannySmurf, your PM sounds scary.)
I'm specifically asking here about using extension methods where previously we had interface methods.
I'm trying to avoid lots of levels of abstract base classes - the classes implementing these models mostly already have base classes. I think this model could be more maintainable and less overly-coupled than adding further object hierarchies.
Is this what MS has done to IEnumerable and IQueryable for Linq?
Extension methods should be used as just that: extensions. Any crucial structure/design related code or non-trivial operation should be put in an object that is composed into/inherited from a class or interface.
Once another object tries to use the extended one, they won't see the extensions and might have to reimplement/re-reference them again.
The traditional wisdom is that Extension methods should only be used for:
utility classes, as Vaibhav mentioned
extending sealed 3rd party APIs
I think the judicious use of extension methods put interfaces on a more equatable position with (abstract) base classes.
Versioning. One advantage base classes have over interfaces is that you can easily add new virtual members in a later version, whereas adding members to an interface will break implementers built against the old version of the library. Instead, a new version of the interface with the new members needs to be created, and the library will have to work around or limit access to legacy objects only implementing the original interface.
As a concrete example, the first version of a library might define an interface like so:
public interface INode {
INode Root { get; }
List<INode> GetChildren( );
}
Once the library has released, we cannot modify the interface without breaking current users. Instead, in the next release we would need to define a new interface to add additional functionalty:
public interface IChildNode : INode {
INode Parent { get; }
}
However, only users of the new library will be able to implement the new interface. In order to work with legacy code, we need to adapt the old implementation, which an extension method can handle nicely:
public static class NodeExtensions {
public INode GetParent( this INode node ) {
// If the node implements the new interface, call it directly.
var childNode = node as IChildNode;
if( !object.ReferenceEquals( childNode, null ) )
return childNode.Parent;
// Otherwise, fall back on a default implementation.
return FindParent( node, node.Root );
}
}
Now all users of the new library can treat both legacy and modern implementations identically.
Overloads. Another area where extension methods can be useful is in providing overloads for interface methods. You might have a method with several parameters to control its action, of which only the first one or two are important in the 90% case. Since C# does not allow setting default values for parameters, users either have to call the fully parameterized method every time, or every implementation must implement the trivial overloads for the core method.
Instead extension methods can be used to provide the trivial overload implementations:
public interface ILongMethod {
public bool LongMethod( string s, double d, int i, object o, ... );
}
...
public static LongMethodExtensions {
public bool LongMethod( this ILongMethod lm, string s, double d ) {
lm.LongMethod( s, d, 0, null );
}
...
}
Please note that both of these cases are written in terms of the operations provided by the interfaces, and involve trivial or well-known default implementations. That said, you can only inherit from a class once, and the targeted use of extension methods can provide a valuable way to deal with some of the niceties provided by base classes that interfaces lack :)
Edit: A related post by Joe Duffy: Extension methods as default interface method implementations
I think the best thing that extension methods replace are all those utility classes that you find in every project.
At least for now, I feel that any other use of Extension methods would cause confusion in the workplace.
My two bits.
There is nothing wrong with extending interfaces, in fact that is how LINQ works to add the extension methods to the collection classes.
That being said, you really should only do this in the case where you need to provide the same functionality across all classes that implement that interface and that functionality is not (and probably should not be) part of the "official" implementation of any derived classes. Extending an interface is also good if it is just impractical to write an extension method for every possible derived type that requires the new functionality.
I see separating the domain/model and UI/view functionality using extension methods as a good thing, especially since they can reside in separate namespaces.
For example:
namespace Model
{
class Person
{
public string Title { get; set; }
public string FirstName { get; set; }
public string Surname { get; set; }
}
}
namespace View
{
static class PersonExtensions
{
public static string FullName(this Model.Person p)
{
return p.Title + " " + p.FirstName + " " + p.Surname;
}
public static string FormalName(this Model.Person p)
{
return p.Title + " " + p.FirstName[0] + ". " + p.Surname;
}
}
}
This way extension methods can be used similarly to XAML data templates. You can't access private/protected members of the class but it allows the data abstraction to be maintained without excessive code duplication throughout the application.
A little bit more.
If multiple interfaces have the same extension method signature, you would need to explicitly convert the caller to one interface type and then call the method. E.g.
((IFirst)this).AmbigousMethod()
Ouch. Please don't extend Interfaces.
An interface is a clean contract that a class should implement, and your usage of said classes must be restricted to what is in the core Interface for this to work correctly.
That is why you always declare the interface as the type instead of the actual class.
IInterface variable = new ImplementingClass();
Right?
If you really need a contract with some added functionality, abstract classes are your friends.
I see a lot of people advocating using a base class to share common functionality. Be careful with this - you should favor composition over inheritance. Inheritance should only be used for polymorphism, when it makes sense from a modelling point of view. It is not a good tool for code reuse.
As for the question: Be ware of the limitations when doing this - for example in the code shown, using an extension method to implement GetChildren effectively 'seals' this implementation and doesn't allow any IHaveChildren impl to provide its own if needed. If this is OK, then I dont mind the extension method approach that much. It is not set in stone, and can usually be easily refactored when more flexibility is needed later.
For greater flexibility, using the strategy pattern may be preferable. Something like:
public interface IHaveChildren
{
string ParentType { get; }
int ParentId { get; }
}
public interface IChildIterator
{
IEnumerable<IChild> GetChildren();
}
public void DefaultChildIterator : IChildIterator
{
private readonly IHaveChildren _parent;
public DefaultChildIterator(IHaveChildren parent)
{
_parent = parent;
}
public IEnumerable<IChild> GetChildren()
{
// default child iterator impl
}
}
public class Node : IHaveChildren, IChildIterator
{
// *snip*
public IEnumerable<IChild> GetChildren()
{
return new DefaultChildIterator(this).GetChildren();
}
}
Rob Connery (Subsonic and MVC Storefront) implemented an IRepository-like pattern in his Storefront application. It's not quite the pattern above, but it does share some similarities.
The data layer returns IQueryable which permits the consuming layer to apply filtering and sorting expression on top of that. The bonus is being able to specify a single GetProducts method, for example, and then decide appropriately in the consuming layer how you want that sorting, filtering or even just a particular range of results.
Not a traditional approach, but very cool and definitely a case of DRY.
One problem I can see is that, in a large company, this pattern could allow the code to become difficult (if not impossible) for anyone to understand and use. If multiple developers are constantly adding their own methods to existing classes, separate from those classes (and, God help us all, to BCL classes even), I could see a code base spinning out of control rather quickly.
Even at my own job, I could see this happening, with my PM's desire to add every bit of code that we work on to either the UI or the data access layer, I could totally see him insisting on 20 or 30 methods being added to System.String that are only tangentially-related to string handling.
I needed to solve something similar:
I wanted to have a List<IIDable> passed to the extensions function where IIDable is an interface that has a long getId() function.
I tried using GetIds(this List<IIDable> bla) but the compiler didn't allow me to do so.
I used templates instead and then type casted inside the function to the interface type. I needed this function for some linq to sql generated classes.
I hope this helps :)
public static List<long> GetIds<T>(this List<T> original){
List<long> ret = new List<long>();
if (original == null)
return ret;
try
{
foreach (T t in original)
{
IIDable idable = (IIDable)t;
ret.Add(idable.getId());
}
return ret;
}
catch (Exception)
{
throw new Exception("Class calling this extension must implement IIDable interface");
}

Categories

Resources