Search Results

Search found 944 results on 38 pages for 'exposed'.

Page 32/38 | < Previous Page | 28 29 30 31 32 33 34 35 36 37 38  | Next Page >

  • Unity framework DependencyAttribute only works for public properties?

    - by rally25rs
    I was trying to clean up some accessability stuff in my code, and inadvertently broke Unity dependency injection. After a while I realized that I marked some public properties that I didn't really want exposed outside my DLLs to internal. Then I started getting exceptions. So it seems that using the [Dependency] attribute in Unity only works for public properties. I suppose that makes sense since the internal and private props wouldnt be visible to the Unity assembly, but feels really dirty to have a bunch of public properties that you never want anyone to set or be able to set, other than Unity. Is there a way to let unity set internal or private properties too? Here is the unit test I'd like to see pass. Currently only the public prop test passes: [TestFixture] public class UnityFixture { [Test] public void UnityCanSetPublicDependency() { UnityContainer container = new UnityContainer(); container.RegisterType<HasPublicDep, HasPublicDep>(); container.RegisterType<TheDep, TheDep>(); var i = container.Resolve<HasPublicDep>(); Assert.IsNotNull(i); Assert.IsNotNull(i.dep); } [Test] public void UnityCanSetInternalDependency() { UnityContainer container = new UnityContainer(); container.RegisterType<HasInternalDep, HasInternalDep>(); container.RegisterType<TheDep, TheDep>(); var i = container.Resolve<HasInternalDep>(); Assert.IsNotNull(i); Assert.IsNotNull(i.dep); } [Test] public void UnityCanSetPrivateDependency() { UnityContainer container = new UnityContainer(); container.RegisterType<HasPrivateDep, HasPrivateDep>(); container.RegisterType<TheDep, TheDep>(); var i = container.Resolve<HasPrivateDep>(); Assert.IsNotNull(i); Assert.IsNotNull(i.depExposed); } } public class HasPublicDep { [Dependency] public TheDep dep { get; set; } } public class HasInternalDep { [Dependency] internal TheDep dep { get; set; } } public class HasPrivateDep { [Dependency] private TheDep dep { get; set; } public TheDep depExposed { get { return this.dep; } } } public class TheDep { } Updated: I noticed the call stack to set the property passed from: UnityCanSetPublicDependency() --> Microsoft.Practices.Unity.dll --> Microsoft.Practices.ObjectBuilder2.dll --> HasPublicDep.TheDep.set() So in an attempt to at least make the internal version work, I added these to my assembly's properties: [assembly: InternalsVisibleTo("Microsoft.Practices.Unity")] [assembly: InternalsVisibleTo("Microsoft.Practices.Unity.Configuration")] [assembly: InternalsVisibleTo("Microsoft.Practices.ObjectBuilder2")] However, no change. Unity/ObjectBuilder still won't set the internal property

    Read the article

  • Svcutil generating bad config with multiple endpoints

    - by vfilby
    I have a WCF service that has exposed a soap and an xml endpoint. When I use svcutil to generate the proxy code on the client side the generated configuration contains two endpoints which causes the client to fail. If I edit the web.config file and remove the second endpoint (with the custom binding) all works as expected. Is there a way I can get svcutil to generate a config that just works so that I don't need to hand edit the file everytime? Client-side error: An endpoint configuration section for contract 'MyNamespace.ITestService' could not be loaded because more than one endpoint configuration for that contract was found. Please indicate the preferred endpoint configuration section by name. Svcutil command: svcutil http://api.local/Test.svc /reference:bin\MyNamespace.Interface.dll /config:web.config /mergeConfig /out:"Service References\TestService.cs" /n:*,MyNamespace Generated client config: <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicHttpBinding_ITestService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <security mode="None"> <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> </basicHttpBinding> <customBinding> <binding name="CustomBinding_ITestService"> <textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16" messageVersion="Soap12" writeEncoding="utf-8"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> </textMessageEncoding> </binding> </customBinding> </bindings> <client> <endpoint address="http://api2.local/Test.svc/soap" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ITestService" contract="MyNamespace.ITestService" name="BasicHttpBinding_ITestService" /> <endpoint binding="customBinding" bindingConfiguration="CustomBinding_ITestService" contract="MyNamespace.ITestService" name="CustomBinding_ITestService" /> </client> </system.serviceModel>

    Read the article

  • KISS: Simple C# application which communicates with a RESTful web service.

    - by Workshop Alex
    Following the KISS principle, I suddenly realised the following: In .NET, you can use the Entity Model Framework to wrap around a database. This model can be exposed as a web service through WCF. This web service would have a very standardized definition. A client application could be created which could consume any such RESTful web service. I don't want to re-invent the wheel and it wouldn't surprise me if someone has already done this, so my question is simple: Has anyone already created a simple (desktop, not web) client application that can consume a RESTful service that's based on the Entity Framework and which will allow the user to read and write data directly to this service? Otherwise, I'll just have to "invent" this myself. :-)Problem is, the database layer and RESTful service is already finished. The RESTful service will only stay in the project during it's development phase, since we can use the database-layer assembly directly from the web applications that are build around it. When the web application is deployed, the RESTful services are just kept out of the deployment. But the database has a lot of data to manage over nearly 50 tables. When developing against a local database, we can have straight access to the database so I wouldn't need this tool for this. When it's deployed, the web application would be the only way to access the data so I could not use this tool. But we're also having a test phase where the database is stored on another system outside the local domain and this database is not available for developers. Only administrators have direct access to this database, making tests a bit more complex. However, through the RESTful service, I can still access the data directly. Thus, when some test goes wrong, I can repair the data through this connection or just create a copy of the data for tests on my local system. There's plenty of other functionality and it's even possible to just open the URL to a table service straight in Excel or XMLSpy to see the contents. But when I want to write something back, I have to write special code to do just that. A generic tool that would allow me to access the data and modify it would be easier. Since it's a generic setup around the ADO.NET Data services, this should be reasonable easy too. Thus, I can do it but hoped someone else has already done something similar. But it appears that there's no such tool made yet...

    Read the article

  • Easiest Way To Get Started In Dot Net

    - by Avery Payne
    Ok, so the initial search in StackOverflow shows nothing related for this question. So here it goes: Let's pretend for a moment that you're just getting started in a career in computer programming. Let's say that, for whatever reason, you decide to use the .Net framework as a basis for your programming. Let's also say that you've been exposed to some programming background, but not one in .Net, so it seems foreign to you at first. And lastly, you don't have the benefit of 25 years of exposure to the Win32 API, which explains why it seems so foreign to you when you start looking at it. So the questions are: What is a comprehensive overview of what .Net is? It appears to be a combination of a runtime environment, a set of languages, a common set of libraries, and perhaps a few other things...so it's about as clear as mud. Specifically, what are the key components to .Net? What is the easiest way to understand .Net programming with regard to available APIs? Which language would best suit beginning programming out of the "stock" languages that Microsoft has to offer? (C++, C#, VB, etc.) What are some differences between .Net programming and programming in a procedural language (aka Pascal, Modula, etc.) What are some differences between .Net programming and programming in a "traditional" object-oriented language? (aka Smalltalk, Java, Python, Ruby, etc.) As I currently understand it, the CLR provides a foundation for all of the other languages to run on. What are some of the inherent limitations of the CLR? Given the enormous amount of API to cover, would it even be worth learning a .Net language (using the Microsoft APIs) given that you would not have prior exposure to Win32 programming? Let's say you write a for-profit program with .Net. Can you resell the program without running afoul of licensing issues? Let's say you write a gratis (free) program with .Net. Can you offer the program to the public under a "free" license (GPL, BSD, Artistic, etc.) without running afoul of licensing issues? Thank you in advance for your patience.

    Read the article

  • .NET asmx web services: serialize object property as string property to support versioning

    - by mcliedtk
    I am in the process of upgrading our web services to support versioning. We will be publishing our versioned web services like so: http://localhost/project/services/1.0/service.asmx http://localhost/project/services/1.1/service.asmx One requirement of this versioning is that I am not allowed to break the original wsdl (the 1.0 wsdl). The challenge lies in how to shepherd the newly versioned classes through the logic that lies behind the web services (this logic includes a number of command and adapter classes). Note that upgrading to WCF is not an option at the moment. To illustrate this, let's consider an example with Blogs and Posts. Prior to the introduction of versions, we were passing concrete objects around instead of interfaces. So an AddPostToBlog command would take in a Post object instead of an IPost. // Old AddPostToBlog constructor. public AddPostToBlog(Blog blog, Post post) { // constructor body } With the introduction of versioning, I would like to maintain the original Post while adding a PostOnePointOne. Both Post and PostOnePointOne will implement the IPost interface (they are not extending an abstract class because that inheritance breaks the wsdl, though I suppose there may be a way around that via some fancy xml serialization tricks). // New AddPostToBlog constructor. public AddPostToBlog(Blog blog, IPost post) { // constructor body } This brings us to my question regarding serialization. The original Post class has an enum property named Type. For various cross-platform compatibility issues, we are changing our enums in our web services to strings. So I would like to do the following: // New IPost interface. public interface IPost { object Type { get; set; } } // Original Post object. public Post { // The purpose of this attribute would be to maintain how // the enum currently is serialized even though now the // type is an object instead of an enum (internally the // object actually is an enum here, but it is exposed as // an object to implement the interface). [XmlMagic(SerializeAsEnum)] object Type { get; set; } } // New version of Post object public PostOnePointOne { // The purpose of this attribute would be to force // serialization as a string even though it is an object. [XmlMagic(SerializeAsString)] object Type { get; set; } } The XmlMagic refers to an XmlAttribute or some other part of the System.Xml namespace that would allow me to control the type of the object property being serialized (depending on which version of the object I am serializaing). Does anyone know how to accomplish this?

    Read the article

  • App.config in WCF Library and its Windows Service Host

    - by inutan
    Hello there, I have two Services called TemplateService, TemplateReportService (both defined in one WCF Service Library) to be exposed to the client application. And, I am trying to host these services under Windows Service. Can anyone please guide me if App.config in Windows Service will be same as the one in WCF Library? Here is my app.config in WCF Library: <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.web> <compilation debug="true" /> </system.web> <system.serviceModel> <services> <service behaviorConfiguration="ReportingComponentLibrary.TemplateServiceBehavior" name="ReportingComponentLibrary.TemplateService"> <endpoint address="" binding="wsHttpBinding" contract="ReportingComponentLibrary.ITemplateService" > <identity> <dns value="localhost" /> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" ></endpoint> <host> <baseAddresses> <add baseAddress="http://localhost:8080/ReportingComponentLibrary/TemplateService/" /> </baseAddresses> </host> </service> <service behaviorConfiguration="ReportingComponentLibrary.TemplateServiceBehavior" name="ReportingComponentLibrary.TemplateReportService"> <endpoint address="" binding="wsHttpBinding" contract="ReportingComponentLibrary.ITemplateReportService" > <identity> <dns value="localhost" /> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> <host> <baseAddresses> <add baseAddress="http://localhost:8080/ReportingComponentLibrary/TemplateReportService/" /> </baseAddresses> </host> </service> </services> <behaviors> <serviceBehaviors> <behavior name="ReportingComponentLibrary.TemplateServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="True" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration> So, the App.config in my Windows Service(Where I am hosting above two services) will be same as above or there are only some particular sections that I need to move. Please guide. Thank you!

    Read the article

  • SQL CLR Stored Procedure and Web Service

    - by Nathan
    I am current working on a task in which I am needing to call a method in a web service from a CLR stored procedure. A bit of background: Basically, I have a task that requires ALOT of crunching. If done strictly in SQL, it takes somewhere around 30-45 mins to process. If I pull the same process into code, I can get it complete in seconds due to being able to optimize the processing so much more efficiently. The only problem is that I have to have this process set as an automated task in SQL Server. In that vein, I have exposed the process as a web service (I use it for other things as well) and want the SQL CLR sproc to consume the service and execute the code. This allows me to have my automated task. The problem: I have read quite a few different topics regarding how to consume a web service in a CLR Sproc and have done so effectivly. Here is an example of what I have followed. http://blog.hoegaerden.be/2008/11/11/calling-a-web-service-from-sql-server-2005/ I can get this example working without any issues. However, whenever I pair this process w/ a Web Service method that involves a database call, I get the following exceptions (depending upon whether or not I wrap in a try / catch): Msg 10312, Level 16, State 49, Procedure usp_CLRRunDirectSimulationAndWriteResults, Line 0 .NET Framework execution was aborted. The UDP/UDF/UDT did not revert thread token. or Msg 6522, Level 16, State 1, Procedure MyStoredProc , Line 0 A .NET Framework error occurred during execution of user defined routine or aggregate 'MyStoredProc': System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. System.Security.SecurityException: at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) at System.Security.CodeAccessPermission.Demand() at System.Net.CredentialCache.get_DefaultCredentials() at System.Web.Services.Protocols.WebClientProtocol.set_UseDefaultCredentials(Boolean value) at MyStoredProc.localhost.MPWebService.set_UseDefaultCredentials(Boolean Value) at MyStoredProclocalhost.MPWebService..ctor() at MyStoredProc.StoredProcedures.MyStoredProc(String FromPostCode, String ToPostCode) I am sure this is a permission issue, but I can't, for the life of me get it working. I have attempted using impersonation in the CLR sproc and a few other things. Any suggestions? What am I missing?

    Read the article

  • Creating same-width hit-zones on MenuItems in ASP.NET 2.0 Menus that include MenuItems added at runt

    - by Cary Jensen
    In an ASP.NET 2.0 application, I want to permit a user to select a MenuItem, even if the user does not click the actual text of the MenuItem, but instead only clicks the highlight area that ASP.NET places around the currently selected MenuItem (represented by the DynamicHoverStyle.BackColor property). Since the BackColor is displayed the same width for each MenuItem in a submenu, based on MenuItem with the longest text, I would like to make the hit-zone (clickable area) of each sub-MenuItem the same width (same at the BackColor area), regardless of how much text is displayed in the in each individual sub-MenuItem. Here's the setup. I am using a Menu on a MasterPage to display a similar menu on each of my pages. Some of the pages suppress this menu, and some of them add addition MenuItems, sometimes to the top level, sometimes adding sub-MenuItems to an existing top-level MenuItem, and sometimes both (adding a MenuItem to the top level and then additional MenuItems as submenuitems to that newly added top level. This menu has a horizontal orientation, and it is dynamic, in that only the top level is initially exposed, and the submenus are displayed when selected. During usability testing, we noticed that users would select a top-level menu item to expose the submenu, and then select a submenu item, but not by necessarily clicking on the submenu item text, but instead clicking on the BackColor area of the submenu item. Since the text of some MenuItems are longer than others, MenuItems with short Text have a rather large BackColor area. When the user clicks on the BackColor area, but not directly on the MenuItem Text, nothing happens, since the user didn't actually click on the submenu item hit zone. Although there are visual cues as to what part of the displayed MenuItem is clickable (the mouse pointer changes to a link cursor when the mouse is positioned on the MenuItem Text, but not when it is only hovering over the BackColor), this behavior confused the users. They highlighted a MenuItem, and clicked it, but nothing happened. I would to make clicking a MenuItem successful, even if the user did not click on the actual Text of the MenuItem, but simply click on the BackColor area. It seems like there should be a property somewhere to control the width of the active area of the displayed MenuItems, but I do not see it. Any suggestions, given that I am creating some of these MenuItems at runtime?

    Read the article

  • How can I call VC# webservice methods without ArgumentException?

    - by Zarius
    Currently, I'm trying to write a small tray application that will show the status and provide control of a server-side application exposed over webservice. The webservice only has 3 operations: start, stop and status. When I call any of these operations in code, they throw an ArgumentException citing "An item with the same key has already been added". I am compiling the webservice on Visual C# Express 2008, and .NET 3.5. The Code: private TelnetConnClient Conn { get { return new TelnetConnClient(); } } private bool Connected //call webservice operations { get { return Conn.Status(); } set { if(value) Conn.Start(); else Conn.Stop(); } } The Stacktrace: A first chance exception of type 'System.ArgumentException' occurred in mscorlib.dll at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) at System.ServiceModel.TransactionFlowAttribute.ApplyBehavior(OperationDescription description, BindingParameterCollection parameters) at System.ServiceModel.TransactionFlowAttribute.System.ServiceModel.Description.IOperationBehavior.AddBindingParameters(OperationDescription description, BindingParameterCollection parameters) at System.ServiceModel.Description.DispatcherBuilder.AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection parameters) at System.ServiceModel.Description.DispatcherBuilder.BuildProxyBehavior(ServiceEndpoint serviceEndpoint, BindingParameterCollection& parameters) at System.ServiceModel.Channels.ServiceChannelFactory.BuildChannelFactory(ServiceEndpoint serviceEndpoint) at System.ServiceModel.ChannelFactory.CreateFactory() at System.ServiceModel.ChannelFactory.OnOpening() at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.ChannelFactory.EnsureOpened() at System.ServiceModel.ChannelFactory`1.CreateChannel(EndpointAddress address, Uri via) at System.ServiceModel.ChannelFactory`1.CreateChannel() at System.ServiceModel.ClientBase`1.CreateChannel() at System.ServiceModel.ClientBase`1.CreateChannelInternal() at System.ServiceModel.ClientBase`1.get_Channel() at KordiaConnect.ferries.TelnetConnClient.Start() in C:\My Dropbox\Coding\RTF\KordiaConnect\KordiaConnect\Service References\ferries\Reference.cs:line 86 at coldshark.ferries.Main.set_Connected(Boolean value) in C:\My Dropbox\Coding\RTF\KordiaConnect\KordiaConnect\Main.cs:line 22 at coldshark.ferries.Main.<.ctor>b__0(Object sender, EventArgs e) in C:\My Dropbox\Coding\RTF\KordiaConnect\KordiaConnect\Main.cs:line 43 at System.Windows.Forms.NotifyIcon.OnClick(EventArgs e) at System.Windows.Forms.NotifyIcon.WmMouseUp(Message& m, MouseButtons button) at System.Windows.Forms.NotifyIcon.WndProc(Message& msg) at System.Windows.Forms.NotifyIcon.NotifyIconNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.PeekMessage(MSG& msg, HandleRef hwnd, Int32 msgMin, Int32 msgMax, Int32 remove) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run() at coldshark.ferries.Main..ctor() in C:\My Dropbox\Coding\RTF\KordiaConnect\KordiaConnect\Main.cs:line 55 I can just call the webservice from the web interface, but this application will give me a handy status notification icon, and I'd really love to know why the out-of-the-box auto-generated code fails for no particular reason.

    Read the article

  • NHibernate - I have many, but I only want one!

    - by MartinF
    Hello, I have a User which can have many Emails. This is mapped through a List collection (exposed by IEnumerable Emails on the User). For each User one of the Emails will be the Primary one ("Boolean IsPrimary" property on Email). How can I get the primary Email from User without NHibernate loads every email for the User ? I have the following two entities, with a corresponding table for each public class User { public virtual int Id { get; set; } public virtual IEnumerable<Email> Emails { get; set; } // public virtual Email PrimaryEmail { get; set; } - Possible somehow ? } public class Email { public virtual int Id { get; set; } public virtual String Address { get; set; } public virtual Boolean IsPrimary { get; set; } public virtual User User { get; set; } } Can I map a "Email PrimaryEmail" property etc. on the User to the Email which have "IsPrimary=1" set somehow ? Maybe using a Sql Formula ? a View ? a One-To-One relationship ? or another way ? It should be possible to change the primary email to be one of the other emails, so i would like to keep them all in 1 table and just change the IsPrimary property. Using a Sql Formula, is it be possible to keep the "PrimaryEmail" property on the User up-to-date, if I set the IsPrimary property on the current primary email to false, and then afterwards set the PrimaryEmail property to the email which should be the new primary email and set IsPrimary to true ? Will NHibernate track changes on the "old/current" primary Email loaded by the Sql Formula ? What about the 1 level cache and the 2 level cache when using SqlFormula ? I dont know if it could work by using a View ? Then i guess the Email could be mapped like a Component ? Will it work when updating the Email data when loaded from the View ? Is there a better way ? As I have a bi-directional relationship between User and Email I could in many cases of course query the primary Email and then use the "User" property on the Email to get the User (instead of the other way around - going from User to the primary Email) Hope someone can help ?

    Read the article

  • What was "The Next Big Thing" when you were just starting out in programming?

    - by Andrew
    I'm at the beginning of my career and there are lots of things which are being touted as "The Next Big Thing". For example: Dependency Injection (Spring, etc) MVC (Struts, ASP.NET MVC) ORMs (Linq To SQL, Hibernate) Agile Software Development These things have probably been around for some time, but I've only just started out. And don't get me wrong, I think these things are great! So, what was "The Next Big Thing" when you were starting out? When was it? Were people sceptical of it at first? Why? Did you think it would catch on? Did it pan out and become widely accepted/used? If not, why not? EDIT It's been nearly a week since I first posted this question and I can safely say that I did not expect such explosive interest. I asked the question so that I could gain a perspective of what kinds of innovations in programming people thought were most important when they were starting out. At the time of writing this I have read ~95% of all answers. To answer a few questions, the "Next Big Things" I listed are ones that I am currently really excited about and that I had not really been exposed to until I started working. I'm hoping to implement some or all of these in the near future at my current workplace. To many people they are probably old news. In regards to the "is this a real question" debate, I can see that obviously hasn't been settled yet. I feel bad whenever I read a comment saying that these kinds of questions take away from the real meaning of SO. I'm not wholly convinced that it doesn't. On the other hand, I have seen a lot of comments saying what a great question it is. Anyway, I have chosen "The Internet!" as my answer to this question. I don't think (in my very humble opinion, and, it seems many SOers opinions) that many things related to programming can compare. Nowadays every business and their dog has a website which can do anything from simply supplying information to purchasing goods halfway around the world to updating your blog. And of course, all these businesses need people like us. Thanks to everyone for all the great answers!

    Read the article

  • With EJB 2.1, is declaring references to resources in ejb-jar.xml required?

    - by zwerd328
    I'm using Weblogic 9.2 with a lot of MDBs. These MDBs access JDBC DataSources and write to both locally and externally managed JMS Destinations using local and foreign XAConnectionFactorys, respectively. Each MDB demarcates a container-managed JTA transaction that should be distributed amongst all of these resources. Below is an excerpt from my ejb-jar.xml for an MDB that consumes from a local Queue called "MyDestination" and produces to an IBM Websphere MQ Queue called "MyOtherDestination". These logical names are linked to physical objects in my weblogic-ejb-jar.xml file. Is it required to use the <resource-ref> and <message-destination-ref> tags to expose the ConnectionFactory and Queue to the MDB? If so, is it required by Weblogic or is it required by the J2EE spec? And for what purpose? For example, is it required to support XA transactionality? I'm already aware of the benefit of decoupling the administered objects from my MDB using names exposed to the naming context of the MDB. Is this the only value added when specifying these tags? In other words, is it acceptable to just reference these objects from my MDB using the InitialContext and the objects' fully-qualified names? <enterprise-bean> <message-driven> <ejb-name>MyMDB</ejb-name> <ejb-class>com.mycompany.MyMessageDrivenBean</ejb-class> <transaction-type>Container</transaction-type> <message-destination-type>javax.jms.Queue</message-destination> <message-destination-link>MyDestination</message-destination-link> <resource-ref> <res-ref-name>jms/myQCF</res-ref-name> <res-type>javax.jms.XAConnectionFactory</res-type> <res-auth>Container</res-auth> </resource-ref> <message-destination-ref> <message-destination-ref-name>jms/myOtherDestination</message-destination-ref-name> <message-destination-type>javax.jms.Queue</message-destination-type> <message-destination-usage>Produces</message-destination-usage> <message-destination-link>MyOtherDestination</message-destination-link> </message-destination-ref> </message-driven> <enterprise-bean>

    Read the article

  • Constructor Injection and when to use a Service Locator

    - by Simon
    I'm struggling to understand parts of StructureMap's usage. In particular, in the documentation a statement is made regarding a common anti-pattern, the use of StructureMap as a Service Locator only instead of constructor injection (code samples straight from Structuremap documentation): public ShippingScreenPresenter() { _service = ObjectFactory.GetInstance<IShippingService>(); _repository = ObjectFactory.GetInstance<IRepository>(); } instead of: public ShippingScreenPresenter(IShippingService service, IRepository repository) { _service = service; _repository = repository; } This is fine for a very short object graph, but when dealing with objects many levels deep, does this imply that you should pass down all the dependencies required by the deeper objects right from the top? Surely this breaks encapsulation and exposes too much information about the implementation of deeper objects. Let's say I'm using the Active Record pattern, so my record needs access to a data repository to be able to save and load itself. If this record is loaded inside an object, does that object call ObjectFactory.CreateInstance() and pass it into the active record's constructor? What if that object is inside another object. Does it take the IRepository in as its own parameter from further up? That would expose to the parent object the fact that we're access the data repository at this point, something the outer object probably shouldn't know. public class OuterClass { public OuterClass(IRepository repository) { // Why should I know that ThingThatNeedsRecord needs a repository? // that smells like exposed implementation to me, especially since // ThingThatNeedsRecord doesn't use the repo itself, but passes it // to the record. // Also where do I create repository? Have to instantiate it somewhere // up the chain of objects ThingThatNeedsRecord thing = new ThingThatNeedsRecord(repository); thing.GetAnswer("question"); } } public class ThingThatNeedsRecord { public ThingThatNeedsRecord(IRepository repository) { this.repository = repository; } public string GetAnswer(string someParam) { // create activeRecord(s) and process, returning some result // part of which contains: ActiveRecord record = new ActiveRecord(repository, key); } private IRepository repository; } public class ActiveRecord { public ActiveRecord(IRepository repository) { this.repository = repository; } public ActiveRecord(IRepository repository, int primaryKey); { this.repositry = repository; Load(primaryKey); } public void Save(); private void Load(int primaryKey) { this.primaryKey = primaryKey; // access the database via the repository and set someData } private IRepository repository; private int primaryKey; private string someData; } Any thoughts would be appreciated. Simon

    Read the article

  • C# Detect Localhost Port Usage

    - by ThaKidd
    In advance, thank you for your advice. I am currently working on a program which uses Putty to create a SSH connection with a server that uses local port forwarding to enable a client, running my software, to access the service behind the SSH server via localhost. IE: client:20100 - Internet - Remote SSH server exposed via router/firewall - Local Intranet - Intranet Web POP3 Server:110. Cmd Line: "putty -ssh -2 -P 22 -C -L 20100:intranteIP:110 -pw sshpassword sshusername@sshserver" Client would use putty to create a SSH connection with the SSH server specifying in the connection string that it would like to tie port 110 of the Intranet POP3 Server to port 20100 on the client system. Therefore the client would be able to open up a mail client to localhost:20100 and interact with the Internal POP3 server over the SSH tunnel. The above is a general description. I already know what I am trying to do will work without a problem so am not looking for debate on the above. The question is this...How can I ensure the local port (I cannot use dynamic ports, so it must be static) on localhost is not being used or listened to by any other application? I am currently executing this code in my C# app: private bool checkPort(int port) { try { //Create a socket on the current IPv4 address Socket TestSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Create an IP end point IPEndPoint localIP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port); // Bind that port TestSocket.Bind(localIP); // Cleanup TestSocket.Close(); return false; } catch (Exception e) { // Exception occurred. Port is already bound. return true; } } I am currently calling this function starting with a specific port in a for loop to get the 'false' return at the first available port. The first port I try is actually being listened to by uTorrent. The above code does not catch this and my connection fails. What is the best method to ensure a port is truly free? I do understand some other program may grab the port during/after I have tested it. I just need to find something that will ensure it is not currently in use AT ALL when the test is executed. If there is a way to truly reserve the localhost port during the test, I would love to hear about it.

    Read the article

  • How can I specify resources in an MVVM view model?

    - by gix
    Suppose I want to show list of objects where each object should have a name and a suitable image (for example MenuItems with Icons, or buttons with text and image). All examples and programs exposed the image in the viewmodel as a path to a PNG file and then bound the Source of an Image to that. But what if I want to use vector images (for example as a DrawingImage in a local ResourceDictionary)? Exposing the DrawingImage from the view model seems bad because I would have to store a reference to the application/window/user control/... (and it is advised to not expose such XAML objects from view models). So a better approach would be to use a string identifier in the view model and then somehow select the appropriate resource. If that identifier is the resource key this snippet looks tempting but does not work: <Image Source="{StaticResource {Binding Icon}}"/> I found two workarounds for that though they did not work for me. The first one was using a normal binding to the icon with a converter that looked up the resource in Application.Current. This does not work if the resource is stored somewhere else I think (and the situation where I initially bumped into this problem had no Application running yet since it was a Window choosing the Application to launch!). The second workaround was using a markup extension derived from StaticResourceExtension that fetched its ResourceKey from the passed binding: <Image Source="{local:BindableStaticResource {Binding Icon}"/> This one looks really neat because it could use local resources, also be used for other things. But when using it I always got an exception ("Resource named {FooIcon} could not be found.", showing the correct XAML file and position of the extension). Even an empty resource extension derived from StaticResourceExtension that just passed the resource key to the base constructor did not work and I cannot explain why. Just using StaticResourceExtension worked just fine. Any ideas how I could fix the second approach, or even better solutions? Edit I noticed that it does work when used directly like this: <Window> <Window.Resources> <DrawingImage x:Key="SomeIcon"/> </Window.Resources> <Image Source="{BindableStaticResource {Binding Icon}}"/> </Window> but fails for example in a DataTemplate. Though a normal StaticResourceExtension works on both occasions so I am puzzled what is going wrong.

    Read the article

  • Using IOperationBehavior to supply a WCF parameter

    - by Chris Kemp
    This is my first step into the world of stackoverflow, so apologies if I cock anything up. I'm trying to create a WCF Operation which has a parameter that is not exposed to the outside world, but is instead automatically passed into the function. So the world sees this: int Add(int a, int b) But it is implemented as: int Add(object context, int a, int b) Then, the context gets supplied by the system at run-time. The example I'm working with is completely artificial, but mimics something that I'm looking into in a real-world scenario. I'm able to get close, but not quite the whole way there. First off, I created a simple method and wrote an application to confirm it works. It does. It returns a + b and writes the context as a string to my debug. Yay. [OperationContract] int Add(object context, int a, int b); I then wrote the following code: public class SupplyContextAttribute : Attribute, IOperationBehavior { public void Validate(OperationDescription operationDescription) { if (!operationDescription.Messages.Any(m => m.Body.Parts.First().Name == "context")) throw new FaultException("Parameter 'context' is missing."); } public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation) { dispatchOperation.Invoker = new SupplyContextInvoker(dispatchOperation.Invoker); } public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation) { } public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters) { // Remove the 'context' parameter from the inbound message operationDescription.Messages[0].Body.Parts.RemoveAt(0); } } public class SupplyContextInvoker : IOperationInvoker { readonly IOperationInvoker _invoker; public SupplyContextInvoker(IOperationInvoker invoker) { _invoker = invoker; } public object[] AllocateInputs() { return _invoker.AllocateInputs().Skip(1).ToArray(); } private object[] IntroduceContext(object[] inputs) { return new[] { "MyContext" }.Concat(inputs).ToArray(); } public object Invoke(object instance, object[] inputs, out object[] outputs) { return _invoker.Invoke(instance, IntroduceContext(inputs), out outputs); } public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state) { return _invoker.InvokeBegin(instance, IntroduceContext(inputs), callback, state); } public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result) { return _invoker.InvokeEnd(instance, out outputs, result); } public bool IsSynchronous { get { return _invoker.IsSynchronous; } } } And my WCF operation now looks like this: [OperationContract, SupplyContext] int Amend(object context, int a, int b); My updated references no longer show the 'context' parameter, which is exactly what I want. The trouble is that whenver I run the code, it gets past the AllocateInputs and then throws an Index was outside the bounds of the Array. error somewhere in the WCF guts. I've tried other things, and I find that I can successfully change the type of the parameter and rename it and have my code work. But the moment I remove the parameter it falls over. Can anyone give me some idea of how to get this to work (or if it can be done at all).

    Read the article

  • Passing Auth to API calls with Web Service References

    - by coffeeaddict
    I am new to web services. The last time I dealt with SOAP was when I created a bunch of wrapper classes that sent requests and received responses back per some response objects/classes I had created. So I had an object to send certain API requests and likewise a set of objects to hold the response back as an object so I could utilize that 3rd party API. Then someone came to me and said why not just use the wsdl and a web service. Ok, so today I went and created a "Service Reference". I see that this is what's called a "Proxy Class". You just instantiate an instance of this and then walla you have access to all the methods from the wsdl. But this leaves me with auth questions. Back when I created my own classes manually, I had a class which exposed properties that I would set then access for things like signature, username, password that got sent along with the Http request that were required by whatever 3rd party API I was using to make API calls. But then with using a Service Reference, how then would I pass this information just like I had done in my custom classes? For instance I'm going to be working with the PayPal API. It requires you to send a signature and a few other pieces of information like username and password. // Determins if API call needs to use a session based URI string requestURI = UseAuthURI == true ? _requestURIAuthBased + aSessionID : _requestURI; byte[] data = XmlUtil.DocumentToBytes(doc); // Create the atual Request instance HttpWebRequest request = CreateWebRequest(requestURI, data.Length); So how do I pass username, password, signature, etc. when using web service references for each method call? Is it as simple as specifying it as a param to the method or do you use the .Credentials and .URL methods of your proxy class object? It seems to me Credentials means windows credentials but I could be wrong. Is it limited to that or can you use that to specify those required header values that PayPal expects with each method call/API request?

    Read the article

  • User Defined Exceptions with JMX

    - by Daniel
    I have exposed methods for remote management in my application server using JMX by creating an MXBean interface, and a class to implement it. Included in this interface are operations for setting attributes on my server, and for getting the current value of attributes. For example, take the following methods: public interface WordManagerMXBean { public void addWord(String word); public WordsObject getWords(); public void removeWord(String word); } The WordsObject is a custom, serializable class used to retrieve data about the state of the server. Then I also have a WordManager class that implements the above interface. I then create a JMX agent to manage my resource: MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName wordManagerName = new ObjectName("com.example:type=WordManager"); mbs.registerMBean(wordManager, wordManagerName); I have created a client that invokes these methods, and this works as expected. However, I would like to extend this current configuration by adding user defined exceptions that can be sent back to my client. So I would like to change my interface to something like this: public interface WordManagerMXBean { public void addWord(String word) throws WordAlreadyExistsException; public WordsObject getWords(); public void removeWord(String word); } My WordAlreadyExistsException looks like this: public class WordAlreadyExistsException extends Exception implements Serializable { private static final long serialVersionUID = -9095552123119275304L; public WordAlreadyExistsException() { super(); } } When I call the addWord() method in my client, I would like to get back a WordAlreadyExistsException if the word already exists. However, when I do this, I get an error like this: java.rmi.UnmarshalException: Error unmarshaling return; nested exception is: java.lang.ClassNotFoundException: com.example.WordAlreadyExistsException The WordAlreadyExistsException, the WordsObject and the WordManagerMXBean interface are all in a single jar file that is available to both the client and the server. If I call the getWords() method, the client has no difficulty handling the WordsObject. However, if a user defined exception, like the one above, is thrown, then the client gives the error shown above. Is it possible to configure JMX to handle this exception correctly in the client? Following some searching, I noticed that there is an MBeanException class that is used to wrap exceptions. I'm not sure if this wrapping is performed by the agent automatically, or if I'm supposed to do the wrapping myself. I tried both, but in either case I get the same error on the client. I have also tried this with both checked and unchecked exceptions, again the same error occurs. One solution to this is to simply pass back the error string inside a generic error, as all of the standard java exceptions work. But I'd prefer to get back the actual exception for processing by the client. Is it possible to handle user defined exceptions in JMX? If so, any ideas how?

    Read the article

  • jQuery Form plugin - no data from file upload?

    - by pojo
    I've been struggling a bit with the jQuery Form plugin. I want to create a file upload form that posts the data (JSON, from the chosen file) into a REST service exposed by a servlet. The URL for the POST is calculated from what the user chooses in a SELECT dropdown. When the upload is complete, I want to notify the user immediately, AJAX-style. The problem is that the POST header has a Content-Length of 0 and contains no data. I would appreciate any help! <html> <head> <script type="text/javascript" src="js/jquery-1.4.2.min.js">/* ppp */</script> <script type="text/javascript" src="js/jquery.form.js">/* ppp */</script> <script type="text/javascript"> function cb_beforesubmit (arr, $form, options) { // This should override the form's action attribute options.url = "/rest/services/" + $('#selectedaction')[0].value; return true; } function cb_success (rt, st, xhr, wf) { $('#response').html(rt + '<br>' + st + '<br>' + xhr); } $(document).ready(function () { var options = { beforeSubmit: cb_beforesubmit, success: cb_success, dataType: 'json', contentType: 'application/json', method: 'POST', }; $('#myform').ajaxForm(options); $.getJSON('/rest/services', function (data, ts) { for (var property in data) { if (typeof property == 'string') { $('#selectedaction').append('<option>' + property + '</option>'); } } }); }); </script> </head> <body> <form id="myform" action="/rest/services/foo1" method="POST" enctype="multipart/form-data"> <!-- The form does not seem to submit at all if I don't set action to a default value? !--> <select id="selectedaction"> <script type="text/javascript"> </script> </select> <input type="file" value="Choose"/> <input type="submit" value="Submit" /> </form> <div id="response"> </div> </body> </html>

    Read the article

  • Rails send mail with GMail

    - by Danny McClelland
    Hi Everyone, I am on rails 2.3.5 and have the latest Ruby installed and my application is running well, except, GMail emails. I am trying to setup my gmail imap connection which has worked previously but now doesnt want to know. This is my code: # Be sure to restart your server when you modify this file # Uncomment below to force Rails into production mode when # you don't control web/app server and can't set it the proper way # ENV['RAILS_ENV'] ||= 'production' # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.5' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # Gems config.gem "capistrano-ext", :lib => "capistrano" config.gem "configatron" # Make Time.zone default to the specified zone, and make Active Record store time values # in the database in UTC, and return them converted to the specified local zone. config.time_zone = "London" # The internationalization framework can be changed to have another default locale (standard is :en) or more load paths. # All files from config/locales/*.rb,yml are added automatically. # config.i18n.load_path << Dir[File.join(RAILS_ROOT, 'my', 'locales', '*.{rb,yml}')] #config.i18n.default_locale = :de # Your secret key for verifying cookie session data integrity. # If you change this key, all old sessions will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. config.action_controller.session = { :session_key => '_base_session', :secret => '7389ea9180b15f1495a5e73a69a893311f859ccff1ffd0fa2d7ea25fdf1fa324f280e6ba06e3e5ba612e71298d8fbe7f15fd7da2929c45a9c87fe226d2f77347' } config.active_record.observers = :user_observer end ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(:default => '%d/%m/%Y') ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(:default => '%d/%m/%Y') require "will_paginate" ActionMailer::Base.delivery_method = :smtp ActionMailer::Base.smtp_settings = { :enable_starttls_auto => true, :address => "smtp.gmail.com", :port => 587, :domain => "XXXXXXXX.XXX", :authentication => :plain, :user_name => "XXXXXXXXXX.XXXXXXXXXX.XXX", :password => "XXXXX" } But the above just results in an SMTP auth error in the production log. I have read varied reports of this not working in Rails 2.2.2 but nothing for 2.3.5, anyone got any ideas? Thanks, Danny

    Read the article

  • remove data layer and put into it's own domain

    - by user334768
    I have a SL4 application that uses EF4 & RIA Services. DB is SQL 2008. All is working well. Now I want to put the Database and web services on one domain (A.com) with the web service exposing the same methods available in my working project. (one listed at top of message) Then put a Silverlight application (same one as above) on domain(B.com) and call the web services on A.com. I thought I had a fair understanding of RIA Services. Enough to get the above application working. Now when I say "working" I do mean on my local dev machine. I have yet to deployed as SL4 & .NET 4 application to my hosting site. But I don't think I understand it well enough. I normally create a new business app, add EF then create the RIA DomainService. Add any [Includes] I need, modify my linq queries and run application. And it works. Now I need to break off my data layer and put it on another hosting site (A.com) And put my UI and business logic on another hosting site (B.com) I think I need to do the following : On the Database & web service site: domain(A.com) create application, create EF4, create RIA Services and deploy. At this time, are the methods exposed available as a "WEB SERVICE" to other applications calling by http:// a.com/serviceName.svc address? I think I need to do the following : On the application site : domain(B.com) create a business application (later will need authentication and navigation). How can I create an EF when I don't have access to the database? (I know I do have access but I want know what happens here when I do not have access to the database, but only data provided by a web service) If I can not create an EF how do I create my RIA Service? I hope any one who takes time to help me understands what I'm asking. Sorry so long.

    Read the article

  • Best way to version control a WCF application with Git?

    - by Sam
    Suppose I have the following projects. The format is [ProjectName] : [ProjectDependency1, ProjectDependency2, etc.] // Service CoolLibrary WcfApp.Core WcfApp.Contracts WcfApp.Services : CoolLibrary, WcfApp.Core, WcfApp.Contracts // Clients CustomerX.App : WcfApp.Contracts CustomerY.App : WcfApp.Contracts CustomerZ.App : WcfApp.Contracts (On a side note, WcfApp.Contracts should not depend on WcfApp.Core, right? Else CustomerX.App would also depend on and thus be exposed to the service domain model?) (CoolLibrary is shared with other applications, so I can't just put it inside of WcfApp.Services.) All of this code is in-house. I was thinking of having 6 repositories for this. The format is [repository folder name] : [Projects included in repository.] 1. CoolLibrary.git : CoolLibrary 2. WcfApp.Contracts.git : WcfApp.Contracts 3. WcfApp.git : WcfApp.Core, WcfApp.Services 4. CustomerX.App.git : CustomerX.App 5. CustomerY.App.git : CustomerY.App 6. CustomerZ.App.git : CustomerZ.App How should I manage my project dependencies? I see three options: I could use binaries which I have to manually copy to each dependent repository. This would be easiest at the start, but my repositories would be a little bloated, and it'd become more tedious as I add more client apps for customers. I could import dependent code as submodules. This is what I will probably end up doing, although I keep reading on the web that submodules are a hassle. I also read that I can use something called the subtree merge strategy, but I am not sure how it is different from just cloning the repo into a subdirectory and adding the subdirectory to .gitignore. Is the difference that the subtree is recorded in the master repository, so (for example) cloning it from a different location will also pull the subtree? I know I asked a lot of questions in this post, but the most important two questions I have are: 1. Am I using the right number and layout of repositories? Should I use less or more? 2. Which of the three dependency management strategies would you recommend? Is there another strategy I haven't considered?

    Read the article

  • Is there anything wrong with having a few private methods exposing IQueryable<T> and all public meth

    - by Nate Bross
    I'm wondering if there is a better way to approach this problem. The objective is to reuse code. Let’s say that I have a Linq-To-SQL datacontext and I've written a "repository style" class that wraps up a lot of the methods I need and exposes IQueryables. (so far, no problem). Now, I'm building a service layer to sit on top of this repository, many of the service methods will be 1<-1 with repository methods, but some will not. I think a code sample will illustrate this better than words. public class ServiceLayer { MyClassDataContext context; IMyRepository rpo; public ServiceLayer(MyClassDataContext ctx) { context = ctx; rpo = new MyRepository(context); } private IQueryable<MyClass> ReadAllMyClass() { // pretend there is some complex business logic here // and maybe some filtering of the current users access to "all" // that I don't want to repeat in all of the public methods that access // MyClass objects. return rpo.ReadAllMyClass(); } public IEnumerable<MyClass> GetAllMyClass() { // call private IQueryable so we can do attional "in-database" processing return this.ReadAllMyClass(); } public IEnumerable<MyClass> GetActiveMyClass() { // call private IQueryable so we can do attional "in-database" processing // in this case a .Where() clause return this.ReadAllMyClass().Where(mc => mc.IsActive.Equals(true)); } #region "Something my class MAY need to do in the future" private IQueryable<MyOtherTable> ReadAllMyOtherTable() { // there could be additional constrains which define // "all" for the current user return context.MyOtherTable; } public IEnumerable<MyOtherTable> GetAllMyOtherTable() { return this.ReadAllMyOtherTable(); } public IEnumerable<MyOtherTable> GetInactiveOtherTable() { return this.ReadAllMyOtherTable.Where(ot => ot.IsActive.Equals(false)); } #endregion } This particular case is not the best illustration, since I could just call the repository directly in the GetActiveMyClass method, but let’s presume that my private IQueryable does some extra processing and business logic that I don't want to replicate in both of my public methods. Is that a bad way to attack an issue like this? I don't see it being so complex that it really warrants building a third class to sit between the repository and the service class, but I'd like to get your thoughts. For the sake of argument, lets presume two additional things. This service is going to be exposed through WCF and that each of these public IEnumerable methods will be calling a .Select(m => m.ToViewModel()) on each returned collection which will convert it to a POCO for serialization. The service will eventually need to expose some context.SomeOtherTable which wont be wrapped into the repository.

    Read the article

  • Should the argument be passed by reference in this .net example?

    - by Hamish Grubijan
    I have used Java, C++, .Net. (in that order). When asked about by-value vs. by-ref on interviews, I have always done well on that question ... perhaps because nobody went in-depth on it. Now I know that I do not see the whole picture. I was looking at this section of code written by someone else: XmlDocument doc = new XmlDocument(); AppendX(doc); // Real name of the function is different AppendY(doc); // ditto When I saw this code, I thought: wait a minute, should not I use a ref in front of doc variable (and modify AppendX/Y accordingly? it works as written, but made me question whether I actually understand the ref keyword in C#. As I thought about this more, I recalled early Java days (college intro language). A friend of mine looked at some code I have written and he had a mental block - he kept asking me which things are passed in by reference and when by value. My ignorant response was something like: Dude, there is only one kind of arg passing in Java and I forgot which one it is :). Chill, do not over-think and just code. Java still does not have a ref does it? Yet, Java hackers seem to be productive. Anyhow, coding in C++ exposed me to this whole by reference business, and now I am confused. Should ref be used in the example above? I am guessing that when ref is applied to value types: primitives, enums, structures (is there anything else in this list?) it makes a big difference. And ... when applied to objects it does not because it is all by reference. If things were so simple, then why would not the compiler restrict the usage of ref keyword to a subset of types. When it comes to objects, does ref serve as a comment sort of? Well, I do remember that there can be problems with null and ref is also useful for initializing multiple elements within a method (since you cannot return multiple things with the same easy as you would do in Python). Thanks.

    Read the article

  • TFS 2010 Build Custom Activity for Merging Assemblies

    - by Jakob Ehn
    *** The sample build process template discussed in this post is available for download from here: http://cid-ee034c9f620cd58d.office.live.com/self.aspx/BlogSamples/ILMerge.xaml ***   In my previous post I talked about library builds that we use to build and replicate dependencies between applications in TFS. This is typically used for common libraries and tools that several other application need to reference. When the libraries grow in size over time, so does the number of assemblies. So all solutions that uses the common library must reference all the necessary assemblies that they need, and if we for example do a refactoring and extract some code into a new assembly, all the clients must update their references to reflect these changes, otherwise it won’t compile. To improve on this, we use a tool from Microsoft Research called ILMerge (Download from here). It can be used to merge several assemblies into one assembly that contains all types. If you haven’t used this tool before, you should check it out. Previously I have implemented this in builds using a simple batch file that contains the full command, something like this: "%ProgramFiles(x86)%\microsoft\ilmerge\ilmerge.exe" /target:library /attr:ClassLibrary1.bl.dll /out:MyNewLibrary.dll ClassLibrary1.dll ClassLibrar2.dll ClassLibrary3.dll This merges 3 assemblies (ClassLibrary1, 2 and 3) into a new assembly called MyNewLibrary.dll. It will copy the attributes (file version, product version etc..) from ClassLibrary1.dll, using the /attr switch. For more info on ILMerge command line tool, see the above link. This approach works, but requires a little bit too much knowledge for the developers creating builds, therefor I have implemented a custom activity that wraps the use of ILMerge. This makes it much simpler to setup a new build definition and have the build automatically do the merging. The usage of the activity is then implemented as part of the Library Build process template mentioned in the previous post. For this article I have just created a simple build process template that only performs the ILMerge operation.   Below is the code for the custom activity. To make it compile, you need to reference the ILMerge.exe assembly. /// <summary> /// Activity for merging a list of assembies into one, using ILMerge /// </summary> public sealed class ILMergeActivity : BaseCodeActivity { /// <summary> /// A list of file paths to the assemblies that should be merged /// </summary> [RequiredArgument] public InArgument<IEnumerable<string>> InputAssemblies { get; set; } /// <summary> /// Full path to the generated assembly /// </summary> [RequiredArgument] public InArgument<string> OutputFile { get; set; } /// <summary> /// Which input assembly that the attibutes for the generated assembly should be copied from. /// Optional. If not specified, the first input assembly will be used /// </summary> public InArgument<string> AttributeFile { get; set; } /// <summary> /// Kind of assembly to generate, dll or exe /// </summary> public InArgument<TargetKindEnum> TargetKind { get; set; } // If your activity returns a value, derive from CodeActivity<TResult> // and return the value from the Execute method. protected override void Execute(CodeActivityContext context) { string message = InputAssemblies.Get(context).Aggregate("", (current, assembly) => current + (assembly + " ")); TrackMessage(context, "Merging " + message + " into " + OutputFile.Get(context)); ILMerge m = new ILMerge(); m.SetInputAssemblies(InputAssemblies.Get(context).ToArray()); m.TargetKind = TargetKind.Get(context) == TargetKindEnum.Dll ? ILMerge.Kind.Dll : ILMerge.Kind.Exe; m.OutputFile = OutputFile.Get(context); m.AttributeFile = !String.IsNullOrEmpty(AttributeFile.Get(context)) ? AttributeFile.Get(context) : InputAssemblies.Get(context).First(); m.SetTargetPlatform(RuntimeEnvironment.GetSystemVersion().Substring(0,2), RuntimeEnvironment.GetRuntimeDirectory()); m.Merge(); TrackMessage(context, "Generated " + m.OutputFile); } } [Browsable(true)] public enum TargetKindEnum { Dll, Exe } NB: The activity inherits from a BaseCodeActivity class which is an internal helper class which contains some methods and properties useful for moste custom activities. In this case, it uses the TrackeMessage method for writing to the build log. You either need to remove the TrackMessage method calls, or implement this yourself (which is not very hard… ) The custom activity has the following input arguments: InputAssemblies A list with the (full) paths to the assemblies to merge OutputFile The name of the resulting merged assembly AttributeFile Which assembly to use as the template for the attribute of the merged assembly. This argument is optional and if left blank, the first assembly in the input list is used TargetKind Decides what type of assembly to create, can be either a dll or an exe Of course, there are more switches to the ILMerge.exe, and these can be exposed as input arguments as well if you need it. To show how the custom activity can be used, I have attached a build process template (see link at the top of this post) that merges the output of the projects being built (CommonLibrary.dll and CommonLibrary2.dll) into a merged assembly (NewLibrary.dll). The build process template has the following custom process parameters:   The Assemblies To Merge argument is passed into a FindMatchingFiles activity to located all assemblies that are located in the BinariesDirectory folder after the compilation has been performed by Team Build. Here is the complete sequence of activities that performs the merge operation. It is located at the end of the Try, Compile, Test and Associate… sequence: It splits the AssembliesToMerge parameter and appends the full path (using the BinariesDirectory variable) and then enumerates the matching files using the FindMatchingFiles activity. When running the build, you can see that it merges two assemblies into a new one:     And the merged assembly (and associated pdb file) is copied to the drop location together with the rest of the assemblies:

    Read the article

< Previous Page | 28 29 30 31 32 33 34 35 36 37 38  | Next Page >