How to save data into application vb.net ? (Not use database or txt file) - vb.net

I a newbie in VB.net. I have a small project that save data from textbox. (just simple: create textbox, fill my name to textbox and save it).
But I don't want use database or txtfile because if I use like that, I will have 2 file: my app.exe and database file. I don't know whether there have anyway to save data into this my app.exe. Just have 1 file app.exe, database is included in this app (App is same to excel file: just have 1 file excel which can fill data and save)

Obviously you have a class Student (from your comment)
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
For binding to DataGridView you can use BindingList<Student>.
Then when you close your application save in JSON format.
var data = _yourBindingList.ToList();
var serializedData = Newtonsoft.Json.JsonConvert.SerializeObject(data);
System.IO.File.WriteAllText(#"fileName.anyExtensionYouWant", serializedData);
When application starts load data from the file and deserialize it.
var data = System.IO.File.ReadAllText(#"fileName.anyExtensionYouWant", serializedData);
var loadedStudents = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Student>>(data);
_yourBindingList = new BindingList(loadedStudents);
yourDataGridView.DataSource = _yourBindingList;

The easy way is to save the text to a txt file
My.Computer.FileSystem.WriteAllText
https://msdn.microsoft.com/es-es/library/27t17sxs(v=vs.90).aspx
So
My.Computer.FileSystem.WriteAllText("C:\TestFolder1\test.txt", "This is new text to be added.", False)
on your're case can be
My.Computer.FileSystem.WriteAllText("C:\TestFolder1\test.txt", textbox1.text, False)
If you need to use MyDocuments or Desktop folders you need to use relative system routes

Related

ASP.NET Export file to pdf

I am newbie. I have 8 files cshtml and I want to combine all to 1 file (index.cshtml, I will export it to pdf). Can you help me? What should I write code to index.cshtml.
Thank for your help!
enter image description here
Hello Nguyễn Chí Linh,
If you know how to populate one viewmodel, you can combine these viewmodels into one like so:
public class viewModelGroup
{
public ViewModel1 viewModel1 { get; set; } = new ViewModel1();
public ViewModel2 viewModel2 { get; set; } = new ViewModel2();
}
For the output to PDF you can then use the nuget package manager to find many packages that will allow you to export the data to pdf. These packages come with their own documentation to show you how to convert your viewModelGroup into a PDF document.
Goodluck.

RazorEngine Error trying to send email

I have an MVC 4 application that sends out multiple emails. For example, I have an email template for submitting an order, a template for cancelling an order, etc...
I have an Email Service with multiple methods. My controller calls the Send method which looks like this:
public virtual void Send(List<string> recipients, string subject, string template, object data)
{
...
string html = GetContent(template, data);
...
}
The Send method calls GetContent, which is the method causing the problem:
private string GetContent(string template, object data)
{
string path = Path.Combine(BaseTemplatePath, string.Format("{0}{1}", template, ".html.cshtml"));
string content = File.ReadAllText(path);
return Engine.Razor.RunCompile(content, "htmlTemplate", null, data);
}
I am receiving the error:
The same key was already used for another template!
In my GetContent method should I add a new parameter for the TemplateKey and use that variable instead of always using htmlTemplate? Then the new order email template could have newOrderKey and CancelOrderKey for the email template being used to cancel an order?
Explanation
This happens because you use the same template key ("htmlTemplate") for multiple different templates.
Note that the way you currently have implemented GetContent you will run into multiple problems:
Even if you use a unique key, for example the template variable, you will trigger the exception when the templates are edited on disk.
Performance: You are reading the template file every time even when the template is already cached.
Solution:
Implement the ITemplateManager interface to manage your templates:
public class MyTemplateManager : ITemplateManager
{
private readonly string baseTemplatePath;
public MyTemplateManager(string basePath) {
baseTemplatePath = basePath;
}
public ITemplateSource Resolve(ITemplateKey key)
{
string template = key.Name;
string path = Path.Combine(baseTemplatePath, string.Format("{0}{1}", template, ".html.cshtml"));
string content = File.ReadAllText(path);
return new LoadedTemplateSource(content, path);
}
public ITemplateKey GetKey(string name, ResolveType resolveType, ITemplateKey context)
{
return new NameOnlyTemplateKey(name, resolveType, context);
}
public void AddDynamic(ITemplateKey key, ITemplateSource source)
{
throw new NotImplementedException("dynamic templates are not supported!");
}
}
Setup on startup:
var config = new TemplateServiceConfiguration();
config.Debug = true;
config.TemplateManager = new MyTemplateManager(BaseTemplatePath);
Engine.Razor = RazorEngineService.Create(config);
And use it:
// You don't really need this method anymore.
private string GetContent(string template, object data)
{
return Engine.Razor.RunCompile(template, null, data);
}
RazorEngine will now fix all the problems mentioned above internally. Notice how it is perfectly fine to use the name of the template as key, if in your scenario the name is all you need to identify a template (otherwise you cannot use NameOnlyTemplateKey and need to provide your own implementation).
Hope this helps.
(Disclaimer: Contributor of RazorEngine)

convert string to array in mvc 4

In my recent mvc 4 project, I store multiple image and other files (such as doc, pdf, ppt etc.) as string in my database. Now I want to show this multiple image and want to show link of other files.
For example, I store data as string in my db as like as given below:
1980082_10201802177236118_516383197_o.jpg, ASP.NET MVC Interview Questions &amp; Answers.pdf, Sample-1.jpg,
Now I want to fetch this string and show image and give the link of the other files.
I hope it will help.First when you save in your database you have to make sure you save it with all the paths, not only the filenames. In simple In your Action:
public FilePathResult GetDoc(int yourParam)
{
var path= (from r in yourContext.yourTable where id == yourParam
select r.path).FirstOrDefault()
//Considering that your path contains also the folder
return new FilePathResult(path);
}
In your View:
<img src="#Url.Action("GetDoc", "YourController", new { yourParam=Model.yourParam}) " />
#*For a link*#
<a href="#Url.Action("GetDoc", "YourController", new { yourParam=Model.yourParam}) ">#Model.TheNameOfYourFile <a/>
Firstly note that, it is not good idea to store that file names in one row in db. If I understood you right, to extract images and files from that rows, create a model that contains list of different file list:
public class RowResult
{
public RowResult()
{
Images = new List<string>();
Pdfs = new List<string>();
}
public List<string> Images { get; set; }
public List<string> Pdfs { get; set; }
//you can add other file types here
}
Create a method that return result for every row:
public RowResult ExtractFilesFromRow(string row)
{
RowResult result = new RowResult();
string[] parts = row.Split(' ');
foreach (string part in parts)
{
if (part.TrimEnd(',').EndsWith(".jpeg")) result.Images.Add(part);
if (part.TrimEnd(',').EndsWith(".pdf")) result.Pdfs.Add(part);
//add others here..
}
return result;
}
And finally, to show them in view for each row you can get RowResult in db and fill List<RowResult>. In Action:
....
List<RowResult> list = new List<RowResult>();
foreach (string row in rows)
{
list.Add(ExtractFilesFromRow(row));
}
...
return list;
In view:
#foreach (string result in Model)
{
//here depends on you want
<img src="#Url.Content("~/Uploads/Images/" + result.Images[0])" />
....
<img src="#Url.Content("~/Uploads/Images/" + result.Images[1])" />
}
I store multiple image and other files (such as doc, pdf, ppt etc.) as string in my database
I assume you mean you save the file names as string in your database.
Now let's start with the db data you shared
For example, I store data as string in my db as like as given below:
1980082_10201802177236118_516383197_o.jpg, ASP.NET MVC Interview Questions & Answers.pdf, Sample-1.jpg,
when comma seperated becomes this
1980082_10201802177236118_516383197_o.jpg
ASP.NET MVC Interview Questions & Answers.pdf
Sample-1.jpg
Now what we have here is only filenames and to "physical path" to where these files are stored.
So for this to work you WILL have to save the file path in the database too. Unless you have defined a path say "C:/SomeApp/MyDump/" and you are simply dumping all the files here.
In case you are then you can use that path append it with the file name and show on the UI. The file extension could help you decide what HTML to use (<img> or <a> to display image or show a download link)

MVC DBContext, how to connect to a table?

im just creating my first MVC applicaiton and am having trouble connecting to my database located on my sql server.
i have added the connection string to the web config as normal, created a model with all the fields in.
i created a model and created a new DBContext as there wasnt one listed. this created the below file
im not sure how it connects to the right table in my SQLDB, how do i do this?
also how do i make it run stored procedures?
Thanks
public EquipmentDBContext()
: base("name=ITAPPConnectionString")
{
}
public DbSet<Equipment> Equipments { get; set; }
public EquipmentDBContext()
: base("name=ITAPPConnectionString")//this name should be the name of database
{
}
public DbSet<Equipment> Equipments { get; set; }
here you say you have a
Datamodoel called Equipment. Your context also defines a single property, Equipments, which is of type DbSet. This property acts as a collection that allows you to query the data in you table in database as though it were an in-memory collection of objects.
So, if you create an object of class EquipmentDbContext in controller named lets say db, then you can access the data in table with something like
db.Equipments
To expand further on Cybercop's answer you would do something like this
using (var context = new EquipmentDBContext())
{
var equipments = context.Equipments.ToList();
var equipment = context.Equipments.FirstOrDefault(c=>c.Id == 1);
var blueThings= context.Equipments.Where(c=>c.Color == "blue").ToList();
}

Creating a new Content Item in the migration with Orchard CMS

Here's my migration code:
public Migrations(IRepository<ProductPartRecord> productPartRepository, IRepository<CategoryPartRecord> categoryPartRepository)
{
_productPartRepository = productPartRepository;
_categoryPartRepository = categoryPartRepository;
}
public int Create() {
ContentDefinitionManager.AlterTypeDefinition("Category", builder => builder
.WithPart("CommonPart")
.WithPart("TitlePart")
.WithPart("AutoroutePart"));
ContentDefinitionManager.AlterTypeDefinition("Category", builder => builder
.WithPart("AutoroutePart", partBuilder => partBuilder
.WithSetting("AutorouteSettings.AllowCustomPattern", "true")
.WithSetting("AutorouteSettings.AutomaticAdjustmentOnEdit", "false")
.WithSetting("AutorouteSettings.PatternDefinitions", "[{Name:'Category Title', Pattern: 'category/{Content.Slug}', Description: 'category/category-title'}]")));
SchemaBuilder.CreateTable("CategoryPartRecord", table => table
.ContentPartRecord()
.Column<string>("Name")
.Column<string>("Description")
.Column<string>("Image")
);
ContentDefinitionManager.AlterTypeDefinition("Category", builder => builder
.WithPart("CategoryPart"));
ContentDefinitionManager.AlterTypeDefinition("Category", builder => builder
.Creatable()
.Draftable());
return 1;
}
public int UpdateFrom1() {
_categoryPartRepository.Create(new CategoryPartRecord { Name = "Category1", Description = "Description1", Image = "Image1" });
return 2;
}
UpdateFrom1 obviously attempts to insert a dummy record, but this causes nHibernate to throw this exception:
"attempted to assign id from null one-to-one property: ContentItemRecord"
The Part Record looks like:
public class CategoryPartRecord : ContentPartRecord {
public CategoryPartRecord()
{
CategoryProducts = new List<CategoryProductRecord>();
}
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual string Image { get; set; }
public virtual IList<CategoryProductRecord> CategoryProducts { get; set; }
}
Any clues as to where I'm going wrong here? Google produced nothing.
Okay, so you are creating a contentpartrecord, not a content item there. What you want is something more along the lines of:
var item = _orchardServices.ContentManager.New("Category").As<CategoryPart>();
item.Name = "Bobs Item"; // Something like that...
item.ContentItem.As<TitlePart>().Title = "Yay a title"; // This syntax may be wrong, I'm very tired
_orchardServices.ContentManager.Create(item);
_orchardServices.ContentManager.Publish(item.ContentItem);
I think that is how you would do it. Maybe you would want to look into creating content items using the import/export module, that is the more common and safe way to do it.
Not sure if the answer from Hazza works. Haven't tried that.
I usually just do this: (But not sure if it's an inferior approach in some way)
var item = _orchardServices.ContentManager.New("Category");
var cpart = item.As<CategoryPart>();
var tpart = item.As<TitlePart>();
cpart.Name = "SomeName";
tpart.Title = "SomeTitle";
_orchardServices.ContentManager.Create(item);
But to address the comment by Lawrence Johnson:
Category in this case is the content item. He is creating a new Category content item, and then extracting the corresponding CategoryPart from it.
If you are getting null when trying to extract the part you're probably missing something.
In order for this to work you need to implement the CategoryPart, CategoryPartRecord, CategoryPartHandler and CategoryPartDriver. (And of course make sure to attach your CategoryPart to you Category content item. Not certain if placement.info is required, but would add it for consistency anyway.)
You can't leave any of these out if you plan to use a Part attached to a content item.
I'm not sure if/how you can create a Part with no content item, but you can create a Record with no part and no content item (Just make sure you don't inherit ContentPartRecord in your record object). If you simply want to add a record with no part or content item, then the code in UpdateFrom1 used by Ben Power would work for creating a record. (But migration part would have to be changed, taking out the content item and part, and manually setting the Id to be a primary key for the record)