Permanently disable saving of a model in Yii - yii

Is it possible to create an AR model in yii in such a way as to disable the save() function? I am using the models to display data that is entered into the DB from another source and will never need to update it.
UPDATE:
So which methods do I override, which methods in the base class actually write something to DB?

Simply override save and have it throw an appropriate exception. For example:
public function save(bool $runValidation=true, array $attributes=NULL)
{
throw new \LogicException("This kind of model does not support saving.");
}
This way it's also clear to anyone that mistakenly calls the method what is going on.
Don't forget to also override saveAttributes since the two methods are unfortunately completely independent.

Related

VB.NET How to "Refresh" data DbContext in winform

I have a DataDridview filled with objects queried with my DbContext.
I show some basic informations about my objects in this form.
I would like to query the most recent infos from the BD every time I select a different object in the DataDridview. I also want to be able to modify these objects.
I'm already able to do that. To modify an object, for example, I will do these steps:
-create a new DbContext
-get the object from my Datagridview using .Selectedrows(0).DatabountItem
-with that object's id I will query the (most recent) record in the DB using my new DbContext
-assign the old object (modified) properties to the new ones, one by one
-.SaveChanges on my new Dbcontext.
But there has to a better way, right? :/
If I understand correctly, by doing it this way I end up with a ton of unused Dbcontext and I doubt it's best practices.
But whenever I .Dispose my context, all EF navigation properties are broken and I get exceptions popping all over the place... So the ideal solution seems to me to just, refresh the data in a unique DbContext that I would use for the entire form. But is it even possible?
Maybe the solutions is obvious but I just can't see it.
If I'm unclear, please let me know I'll do my best to reformulate.
Any help would be appreciated, thanks!
** Edit **
In the end, here's the solution that worked best for me:
I do create a new DbContext for every logical operation, then immediatly .Dispose it...
Except for when I show informations about a specific row in my datagridview.
Instead, I create a new Context and leave it open. I will .Dispose only when the datagridview.SelectionChanged event fires.
The reason for not Disposing this context immediatly is: If a user saves his changes, but in the meantime someone else also saved changes on the same record, the (not-synced) context will hit a concurrency issue.. and I can let the user know about it, instead of overriding that row, which would be bad.
If I need these navigations properties from EF elsewhere, I can simply do eager loding by .Include("MyOtherTable") everything I need.( because navigation properties stop working when a context is Disposed)
I would use only one context in this case. You must just pay attention for accesing context from another threads - it can result in transaction errors ("New transaction is not allowed because there are other threads running in the session")
If you use DataGridView with DataSource from EF Context, all you have to do is just reload entities.
I wrote extension method in my context:
public partial class MyContext : testEntities1
{
public void Refresh(IEnumerable entities)
{
var ctx = ((IObjectContextAdapter)this).ObjectContext;
ctx.Refresh(System.Data.Entity.Core.Objects.RefreshMode.StoreWins, entities);
}
}
it is much faster than entry.Reload();
F.E.:
List<MyEntities> items = new List<MyEntities>();
foreach(DataGridViewRow row in dataGridView1.SelectedRows)
{
items.Add((MyEntities)row.DataBoundItem);
}
context.Refresh(items);

Calling Collection.allow() manually to check permissions

