Suggestion for ServiceStack.NET - c#

The suggested way of using ServiceStack.NET with Silverlight is to use the Linked-Project addon. This enables two synchronous Projects and their sources, one for Silverlight, one for .NET 3.5+.
But when it comes to validation, this gets a bit annoying.
ServiceStack is using FluentValidation, which is cool. But it has changed the namespace.
So I end up with:
using MyNamespace.Model;
// HERE ----------------------------
#if SILVERLIGHT
using FluentValidation;
#else
using ServiceStack.FluentValidation;
#endif
//TO HERE------------------------
namespace HR.RoBP.Contracts.Validators.Model
{
public class CustomerValidator : AbstractValidator<Customer>
{
public CustomerValidator()
{
RuleFor(r => r.Name).NotEmpty().NotNull();
}
}
}
This is not much, but it gets really annoing when writing a new validator each time. I often forget it, compile, have errors, fix it.
I know there is something changed in FluentValidation on ServiceStack.NET.
But must it be in a seperate Namespace?
I think its in the interest of servicestack to keep code files clean.
But using the the same validation on client and server forces me to do this.
If there is a elegant way to fix this issue, I would love to hear about it.

You unfortunately can't set a project-wide namespace alias. You could however try to write a template for your validator class that has that boilerplate code built in, and you can easily click Add -> New Item -> Your Validator Template.

Related

C# wrong reference to namespace

Okay this is driving me crazy. I got one almost finished project (which works perfectly) and I wanted to make another one in the same way. The thing is there is a solution with two layers DataAccessLayer and BusinessLogicLayer. Both of these layers have a Model library with all models in the project. I need to convert the model from the first layer to a model of a second layer in the manager library. This works in the finished project I received but I can not manage to make it on mine.
The thing is I can't make the necessary references to work like they do on the finished project. The structure is:
BusinessLogicLayer
--Managers
----Users
--Models
----User
DataAccessLayer
--Models
----User
In the Managers project I have a reference added to DataAccessLayer.Models.
And inside the Users class I got:
using Library.BusinessLogicLayer.Models;
Now in my project this line is red underlined:
Error CS0234 The type or namespace name 'Models' does not exist in the
namespace 'Library.BusinessLogicLayer' (are you missing an assembly
reference?)
I am not even sure how and why this works on that original project. But I can't figure it out so it's working right on my project and the structure is the exact same. Anyone have an idea about this?
EDIT:
Dunno why I didn't upload this earlier. Here is the structure.
https://i.imgur.com/srnySFJ.jpg
EDIT2:
Since it is not quite understandable I uploaded the whole project on github so you can take a closer look at it.
https://github.com/Morsusy2k/Library
And here is the problem:
https://i.imgur.com/DvCvnMA.jpg
From what you described above and from my understanding, it seems that Managers and Models are two different projects. If that is the case, make sure that you add a reference to BusinessLogicLayer.Models in your BusinessLogicLayer.Managers.
If, on the other hand, you have only two projects BusinessLogicLayer and DataAccessLayer then it could very well mean that Library.BusinessLogicLayer.Models is not the name of the namespace.
UPDATE
From the picture that you added, you might need to add a reference to Library.BusinessLogicLayer.Models.Models. You have a folder named Models and a project named Models. Visual Studio automatically generates namespaces based on the Solution name, Solution folders, project name, folders within project.
There were three issues with your code. The first one is that you are supposed to add a reference to Library.DataAccessLayer.Models and not to Library.BusinessLogicLayer.Models. This is due to the fact that you have User in DataAccessLayer.Models and User2 in BusinessLogicLayer.Models.
The other two issues were with the Map method where you are sending incorrect number of arguments to the constructor (you are missing UserId) and the other issues is with your DateOfBirth and DateJoined being in the wrong order in the same method.
using System;
using System.Collections.Generic;
using System.Linq;
using global::Library.BusinessLogicLayer.Models;
using Library.BusinessLogicLayer.Managers.Properties;
using Library.DataAccessLayer.Models; // <-- Add reference to this
namespace Library.BusinessLogicLayer.Managers
{
public class Users2
{
public IEnumerable<User> GetAll()
{
using(DataAccessLayer.DBAccess.Library library = new DataAccessLayer.DBAccess.Library(Settings.Default.LibraryDbConnection))
{
return library.Users.GetAll().Select(user => Map(user));
}
}
private User Map(DataAccessLayer.Models.User dbUser)
{
if (dbUser == null)
return null;
// TODO: Constructor is missing a paremeter. I'll add a temporary one
int tempUserId = 0;
User user = new User(tempUserId, dbUser.Name, dbUser.UserName, dbUser.Password, dbUser.Email, dbUser.DateJoined, dbUser.DateOfBirth) // <-- The last two params are in the wrong order
{
Id = dbUser.Id
};
return user;
}
private Library.DataAccessLayer.Models.User Map(User2 user)
{
if (user == null)
throw new ArgumentNullException("user","Valid user is mandatory!");
return new DataAccessLayer.Models.User(user.Id,user.Name, user.UserName, user.Password, user.Email, user.DateJoined, user.DateOfBirth);
}
}
}
Also, regarding the last screenshot that you provided, you do not have Library.BusinessLogicLayer.Models2 namespace. Remove number 2 to get it to work.
As I don't have permission to update your repo with the fixed code, you'll have to fix it manually based on my answer. Otherwise, let me know so that we see how I can push the code back.
There are a few things you could try:
This error could be appearing within BusinessLogicLayer because DataAccessLayer failed to build. Try building DataAccessLayer by itself to see if you get a different error.
The references might be "added", but you might not be referencing the correct DLL or version for some reason. Check your .csproj files manually to ensure all references and versions are correct, have the right hint paths, etc. If you have any config files, you should also review them to ensure there are no version conflicts.
In addition to checking the references, it is possible to add if-then and switch case logic inside of the .csproj files. This is an MSBuild feature that Visual Studio doesn't support through its GUI, so you may need to copy/update this logic manually in your current .csproj files if any existed.
Check your default namespaces in project properties to see if they are the same as your old project. If you added new files since you moved to this project, they may have been inadvertently added with the wrong namespace and that namespace may be causing a conflict. You could also try using global::Library.BusinessLogicLayer.Models; to see if that fixes or changes the error message or at least if Intellisense is picking the namespace up.
If that doesn't work, review all of your namespaces in all .cs files to see if you have any that have gone rogue.
Since your Models namespace has the problem and you have 2 of them with the same name, try temporarily renaming one of them (yes, every .cs file in one of the projects) to Models2 to see if it provides a clue (such as the error going away or changing).

