I have a enum:
[Flags]
public enum ResultType {
Success = 0x01,
Failed = 0x02,
Comment = 0x03
}
How do I access it in my MVC4 Razor View? Something like this:
You have: #ResultType.Failed!!!
That will work fine.
However, you need to import the namespace:
#using Some.Namespace;
The answer that #SLacks gave does work, but I'd like to expand on it. I keep all of my app enums in a single file (for maintainability) and you can add the namespace of that (and anything else you consistently need in views) in the ~/Views/Web.Config or other relevant config file. This will allow you to use the enums without having to remember to add the namespaces, and is especially helpful if you are using visual studio scaffolding.
<namespaces>
<add namespace="YourApp.Enums" />
</namespaces>
Related
We are developing a MVC 5 application. Suppose the main site is like www.sport.com
Now we want to create 3 sub domain like cricket.sport.com, football.sport.com and hockey.sport.com
Most of the functionality will be same for this 3 sub-sites.
We have implemented 2 approaches :
Approach 1: Create 3 area for each cricket/football/hockey. But this will create code redundancy. So whenever request comes from URL we check and forward request to specific area.
Approach 2 : Create Single Controller - Check URL SubDomain and redirect depending upon each request and display specific view. In this approach, each time we need to check request sub domain and forward to same.
What is best possible way to implement sub domain in MVC application?
We want to deploy this site on Windows Azure.
What you mean by implement sub domain isn't all too clear.
If you are trying to host the same sight at different sub domains and expect them to work differently then you should have something in your web.config or some other setting that then tell each site what it is.
Something like:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="AppType" value="criket" />
</appSettings>
</configuration>
Then inside your application you'll do:
if(ConfigurationSettings.AppSettings["AppType"] == "cricket")
{
//do cricket app specific stuff
} else { /* do something else */ }
If this whole thing doesn't need to be dynamic you could also have a build symbol :
//uncomment or comment accordingly
#define CRIKET
//#define FOOTBALL
public class HomeController
{
public ActionResult Index()
{
#if CRICKET
return View("Cricket");
#elif FOOTBALL
return View("Football");
#endif
}
}
A config setting is slower than a build symbol but it gives you a dynamic approach. Choose according to your need.
I have following class
namespace MyApplication.Services
{
public class TagEqualityComparer : IEqualityComparer<Tag>{/*code goes here*/}
}
Now what I would like to register it in autofac using .config file based configuration:
<autofac>
<components>
<component type="MyApplication.Services.TagEqualityComparer, MyApplication.Services"
service="System.Collections.Generic.IEqualityComparer, mscorlib" />
</components>
</autofac>
I have already spent whole sunday searching for solution I failed to find any. Other registrations, non templates, works perfectly but this one refuses.
Any idea how to solve it?
You need to define the rest of the generic type to specify the parameter type. Something like this:
<component type="MyApplication.Services.TagEqualityComparer, MyApplication.Services"
service="System.Collections.Generic.IEqualityComparer`1[[MyApplication.Services.Tag, MyApplication.Services]], mscorlib" />
I'm done trying to Google for this. I have installed SQL Server CE 4.0, and have EF 4.1, but I can't get a proper connection string. Nothing on connectionstrings.com applies to me.
I just want to create a SqlCeEngine object, but no matter what I try I get some exception. Most recently it's been
Unknown connection option in connection string
with either "metadata", "app", "provider", or "provider connection string" after it. I know EF requires metadata in the connection string. And I can't imagine how anything could do without "provider connection string".
So far I have this:
<add name="DBContext"
connectionString="provider connection string="Data Source=MyDbFile.sdf;Persist Security Info=False;""
providerName="System.Data.EntityClient" />
At one point I had it with metadata:
<add name="DBContext"
connectionString="metadata=res://*/Data.DBContext.csdl|res://*/Data.DBContext.ssdl|res://*/Data.DBContext.msl;provider=System.Data.SqlClient;provider connection string="Data Source=MyDbFile.sdf;Persist Security Info=False;""
providerName="System.Data.EntityClient" />
Does it need metadata or not? What goes in the "app" part of the connection string? What should the provider be, System.Data.SqlClient or some SQL Server CE version? (which I still can't find when I try to add references. My add references window still only contains System.Data.SqlServerCe version 3.5.1.0.) Or nothing?
And what should go in the providerName attribute? Is System.Data.EntityClient correct? It's like there are 10 different variables here and every combination gives me a new equally mysterious error, none of which turns up anything useful on Google. I'm at my wits' end. Is this even possible?
You could try this in your App.config file (EF5 Code first migrations and SQL Server CE 4.0):
<connectionStrings>
<add name="DefaultConnection"
providerName="System.Data.SqlServerCe.4.0"
connectionString="Data Source=|DataDirectory|\Data\ProjectDb.sdf"/>
</connectionStrings>
And in you ProjectDb class:
class ProjectDb : DbContext
{
public ProjectDb()
: base("DefaultConnection")
{
}
}
It will work like a charm.
You can find more information here: http://blogs.msdn.com/b/adonet/archive/2011/01/27/using-dbcontext-in-ef-feature-ctp5-part-2-connections-and-models.aspx
I’d stuck with the same problem on Entity Framework 5.0 Code First approach with SQL Server Compact Edition 4.0
To solve it I pass instance of SqlCeConnection to DbContext's constructor:
public class Storage : DbContext
{
public Storage()
: base(new SqlCeConnection("Data Source=Database.sdf;Persist Security Info=False;"),
contextOwnsConnection: true)
{ }
//...
}
If you don’t want to inline connection string you could get it from App.config through ConfigurationManager
And of course you should add reference to the right version of System.Data.SqlServerCe (look inside Extentions tab in the Add Reference dialog)
This TechNet article outlines the steps for using EF with SQL Server Compact. This line jumped out at me, and may solve your problems:
make sure that provider=System.Data.SqlServerCe.3.5 in the connection
string.
(I would assume that you would want 4.0 instead of 3.5)
Give that a try and see how things go.
The Lu55's solution didn't work for me, but I found fow to fix it. To still use the automatic code generation (which can overwrite changes in a generated file), I added one more file with the following code:
using System.Data.Entity;
using System.Data.Objects;
namespace MyProject.Data
{
internal partial class Entities : DbContext
{
public Entities(string connectionString)
: base(
new ObjectContext(
#"metadata=res://*/Data.Model.csdl|
res://*/Data.Model.ssdl|
res://*/Data.Model.msl;
provider=System.Data.SqlServerCe.4.0;"),
true)
{
Database.Connection.ConnectionString = connectionString;
}
}
}
You have mixed a bit.
For SQL Server CE connection string can be quite easy (possibly replace DbContext with YourNameSpace.DbContextName):
<add name="DbContext"
connectionString="MyDbFile.sdf"
providerName="System.Data.SqlServerCe.4.0" />
I also had a lot of trouble with connections, so I did the following:
installed Entity Framework for SQL Server CE
Checked that web.config contains provider with invariant System.Data.SqlServerCe.4.0
Verified that there are NO string fields (which will be represented as columns in db) with length max or mode than 4000 symbols (to add restriction use annotation [MaxLength(4000)], by default == MAX)
Metadata are necessary when you use database-first model instead of code-first, so there is .edmx file which represents generated model of the database.
Well, first of all sorry about this question it must be pretty straight forward for you guys but I'm struggling myself on it, and I need to make it work :(
Well I'm trying t o use DataSet on my application
and when I render it I got:
The type 'System.Data.DataSet' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data
in my application System.Data is already being referenced from C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Data.dll
and I'm using on my using clauses as well
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
This DataSet is a response from a Webservice
So any Ideas on how to fix this problem?
PS. I don't know if it helps, but I'm using nHaml to render my view
Thanks a lot
UPDATE:
The only solution I found for now was to instead passing a DataSet to the view converter the DataSet to a
<List<List<String>>
and pass a loop through the entire DataSet like this
List<List<String>> myList = new List<List<String>>();
foreach (DataRow row in dsTrades.Tables[0].Rows)
{
List<String> myListColumns = new List<String>();
for (var index = 0; index < dsTrades.Tables[0].Columns.Count; index ++)
{
myListColumns.Add(row[index].ToString());
}
myList.Add(myListColumns);
}
// THIS SHOULD BE THE DATASET AND NOW
// IT'S CONVERTED TO A LIST WITH STRINGS LIST INSIDE
viewModel.Trades = myList;
return View(viewModel);
Actually this is completely crazy ins't it?
All this job could be easily done into the view if using DataSet directly
I hope anyone can help me with a more simplistic way to do it
Thank you :)
UPDATE (SOLUTION)
Simon's answer was really effective and it worked on the first try after adding namespaces for System.Data and System.Xml but at the same time, Josh's answer present a very nice and cool way to work with DataSets, which on my opinion works much better and I think I'll go for it now.
Thanks for you help
try adding an explicit reference to System.Data in your nhaml configuration
<?xml version="1.0"?>
<configuration>
...
<configSections>
<section name="nhaml" type="NHaml.Configuration.NHamlConfigurationSection, NHaml"/>
</configSections>
...
<nhaml autoRecompile="true">
<assemblies>
<clear/>
...
<add assembly="System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</assemblies>
<namespaces>
<clear/>
...
<add namespace="System.Data"/>
</namespaces>
</nhaml>
obviously replacing "..." with your other references and config
The only thing I could think of is that in the context of the page, the System.Data reference is not visible.
Try adding the namespace in your web.config:
<pages>
<controls />
<namespaces>
<add namespace="System.Data"/>
</namespaces>
</pages>
I know it's not really part of your question, but I would recommend building a class filled with properties representing the fields in your datatable. Using Linq, you can easily convert your rows into the class object and return a list of them. Here's some rough (and uncompiled) code.
[Serializable]
public class MyClass
{
public string Property1 { get; set; }
public string Property1 { get; set; }
}
You want it to be serializable so your web service can return it as xml or json (however you are returning it). The linq would look something like this:
var result = from r in dataSet.Table[0].Rows.AsEnumerable()
select new MyClass() {
Property1 = r["Field1"].ToString()
Property2 = r["Field2"].ToString()
};
return result.ToList();
In my personal experience, DataSets tend to be resource hogs. Also, Linq will be more efficient than your for loops.
Hope this helps.
Delete the Reffrence(system.Data) ..and Add the same reffrence again .. it might be work..
I have my target language in Session["lang"], which is either "en" or "it". I have added this to the Site.master:
<script runat="server">
void Page_Load(object sender, EventArgs e) {
string lang = Session["lang"].ToString();
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(lang);
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.CreateSpecificCulture(lang);
}
</script>
Then I'd like to invoke a resource string like this:
<asp:Label ID="Label1" runat="server" Text="<%$ Resources:Global, test %>"></asp:Label>
I have two files in the App_GlobalResources, named Global.resx and Global.en.resx.
The problems is that no matter what is in the lang variable, I always get the results from the main Global.resx, and I never get the english version from Global.en.resx
I am doing this wrong entirely??
I tried putting the System.Threading... part in the Application_PreRequestHandlerExecute method in Global.asax.cs but the result was the same.
Thanks
PS: I am asking about a way to make this work in a simple way. If I was to use the complicate way, I'd go with this: http://helios.ca/2009/05/27/aspnet-mvc-and-localization/
i had the same dilema(how to implement localization) in my asp.net mvc app.
I followed the instructions posted here and it works like a charm.
So i created a folder named Localization under Content and then i create Resources resx files for each language i want to translate. Keep in mind that there is a convention for the resx file names. ie
Resources.resx is the default fall back for everything.
Resources.en-GB.resx is for english GB
Resources.en-US.resx is for english US
etc.
Just make sure you follow the instructions posted in the link to embed and make the Resources available in all places in your app (views, controllers etc)
Edit:
I want to add that i ommited this line from web.config since i wanted to manually set the local from my app.
<globalization uiCulture="auto" culture="auto"/>
Instead i have created the following class:
public class SmartController : Controller
{
public SmartController()
{
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
}
}
All controllers inherit from this class.
Since this is an administrative set of the locale i have to set it from my apps settings. You could read it from Cookies and set it, or otherwise. This is imo the simplest solution for localization that i have encountered so far.
Once implemented you can refer to any string you add by the following simple line of code, no extra code needed.
<%= Resources.Strings.TranslatedTerm %>
I bet this one is a duplicate.
Anyway - all you need is here (assuming that you are using webforms viewengine (might work with others too, haven't investigated)).
Oh well... here goes my 'summary':
Helpers are just a part. You need to do some modifications with your default view engine too . On createview/createpartialview it should return localizationwebformview which adds a path key to viewdata which is used by htmlhelper to find resourceexpressionsfields and pass them to localizationhelpers class which retrieves desired value.
Little bonus=>
This might be handy if you don't want to recreate resource folders for view subfolders
(in case you modify viewengine.view/partialviewlocationformats):
private static string ReformatVirtualPath(string virtualPath)
{
//This allows NOT to duplicate App_localResources directory
// ~/Views/Shared/Partial/Some/BulltihS/_View.ascx
// turns into =>
// ~/Views/Shared/_View.ascx
var start = #"(~(/?\w*/?){2})";
var end = #"(\w*.as(c|p)x)";
start = Regex.Match(virtualPath, start).Value;
end = Regex.Match(virtualPath, end).Value;
return start + end;
}
usage:
internal static ResourceExpressionFields GetResourceFields
(string expression, string virtualPath)
{
virtualPath = ReformatVirtualPath(virtualPath);
var context = new ExpressionBuilderContext(virtualPath);
var builder = new ResourceExpressionBuilder();
return (ResourceExpressionFields)
builder.ParseExpression(expression, typeof(string), context);
}
EDIT:
but it might be a good idea to avoid App_GlobalResources and App_LocalResources as K. Scott Allen suggests (check Konstantinos answer).