In Meteor JS I want to perform a task before adding an object to my collection. So I created my own method, eg: addObject like so:
Meteor.methods({
...
addObject: function(obj) {
/*
// this is what i'm trying to figure out...
if ( !MyColl.allow('insert', Meteor.userId, obj) )
throw Meteor.Error(403, 'Sorry');
*/
MyColl.update({ ... }}, { 'multi': true });
MyColl.insert(obj);
},
...
});
But I noticed that .allow is no longer being called because it's "trusted" code. The thing is the method is on the server but being called from the client (through ObjectiveDDP) so I still need a way to validate that the client has permissions to call addObject - is there any way to manually call .allow() on a collection from my server code? I tried it but getting an internal server error, and not sure what the syntax should be... couldn't find anything in the Meteor docs.
Edit:
I just found out that this works:
var allowedToInsert = MyColl._validators.insert.allow[0];
if (!allowedToInsert)
throw new Meteor.Error(403, 'Invalid permissions.');
But that's probably a no-no calling private methods such as _validators. Does anyone know of a more 'best practices' way?
You can do validation in the addobject method. For example, if you only want logged in users to be able to add an object, you can write:
if (!Meteor.user()) throw new Meteor.Error();
at the beginning of the addobject method.
Personally I never use allow.
On a related note, the collection2 and simple-schema packages can often help a lot with validation.
The validation pattern you are using might not be the best way to do things.
If you assume that methods can be called from the client, you shouldn't 'hack' it into doing something it's not meant to do.
If you are calling a method that changes data in the database you should check within that method that the currently logged in user has permission to do so.
However, are you sure you want to do this? Meteor also has Collection.allow and Collection.deny methods that you can use to define read/write/update/delete permission with. That's the recommended way to handle permissions, so what you are doing is an anti-pattern. However, perhaps in your case it is strictly necessary? If not, you might want to rethink the use case.
Like another response suggests, using something like Collections or SimpleSchema to validate data structure is also a good idea.

#ValidateConnection method is failing to be called when using "#Category component"

I have an issue in a new devkit Project where the following #ValidateConnection method is failing to be called (but my #processor methods are called fine when requested in the flows)
#ValidateConnection
public boolean isConnected() {
return isConnected;
}
I thought that the above should be called to check whether to call the #Connect method.
I think it is because I am using a non default category (Components) for the connector
#Category(name = "org.mule.tooling.category.core", description = "Components")
And the resulting Behavoir is different to what I am used to with DevKit in Cloud connector mode.
I guess I will need to do checks in each #processor for now to see if the initialization logic is done, as there doesn't seem to be an easy way to run a one time config.
EDIT_________________
I actually tried porting it back to a cloud connector #cat and the same behaviour, maybe its an issue with devkit -DarchetypeVersion=3.4.0, I used 3.2.x somthing before and things worked a bit better
The #ValidateConnection annotated method in the #Connector is called at the end of the makeObject() method of the generated *ConnectionFactory class. If you look for references of who is calling your isConnected() you should be able to confirm this.
So no, you should not need to perform the checks, it should be done automatically for you.
There must be something else missing... do you have a #ConnectionIdentifier annotated method?
PS. #Category annotation is purely for cosmetic purposes in Studio.

Method Interception, replace return value