MvvmCross - missing viewmodels parameters with Link all assemblies enabled

Trying to reduce an app size, I enabled 'Link all assemblies' option on my Xamarin.iOS app. Unfortunately, when I launch the app, passing simple view model parameters doesn't work. On the application output I can see the following warning:
mvx:Diagnostic: 1.93 Missing parameter for call to ViewModel - missing parameter isLaunchedForTheFirstTime - assuming null - this may fail for value types! mvx:Error: 1.94 Failed to parse BoolParser parameter isLaunchedForTheFirstTime from string
I have no idea what to add to LinkerPleaseInclude.cs to make it work. Any ideas?
Thanks in advance!
EDIT:
Here's my preserve.xml file which contains all referenced assemblies:
http://pastebin.com/cEmLDxqn
And my view model navigation:
ShowViewModel<FirstViewModel>(new {isLaunchedForTheFirstTime = true})
[ImplementPropertyChanged]
public class FirstViewModel : MvxViewModel
{
//properties
public void Init(bool isLaunchedForTheFirstTime)
{
//handling parameter
}
}
Not all the time the linker is smart enough to detect everything that you need for you project to run, especially if you're using DI or reflection. In these cases, you can configure it to include the assemblies/types or methods that it might've missed.

Microsoft Fakes: Trying to shim a class but dependencies are still there

