I am working in video application in my application am using many controls for user friendly first i will Load the base from only after that i ll load the other controls based on user need.... here my need is if user load ten controls in this case if he shutdown the machine means when he restart the machine i need to bring the all controls back what he was load the controls before he shutdown. thanks in advance
is there is any possible to achive this without store the current control set, and positions etc..
You need to look at something like
Form and Control Position and Size
Utility
Save and restore Form position and
layout with this component
Basically what it boils down to, is that you need a way to store the current control set, and positions (possibly values too) to some sort of storage (XML file, Registry, Database) when the user exits your form/application.
Then once they reopen the form/application, you need to retrieve these settings for the given user (if any is available) and restore the form/application to that state.
How about making extension methods to Control class?
(Actually, appropriate .NET abstract base class, a sub-class of Control class, depending on UI. Do you use Windows Forms or XAML or ASP.NET?)
Something like:
public static class MyPositionExtensions{
public static void SaveState(this Control c){ /* Save position to xml-file */ }
public static void RestoreState(this Control c){ /* Load from xml-file */ }
}
Then in your closing just loop like
foreach(var c in MyControls)c.SaveState();
and opening like
foreach(var c in MyControls)c.RestoreState();
Related
I Would like to know if the Genexus Extension SDK already implements something to store persistent data locally (KB Independant and per KB), something like PersistentDictionary from ManagedEsent
I know that genexus uses SQL Server to store KB Related information, is there an interface for me to extend that?
I want to save data per genexus instance (locally) and use that data to load my extension config, everytime the users executes Genexus.
We don't use PersistentDictionary. I would advice not to use it, as it's a Windows specific API, and we are trying make everything new cross platform, as part of our journey of making GeneXus BL run on other OS.
There are different options of persistence, depending on the specific details of your scenario.
If you want to store something like configuration settings for your extension, you can use the ConfigurationHelper class located in Artech.Common.Helpers. This class provides read access to the configurations defined in the GeneXus.exe.config file in the GeneXus installation folder, as well as read/write access to the Environment.config file located in %AppData%\GeneXus\GeneXus\<version>\Environment.config. Note this file depends on the current user, and is shared between different GeneXus instances of a same main version.
The ConfigurationHelper class provides operations to read and save settings of basic types string, int and bool.
const string MY_EXTENSION = "MyExtensionSettings";
const string SETTING1 = "Setting1";
const string SETTING1_DEFAULT_VALUE = "This is the default value";
const string SETTING2 = "Setting2";
const int SETTING2_DEFAULT_VALUE = 20;
string setting1Value = ConfigurationHelper.GetUserSetting(MY_EXTENSION, SETTING1, SETTING1_DEFAULT_VALUE);
int setting2Value = ConfigurationHelper.GetUserSetting(MY_EXTENSION, SETTING2, SETTING2_DEFAULT_VALUE);
// Do something and maybe change the setting values
ConfigurationHelper.SetUserSetting(MY_EXTENSION, SETTING1, setting1Value);
ConfigurationHelper.SetUserSetting(MY_EXTENSION, SETTING2, setting2Value);
If you want to store something in a file based on the current opened KB, there's no specific API that'll help you handle the persistence. You can use the properties Location and UserDirectory of the KnowledgeBase class to access the KB location or a directory for the current user under the KB location, but it's up to you the handling of the file. You'll have to decide on the file format (binary or text), file encoding in case of text files, and handle all read and write operations to that file.
We use the kb.UserDirectory path to store non-critical stuff, such as the set of objects that were opened the last time the KB was closed, or the filter values for different dialogs.
In case you'd like to store settings inside the KB, there are plenty of options.
You can add properties to existing objects, KB version or environment. Making it a property doesn't necessary mean you'll have to edit the value in the property grid, although it's usually the way to go.
You can define a new kind of entity. Entities are the basic elements that can be stored in a KB. The entity may be stored depending on the active version of the KB, or may be independent of the current version. Entities can have properties, whose serialization is handled by the property engine, and also can read and store a byte array whose format and content will be handled by you.
You can add a part to an existing object. For instance you may want to add a part to Procedure objects. In order to do this you'll have to extend KBObjectPart, define your part in a BL package, declare that the part composes objects of certain type, and provide an editor for your new part in a UI package. KBObjectPart extends Entity so the serialization of the part is similar as in the previous case. A caveat of this option is that you'll also have to handle how the part content is imported, exported, and compared.
You can add a new kind of object. Objects extend the KBObject class, which extends Entity. Objects are not obliged to have parts (for instance the Folder object doesn't have any). When choosing to provide a new kind of object you have to consider a couple of things, such as:
Do you want to be able to create new instances from the new object dialog?
Will it be shown in the folder view?
Can it be added into modules?
Can it have the same name as other objects of different types?
As a general guideline, if you choose to add a new property, add it to objects, versions, or environments, not parts. Adding properties to parts is not so good for discoverability. Also if you choose to add a new kind of object, even though it inherits from Entity which as mentioned earlier can read and store a byte array, it's preferred to don't use the byte array in KBObject and add a KBObjectPart to it instead. That way the KBObject remains as lightweight as possible, and loading the object definition from the DB remains fast, and the blob content is loaded only when truly needed.
There's no rule of thumb. Depending on the specifics of the scenario, one option may be more suited than others.
I'm trying to implement the Clean Architecture described by Robert Martin.
More specifically I'm using VIPER which is an iOS version of Clean Architecture.
The problem I have is as follows:
The user starts looking at a map with places (pins) on it.
If he clicks a button, a pin is dropped and he is taken to another view to create (or edit if it was a click to an existent pin) the place (or cancel).
In this other view, the user can edit the place's information and then click "back" or "done" (or "edit").
If he clicks "done", the PlaceDetailsViewController sends a message to the PlaceDetailsPresenter with the place information and the PlaceDetailsPresenter uses the CreatePlaceInteractor to create the place. This interactor returns the GUID which is used to identify the place.
If the user clicks back before creating the place, he gets back to the map and the dropped pin goes up and away (since it has no GUID, it is a new place and goes away).
If he clicks back after creating, the pin stays there (because it should have a GUID).
How should I connect all that and where should the place information (including GUID) be stored?
To clarify a little bit more:
Who should inform the MapPresenter that the pin stays there or goes away?
Is it the PlaceDetailsPresenter or should I pass this information to the PlaceDetailsWireframe -> MapWireframe -> MapPresenter -> MapView ?
Before going back, where should this GUID be stored, in the PlaceDetailsPresenter or in the PlaceDetailsViewController?
Right now that's what I have:
EDIT:
Basically I think the problem is that VIPER came from Robert Martin's Clean Architecture and he comes from a Web (Rails) background, so he doesn't think much about state (or don't specify it in his talks).
Which is mainly my question, where should the state be stored, how should the different modules communicate, should it be through the Wireframe, or through the database, or through the interactors, or through the Presenters communicating with each other like here https://github.com/objcio/issue-13-viper-swift.
I don't know much about Viper, so I can't comment about that. However, the gross state of the system should be held in the entity objects and manipulated by the interactors. The detailed state of the GUI (selection rectangles, etc) should be managed by a special connection between the controller and the presenter.
In your case there are two screens. The map, and the place editor. Clicking on the map causes either the placePinController to be invoked. It gathers the location of the click, and any other contextual data, constructs a placePinRequest data structure and passes it to the PlacePinInteractor which checks the location of the pin, validates it if necessary, create a Place entity to record the pin, constructs a EditPlaceReponse object and passes it to the EditPlacePresenter which brings up the place editor screen.
If the Done button is clicked on the place editor screen it invokes the EditPlaceController which gathers up the edited data into an EditPlaceRequest data structure and passes it to the EditPlaceInteractor. etc..
You specifically asked about the GUID of the pin. That would be created by the Place entity and passed back to the editPlacePresenter PlacePinInteractor.
In pure VIPER Router should hold modules input in form of a protocol. And modules Presenter should conform to it. So when Router uses other modules Router to assemble new module it passes it's input to it.
The second Router then assigns the input to its Presenters output. So basically Presenter of the first module becomes a delegate for the second modules Presenter.
So in your case when a user selects a place MapPresenter asks MapInteractor for a GUID and tells MapRouter to navigate to details for this GUID.
MapRouter asks PlaceDetailsRouter to assemble PlaceDetailsModule for this GUID and passes MapModuleInput to it. PlaceDetailsRouter assigns MapModuleInput to PlaceDetailsPresenter. PlaceDetailsRouter puts GUID in the PlaceDetailsInteractor
I am trying to conditionally suppress a widget from its driver. I basically have logic that if met, should display the widget and if not, should suppress it. The widget loads properties from the current page content item, and based on some properties should display or hide. I've got all the logic working, the only part left is suppressing the actual output.
I've tried returning null from the driver, however this simply outputs an empty widget (with its wrapper). How do I completely remove the widget from view?
Finally, the zone that this widget is placed in should suppress if none of the conditional widgets display.
Is this type of flexibility possible in Orchard? Preferably from my custom module not my theme, I'm trying to separate functionality from styling.
EDIT:
Here is the context of my situation and what I am trying to accomplish. I'm sure there is a much cleaner way to do this within Orchard than how I have naively designed it the first go-around: My client's copywriters tag pages as they see fit (using the Tags module/part). I have created 2 custom content types, "Testimonials" and "Offers", both with tags themselves among other properties [these are managed by a different team of copywriters].
On most "inner pages" of the website (I'm using a layer to determine the appropriate pages), the page's sidebar gets a "Testimonial" widget and a "Offer" widget. These widgets both operate the same, although independently of each other:
They grab the tags of the current page, then pull a random [Testimonial|Offer] that has any matching tags as well. There are 4 cases that can happen given any inner page: a testimonial is displayed and the offer is hidden (testimonial tag matched, offer tag didn't), the testimonial is hidden and the offer is displayed, both the testimonial and offer displays, and finally neither displays. The first 3 use cases are working great, the 4th is what I'm having difficulty with, as the sidebar [zone] still displays even if both widgets do not (returning null from their respective drivers).
A bit of context about widgets: widgets are supposed to be pieces of contents that are visible on some or all pages of the site, and that provide information that is not directly related to the main content item on the page (if there is such a thing).
As a consequence, what you are describing should not be implemented as widgets (all that you had to do to make it work attests to that further), because they are really part of the content item. Instead, you should have implemented a part or a field. You can then simply place the shape for this part of field, using placement, by specifying a top-level zone: <place the_shape_name="/the_zone_where_you_want_it:1"/>
Unfortunately I've had to use a bit of a hack so that I could move on with the project as I'm under an aggressive deadline, but if there is a better method and/or solution I'll test as I get the chance and mark as the answer.
To get it to work, I overwrote the Widget.Wrapper.cshtml file within my theme. There, I assigned a variable to the Display(Model.Child) call, and if the result is an empty string simply return. This removes any empty widget wrapping tags. (I personally feel Orchard should behave this way by default):
var child = Display(Model.Child);
// -- NOTE: shape tracing breaks this logic!
if (string.IsNullOrWhiteSpace(child.ToString())) {
return;
}
Then simply replace the #Display(Model.Child) between the header and footer with #(child)
I then added the following method to my Layout.cshtml file.
Func<dynamic, IHtmlString> CollapsableZone = x =>
{
var display = Display(x);
string zoneName = x.ZoneName;
if (string.Equals(display.ToString(), string.Format("<div class=\"zone zone-{0}\"></div>", zoneName.HtmlClassify()), StringComparison.CurrentCultureIgnoreCase))
{
return new HtmlString(string.Empty);
}
return display;
};
Simple function that assigns the display call to a variable, checks if it is an empty zone tag, and returns. I then create variables for each zone assigned to the value of the function above. I replace all the #if (Model.ZoneName != null) with #if (!string.IsNullOrWhiteSpace(zoneVariable)), and replace the calls to #Zone(Model.ZoneName) with #(zoneVariable).
This is working for the time being. It is quite a hack and brittle solution but I've had to move on to other things.
In my project I use entity framework 4.0 as ORM to persist data in a SQL Server.
My project is a ribbon from application with a grid view and navigation tree in the main form with ribbon panel on top of it. My app basically acts a CRUD UI with very little business logic.
Being first time with EF, I developed this project by creating and holding an instance of objectContext in the orchestrating form (main form or the one that shows up as application to user) as a member variable and bound a query to a grid view.
For various events like ribbon panel button clicks, grid view row clicks etc, I open another windows form. In that window form I create another object context and stored in member variable of that form class.
I had read through few blogs and questions like:
How to decide on a lifetime for your objectcontext
Entity Framework and ObjectContext n-tier architecture etc.
One set of authors suggests to share the object context while other suggest to short lived and non-shared.
I reached this state of confusion because I am now in a state where the changes I made to objectContext in one of the child form is not reflecting the parent form that showed it. I attempted to refresh but still nothing useful. Just for an experiment, I shared the objectContext that I first created in the most parent class through constructor injection and my problem of change reflection is solved.
It is a huge work for me to convert all my child forms to share objectContext. But I am ready if it is worth. I am not sure what will be the lurking problems of sharing it?
I may opt for a static instance of objectContext as I am not using this for Web and not planning for multi threaded scenarios. If required I can rise to as a singleton.
My Questions:
To share or not to share ObjectContext for my situation?
If not to share, how can I solve my present problem of updating one objectContext with the changes made in other?
If to share - which would be better way? Static or singleton or something else?
The details of the project and environment are as below:
Winforms
C#
VS 2012
EF 4.0, model created with data first approach.
I am posting this after searching and reading through many questions and blog posts. The more I read, the more confusing it becomes :) Please bear with me if I am leaving someone to assume something to answer. I will try to update the question if such clarifications are asked through comments.
Your Questions
To share or not to share ObjectContext for my situation?
Do not share your context. The EntityFramework context should follow a UnitOfWork pattern. Your object context should be as short lived as possible without unnecessarily creating/destroying too many contexts. This usually translates to individual "operations" in your app as units of work. For a web app/api this might be per HttpWebRequest, or you might do it per logical data operation (for each of your implemented pieces of "Business Logic").
For example:
LoadBusinssObjects() would create a context, load your list of data plus any related data you want then dispose of the context.
CreateBusinessObject() would create a context, create an instance of some entity, populate it with data, attached it to a collect in the context, save changes and then dispose of the context.
UpdateBusinessObject() would read some object from the context, update it, save changes, and dispose of the context.
DeleteBusinessObject() would find a business object in the context, remove it from the collection in the context, save changes and dispose of the context.
If not to share, how can I solve my present problem of updating one objectContext with the changes made in other?
This is a job for a pub/sub architecture. This can be as simple as a few static event handlers on your objects for each operation you implemented above. Then in your code for each business operation, you fire the corresponding events.
If to share - which would be better way? Static or singleton or something else?
This is incorrect. The EF context will continue to grow in memory footprint as the context's state manager continuously collects up cached objects (both attached and not-attached) for every single interaction you do in your application. The context is not designed to work like this.
In addition to resource usage, the EF context is not thread safe. For example what if you wanted to allow one of your editor forms to save some changes at the same time as the tree list is loading some new data? With one static instance you better make sure this is all running on the UI thread or synchronized with a semaphore (yuck, and yuck - bad practices).
Example
Here's an example using C# and code first approach as per your post. Note, I'm not addressing things like data concurrency or threading to keep the example short. Also in a real application this concept is implemented with generics and reflection so that ALL of our models have basic events on them for Creating, Updating, Deleting.
public class MyCodeFirstEntityChangedArgs : EventArgs
{
/// <summary>
/// The primary key of the entity being changed.
/// </summary>
public int Id {get;set;}
/// <summary>
/// You probably want to make this an ENUM for Added/Modified/Removed
/// </summary>
public string ChangeReason {get;set;}
}
public class MyCodeFirstEntity
{
public int Id {get;set;}
public string SomeProperty {get;set;}
/// <summary>
/// Occurs when an instance of this entity model has been changed.
/// </summary>
public static event EventHandler<MyCodeFirstEntityChangedArgs> EntityChanged;
}
public class MyBusinessLogic
{
public static void UpdateMyCodeFirstEntity(int entityId, MyCodeFirstEntity newEntityData)
{
using(var context = new MyEFContext())
{
// Find the existing record in the database
var existingRecord = context.MyCodeFirstEntityDbSet.Find(entityId);
// Copy over some changes (in real life we have a
// generic reflection based object copying method)
existingRecord.Name = newEntityData.Name;
// Save our changes via EF
context.SaveChanges();
// Fire our event handler so that other UI components
// subscribed to this event know to refresh/update their views.
// ----
// NOTE: If SaveChanges() threw an exception, you won't get here.
MyCodeFirstEntity.EntityChanged(null, new MyCodeFirstEntityChangedArgs()
{
Id = existingRecord.Id,
ChangeReason = "Updated"
});
}
}
}
Now you can attach event handlers to your model from anywhere (its a static eventhandler) like this:
MyCodeFirstEntity.EntityChanged += new EventHandler<MyCodeFirstEntityChangedArgs>(MyCodeFirstEntity_LocalEventHandler);
and then have a handler in each view that will refresh local UI views whenever this event is fired:
static void MyCodeFirstEntity_LocalEventHandler(object sender, MyCodeFirstEntityChangedArgs e)
{
// Something somewhere changed a record! I better refresh some local UI view.
}
Now every UI component you have can subscribe to what events are important to it. If you have a Tree list and then some editor form, the tree list will subscribe for any changes to add/update/remove a node (or the easy way - just refresh the whole tree list).
Updates Between Applications
If you want to go a step further and even link separate instances of your app in a connected environment you can implement a pub/sub eventing system over the network using something like WebSync - a comet implementation for the Microsoft Technology Stack. WebSync has all the stuff built in to separate events into logical "channels" for each entity/event you want to subscribe to or publish to. And yes, I work for the software company who makes WebSync - they're paying for my time as I write this. :-)
But if you didn't want to pay for a commercial implementation, you could write your own TCP socket client/server that distributes notifications for the above events when an entity changes. Then when the subscribing app gets the notification over the network, it can fire its local event handlers the same way which will cause local views to refresh. You can't do this with a poorly architected static instance of your data context (you'd be bound to only ever have one instance of your app running). With some good setup early on, you can easily tack on a distributed pub-sub system later that works across multiple instances of native apps and web apps all at the same time! That gets very powerful.
So far all of the examples that I have seen for adding a new entity would go through the following steps:
Create a bunch of "new-" variables that get bound to on screen controls.
When user wants to submit the addition, created an uninitialized new entity.
Copy "new-" variables to each member of the new entity one by one.
Push the new entity onto the manager's entity list.
Save changes.
Clear all of the "new-" variables.
This is problematic for many reasons. These "new-" variables have to be maintained in addition to the on screen controls. When server side entities change, they must be changed manually. This is time consuming and error prone.
I would like to be able to create an uninitialized new entity first, and bind it to on screen controls immediately, without using those variables with the "new-" prefix. When user wants to submit the addition, push the new entity onto the manager's entity list, and then save changes. Then bind the on screen controls immediately to a newly created uninitialized entity.
This way, we can avoid dealing with individual entity attributes in the view model, which would produce more robust code, and save a lot of time.
Right now, the metadata for creating a new entity is not available when the document becomes ready. If I download it, I have to deal with asynchronous completion before I can bind a new entity to on screen controls.
So my question is: is there a way to have the metadata downloaded with the initial HTML download so that I can create an uninitialized new entity without waiting, and bind it to on screen HTML controls immediately?
I'm not sure what means uninitialized new entity, but yes - you can create for example a new car like this:
var newCar = manager.metadataStore.getEntityType("Car").createEntity();
manager.addEntity(newCar);
Bind your controls to the newCar. To save the changes call manager.saveChanges();, to cancel call manager.rejectChanges();
To be able to work with entities breeze needs metadata. If you want, you can send metadata with the page itself. You can then use manager.importMetadata() to import it into the manager. The only problem is that you will need to write a small app that will generate the metadata string (during build) so that later it can be passed to importMetadata(). Take a look at MetadataStore Class API for more info.