We’re using Ninject.Extensions.Interception (LinFu if it matters) to do a few things and I want to know if its possible to return a value form the method being intercepted.
EG
A Call is made into one of our repository methods
Our Interceptor gets the BeforeInvoke event, we use this to look into the ASP.NET Cache to see if there is any relevant data
- Return the relevant data (this would cause the method to return immediately and NOT execute the body of the method
- Or Allow the method to run as per normal
Extra points if in the AfterInvoke method we take a peek at the data being returned and add it to the cache.
Has anybody done something similar before?
From your question I assume that you derive from SimpleInterceptor. This will not allow to return imediately. Instead you have to implement the Iinterceptor interface. You can decide to call the intercepted method by calling the Proceed method on the invocation or not.

How should one class request info from another one?

I am working on a VB.NET batch PDF exporting program for CAD drawings. The programs runs fine, but the architecture is a mess. Basically, one big function takes the entire process from start to finish. I would like to make a separate class, or several, to do the exporting work.
Here's the problem:
Sometimes the pdf file which will be created by my program already exists. In this case, I would like to ask the user if he/she would like to overwrite existing PDFs. I only want to do this if there is actually something which will be overwritten and I only want to do this once. In other words, "yes" = "yes to all." It seems wrong to have the form (which will be calling this new PDF exporting class) figure out what the PDF files will be called and whether there will be any overwrites. In fact, it would be best to have the names for the PDF files determined as the individual CAD drawings are processed (because I might want to use information which will only become available after loading the files in the CAD program in the background).
Here's the question:
How should I handle the process of prompting the user? I would like to keep all GUI logic (even something as simple as a dialog box) out of my PDF exporting class. I need a way for the PDF exporting class to say, "Hey, I need to know if I should overwrite or skip this file," and the form class (or any other class) to say, "Um, ok, I'll ask the user and get back to you."
It seems there ought to be some pattern to handle this situation. What is it?
Follow-ups:
Events: It seems like this is a good way to go. Is this about what the code should look like in the PDF exporting class?
Dim e As New FileExistsEventArgs(PDFFile)
RaiseEvent FileExists(Me, e)
If e.Overwrite Then
'Do stuff here
End If
A crazy idea: What about passing delegate functions to the export method of the PDF exporting class to handle the overwrite case?
You could use an Event, create a custom event argument class with a property on it that the application can call. Then when your app is handling the event prompt the user and then tell the exporter what to do. I'm a c# guy so let me give you a sample in there first:
void form_Load(object sender,EventArgs e)
{
//We are subscribing to the event here. In VB this is done differently
pdfExporter.FileExists+=new FileExistsEventHandler(pdfExporter_fileExists)
}
void pdfExporter_fileExists(object sender, FileExistsEventArgs e)
{
//prompUser takes the file and asks the user
if (promptUser(e.FileName))
{
}
}
Your PDF making class should raise an event. This event should have an eventargs object, which can have a boolean property called "Overwrite" which the GUI sets in whatever fashion you want. When the event returns in your PDF class you'll have the user's decision and can overwrite or not as needed. The Gui can handle the event anyway it likes.
Also, I commend you for working to keep the two seperate!
So the appropriate method on your class needs an optional parameter of
[OverwriteExisting as Boolean = False]
However your form will need to handle the logic of establishing whether or not a file exists. It seems to me that this would not be a function that you would want encapsulated within your PDF export class anyway. Assuming that your form or other function/class ascertains that an overwrite is required then the export methos is called passing True as a Boolean to your export class.
You could do a two phase commit type of thing.
The class has two interfaces, one for prepping the filenames and filesystem, and another for doing the actual work.
So the first phase, the GUI calls the initialization interface, and gets a quick answer as to whether or not anything needs over-writing. Possibly even a comprehensive list of the files that will get over-written. User answers, the boolean variable in the other responses is known, and then the exporter gets to the real work, and the user can go do something else.
There would be some duplication of computation, but it's probably worth it to get the user's part of the operation over with as soon as possible.
You can't keep the GUI stuff out of the PDF Exporting Code. but you can precisely define the minimum needed and not be tied to whatever framework you are using.
How I do it is that I have a Status class, and a Progress class. The two exist because Status is design to update a status message, and the Progress Bar is designed to work with a indicator of progress.
Both of them work with a object that has a class type of IStatusDisplay and IPrograssDisplay respectfully.
My GUI defines a object implementing IStatusDisplay (or IProgressDisplay) and registers as the current display with the DLL having Status and Progress. The DLL with Status and Progress also have two singleton called NullStatus and NullProgress that can be used when there is no UI feedback wanted.
With this scheme I can pepper my code with as many Status or Progress updates I want and I only worry about the implementations at the GUI Layer. If I want a silent process I can just use the Null objects. Also if I completely change my GUI Framework all the new GUI has to do is make the new object that implements the IStatusDisplay, IProgressDisplay.
A alternative is to raise events but I find that confusing and complicated to handle at the GUI level. Especially if you have multiple screen the user could switch between. By using a Interface you make the connection clearer and more maintainable in the longe.
EDIT
You can create a Prompt Class and a IPromptDisplay to handle situation like asking whether you want to overwrite files.
For example
Dim P as New Prompt(MyPromptDisplay,PromptEnum.YesNo)
'MyPromptDisplay is of IPromptDisplay and was registered by the GUI when the application was initialized
If PromptYesNo.Ask("Do you wish to overwrite files")= PromptReply.Yes Then
'Do stuff here
End If