Ok, so here's the deal: I have a complex, heavily dependent class LegacyClass that I'd like to shim so that I get rid of all its dependencies while unit testing other parts of the code base. That class creates dependencies already inside its default constructor, so I need to override it with something with no external dependencies, say, with an empty default constructor. And this is what I'm trying to do (using the Visual Studio 2013 Professional Test Framework):
using System;
using Microsoft.QualityTools.Testing.Fakes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MyApp_Unit_Tests {
[TestClass]
public class UnitTest1 {
[TestMethod]
public void TestInstantiation1() {
using (ShimsContext.Create()) {
MyNamespace.Fakes.ShimLegacyClass.Constructor = x => { };
var legacyClassInstance = new MyNamespace.Fakes.ShimLegacyClass();
var sut = new MyNamespace.Gui.ViewModels.MainWindowViewModel(legacyClassInstance);
}
}
}
}
However, this does not work. When MainWindowViewModel is instantiated, for some reason all the same external dependencies are still required as with using the original class! Why?
The exception I'm getting, though, is System.BadImageFormatException, so I probably have some confusion about the target CPU settings, too, but anyway the root cause is that it's attempting to load the external DLL referred to only in the original (non-shimmed) legacy class in its default constructor, while I think it no longer should.
Obviously I've been misunderstood, but where's the mistake? Can I not override default constructors, after all, even with using Shims, or is my approach just wrong? What am I missing?
Thanks a million in advance for any advice!
-Seppo
I had same problem and I solved it maybe this approach going to help you
using (ShimsContext.Create())
{
LegacyClass obj=new LegacyClass();
ShimLegacyClass shimobj=new ShimLegacyClass(obj);
//
// modify every thing you want on shimobj
//
shimobj.InstanceBehavior = ShimBehaviors.Fallthrough;
//rest of test
}
This approach helps you to break dependencies in every part you want and keep the rest same as main class

Writing reusable c# code for ASP.NET websites

I have been learning C# for the past few days for use with ASP.NET to create websites.
I am very new to C# but I have been thinking about how I should go about writing my code to make it as reusable as possible.
As a quick example, lets say I wanted to create a piece of code to check a users login details which I could just drop into another site at any time, and have it work with the data it gets given.
Remembering that I have no idea how I should layout my code to do this, this is the idea I came up with (I will keep it short with some kind of pseudo code):
First I create a class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Module {
public class Login {
public static bool check_login(string usernameCheck = "", string passwordCheck = "") {
if(usernameCheck == "user" && passwordCheck == "password") {
return true;
}
return false;
}
}
}
Then I would have an aspx page where the login form would go, for example:
<asp:Content ContentPlaceHolderID="column1" runat="server">
<asp:TextBox ID="usernameInput" runat="server"></asp:TextBox>
<asp:TextBox ID="passwordInput" runat="server"></asp:TextBox>
<asp:Button OnClick="check_login" Text="Login" runat="server" />
</asp:Content>
And the code behind file would look like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Module {
public partial class _default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
}
protected void check_login(object sender, EventArgs e) {
if(Login.check_login(usernameInput.Text, passwordInput.Text)) {
Response.Redirect("some other place");
}
}
}
}
This works as expected, but what I want to know is:
Is there a better way to create reusable code?
How do you design your reusable code?
I'm sure there must be a better way for me to do this, but I just can't think of it on my own.
With regard to ASP.NET WebForms and reusability, it has to be said that the most common issue lies with putting too much logic into the code-behind files. Programmers, especially those new to ASP.NET WebForms, tend to put there parts of business logic and even database access code. After a while, it turns their application into a giant hard-to-maintain blurb.
Extract away your business logic into a separate layer. Access it from the code-behind. Just access, not implement it directly. Stay away from the database. Only the business layer should be allowed to talk to it.
You could even put your business logic and domain model entities into a separate class library. Then it's how it becomes reusable.
That's first simple considerations before you get your hands dirty with some serious coding.
Reusability techniques in .NET mostly revolve around shelving common code into class libraries to be used by a variety of applications.
Reusability as applied to web applications (ASP.NET) is usually achieved with UserControls (*.ascx) for the presentation part and exposing parts of the application via web services.
One could also mention moving the business logic into the database layer (putting it into stored procedures) but this one is commonly perceived as controversial these days.
Maybe login is a bad example, because there are ASP.NET built-in ways to do this, but, in general, you are on the right track: Don't put the business logic that you might want to reuse into the Page itself, but rather into some classes -- this has the additional advantage of structuring your code in a more logical way: User-interface related stuff is in the ASPX page (and it's codebehind), program logic resides in separate classes. Eventually, you'll want to move some of those classes into a separate library project, which can be linked to by many different web applications.
If you want to reuse ASP.NET user interface elements, you have the possibility to write ASP.NET Server Controls, which you put into your library and use in your ASP.NET pages like this:
<asp:Content ContentPlaceHolderID="column1" runat="server">
<custom:MyCustomLoginControl runat="server"
OnSuccessRedirectTo="myStartPage.aspx" />
</asp:Content>
The best way I've found to re-use WebForms pages and code is to use the MVP pattern. We implemented MVP for some of our pages on our old website as described here, and when we moved to ASP.NET MVC, we found the process to be really simple.
There is a simple solution to code reuse in ASP.NET.
After researching, I found two solutions:
working with virtual directories, or
move the entire contents to the root directory.
Checking the two solutions, identified what really needs to be done: it is enough to just set the BIN folder of our project to target the root directory (C:\inetpub\wwwroot\bin).
Here's a simple example in the attached file: LibExemplo.zip.
Currently I use SharpDevelop which does not need lengthy installations or configurations.
Regards,
Reinaldo Fernando

