How do I edit information from an customer settings data model, which doesn't come from a database.
I've created a view which starts with
edit.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage" %>
Notice it contains MyApp.Models.LocationDisplayOptions. How can I save data on the form, which isn't linked to a database. I'm sorry if this isn't clear, but simply I need to save data not stored in a database.
namespace MyApp.Models
{
public class LocationDisplayOptions
{
public string Town { get; set; }
public string Country { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public LocationDisplayOptions()
{
// Some web url stuff
Town = dt.Rows[0]["City"].ToString();
Country = dt.Rows[0]["CountryCode"].ToString();
Latitude = System.Convert.ToDouble(dt.Rows[0]["Latitude"].ToString());
Longitude = System.Convert.ToDouble(dt.Rows[0]["Longitude"].ToString());
}
}
}
Why do you need to save it? What are you going to do with the data after you save it. That's going to really drive the answer.
If you just need to persist information from one view of the page to another, you can put it in a Session variable.
If you need to persist it longer than that, you could store it in a file on the web server, but if it is a high volume website, that can really slow things down.
You could consider a database. Microsoft SQL CE is a good option for small-footprint data stores, as it doesn't require any server-side installs-- just a DLL that goes along with the rest of your application.
Here's a link to ScottGu's post about SQL CE: http://weblogs.asp.net/scottgu/archive/2010/06/30/new-embedded-database-support-with-asp-net.aspx
Do you merely used drag and drop to work with databases, letting magic happen as far as editing of data is concerned?
While you can exist with LINQ to SQL or EF drag and drop, the "magic" underneath the hood is worthwhile to learn, especially in light of other forms of persistant mechanisms.
To persist to a file, you have to capture the form data and then create a class that handles the save to the file. The best path is to Google saving to the type of file (comma separated, XML, etc) and create the software to handle the persistance of that information. You can test it with a simple console app. When you are happy, use the same pattern to wire to your MVC application. The main difference is you have to get the path from the ASP.NET internals (hard coded == bad).
Someone may have an open source "module" that does this work, so search the open source sites.
Peace and Grace,
Greg
Twitter: #gbworld
Blog: http://gregorybeamer.wordpress.com
Related
How can I save data from a object to the browser and retrieve that data using server-side Blazor?
I have a model to filter an overview, but if you navigate away from the overview and come back the filter is gone. It's a pretty advanced filter so filling it out every time is not really an option.
Let's do this simplified example:
public class OverviewFilterModel
{
public string Keywords { get; set; }
public int PartnerId { get; set; }
public EnumStatus Status { get; set; }
}
public enum EnumStatus
{
A,
B,
C
}
How do I save above model in browser and retrieve it again? Or is there no such thing? I do not want to use an SQL database for this, or anything server-side.
You can use Blazored.LocalStorage. Its a third party library developed by Chris Sainty to store data in your browser which persists across pages and you can access that data from a new tab as well.
Just pull the library from Nuget, register the service in your Startup class, inject it into any page or component you want and then store whatever data you want in the browser local storage.
#inject Blazored.LocalStorage.ILocalStorageService localStorage
#code {
protected override async Task OnInitializedAsync()
{
await localStorage.SetItemAsync("name", "John Smith");
var name = await localStorage.GetItemAsync<string>("name");
}
}
You can add complex nested objects as well.
You can verify the data/model that you have stored in your browser local storage if you open developer options.
Here's the github repo link. You will find all the documentation here :
https://github.com/Blazored/LocalStorage
I have created a client server application which is currently able to send messages as containers:
[Serializable]
public class MsgContainer
{
public string TableName { get; set; }
public bool SomethingBool { get; set; }
public DataTable DataTableData { get; set; }
}
The problem: Depending on the request from the user I would like the server to be able to send Forms
public Form requestedForm { get; set; }
The problem with that (as i have read in the web and tried in my application) WinForms are not serializable which is why i receive the following error:
System.Runtime.Serialization.SerializationException: 'Type 'System.Windows.Forms.Form' in Assembly 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.'
Is there any workaround to my problem?
I would strongly advise you find a different approach to whatever you're trying to do. The Form is not serializable. You could:
Make a serializable class to transfer all the form information and regenerate a form based on it.
Write your own serializer and deserializer for a form.
Either way you would need to overcome the many following issues, such as:
Components in the form are also not serializable.
Each control may have a value or a binding to a data source that also needs to be transferred.
You can include infinite different objects and classes in a form that would be part of your main project. Everything would need to be in a library consumed by both server and client.
Basically, this would be your worst nightmare and after spending however much time you may spend working on it, you will eventually realise that you have nothing but bin filler.
You cannot (reasonably) serialise a form.
A better approach, if viable, would be to build the forms into the client app. Then have the server instruct the client as to which form to open. Optionally use an enum for this.
public enum FormType
{
Products,
Customers
}
public FormType RequestedForm { get; set; }
Sending a Form is a pretty pointless excersise. Forms are just there to Display data. If you want a certain form to be dispalyed, send the Data it needs rather then the whole Form.
Honestly it sounds like you either have some very faulty design. Or wanted to do a WebApplication the whole time. Consider that you might be stuck in a XY Problem.
In my application I have this entity:
public class Franchise
{
public Guid Id {get;set;}
public string Name {get;set;}
}
When each of my users log in, they are associated with a franchise.
There is another entity:
public class Client
{
public Guid FranchiseId {get;set;}
public virtual Franchise Franchise {get;set;}
public string Name {get;set;}
/* other useful client information */
}
Depending on my user franchise association will determine which clients they shall see (or are allowed to see)
So equivalent of doing
dbContext.Set<Client>().Where(x => x.FranchiseId.Equals(associatedFranchiseId));
I was wondering what the options where of storing that associatedFranchiseId so each request for data can use that Id to select the appropriate dataset.
APPROACH 1
I created a service that gets these associations and returns the correct dataset. I thought I could use this in each controller where I need to get the information. But I thought this maybe costly in database lookup terms. It would have to based on the User, so getting that out of the request.
I just am not sure how I would go about doing this.
The process is:
User Logs In
Application determines the associated franchise
User request some information
The request uses the associated franchise to select the right dataset
I've used something similar and use the session and application spaces for the objects.
So, when the application fires up load all the franchise objects into application:
Application["Franchise"] = MethodToLoadFranchiseInfo();
You can then access this at anytime via Franchise f = Application["Franchise"];
Similarly, for the clients, when they login, load the client info into Session in a similar fashion.
The only caveat if that you'll need to refresh the Application object when there's an update, and same for the session, or require a log out and log back in.
This way you only have one hit to the database and in memory accessible objects!
* Edit to Add *
Just had some more thoughts on this, and probably something I'll look to implement myself. If you put a timestamp in both the application and session objects, if the session object is older than the application object (which will be updated centrally being application wide), then hit the database and refresh the session object.
That way you do not get the log out / log back in situation when something is changed by the backend / admin.
I have an Asp.Net MVC 5.1 website. We've got 3 types of users and I want to add support for chat between one type of them. I have thought of some models like this:
public class Conversation
{
public NormalUser A { get; set; }
public NormalUser B { get; set; }
public List<PrivateMessaage> Messages { get; set; }
}
public class PrivateMessaage
{
public NormalUser Sender { get; set; }
public NormalUser Receiver { get; set; }
public string Message { get; set; }
public DateTime Created { get; set; }
}
Also, I'm using SignalR in other parts of the project and thought like it's a very good solution to add the chat interface on top of the SignalR. Everything looks good so far. However, I think hitting the database to insert a new message EVERY time a message is being typed is not a good idea. I've created so many strategies to implement custom donut caching in my website to make every single page as fast as possible and it seems like this would cancel all of them out! What is the preferred solution to this problem? I think I might take some approaches like these:
Push them to the database in batches. For instance once a message is past a threshold (its date/time difference is more than X or the message count is more than Y).
Don't support offline messages, just push them in-memory to the other side through SignalR.
Same as the 2nd, but support offline when the target user is offline. I imagine not many messages will be sent to offline users!
Don't cache anything. I'll work out!!
One issue with the first one is that, there might be a situation where the website would go down (for update, power failure, apocalypse(!), etc.) and all the messages in memory would be lost. I can add a custom action to flush everything but it's never quite safe. Since there's a lot of chat solutions out there, I think there are very convenient solutions to this.
If you are not opposed to using other databases, realtime chat is extremely easy using Firebase and AngularJS.
I am looking for the best way to store image data in a model and then retrieve it in a view.
At the moment I have:
public class Product
{
public int Id { get; set; }
public byte[] Image { get; set; }
}
I then have a controller
public class ProductController
{
public ActionResult List()
{
return View(Repository.GetAll())
}
public FileContentResult GetImage(int id)
{
Product p = Repository.GetById(id);
return new FileContentResult(p.Image, "image/jpeg");
}
}
A view...
#model IEnumerable<Product>
#foreach(var product in Model)
{
<img src="#Url.Action("GetImage", "Person", new { id = item.Id })" alt="Person Image" />
}
What happens is as I get more and more products in the list, the images start to flash up on the screen as appose to loading instantly.
I am publishing to Azure so I can't really just go change byte[] to string and make string look in ~/Images/ProductImage.jpeg as I will have to publish the website every time I want to add a new product (as far as I am aware).
I am just looking for an alternative method of doing this or a reason why the images on my view appear gradually and flash up one after the other instead of instantly?
The images "flash" up instead of instantaneously because your browser has to return to the server for each image. Many browsers have a limit on how many extra links (css files, js files, image files, etc.) that it can have open at any given time. So that's why your images don't appear instantaneously.
Some things you can do to help:
If your images don't change often, add an [OutputCache(...)] attribute to your GetImage action. This way, the images will cache on the server and/or on the client for faster loading.
Store your files locally on the server instead of in a database. This will let your IIS access the files directly as static files and avoid the MVC pipeline.
Keep your files in the database, but cache them on your server (for example, under App_Data) as you retrieve them from the database. This avoids a database access.
Edit:
Store the image files in a publicly accessible (or semi-publicly) Azure blob. Your img src tags would point directly to the blob for access.
One of way of doing this would be to display the image directly from the byte array:
<img src="data:image/png; base64, #Convert.ToBase64String(product.Image)">
Should work for small images. You may also wish to store the image MIME so you can differentiate between data/png and data/jpg etc.
This should load the images immediately, as they will be part of the model sent to the view.