I want to add the custom configsection in the app.config file as follows
<Companies>
<Company name="" code=""/>
<Company name="" code=""/>
</Companies>
<Employees>
<Employee name="" Des="" addr="" sal=""/>
<Employee name="" Des="" addr="" sal=""/>
</Employeess>
<Departments>
<Department Id="" Projects=""/>
</Departments>
<Projects>
<Project Path=""/>
</Projects>
In the Department section it is referring to Projects section.
Can anybody tell me way to do it? And how to access it in my code?
#Bhaskar: Please find the code for your comment.
public class RegisterCompaniesConfig : ConfigurationSection
{
public static RegisterCompaniesConfig GetConfig()
{
return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies")?? new RegisterCompaniesConfig();
}
[System.Configuration.ConfigurationProperty("Companies")]
public Companies Companies
{
get
{
object o = this["Companies"]; return o as Companies;
}
}
}
public class Companies : ConfigurationElementCollection
{
public Company this[int index]
{ get { return base.BaseGet(index) as Company; }
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
this.BaseAdd(index, value);
}
}
protected override System.Configuration.ConfigurationElement CreateNewElement()
{ return new Company();
}
protected override object GetElementKey(System.Configuration.ConfigurationElement element)
{ return ((Company)element).Name; }
}
public class Company : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name { get { return this["name"] as string; } }
[ConfigurationProperty("code", IsRequired = true)]
public string Code { get { return this["code"] as string; } }
}
You should check out Jon Rista's three-part series on .NET 2.0 configuration up on CodeProject.
Unraveling the mysteries of .NET 2.0 configuration
Decoding the mysteries of .NET 2.0 configuration
Cracking the mysteries of .NET 2.0 configuration
Highly recommended, well written and extremely helpful! I've learned how to deal with custom config sections from those excellent articles.
I base all my configuration management code on the classes I collected here. This is an example, and here's some documentation. Note that this is code I personally refactored from a blog post that isn't available on-line any more.
This will help you
http://msdn.microsoft.com/en-us/library/2tw134k3(v=vs.80).aspx
Related
I am toying with Swashbuckle.Examples package (3.10.0) in an ASP.NET MVC project. However, I cannot make request examples appear within the UI.
Configuration (SwaggerConfig.cs)
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c => {
c.SingleApiVersion("v1", "TestApp.Web");
c.IncludeXmlComments(string.Format(#"{0}\bin\TestApp.Web.xml", System.AppDomain.CurrentDomain.BaseDirectory));
c.OperationFilter<ExamplesOperationFilter>();
c.OperationFilter<DescriptionOperationFilter>();
c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
})
.EnableSwaggerUi(c => { });
}
Request example classes
public class EchoRequestExample : IExamplesProvider
{
public object GetExamples()
{
return new EchoInput { Value = 7 } ;
}
}
public class EchoInput
{
public int Value { get; set; }
}
Action
[HttpGet]
[Route("Echo")]
[CustomApiAuthorize]
[SwaggerRequestExample(typeof(EchoInput), typeof(EchoRequestExample))]
[ResponseType(typeof(EchoServiceModel))]
public HttpResponseMessage Echo([FromUri] EchoInput model)
{
var ret = new EchoServiceModel
{
Username = RequestContext.Principal.Identity.Name,
Value = value
};
return Request.CreateResponse(HttpStatusCode.OK, ret);
}
Swagger UI shows xml comments and output metadata (model and an example containing default values), but shows no request example. I attached to process and EchoRequestExample.GetExamples is not hit.
Question: How to make SwaggerRequestExample attribute work in ASP.NET MVC 5?
Note: Windows identity is used for authorization.
I received an answer from library owner here:
Swagger request examples can only set on [HttpPost] actions
It is not clear if this is a design choice or just a limitation, as I find [HttpGet] examples also relevant.
I know the feeling, lot's of overhead just for an example, I struggle with this for a while, so I created my own fork of swashbuckle, and after unsuccessful attempts to merge my ideas I ended up detaching and renaming my project and pushed to nuget, here it is: Swagger-Net
An example like that will be:
[SwaggerExample("id", "123456")]
public IHttpActionResult GetById(int id)
{
Here the full code for that: Swagger_Test/Controllers/IHttpActionResultController.cs#L26
Wondering how that looks like on the Swagger-UI, here it is:
http://swagger-net-test.azurewebsites.net/swagger/ui/index?filter=IHttpActionResult#/IHttpActionResult/IHttpActionResult_GetById
I am just following the code examples of a Beginning SilverLight book and here is part of the code about user controls and Dependeny Property that I have typed from the book into my IDE:
public class CoolDownButtonControl: Control
{
public static readonly DependencyProperty CoolDownSecondsProperty =
DependencyProperty.Register(
"CoolDownSeconds",
typeof(int),
typeof(CoolDownButtonControl),
new PropertyMetadata(
new PropertyChangedCallback(
CoolDownButtonControl.OnCoolDownSecondsPropertyChanged
)
)
);
public int CoolDownSeconds
{
get
{
return (int)GetValue(CoolDownSecondsProperty);
}
set
{
SetValue(CoolDownSecondsProperty, value);
}
}
private static void OnCoolDownSecondsPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CoolDownButtonControl cdBuutton = d as CoolDownButtonControl;
cdBuutton.OnCoolDownButtonChange(null);
}
}
The problem is that IDE highlights the line of cdBuutton.OnCoolDownButtonChange(null); complaining about
CoolDownButtonControl does not contain a definition for
OnCoolDownButtonChange
As I am new to this and hoping to learn it from this example I couldn't figure out what is wrong and how to fix it?
You should add that method too, something like this:
protected virtual void OnCoolDownButtonChange(RoutedEventArgs e)
{
}
I have a WebApi project and I am trying to add an area to it.
Is there something different that needs to be done when adding a new area to a webapi project vs a mvc4 application?
I have a simple area registration like
public class MobileAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Mobile";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Mobile_default",
"Mobile/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
A controller like
public class BusinessDetailsController : BaseController
{
public string Index()
{
return "hello world";
}
public HttpResponseMessage Get()
{
var data = new List<string> {"Store 1", "Store 2", "Store 3"};
return Request.CreateResponse(HttpStatusCode.OK, data);
}
}
However I can never reach the api. Am I doing something stupid or is there an extra step with the webapi that needs to be done?
Your code registers an MVC route for the Area, not a Web API route.
To do that use the MapHttpRoute extension method (you'll need to add a using statement for System.Web.Http).
public override void RegisterArea(AreaRegistrationContext context)
{
context.Routes.MapHttpRoute(
name: "AdminApi",
routeTemplate: "admin/api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
However, Areas are not really supported OOTB in ASP.NET Web API and you'll get an exception if you have two controllers with the same name (regardless of whether they are in different areas).
To support this scenario you need to change the way that controllers are selected. You'll find an article that covers how to do this here.
I have the following question that's been nagging at me for quite some time.
I'd like to model the following domain entity "Contact":
public class Contact:IEntity<Contact>
{
private readonly ContactId _Id;
public ContactId Id
{
get { return this._Id; }
}
private CoreAddress _CoreAddress;
public CoreAddress CoreAddress
{
get { return this._CoreAddress; }
set
{
if (value == null)
throw new ArgumentNullException("CoreAddress");
this._CoreAddress = value;
}
}
private ExtendedAddress _ExtendedAddress;
public ExtendedAddress ExtendedAddress
{
get { return this._ExtendedAddress; }
set
{
if (value == null)
throw new ArgumentNullException("ExtendedAddress");
this._ExtendedAddress = value;
}
}
private readonly IList<ContactExchangeSubscription> _Subscriptions
= new List<ContactExchangeSubscription>();
public IEnumerable<ContactExchangeSubscription> Subscriptions
{
get { return this._Subscriptions; }
}
public Contact(ContactId Id, CoreAddress CoreAddress, ExtendedAddress ExtendedAddress)
{
Validations.Validate.NotNull(Id);
this._Id = Id;
this._CoreAddress = CoreAddress;
this._ExtendedAddress = ExtendedAddress;
}
}
As you can see it has a collection of subscriptions. A subscription is modeled like this:
public class ContactExchangeSubscription
{
private ContactId _AssignedContact;
public ContactId AssignedContact
{
get { return this._AssignedContact; }
set
{
if (value == null)
throw new ArgumentNullException("AssignedContact");
this._AssignedContact = value;
}
}
private User _User;
public User User
{
get { return this._User; }
set
{
Validations.Validate.NotNull(value, "User");
this._User = value;
}
}
private ExchangeEntryId _EntryId;
public ExchangeEntryId EntryId
{
get { return this._EntryId; }
set
{
if (value == null)
throw new ArgumentNullException("EntryId");
this._EntryId = value;
}
}
public ContactExchangeSubscription(ContactId AssignedContact, User User, ExchangeEntryId EntryId)
{
this._AssignedContact = AssignedContact;
this._User = User;
this._EntryId = EntryId;
}
}
Now I've been thinking that I shouldnt model a storage technology (Exchange) in my domain, after all, we might want to switch our application to other subscription providers. The property "EntryId" is specific to Exchange. A subscription would always need a User and a ContactId, though.
Is there a better way to model the Subscription? Should I use a factory or abstract factory for the Subscription type to cover other types of subscriptions, should the need arise?
EDIT: So let's toss an abstract factory in the ring and introduce some interfaces:
public interface IContactSubscriptionFactory
{
IContactSubscription Create();
}
public interface IContactSubscription
{
ContactId AssignedContact { get;}
User User { get; }
}
How would a concrete factory for a ContactExchangeSubscription be coded? Remember that this type will need the EntryID field, so it has to get an additional ctr parameter. How to handle different constructor paremeters on different sub-types in factories in general?
I think the answer is staring you in the face in that you need to work against an interface making it easier to introduce new subscription providers (if that's the right term) in the future. I think this is more of an OO design question that DDD.
public interface ISubscriptionProvider
{
ContactId AssignedContact { get; }
User User { get; }
}
And the code in your contract becomes
private readonly IList<ISubscriptionProvider> _subscriptions
= new List<ISubscriptionProvider>();
public IEnumerable<ISubscriptionProvider> Subscriptions
{
get { return _subscriptions; }
}
With regards to using a factory; the purpose of a factory is to construct your domain objects when a creation strategy is required. For example a SubscriptionProviderFactory could be used within your repository when you rehydrate your aggregate and would make the decision to return the ContactExchangeSubscription (as an ISubscriptionProvider) or something else based on the data passed into it.
One final point but perhaps this is just because of the way you have shown your example. But I would say your not really following DDD, the lack of behaviour and with all your propeties having public getters and setters, suggestions your falling into the trap of building an Aemic Domain Model.
After some research I came up with this. Code first, explanation below:
public interface IContactFactory<TSubscription> where TSubscription : IContactSubscription
{
Contact Create(ContactId Id, CoreAddress CoreAddress, ExtendedAddress ExtendedAddress, TSubscription Subscription);
}
public class ContactFromExchangeFactory : IContactFactory<ContactExchangeSubscription>
{
public Contact Create(ContactId Id, CoreAddress CoreAddress, ExtendedAddress ExtendedAddress, ContactExchangeSubscription ExchangeSubscription)
{
Contact c = new Contact(Id, CoreAddress, ExtendedAddress);
c.AddSubscription(ExchangeSubscription);
return c;
}
}
I realized that I dont need a factory for the Contactsubscription but rather for the contact itself.
I learned some things about factories along the way:
They are only to be used when creating (really) new entities, not when rebuilding them from a SQL DB for example
They live in the domain layer (see above!)
Factories are more suitable for similar objects that differ in behaviour rather than data
I welcome comments and better answers.
Im having some problems with NServiceBus, I can get the pubsub example working fine, but now I'm trying to integrate it into a production project and I cant get the thing to work!
My publisher code is exactly the same as the publisher example (I've just imported the project to rule out any other issues) but I then create a void function and call it from my WPF app and I get a "you cant call bus without creating an instance of bus" error
public void RunTest()
{
var eventMessage = new MarketPriceMessage();
eventMessage.Ticker = "IBM";
eventMessage.DataType = "Bid";
eventMessage.Value = (decimal)23.23423;
eventMessage.EventId = Guid.NewGuid();
eventMessage.Time = DateTime.Now; // > 30 ? (DateTime?)DateTime.Now : null;
eventMessage.Duration = TimeSpan.FromSeconds(99999D);
Bus.Publish(eventMessage);
}
Any ideas as to whats going on there and where I'm going wrong?
Following #Adam's comments below this is the code I'm using internally in my WPF App:
public partial class App : Application
{
public IBus bus { get; set; }
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
NServiceBus.Configure.With()
.Log4Net()
.SpringBuilder()
.XmlSerializer()
.MsmqTransport()
.UnicastBus()
.LoadMessageHandlers()
.CreateBus()
.Start();
}
}
}
and
namespace WpfApplication2
{
class EndpointConfig : IConfigureThisEndpoint, AsA_Publisher { }
}
and
namespace WpfApplication2
{
public class SubscriptionAuthorizer : IAuthorizeSubscriptions
{
public bool AuthorizeSubscribe(string messageType, string clientEndpoint, string clientWindowsIdentity, IDictionary<string, string> headers)
{
return true;
}
public bool AuthorizeUnsubscribe(string messageType, string clientEndpoint, string clientWindowsIdentity, IDictionary<string, string> headers)
{
return true;
}
}
}
App Config
<configuration>
<configSections>
<section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core"/>
<section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core"/>
</configSections>
<MsmqTransportConfig
InputQueue="WpfApplication2InputQueue"
ErrorQueue="error"
NumberOfWorkerThreads="1"
MaxRetries="5"/>
<UnicastBusConfig>
<!--DistributorControlAddress="" DistributorDataAddress="" ForwardReceivedMessagesTo="">-->
<MessageEndpointMappings>
</MessageEndpointMappings>
</UnicastBusConfig>
When I'm stepping through my code I can see that bus is a null object.
I am including the references as normal
I'm not too familiar with WPF, but it looks like there is an Application.Startup event that may work. You need to "manually" configure the bus as shown here in the docs
If you're not using Autofac or some other container, the problem is you skipped the assignment to your bus variable. I normally put this in Global.asax Application_Startup, but this way should work too.
If you are using a container, and you register the class that implements your ServiceContract, you can get away with having a local IBus constructor/property injected when it's instantiated.
public IBus bus { get; set; }
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
bus = NServiceBus.Configure.With() // keep a reference to the returned bus.
.Log4Net()
.SpringBuilder()
.XmlSerializer()
.MsmqTransport()
.UnicastBus()
.LoadMessageHandlers()
.CreateBus()
.Start();
}