I am trying to create a very simple Window for display a list of items that comes from an Sqlite3 database. I have a generic list of my objects, and I want to bind that to the controls on the windows. What is the best way to do this?
If it was .NET windows forms, I would do this, what is the Cocco equivalent? myBindingSource.DataSource = new List<MyObject>();
My ViewController.cs code currently looks like this:
List<MyObject> dataSource = DataStore.GetLibraries();
public override AwakeFromNib() {
base.AwakeFromNib();
dataSource = GetMyObjects();
myArrayController.Bind("contentArray", this, "dataSource", null); // Throws error
}
But this throws an error: this class is not key value coding-compliant for the key DataSource.
Thanks!
After linking libsqlite3.dylib to your framework (General:Linked Frameworks and Libraries) and adding the database-file to your project you create an sqlite accessor class, to do the database connections and enable the queries.
If your project should also save into the database, on installation the database must be placed at a position where you have also write-access, this would be in the "Documents"-folder for an iphone app or in "Application Support" on MacOS X, but not in the application bundle itself. (Take care not to mess the owner-name, otherwise only root or you have write access and your customers won't)
To connect your query result to the Array-Controller which seems to be the heart of your question, the query's output needs to be formatted according to apple's KVC rules. This is done by creating an NSDictionary (with objects and keys) and set up the array controller to read in from this dictionary.
The link from where i got this to work in my own projects has unfortunately been deleted, but i found you two tutorials, that give you the necessary function-calls, if you feel you need more details on this:
a) for the sqlite connection: http://www.techotopia.com/index.php/An_Example_SQLite_based_iOS_4_iPhone_Application_(Xcode_4)
b) for connecting an NSArrayController with a Dictionary:
http://ihoneylocust.wordpress.com/2013/02/19/first-mac/
Related
Folks,
I just started to design a new web project. From VS2012, I generated a new Internet website project. It comes with a database that is already laid out with a few tables. This is fine.
Now, I need to extend the database with a few new tables and update UserProfile with few new fields. However, as this is going to be a new database, I don't want to enable migration steps and add code-bloat that is not really needed.
Here is the workaround I found:
Extend UserProfile with new fields as you would want to.
Add new tables in AccountModels.cs. For example,
[Table("Items")]
public class Items {
...
}
For each new table, add a DbSet field to UsersContexts class in AccountModels.cs.
public class UserContext : DbContext {
...
public DbSet<Items> Items {get; set; }
}
Delete the original database file, create a new database file with the same name, and run the application.
Voila. The new database gets filled with all the tables.
Is this the right way to do it?
Although it works, I am not really sure about step 3. I figured somehow the framework needs to know that a new table needs to be created and essentially adding a new field to UserContext triggers the creation of the new table. Is this the approach right?
Thank you in advance for your help.
Regards,
Peter
By not using code first migrations, deleting the database manually is the best thing you can do. There is also the DropCreateDatabaseIfModelChanges initializer but be careful to never use it in a release version of your app.
I would also recommend to write the DbContext in a seperate cs file. When you use the fluent api to configure the EF relations (what i would do), it can get really big. Think about putting the DAL and your models in seperate projects when your solution gets bigger. Using multiple contexts for one db can also cause problems, so naming it SomeAppContext would be better.
we have an architectual problem with our data grid. The grid supports searching, paging and sorting using a linq2entity query, that contains all of the above parameters.
At some pages, the grid should not display the content from the database (e.g. column 'name'), but the translated ressource, loaded by the Resource Provider.
Our Resource Provider gets the translations from the database and caches them to the application cache to avoid unneccessary trips to the database.
At this point, we have the following possibilities:
No searching, sorting and paging on the databse, so loading all rows, then load the translations from the Resource Provider, then do the searching, sorting and paging at the application.
Bad performance, because the database is very big
Searching, sorting and paging on the database, then load the ressources for the results.The Displayed Values will not match to the search and sort configuration
Get the Resources directly from the database, within the linq query.
The Ressource Provider Caching cannot be used. The Join with the Resource Provider Texts will be very bad and slow
Every possibility is very bad, but I can't think of another solution. Any good suggestions? How are these problems solved in other software?
You can do it by bring the associated filtered records from the database and keep it in ViewState.
How can you improve the Performance?
You can make use of JSON / Page Methods for Database Callings. I will explain it to you with the help
of an example.
Click here to check the code for GridView Bindings using JSON
Mark Up With JSON
I am calling the Code Behind methof from Client side
Code Behind
Output
Click here to check the output in case of Update Panels
Is application is holding too much memory then you need a Doctor like Red Gate Ants Memory Profiler. Click here to see more details about it
Make sure to use the Using Statements to avoid Memory Out of Exceptions
using (SqlConnection connection = new SqlConnection())
{
connection.Open();
//Also for SqlCommand... Sample code...
using (SqlCommand cmd = new SqlCommand())
{
}
using (SqlTransaction transaction = connection.BeginTransaction())
{
transaction.Commit();
}
}
Are you aware about the Teleric Grid? It loads all the records first from the database and keeps in Cache. In order to go for this you must use Paging and Disposing the objects is mandatory. Teleric Grid shows these records in Paging. Thus you can avoid the rendering issue to get rid of displaying all records in once.
i don't understand your question properly but if you want to all operations on translated resource you have to store translated resource in database then get them in to session object and apply filter on it if it is either in form of table or list then give source to grid which has to configured as work with translated resource which is filtered from session object.
I am using Adobe Air to get data from SalesForce, and present it in a datagrid.
I am using a query to get the data, and then put it into an arraycollection that is bound to the datagrid, this works correctly and the data is displayed.
I have made the datagrid editable, and I am able to change the values in the datagrid, but I cannot find how to save the changes to the local database.
I am using the following code:-
protected function VisitReportGrid_changeHandler(event:ListEvent):void{
app.wrapper.save(VisitReportGridProvider)
}
But this has the following error when I try and compile it:-
1067: Implicit coercion of a value of type mx.collections:ArrayCollection to an unrelated type mx.data:IManaged.
Obviously I am doing this wrong, but I cannot find the correct syntax.
Thanks in advance for your help
Roy
This code is not enough to understand where actually is the problem
Need to know what is VisitReportGridProvider, what is wrapper.save() method.
**after comment:
F3DesktopWrapper.save():
public function save(item:IManaged):void
Saves the specified Managed object to the local database. You must make an explicit call to syncWithServer() to update the data on the salesforce server. However, do not call syncWithServer() too often (batch your save calls) as this may use up your alloted API usage. If the item is in conflict, the conflict will be resolved.
Parameters:
item:IManaged — The managed object to create or update.
you're passing parameter with type ArrayCollection which doesn't implement IManaged interface.
You need to pass the item in the ArrayCollection that was changed to the save function. Like:
acc.fieldCollection.updateObject(new AsyncResponder(function(o:Object, t:Object):void {
app.wrapper.save(o as Account);
}, function(e:Object):void {
}));
I need to set my connection string for Linq to Sql based on an environment variable. I have a function which will return the connection string from the web.config based on the environment variable, but how do I get Linq to always use this "dynamically created" connection string (preferably without having to specify it every time)?
I know I can specify the connection string using the constructor, but how does that work when using the datacontext in a LinqDataSource?
Use:
MyDataClassesDataContext db = new MyDataClassesDataContext(dynamicConnString);
For a LinqDataSource, intercept the ContextCreating event and create the DataContext manually as above:
protected void LinqDataSource_ContextCreating(object sender, LinqDataSourceContextEventArgs e)
{
e.ObjectInstance = new MyDataClassesDataContext (dynamicConnString);
}
From MSDN:
By default, the LinqDataSource control
creates an instance of the type that
is specified in the ContextTypeName
property. The LinqDataSource control
calls the default constructor of the
data context object to create an
instance of the object. It is possible
that you have to use a non-default
constructor or you have to create an
object that differs from the one
specified in the ContextTypeName
property. In that case, you must
handle the ContextCreating event and
manually create the data context
object.
Open up the LINQ to SQL designer, and open the Properties tab of the designer (the schema itself), expand Connection and set Application Settings to False. Save.
Close that down and open up your DataContext designer file (dbml_name.designer.cs) and alter the DataContext constructor. You will immediately notice how your connection string decided to jump in here as you turned off application wide settings. So the part to focus on here is altering the base() inheritor. Renaming ConnString” below to suit your own. I also noticed a DatabaseAttribute on the class which I don’t think plays a big part and has any implications on the connection settings. You will also need a reference to System.Configuration:
public dbDataContext() : base(ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString, mappingSource)
Open the App.config or Web.config featured in the project where your LINQ to SQL classes reside, and rename the connection string to what you defined as “MyConnString“.
You now must Cut the entire entry with name change and Paste it into either the App.config or Web.config of the application which is to access the data, such as a web application, Silverlight, WPF, WCF etc. It is important that you alter the configuration file of the calling application which is to access the data, as the ConfigurationManager defined in your LINQ to SQL classes will look for the .config file from where the calling application is executing from, no matter where your LINQ to SQL classes have been Defined. As you can see, it works a little differently from before.
Now Right Click and open the Properties on your DAL or project containing your LINQ to SQL classes and remove the connection string “Application Setting” reference on the Settings tab.
Rebuild. You’re all done, now just do a Find in Files check for perhaps your database name that you know was featured in the connection string to check for any stragglers, there shouldn’t be any.
The DataContext class has a constructor that takes in a connection string.
you can change the connection string dynamically if you will implement the OnCreated() function. This function is a partial function and it can be implemented in seperate file other than where you dbml exists.
for detail please see this article
http://aspilham.blogspot.com/2011/01/how-do-i-set-connection-string-in-linq.html
I am using web forms, C#, Asp.net.
As we all know, in this model UI and business logic are often mixed in. How do I separate these effectively?
The example I would like to use is:
I have a GridView and a DataTable (GridView binds to the DataTable and DataTable is fed from the stored procedure).
I would like the GridView (UI) and DataTable (business logic) to be decoupled.
Is it worth it to write an wrapper for DataTable? Are there practical patterns that have been proved and tested that you could recommend to be followed?
If someone with experience could shed some light, that would be awesome.
And, as a final note I would like to say that ASP MVC is not an option right now, so don't recommend it.
My database access layer returns a DataTable.
Note that I HAVE to use this database layer as this is a company policy.
I went through this recently while decoupling much the same thing from our UI layer.
You can see my progress here and here.
In my opinion, A DataTable does not represent business logic. Specifically, it's data pulled directly from the database. Business logic turns that data into a truly useful business object.
The first step, then, is to decouple the DataTable from the Business object.
You can do that by creating objects and List<object> that make up DataTables and Collections of DataTables, and then you can make a ListView that displays those Objects. I cover the latter steps in the links I posted above. And the former steps are as easy as the following:
Create a class that will represent your object.
iterate through your DataTable (or DataSet, or however you retrieve the data) and shove those fields into properties of that object (or that List<T>);
return that List to the Gridview or ListView to display.
This way your ListView or Gridview won't be tightly coupled to the method that you are retrieving your data. What happens if you decide to get your data from a JSON query or a XML file later on? Then you'd have to build this into there.
Step 1 - Getting Data From Database
There are multiple methods to get data from a database, there's no way I can go through all of them here. I assume that you already know how to retrieve data from a database, and if you don't, there are quite a few links to follow. Let's pretend you've connected to the database, and are using an SQLDataReader to retrieve data. We'll pick up there.
Class Diagram
Foo
----
id
Name
Description
And here's the method:
private void FillDefault(SqlDataReader reader, Foos foo)
{
try
{
foo.id = Convert.ToInt32(reader[Foo.Properties.ID]);
foo.Name = reader[Foo.Properties.NAME].ToString();
if (!string.IsNullOrEmpty(
reader[Foo.Properties.DESCRIPTION].ToString()))
foo.Description =
reader[Foo.Properties.DESCRIPTION].ToString();
else foo.Description = string.Empty;
}
catch (Exception ex)
{
throw new Exception(
string.Format("Invalid Query.
Column '{0}' does not exist in SqlDataReader.",
ex.Message));
}
}
Once that happens, you can return a list by going through that process in a while loop that targets the SQLDataReader.Read() function.
Once you do that, let's pretend that your Foo being returned is a List. If you do that, and follow the first link I gave above, you can replace Dictionary<TKey, TValue> with List<T> and achieve the same result (with minor differences). The Properties class just contains the column names in the database, so you have one place to change them (in case you were wondering).
DataTable - Update Based on Comment
You can always insert an intermediate object. In this instance, I'd insert a Business Layer between the DataTable and the UI, and I've discussed what I'd do above. But a DataTable is not a business object; it is a visual representation of a database. You can't transport that to the UI layer and call it de-coupled. They say you have to use a DataTable, do they say that you have to transport that DataTable to the UI? I can't imagine they would. If you do, then you'll never be de-coupled. You'll always need an intermediate object in between the DataTable and the UI layer.
I'd start by decoupling the data table right into the trash can. Build a domain layer, and then some type of data access layer which deals with the DB (ORM recommended).
Then build a servicing layer which provides the data to the UI. All business logic should be within the service or the entities themself.
Consider implementing MVP (model view presenter) pattern. It gives you separation of biz logic through presenter interface, which also allow better unit testing capabilities. Your codebehind of aspx page is then just connector of events and getter/setter of properties. You can find it in MS pattern&practices enterprise application blocks (CAB - composite application block - if i'm not mistaking).
You can read more about it here: http://msdn.microsoft.com/en-us/magazine/cc188690.aspx
But also going from DataTable/DataSets to objects (POCO) is preferred.