how to create pluggable ASP.Net website?

What are the best practices to create a site, with ability to develop plugins for it?
Like you want to create a blog module, and you want users or co-developers to add plugins to extend this module functionality.
Update:
Thanks for the ultra speed answers, but I think this is over kill for me. Isn't there a simpler solution, like I have seen blogengine plugin creation system is you just have to decorate the class plugin with [Extension].
I am kind of mid core developer, so I was thinking of base class, inheritance, interfaces, what do you think ?
Edit
I completely rewrote my answer based on your question edit.
Let me show you just how easy it is to implement a plugin architecture with just the minimal steps.
Step 1: Define an interface that your plugins will implement.
namespace PluginInterface
{
public interface IPlugin
{
string Name { get; }
string Run(string input);
}
}
Step 2: Create a plugin that implements IPlugin.
namespace PluginX
{
using PluginInterface;
public class Plugin : IPlugin
{
public string Name
{
get { return "Plugin X"; }
}
public string Run(string input)
{
return input;
}
}
}
Step 3: Run the plugin.
namespace PluginTest
{
using System;
using System.IO;
using System.Runtime.Remoting;
using PluginInterface;
class Program
{
static void Main( string[] args )
{
string pluginFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PluginX.dll");
ObjectHandle handle = Activator.CreateInstanceFrom(pluginFile, "PluginX.Plugin");
IPlugin plugin = handle.Unwrap() as IPlugin;
string pluginName = plugin.Name;
string pluginResult = plugin.Run("test string");
}
}
}
Keep in mind, this is just the basic, most straightforward example of a plugin architechure. You can also do things such as
create a plugin host to run your plugin inside of it's own AppDomain
choose either interfaces, abstract classes, or attributes to decorate your plugins with
use reflection, interfaces, IL-emitted thunks or delegates to get the late binding job done
if your design so dictates.
It's valuable to separate technical and architecturas perspectives:
In code level MEF (Managed Extensibility Framework) is a good start. Here is a simple example.
Any other DI (Dependency Injection framework) can work well to (ie. Unity)
And it's good to see this problem in architectural level:
Web Client Software Factory from p&p. Here are not only technical but arcihtectural informations about "How to create composite web applications?". See examples.. There is Modularity Boundle package.
Spring Framework.
I think it's a fast and efficient if you read&try some of those frameworks. And ofcoz read the source if you find something interessing.
Edit
if you are searching for an extensible blog engine then try Blog Engine first. It's from ASP.NET community.
This sounds like a job for the Managed Extensibility Framework from Microsoft. It's in a preview release at the moment but it would seem to be a better bet than rolling your own framework for this. There are links to guides about how to use this on the site there.
If you would like to see a real, open source application that impliments this archecture take a look at DotNetNuke.

Categories

Resources