Can I use the MVC 2 DataAnnotations to specify a minimum length for a string field?
Has anyone done this or have they created custom attributes and if so do you mind sharing the source?
I'm trying to follow the tutorial found here to implement a service layer in my MVC application. What I can't figure out is how to wire it all up.
here's what I have so far.
IUserRepository.vb
Namespace Data
Public Interface IUserRepository
Sub AddUser(ByVal openid As String)
Sub UpdateUser(ByVal id As Integer, ByVal about As String, ByVal birthdate As DateTime, ByVal openid As String, ByVal regionid As Integer, ByVal username As String, ByVal website As String)
Sub UpdateUserReputation(ByVal id As Integer, ByVal AmountOfReputation As Integer)
Sub DeleteUser(ByVal id As Integer)
Function GetAllUsers() As IList(Of User)
Function GetUserByID(ByVal id As Integer) As User
Function GetUserByOpenID(ByVal openid As String) As User
End Interface
End Namespace
UserRepository.vb
Namespace Data
Public Class UserRepository : Implements IUserRepository
Private dc As DataDataContext
Public Sub New()
dc = New DataDataContext
End Sub
#Region "IUserRepository Members"
Public Sub AddUser(ByVal openid As String) Implements IUserRepository.AddUser
Dim user = New User
user.LastSeen = DateTime.Now
user.MemberSince = DateTime.Now
user.OpenID = openid
user.Reputation = 0
user.UserName = String.Empty
dc.Users.InsertOnSubmit(user)
dc.SubmitChanges()
End Sub
Public Sub UpdateUser(ByVal id As Integer, ByVal about As String, ByVal birthdate As Date, ByVal openid As String, ByVal regionid As Integer, ByVal username As String, ByVal website As String) Implements IUserRepository.UpdateUser
Dim user = (From u In dc.Users
Where u.ID = id
Select u).Single
user.About = about
user.BirthDate = birthdate
user.LastSeen = DateTime.Now
user.OpenID = openid
user.RegionID = regionid
user.UserName = username
user.WebSite = website
dc.SubmitChanges()
End Sub
Public Sub UpdateUserReputation(ByVal id As Integer, ByVal AmountOfReputation As Integer) Implements IUserRepository.UpdateUserReputation
Dim user = (From u In dc.Users
Where u.ID = id
Select u).FirstOrDefault
''# Simply take the current reputation from the select statement
''# and add the proper "AmountOfReputation"
user.Reputation = user.Reputation + AmountOfReputation
dc.SubmitChanges()
End Sub
Public Sub DeleteUser(ByVal id As Integer) Implements IUserRepository.DeleteUser
Dim user = (From u In dc.Users
Where u.ID = id
Select u).FirstOrDefault
dc.Users.DeleteOnSubmit(user)
dc.SubmitChanges()
End Sub
Public Function GetAllUsers() As System.Collections.Generic.IList(Of User) Implements IUserRepository.GetAllUsers
Dim users = From u In dc.Users
Select u
Return users.ToList
End Function
Public Function GetUserByID(ByVal id As Integer) As User Implements IUserRepository.GetUserByID
Dim user = (From u In dc.Users
Where u.ID = id
Select u).FirstOrDefault
Return user
End Function
Public Function GetUserByOpenID(ByVal openid As String) As User Implements IUserRepository.GetUserByOpenID
Dim user = (From u In dc.Users
Where u.OpenID = openid
Select u).FirstOrDefault
Return user
End Function
#End Region
End Class
End Namespace
IUserService.vb
Namespace Data
Interface IUserService
End Interface
End Namespace
UserService.vb
Namespace Data
Public Class UserService : Implements IUserService
Private _ValidationDictionary As IValidationDictionary
Private _repository As IUserRepository
Public Sub New(ByVal validationDictionary As IValidationDictionary, ByVal repository As IUserRepository)
_ValidationDictionary = validationDictionary
_repository = repository
End Sub
Protected Function ValidateUser(ByVal UserToValidate As User) As Boolean
Dim isValid As Boolean = True
If UserToValidate.OpenID.Trim().Length = 0 Then
_ValidationDictionary.AddError("OpenID", "OpenID is Required")
isValid = False
End If
If UserToValidate.MemberSince = Nothing Then
_ValidationDictionary.AddError("MemberSince", "MemberSince is Required")
isValid = False
End If
If UserToValidate.LastSeen = Nothing Then
_ValidationDictionary.AddError("LastSeen", "LastSeen is Required")
isValid = False
End If
If UserToValidate.Reputation = Nothing Then
_ValidationDictionary.AddError("Reputation", "Reputation is Required")
isValid = False
End If
Return isValid
End Function
End Class
End Namespace
I have also wired up the IValidationDictionary.vb and the ModelStateWrapper.vb as described in the article above.
What I'm having a problem with is actually implementing it in my controller. My controller looks something like this.
Public Class UsersController : Inherits BaseController
Private UserService As Data.IUserService
Public Sub New()
UserService = New Data.UserService(New Data.ModelStateWrapper(Me.ModelState), New Data.UserRepository)
End Sub
Public Sub New(ByVal service As Data.IUserService)
UserService = service
End Sub
....
End Class
however on the line that says Public Sub New(ByVal service As Data.IUserService) I'm getting an error
'service' cannot expose type 'Data.IUserService' outside the project through class 'UsersController'
So my question is TWO PARTS
How can I properly implement a Service Layer in my application using the concepts from that article?
Should there be any content within my IUserService.vb?
Hi There
I need to render a partial view to a string within a controller action. I have the following sample code, but the ControllerContext.ParentActionViewContext does not seem to exist in mvc 1.0
// Get the IView of the PartialView object.
var view = PartialView("MyPartialView").View;
// Initialize a StringWriter for rendering the output.
var writer = new StringWriter();
// Do the actual rendering.
view.Render(ControllerContext.ParentActionViewContext, writer);
Any tips greatly appreciated.
I'm overriding the onrowcreated to add sort images to the header row of a gridview. This works, but actually adding a sortexpression doesn't. What I want to do is set the images as imagebuttons and set their commandarguments to the sort expression of the column they are sorting for.
I would assume I could get the cell and from it's index get the gridviewcolumn. Then, I could just get the sortexpression of the gridview column, but this does not work. The columns are null. OnRowCreated Code snippet below:
//if this is the header row, we add sort images to each cell
if (row.RowType == DataControlRowType.Header)
{
//iterate through the cells
for (int i = 0; i < row.Cells.Count; i++)
{
//if the column is sortable and visible
if (this.Columns[i].SortExpression != string.Empty && this.Columns[i].Visible)
{
string strSort = this.Columns[i].SortExpression;
}
}
}
Can we not get columns in OnRowCreated like this?
I have a form that I want to postback to some other server on button click . I am using onpostbackurl ...Its posting the form to other server but text field input is not getting into other server. If I remove enctype="multipart.. it seems to be working fine...but the thing is I am doing all this in sharepoint and
<formid="aspnetform" enctype="multipart/datapart"...is getting added on its own.....
in my control I am giving text field and button only .....Any idea how to achieve this...?
in Ms-Ajax
suppose iam downloading 3 files , no dependencies have been defined b/w them
Sys.loadScripts(['file1.js',file2.js',file3.js']);
a in which order these files will be loaded??
b in which order these files will be made available to requesting page??
hi, i have following selectlist for dropdownbox in aspnet mvc.
This is the editEmployee Action controller, so while edit page is displayed i want to display a selectvalue in dropdownbox,since "SelectList" takes 3 parameters one for value,one for text and other is for selected value, here i'm not getting what should i pass in 3rd parameter, coz its asking an object for selected value.
ViewData["DepartmentList"] = new SelectList(DepartmentRepository.GetDepartmentsBySchoolIdInList(ViewData["schoolId"].ToString()),"DepartmentId","DepartmentTitle");
here is the view
=Html.DropDownList("DepartmentList")
public void DisplayThickBox(Page page, int width, int height)
{
string script = "<script type='text/javascript'>";
script += "$(document).ready(function(){";
script += "tb.show('null', 'auto-insurance-redirect.aspx?keepThis=true&TB_iframe=true&height=" + height.ToString() + "&width=" + width.ToString() + "',null);";
script += "});";
script +="</script>";
ScriptManager.RegisterStartupScript(page, page.GetType(), "", script, true);
}
^^^Method to display the thickbox...^^^
DisplayThickBox(this, 518, 321);
^^^Call to method in the click event of the button that fires it...^^^
Page is just refreshing and the thickbox is never displayed. I'm trying to call the javascript manually since im doing some other stuff before i display the thickbox in the code behind...
I'm starting a web application that contains the following projects:
Booking.Web
Booking.Services
Booking.DataObjects
Booking.Data
I'm using the repository pattern in my data project only. All services will be the same, no matter what happens. However, if a customer wants to use Access, it will use a different data repository than if the customer wants to use SQL Server.
I have StructureMap, and want to be able to do the following:
Web project is unaffected. It's a web forms application that will only know about the services project and the dataobjects project.
When a service is called, it will use StructureMap (by looking up the bootstrapper.cs file) to see which data repository to use.
An example of a services class is the error logging class:
public class ErrorLog : IErrorLog
{
ILogging logger;
public ErrorLog()
{
}
public ErrorLog(ILogging logger)
{
this.logger = logger;
}
public void AddToLog(string errorMessage)
{
try
{
AddToDatabaseLog(errorMessage);
}
catch (Exception ex)
{
AddToFileLog(ex.Message);
}
finally
{
AddToFileLog(errorMessage);
}
}
private void AddToDatabaseLog(string errorMessage)
{
ErrorObject error =
new ErrorObject
{
ErrorDateTime = DateTime.Now,
ErrorMessage = errorMessage
};
logger.Insert(error);
}
private void AddToFileLog(string errorMessage)
{
// TODO: Take this value from the web.config instead of hard coding it
TextWriter writer = new StreamWriter(@"E:\Work\Booking\Booking\Booking.Web\Logs\ErrorLog.txt", true);
writer.WriteLine(DateTime.Now.ToString() + " ---------- " + errorMessage);
writer.Close();
}
}
I want to be able to call this service from my web project, without defining which repository to use for the data access. My boostrapper.cs file in the services project is defined as:
public class Bootstrapper
{
public static void ConfigureStructureMap()
{
ObjectFactory.Initialize(x =>
{
x.AddRegistry(new ServiceRegistry());
}
);
}
public class ServiceRegistry : Registry
{
protected override void configure()
{
ForRequestedType<IErrorLog>().TheDefaultIsConcreteType<Booking.Services.Logging.ErrorLog>();
ForRequestedType<ILogging>().TheDefaultIsConcreteType<SqlServerLoggingProvider>();
}
}
}
What else do I need to get this to work? When I defined a test, the ILogger object was null.
Thanks,
there is one linkbtn , on click i have to display word document content inside any textBox which supports, i used simple textbox but am facing the formatting problem. and also it does not show image. there is any idea for problem in display word document content inside any textBox .
i dont know about richtextbox, can i get any help, please send me desired code to [email protected]
The sample page for the MaskedEdit says "Tip: Type 'A' or 'P' to switch AM/PM". Are these keys hardcoded? Does the control automatically change itself for cultures that use 12-hour designators that don't start with A or P? Or is just broken for those?
example:
Arabic (Saudi Arabia) - AM: ?
Arabic (Saudi Arabia) - PM: ?
Chinese (Taiwan) - AM: ??
Chinese (Taiwan) - PM: ??
Greek (Greece) - AM: pµ
Greek (Greece) - PM: µµ
Korean (Korea) - AM: ??
Korean (Korea) - PM: ??
Albanian (Albania) - AM: PD
Albanian (Albania) - PM: MD
Persian (Iran) - AM: ?.?
Persian (Iran) - PM: ?.?
Vietnamese (Vietnam) - AM: SA
Vietnamese (Vietnam) - PM: CH
Afrikaans (South Africa) - PM: nm
Punjabi (India) - AM: ?????
Punjabi (India) - PM: ???
Syriac (Syria) - AM: ?.?
Syriac (Syria) - PM: ?.?
If this control doesn't handle this situation, does anyone know of a control that does?
I am implementing a very simple requirements management tool.
I want the URLs to look like this:
Shows home page for "Project One":
http://projectmanager/Project/Project%20One
Shows a list of requirements being worked on for "Project One"
http://projectmanager/Project/Project%20One/Requirements
Shows requirement 1 for "Project One"
http://projectmanager/Project/Project%20One/Requirement/1
How could I set up routes so that
http://projectmanager/Project/Project%20One
is handled by the project controller
http://projectmanager/Project/Project%20One/Requirements
and
http://projectmanager/Project/Project%20One/Requirements/1
is handled by the requirements controller.
Is it even possible?
Im trying to create a custom version of the RequiredAttribute to replace the built in one and I've got it working for properties that have strings values, but with properties that are DateTime or integer for example, the default RequiredAttribute seems to be applied automatically (IF the property is not nullable!)
My problem is that i want to be able to specify a DateTime property as required using my custom required validator which gets the error message from a resources file (I don't want to have to tell the RequiredAttribute the type of the resource file and the key every time i apply it. That is why I'm making a custom one.)
How can i prevent the framework from applying the required attribute to properties of type DateTime and int etc without changing them to nullable.
Thanks
Hello everybody,
I have ascx partial view with html-layout like that
<%=Html.ActionLink<PersonController>(x => x.Publications(param1, param2, ... )) %>
My ascx is pretty big & I'd like to reuse it, changing controller/method in Html.ActionLink with another controller/method. Method of another controller has the same signature as PersonController.Publications. Please, suggest me the best way how to make controller/method configurable for my layout.
Thank you in advance
Hi,
I am confused, wanted to confirm the below statement -
We can create multiple event handle method for the same event?
I think yes, beacuse it is overloading concept? right?
Please correct my understanding or advise.
Thanks.
I have a page that performs a long-running task (10 to 15 seconds) in the page_load method.
I have client-side javascript code that will display a decent "page loading" animated gif to the user.
I am able to invoke the JavaScript method from the code-behind, to display the "page loading" animated gif, however, the long-running task is hanging up the UI such that the animated gif doesn't actually display until after the long-running task is complete, which is the exact opposite of what I want.
To test this out, in my page_load method I make a call to the JavaScript method to display the animated gif. Then, I use Thread.Sleep(10000). What happens is that the animated gif doesn't display until after Thread.Sleep is complete.
Obviously I am doing something incorrect.
Any advice would be appreciated.
Thanks.
Chris
Hi
I know stackoverflow uses open authentication. I want to try and use this as well. I am using asp.net mvc 2.0 with C#.
I found this
http://www.dotnetopenauth.net/
and I am wondering if this is what was used for stackoverflow.
Also any tutorials would be nice as well.
Edit
I am trying to load up some sample projects but when I build it in VS2010 I get
Error 6 'System.Diagnostics.Contracts.ContractInvariantMethodAttribute' is inaccessible due to its protection level C:\Users\chobo2\Downloads\DotNetOpenAuth-3.4.6.10357\DotNetOpenAuth-3.4.6.10357\Samples\OpenIdOfflineProvider\TextBoxTextWriter.cs 73 4 OpenIdOfflineProvider
Error 7 The type or namespace name 'ContractInvariantMethod' could not be found (are you missing a using directive or an assembly reference?) C:\Users\chobo2\Downloads\DotNetOpenAuth-3.4.6.10357\DotNetOpenAuth-3.4.6.10357\Samples\OpenIdOfflineProvider\TextBoxTextWriter.cs 73 4 OpenIdOfflineProvider
I have an aspx page that is supposed to reference a code-behind variable but I am receiving an error of "The name [variable] does not exist in the current context"
Here is the aspx code
<%@ Control Language="C#" AutoEventWireup="true" Inherits="IPAM.Website.Controls.controls_event_header" Codebehind="event_header.ascx.cs" %>
<%# strEventLink %>
<h3><%# strEventDate %></h3>
<%# strLinks %>
Here is part of the aspx.cs code declaring those variables:
public string strEventLink = "";
public string strEventDate;
public string strLinks = "";
Here is the part of the aspx.cs code where it sets those variables:
strEventLink = "<h2>" + parent.Name + "</h2>";
strLinks += "<p><font size=\"+1\"><a href=\"" + Page.ResolveUrl("~" + strScheduleLink) + "\"><b>" + strScheduleLinkText + "</b></a></font></p>\n";
strEventDate = ei.DateSpan;
Please help me with this problem
When extending a COM class in unmanaged C++ where the original class has private interfaces, one way to do this is through the concept of blind aggregation. The idea is that any interface not explicitly implemented on the outer aggregating class is 'blindly' forwarded to the inner aggregated class.
Now .NET as far as I can figure out does not support COM aggregation natively. A somewhat tedious workaround is to create a .NET class where you implement all the required COM interfaces directly on the .NET class and simply forward to an instance of the actual COM class for any methods you don't want to override.
The problem I have is when the original COM object has one or more private interfaces, i.e. undocumented interfaces that are nonetheless used by some consumers of the original class. Using blind aggregation in unmanaged C++ this is a non-issue as the calls to the private interfaces are automatically forwarded to the original class, however I can't find any way of doing the same thing in .NET. Are there any other ways of accomplishing this with .NET?
I would like to write my own model binder for DateTime type. First of all I'd like to write a new attribute that I can attach to my model property like:
[DateTimeFormat("d.M.yyyy")]
public DateTime Birth { get; set,}
This is the easy part. But the binder part is a bit more difficult. I would like to add a new model binder for type DateTime. I can either
implement IModelBinder interface and write my own BindModel() method
inherit from DefaultModelBinder and override BindModel() method
My model has a property as seen above (Birth). So when the model tries to bind request data to this property, my model binder's BindModel(controllerContext, bindingContext) gets invoked. Everything ok, but. How do I get property attributes from controller/bindingContext, to parse my date correctly? How can I get to the PropertyDesciptor of property Birth?
Edit
Because of separation of concerns my model class is defined in an assembly that doesn't (and shouldn't) reference System.Web.MVC assembly. Setting custom binding (similar to Scott Hanselman's example) attributes is a no-go here.
I want to update a class library (a single DLL file) in a production web application. This web app is pre-compiled (published). I read an answer on StackOverflow (sorry, can't seem to find it anymore because the Search function does not work very well), that led me to believe that I could just paste the new DLL in the bin folder and it would be picked up without problems (this would cause the WP to recycle, which is fine with me because we do not use InProc session state).
However, when I tried this, my site blows up and gives a FileLoadException saying that the assembly manifest definition does not match the assembly reference. What in the world is this?! Updating the DLL in Visual Studio and re-deploying the entire site works just fine, but it is a huge pain in the rear. What is the point of having a separate DLL if you have to re-deploy the entire site to implement any changes?
Here's the question: How can I update a DLL on a production web site without breaking the app and without re-deploying all of the files?
Dim db As New SQLDataContext
Try
Dim deleteBoatPics = (From boat In db.Photos
Where boat.boatid = id)
db.Photos.DeleteOnSubmit(deleteBoatPics)
db.SubmitChanges()
Catch ex As Exception
End Try
I'm getting an error that says:
Unable to cast object of type 'System.Data.Linq.DataQuery`1[WhiteWaterPhotos.Photo]' to type 'WhiteWaterPhotos.Photo'.
I have two separate db.SubmitChanges() because when the button is pressed, I have it delete the records from 1 table, and then the next.
I'm lost, can someone help me out?