Search Results

Search found 7418 results on 297 pages for 'argument passing'.

Page 72/297 | < Previous Page | 68 69 70 71 72 73 74 75 76 77 78 79  | Next Page >

  • Are there any free tools for building AIR applications?

    - by rspeed
    There is an ongoing argument on the web right now about the "openness" of the iPhone OS and Adobe Flash platforms. Adobe's argument is that anyone can build a Flash application without having to worry about being allowed to distribute it. This made me wonder… is it possible to build and distribute an AIR application without giving any money to Adobe (without violating any licenses, of course)? Are any of these tools free? Are any open-source?

    Read the article

  • Can AC_CHECK_LIB be used for unconventionally named libraries?

    - by aleph
    AC_CHECK_LIB accepts as an argument the base name of the shared library that you want to check for. So for a library named "libxyz.so" you would specify the base name of the library "xyz" as an argument to AC_CHECK_LIB. If I have a library named xyz.so (Note: Not libxyz.so), how do I check for the availability/usability of this library with autoconf ?

    Read the article

  • Given an array of arguments, how do I send those arguments to a particular function in Ruby?

    - by Steven Xu
    Forgive the beginner question, but say I have an array: a = [1,2,3] And a function somewhere; let's say it's an instance function: class Ilike def turtles(*args) puts args.inspect end end How do I invoke Ilike.turtles with a as if I were calling (Ilike.new).turtles(1,2,3). I'm familiar with send, but this doesn't seem to translate an array into an argument list. A parallel of what I'm looking for is the Javascript apply, which is equivalent to call but converts the array into an argument list.

    Read the article

  • Incompatible pointer type

    - by Boffin
    Hello. I have the function with following signature: void box_sort(int**, int, int) and variable of following type: int boxes[MAX_BOXES][MAX_DIMENSIONALITY+1] When I am calling the function box_sort(boxes, a, b) GCC gives me two warnings: 103.c:79: warning: passing argument 1 of ‘box_sort’ from incompatible pointer type (string where i am calling the function) 103.c:42: note: expected ‘int **’ but argument is of type ‘int (*)[11] (string where the function is defined) The question is why? Whether int x[][] and int** x (and actually int* x[]) are not the same types in C?

    Read the article

  • drupal views block arguments

    - by slimcady
    I currently have a view (Drupal 6 using Views2) that properly aggregates a custom content type (videos) and filters them for a page display. When I create a block display, it previews the results in live preview just great, but when i go to the page expecting to see the block it doesn't appear. I'm fairly certain the argument I'm attempting to pass it fails because when I select "Display all results" for "Action to take if argument does not validate:" the block shows up on the page just fine. Any advice definitely appreciated.

    Read the article

  • Multiple Remote call made simultenously

    - by Sudeep Kumar
    I was making multiple remote calls and they are done sequentially and when I am getting a result event back it's triggering calls to all the methods with ResultEvent as an argument . I am supposed to receive the result event only in the method given inthe event listener but it's triggering calls to all the methods with ResultEvent as an argument . Has anyone come across this kind of problem? Is there any workaround for it?

    Read the article

  • Variable number of arguments in VB

    - by Kratz
    How to create a function with variable number of arguments in visual basic? ex. x = Sum(1,2,3) y = Sum(1,2) Function Sum('how to declare argument here') 'Is there any special argument manipulation inside function before it is usable? End Function

    Read the article

  • Writing an ostream filter?

    - by shoosh
    I'd like to write a simple ostream which wraps an argument ostream and changes the stream in some way before passing it on to the argument stream. The transformation is something simple like changing a letter or erasing a word What would a simple class inheriting from ostream look like? What methods should I override?

    Read the article

  • Spanning-tree setup with incompatible switches

    - by wfaulk
    I have a set of eight HP ProCurve 2910al-48G Ethernet switches at my datacenter that are set up in a star topology with no physical loops. I want to partially mesh the switches for redundancy and manage the loops with a spanning-tree protocol. However, our connection to the datacenter is provided by two uplinks, each to a Cisco 3750. The datacenter's switches are handling the redundant connection using PVST spanning-tree, which is a Cisco-proprietary spanning-tree implementation that my HP switches do not support. It appears that my switches are not participating in the datacenter's spanning-tree domain, but are blindly passing the BPDUs between the two switchports on my side, which enables the datacenter's switches to recognize the loop and put one of the uplinks into the Blocking state. This is somewhat supposition, but I can confirm that, while my switches say that both of the uplink ports are forwarding, only one is passing any real quantity of data. (I am assuming that I cannot get the datacenter to move away from PVST. I don't know that I'd want them to make that significant of a change anyway.) The datacenter has also sent me this output from their switches (which I have expurgated of any identifiable info): 3750G-1#sh spanning-tree vlan nnn VLAN0nnn Spanning tree enabled protocol ieee Root ID Priority 10 Address 00d0.0114.xxxx Cost 4 Port 5 (GigabitEthernet1/0/5) Hello Time 2 sec Max Age 20 sec Forward Delay 15 sec Bridge ID Priority 32mmm (priority 32768 sys-id-ext nnn) Address 0018.73d3.yyyy Hello Time 2 sec Max Age 20 sec Forward Delay 15 sec Aging Time 300 sec Interface Role Sts Cost Prio.Nbr Type ------------------- ---- --- --------- -------- -------------------------------- Gi1/0/5 Root FWD 4 128.5 P2p Gi1/0/6 Altn BLK 4 128.6 P2p Gi1/0/8 Altn BLK 4 128.8 P2p and: 3750G-2#sh spanning-tree vlan nnn VLAN0nnn Spanning tree enabled protocol ieee Root ID Priority 10 Address 00d0.0114.xxxx Cost 4 Port 6 (GigabitEthernet1/0/6) Hello Time 2 sec Max Age 20 sec Forward Delay 15 sec Bridge ID Priority 32mmm (priority 32768 sys-id-ext nnn) Address 000f.f71e.zzzz Hello Time 2 sec Max Age 20 sec Forward Delay 15 sec Aging Time 300 sec Interface Role Sts Cost Prio.Nbr Type ------------------- ---- --- --------- -------- -------------------------------- Gi1/0/1 Desg FWD 4 128.1 P2p Gi1/0/5 Altn BLK 4 128.5 P2p Gi1/0/6 Root FWD 4 128.6 P2p Gi1/0/8 Desg FWD 4 128.8 P2p The uplinks to my switches are on Gi1/0/8 on both of their switches. The uplink ports are configured with a single tagged VLAN. I am also using a number of other tagged VLANs in my switch infrastructure. And, to be clear, I am passing the tagged VLAN I'm receiving from the datacenter to other ports on other switches in my infrastructure. My question is: how do I configure my switches so that I can use a spanning tree protocol inside my switch infrastructure without breaking the datacenter's spanning tree that I cannot participate in?

    Read the article

  • where is the error in this C code , and how to get rid of the warnings?

    - by mekasperasky
    #include<stdio.h> #include<string.h> //This program is a sorting application that reads a sequence of numbers from a file and prints them on the screen . The reading from the file here , is a call back function . typedef int (*CompFunc)(const char* , const char* ); typedef int (*ReadCheck)(char nullcheck); char array[100]; //Let this fucntion be done in the library itself . It doesnt care as to where the compare function and how is it implemented . Meaning suppose the function wants to do sort in ascending order or in descending order then the changes have to be done by the client code in the "COMPARE" function who will be implementing the lib code . void ReadFile(FILE *fp,ReadCheck rc) { char a; char d[100]; int count = 0,count1=0; a=fgetc(fp); while(1 != (*rc)(a)) { if(a=='\0') { strcpy(array[count],d); count=count+1; } else { d[count1]=a; count1=count1+1; } } } void Bubblesort(int* array , int size , int elem_size , CompFunc cf) { int i,j; int *temp; for( i=0;i < size ;i++) { for ( j=0;j < size -1 ; j++) { // make the callback to the comparision function if(1 == (*cf)(array+j*elem_size,array+ (j+1)*elem_size)) { //interchanging of elements temp = malloc(sizeof(int *) * elem_size); memcpy(temp , array+j*elem_size,elem_size); memcpy(array+j*elem_size,array+(j+1)*elem_size,elem_size); memcpy(array + (j+1)*elem_size , temp , elem_size); free(temp); } } } } //Let these functions be done at the client side int Compare(const char* el1 , const char* el2) { int element1 = *(int*)el1; int element2 = *(int*)el2; if(element1 < element2 ) return -1; if(element1 > element2) return 1 ; return 0; } int ReadChecked(char nullcheck) { if (nullcheck=='\n') return 1; else return 0; } int main() { FILE fp1; int k; fp1=fopen("readdata.txt","r"); Readfile(fp1,&ReadChecked); Bubblesort((char*)array,5,sizeof(array[0]),&Compare); printf("after sorting \n"); for (k=0;k<5;k++) printf("%d",array[k]); return 0; } The error i get is fsc1.c: In function ‘ReadFile’: fsc1.c:19: warning: passing argument 1 of ‘strcpy’ makes pointer from integer without a cast fsc1.c: In function ‘Bubblesort’: fsc1.c:40: warning: passing argument 1 of ‘cf’ from incompatible pointer type fsc1.c:40: warning: passing argument 2 of ‘cf’ from incompatible pointer type fsc1.c:43: warning: incompatible implicit declaration of built-in function ‘malloc’ fsc1.c:47: warning: incompatible implicit declaration of built-in function ‘free’ fsc1.c: In function ‘main’: fsc1.c:80: error: incompatible types in assignment fsc1.c:82: warning: passing argument 1 of ‘Bubblesort’ from incompatible pointer type

    Read the article

  • Oracle University Begins Beta Testing For New "Oracle Application Express Developer Certified Expert

    - by Paul Sorensen
    Oracle University has begun beta testing for the new Oracle Application Express Developer Certified Expert certification, which requires passing one exam - "Oracle Application Express 3.2: Developing Web Applications" exam (#1Z1-450).In this video, Marcie Young of Oracle Server Technologies takes you on a quick preview of what is on the exam, how to prepare, and what to expect: The "Oracle Application Express: Developing Web Applications" training course teaches many of of the key concepts that are tested in the exam. This course is not a requirement to take the exam, however it is highly recommended.Additionally, Marcie refers to several helpful resources that are highly recommended while preparing, including the Oracle Application Express hosted instance at apex.oracle.com and Oracle Application Express product page on OTN.You can take the "Oracle Application Express 3.2: Developing Web Applications" exam now for only $50 USD while it is in beta. Beta exams are an excellent way to directly provide your input into the final version of the certification exam as well as be one of the very first certified in the track. Furthermore - passing the beta counts for full final exam credit. Note that beta testing is offered for a limited time only.Register now at pearsonvue.com/oracle to take the exam at a Pearson VUE testing center nearest you.QUICK LINKSRegister For Exam: Pearson VUE About Certification Track: Oracle Application Express Developer Certified ExpertAbout Certification Exam: Oracle Application Express 3.2: Developing Web Applications (1Z1-450)Introductory Training (Recommended): "Oracle Application Express: Developing Web Applications"Advanced Training (Suggested): "Oracle Application Express: Advanced Workshop"Oracle Application Express Hosted Instance: apex.oracle.comOracle Application Express Product Page: on OTNLearn More: Oracle Certification Beta Exams

    Read the article

  • Creating the concept of Time

    - by Jamie Dixon
    So I've reached the point in my exploration of gaming where I'd like to impliment the concept of time into my little demo I've been building. What are some common methodologies for creating the concept of time passing within a game? My thoughts so far: My game loop tendes to spend a fair bit of time sitting around waiting or user input so any time system will likely need to be run in a seperate thread. What I've currently done is create a BackgroundWorker passing in a method that contains a loop triggering every second. This is working fine and I can output information to the console from here etc. Inside this loop I have a DateTime object that is incrimented by 1 minute for every realtime second. (the game begins in the year 01/01/01) Is this a standard way of acheiving this result or are there more tried and tested methods? I'm also curious about how to go about performing time based actions (reducing player energy, moving entities around the game board, life/death etc). Thanks for any pointers or advice. I've searched around however I'm not familiar enough with the terms and so my searches are yeilding little result on this one.

    Read the article

  • How should data be passed between client-side Javascript and C# code behind an ASP.NET app?

    - by ctck
    I'm looking for the most efficient / standard way of passing data between client-side Javascript code and C# code behind an ASP.NET application. I've been using the following methods to achieve this but they all feel a bit of a fudge. To pass data from Javascript to the C# code is by setting hidden ASP variables and triggering a postback: <asp:HiddenField ID="RandomList" runat="server" /> function SetDataField(data) { document.getElementById('<%=RandomList.ClientID%>').value = data; } Then in the C# code I collect the list: protected void GetData(object sender, EventArgs e) { var _list = RandomList.value; } Going back the other way I often use either ScriptManager to register a function and pass it data during Page_Load: ScriptManager.RegisterStartupScript(this.GetType(), "Set","get("Test();",true); or I add attributes to controls before a post back or during the initialization or pre-rendering stages: Btn.Attributes.Add("onclick", "DisplayMessage("Hello");"); These methods have served me well and do the job, but they just dont feel complete. Is there a more standard way of passing data between client side Javascript and C# backend code? Ive seen some posts like this one that describe HtmlElement class; is this something I should look into?

    Read the article

  • Using ASP.NET C# and Javascript

    - by ctck
    I'm looking for the most efficient / standardized way of passing data between client javascript code and C# code behind in an ASP.NET application. Currently ive been using the following methods to achieve this but they all feel a bit like a fudge. The way i pass data from javascript to the C# code behind is by setting hidden asp variables and triggering a postback <asp:HiddenField ID="RandomList" runat="server" /> function SetDataField(data) { document.getElementById('<%=RandomList.ClientID%>').value = data; } Then in C# code i collect the list protected void GetData(object sender, EventArgs e) { var _list = RandomList.value; } Going back the other way i often use either scriptmanager to register a function and pass it data during Page_Load: ScriptManager.RegisterStartupScript(this.GetType(), "Set","get("Test();",true); or i add attributes to controls before a post back or during Initialization / pre rendering stages: Btn.Attributes.Add("onclick", "DisplayMessage("Hello");"); These methods have served me well and do the job. However they just dont feel complete. Is there a more standardized way of passing data between client side markup / javascript and backend code. Ive seen some posts like this one: Injecting JavaScrip : StackOverflow that describe HtmlElement class. Is this something is should look into? Thanks everyone for your time.

    Read the article

  • how to find and filter blobs from segment image using python?

    - by Python Team
    Am trying to detect number plate from an image.I have converted an image to grayscale and segment image. Now i have to find and filter blobs from an image and to detect number plate from an image. I will explain what i did.. I jus read segment image license_plate = cv2.imread('license1_segmented.png',cv2.CV_LOAD_IMAGE_COLOR) license_plate_size = (license_plate.shape[1], license_plate.shape[0]) mask = cv2.cv.CreateImage (license_plate_size, 8, 1) cv2.cv.Set(mask, 1) thresh_image_ipl = cv2.cv.CreateImage(license_plate_size, cv2.cv.IPL_DEPTH_8U, 1) cv2.cv.SetData(thresh_image_ipl,thresh_image.tostring(),thresh_image.dtype.itemsize * 1 * thresh_image.shape[1]) min_blob_size = 100 # Blob must be 30 px by 30 px max_blob_size = 10000 threshold = 100 **myblobs = CBlobResult(thresh_image_ipl,mask, threshold, True)** myblobs.filter_blobs(min_blob_size, max_blob_size) blob_count = myblobs.GetNumBlobs() trying to find and filter blobs from an image.But am getting error while passing the parameters to CBlobResult which i highlighted above code.I mentioned the error below what i get while passing. Traceback (most recent call last): File "rectdetect1.py", line 110, in <module> myblobs = CBlobResult(thresh_image_ipl,image_area, threshold, True) File "/home/oomsys/pyblobs-read-only/blobs/BlobResult.py", line 92, in __init__ this = _BlobResult.new_CBlobResult(*args) NotImplementedError: Wrong number or type of arguments for overloaded function 'new_CBlobResult'. Possible C/C++ prototypes are: CBlobResult::CBlobResult() CBlobResult::CBlobResult(IplImage *,IplImage *,int,bool) CBlobResult::CBlobResult(CBlobResult const &) Anyone help me to find out the erros and to solve this and all... Thanks in advance...

    Read the article

  • Organizing MVC entities communication

    - by Stefano Borini
    I have the following situation. Imagine you have a MainWindow object who is layouting two different widgets, ListWidget and DisplayWidget. ListWidget is populated with data from the disk. DisplayWidget shows the details of the selection the user performs in the ListWidget. I am planning to do the following: in MainWindow I have the following objects: ListWidget ListView ListModel ListController ListView is initialized passing the ListWidget. ListViewController is initialized passing the View and the Model. Same happens for the DisplayWidget: DisplayWidget DisplayView DisplayModel DisplayController I initialize the DisplayView with the widget, and initialize the Model with the ListController. I do this because the DisplayModel wraps the ListController to get the information about the current selection, and the data to be displayed in the DisplayView. I am very rusty with MVC, being out of UI programming since a while. Is this the expected interaction layout for having different MVC triplets communicate ? In other words, MVC focus on the interaction of three objects. How do you put this interaction as a whole into a larger context of communication with other similar entities, MVC or not ?

    Read the article

  • How do references work in R?

    - by djechlin
    I'm finding R confusing because it has such a different notion of reference than I am used to in languages like C, Java, Javascript... Ruby, Python, C++, well, pretty much any language I have ever programmed in ever. So one thing I've noticed is variable names are not irrelevant when passing them to something else. The reference can be part of the data. e.g. per this tutorial a <- factor(c("A","A","B","A","B","B","C","A","C")) results <- table(a) Leads to $a showing up as an attribute as $dimnames$a. We've also witnessed that calling a function like a <- foo(alpha=1, beta=2) can create attributes in a of names alpha and beta, or it can assign or otherwise compute on 1 and 2 to properties already existing. (Not that there's a computer science distinction here - it just doesn't really happen in something like Javascript, unless you want to emulate it by passing in the object and use key=value there.) Functions like names(...) return lvalues that will affect the input of them. And the one that most got me is this. x <- c(3, 5, 1, 10, 12, 6) y = x[x <= 5] x[y] <- 0 is different from x <- c(3, 5, 1, 10, 12, 6) x[x <= 5] <- 0 Color me confused. Is there a consistent theory for what's going on here?

    Read the article

  • Design in "mixed" languages: object oriented design or functional programming?

    - by dema80
    In the past few years, the languages I like to use are becoming more and more "functional". I now use languages that are a sort of "hybrid": C#, F#, Scala. I like to design my application using classes that correspond to the domain objects, and use functional features where this makes coding easier, more coincise and safer (especially when operating on collections or when passing functions). However the two worlds "clash" when coming to design patterns. The specific example I faced recently is the Observer pattern. I want a producer to notify some other code (the "consumers/observers", say a DB storage, a logger, and so on) when an item is created or changed. I initially did it "functionally" like this: producer.foo(item => { updateItemInDb(item); insertLog(item) }) // calls the function passed as argument as an item is processed But I'm now wondering if I should use a more "OO" approach: interface IItemObserver { onNotify(Item) } class DBObserver : IItemObserver ... class LogObserver: IItemObserver ... producer.addObserver(new DBObserver) producer.addObserver(new LogObserver) producer.foo() //calls observer in a loop Which are the pro and con of the two approach? I once heard a FP guru say that design patterns are there only because of the limitations of the language, and that's why there are so few in functional languages. Maybe this could be an example of it? EDIT: In my particular scenario I don't need it, but.. how would you implement removal and addition of "observers" in the functional way? (I.e. how would you implement all the functionalities in the pattern?) Just passing a new function, for example?

    Read the article

  • Is IDirectInput8::FindDevice totally broken on Windows 7?

    - by Noora
    I'm developing on Windows 7, and using DirectInput8 for my input needs. I'm tracking gamepad additions and removals (that is, GUID_DEVINTERFACE_HID devices) using the DBT_DEVICEARRIVAL and DBT_DEVICEREMOVECOMPLETE messages, which works fine. However, what I've come to find out is that no matter what I do, passing the received values from DBT_DEVICEARRIVAL to IDirectInput8's FindDevice method, it will always fail to identify the device, returning DIERR_DEVICENOTREG. DirectInput still clearly knows about the device, because I can enumerate and create it just fine. I've tried with three different gamepads, and the error persists, so it's not about that either. I also tried passing some alternative interface GUIDs for the RegisterDeviceNotification call, didn't help. So, has anyone else faced the same problem, and have you found a usable workaround? I'm afraid I'll soon have to stoop down to re-enumerating all devices when something is added or removed, but I'll first give this question one last shot here. EDIT: For the record, I've also tried pretty much every single HID API & SetupAPI function for alternative ways of figuring out the needed GUIDs, with zero success. So if you're facing the same problem as me, don't bother with that route. I'm pretty sure those GUIDs are made up by DirectInput itself somehow. Short of reverse engineering dinput8.dll, I'm truly out of ideas now.

    Read the article

  • How should I group these variables?

    - by stariz77
    I have a shape that will be defined by: char s_type; char color; double height; double width; These variables are scanned in from a request string sent to my server and passed into my printing function, which then prints out the shape. Currently they are just local variables sitting in my main(); however, I was wondering if there would be any advantage in creating a struct containing these variables, and then passing the struct to my printing function? or how else might I improve my program's structure/style, would passing a struct by reference have any kind of performance benefit if there were many requests and therefore many printing function calls? printer(char st, char cr, double ht, double wd); int main() { // Other main functionality. char s_type; char color; double height; double width; sscanf (serv_req, "GET /%c/%c/%lf/%lf", &s_type, &color, &height, &width); printer(s_type, color, height, width); // Other main functionality. return 0; } It seemed "neater" if I had a struct or something that didn't leave me with declarations in the middle of everything else going on in main. I'm interested in structure/style as well as performance. EDIT: didn't mean to put printer declaration inside main.

    Read the article

  • Architecture Question

    - by katie77
    I am writing a rules/eligibility Module. I have 2 sets of data, one is the customer data and the other is the customer products data. Customer data to Customer products data is one to many. Now I have to go through a set of Eligibility rules for each of this Customer product data. For each customer products data, I can say the customer is eligible for that product or decline the eligibility and should move on to the next product record. So in all the rules, I need to have access to customer and customer product data(the particular record that the rules are being executed against). Since all the rules can either approve a product or decline a product, I created an interface with those 2 methods and is implementing the this interface for all the rules. I am passing the Customer data and one product data for all the rules (because rules should be executed on each row of customer product data). An Ideal situation would be having the customer and customer product data available for the rule instead of passing them to each rule. What is the best way of doing this in-terms of architecture?

    Read the article

  • Get Func-y

    - by PhubarBaz
    I was working on a Windows form app and needed a way to call out to a service without blocking the UI. There are a lot of ways to do this but I came up with one that I thought was pretty simple. It utilizes the System.Func<> generic class, which is basically a way to create delegates using generics. It's a lot more compact and simpler than creating delegates for each method you want to call asynchronously. I wanted to get it down to one line of code, but it was a lot simpler to use three lines.In this case I have a MyServiceCall method that takes an integer parameter and returns a ServiceCallResult object.public ServiceCallResult MyServiceCall(int param1)...You start by getting a Func<> object for the method you want to call, in this case MyServiceCall. Then you call BeginInvoke() on the Func passing in the parameter. The two nulls are parameters BeginInvoke expects but can be ignored here. BeginInvoke returns an IAsyncResult object that acts like a handle to the method call. Finally to get the value you call EndInvoke on the Func passing in the IAsyncResult object you got back from BeginInvoke.Func<int, ServiceCallResult> f = MyServiceCall;IAsyncResult async = f.BeginInvoke(23, null, null);ServiceCallResult result = f.EndInvoke(async);Doing it this way fires off a new thread that calls the MyServiceCall() method. This leaves the main application thread free to update the UI while the method call is running so it doesn't become unresponsive.

    Read the article

  • Mulit-tenant ASP.NET MVC – Controllers

    - by zowens
    Part I – Introduction Part II – Foundation   The time has come to talk about controllers in a multi-tenant ASP.NET MVC architecture. This is actually the most critical design decision you will make when dealing with multi-tenancy with MVC. In my design, I took into account the design goals I mentioned in the introduction about inversion of control and what a tenant is to my design. Be aware that this is only one way to achieve multi-tenant controllers.   The Premise MvcEx (which is a sample written by Rob Ashton) utilizes dynamic controllers. Essentially a controller is “dynamic” in that multiple action results can be placed in different “controllers” with the same name. This approach is a bit too complicated for my design. I wanted to stick with plain old inheritance when dealing with controllers. The basic premise of my controller design is that my main host defines a set of universal controllers. It is the responsibility of the tenant to decide if the tenant would like to utilize these core controllers. This can be done either by straight usage of the controller or inheritance for extension of the functionality defined by the controller. The controller is resolved by a StructureMap container that is attached to the tenant, as discussed in Part II.   Controller Resolution I have been thinking about two different ways to resolve controllers with StructureMap. One way is to use named instances. This is a really easy way to simply pull the controller right out of the container without a lot of fuss. I ultimately chose not to use this approach. The reason for this decision is to ensure that the controllers are named properly. If a controller has a different named instance that the controller type, then the resolution has a significant disconnect and there are no guarantees. The final approach, the one utilized by the sample, is to simply pull all controller types and correlate the type with a controller name. This has a bit of a application start performance disadvantage, but is significantly more approachable for maintainability. For example, if I wanted to go back and add a “ControllerName” attribute, I would just have to change the ControllerFactory to suit my needs.   The Code The container factory that I have built is actually pretty simple. That’s really all we need. The most significant method is the GetControllersFor method. This method makes the model from the Container and determines all the concrete types for IController.  The thing you might notice is that this doesn’t depend on tenants, but rather containers. You could easily use this controller factory for an application that doesn’t utilize multi-tenancy. public class ContainerControllerFactory : IControllerFactory { private readonly ThreadSafeDictionary<IContainer, IDictionary<string, Type>> typeCache; public ContainerControllerFactory(IContainerResolver resolver) { Ensure.Argument.NotNull(resolver, "resolver"); this.ContainerResolver = resolver; this.typeCache = new ThreadSafeDictionary<IContainer, IDictionary<string, Type>>(); } public IContainerResolver ContainerResolver { get; private set; } public virtual IController CreateController(RequestContext requestContext, string controllerName) { var controllerType = this.GetControllerType(requestContext, controllerName); if (controllerType == null) return null; var controller = this.ContainerResolver.Resolve(requestContext).GetInstance(controllerType) as IController; // ensure the action invoker is a ContainerControllerActionInvoker if (controller != null && controller is Controller && !((controller as Controller).ActionInvoker is ContainerControllerActionInvoker)) (controller as Controller).ActionInvoker = new ContainerControllerActionInvoker(this.ContainerResolver); return controller; } public void ReleaseController(IController controller) { if (controller != null && controller is IDisposable) ((IDisposable)controller).Dispose(); } internal static IEnumerable<Type> GetControllersFor(IContainer container) { Ensure.Argument.NotNull(container); return container.Model.InstancesOf<IController>().Select(x => x.ConcreteType).Distinct(); } protected virtual Type GetControllerType(RequestContext requestContext, string controllerName) { Ensure.Argument.NotNull(requestContext, "requestContext"); Ensure.Argument.NotNullOrEmpty(controllerName, "controllerName"); var container = this.ContainerResolver.Resolve(requestContext); var typeDictionary = this.typeCache.GetOrAdd(container, () => GetControllersFor(container).ToDictionary(x => ControllerFriendlyName(x.Name))); Type found = null; if (typeDictionary.TryGetValue(ControllerFriendlyName(controllerName), out found)) return found; return null; } private static string ControllerFriendlyName(string value) { return (value ?? string.Empty).ToLowerInvariant().Without("controller"); } } One thing to note about my implementation is that we do not use namespaces that can be utilized in the default ASP.NET MVC controller factory. This is something that I don’t use and have no desire to implement and test. The reason I am not using namespaces in this situation is because each tenant has its own namespaces and the routing would not make sense in this case.   Because we are using IoC, dependencies are automatically injected into the constructor. For example, a tenant container could implement it’s own IRepository and a controller could be defined in the “main” project. The IRepository from the tenant would be injected into the main project’s controller. This is quite a useful feature.   Again, the source code is on GitHub here.   Up Next Up next is the view resolution. This is a complicated issue, so be prepared. I hope that you have found this series useful. If you have any questions about my implementation so far, send me an email or DM me on Twitter. I have had a lot of great conversations about multi-tenancy so far and I greatly appreciate the feedback!

    Read the article

  • Super constructor must be a first statement in Java constructor [closed]

    - by Val
    I know the answer: "we need rules to prevent shooting into your own foot". Ok, I make millions of programming mistakes every day. To be prevented, we need one simple rule: prohibit all JLS and do not use Java. If we explain everything by "not shooting your foot", this is reasonable. But there is not much reason is such reason. When I programmed in Delphy, I always wanted the compiler to check me if I read uninitializable. I have discovered myself that is is stupid to read uncertain variable because it leads unpredictable result and is errorenous obviously. By just looking at the code I could see if there is an error. I wished if compiler could do this job. It is also a reliable signal of programming error if function does not return any value. But I never wanted it do enforce me the super constructor first. Why? You say that constructors just initialize fields. Super fields are derived; extra fields are introduced. From the goal point of view, it does not matter in which order you initialize the variables. I have studied parallel architectures and can say that all the fields can even be assigned in parallel... What? Do you want to use the unitialized fields? Stupid people always want to take away our freedoms and break the JLS rules the God gives to us! Please, policeman, take away that person! Where do I say so? I'm just saying only about initializing/assigning, not using the fields. Java compiler already defends me from the mistake of accessing notinitialized. Some cases sneak but this example shows how this stupid rule does not save us from the read-accessing incompletely initialized in construction: public class BadSuper { String field; public String toString() { return "field = " + field; } public BadSuper(String val) { field = val; // yea, superfirst does not protect from accessing // inconstructed subclass fields. Subclass constr // must be called before super()! System.err.println(this); } } public class BadPost extends BadSuper { Object o; public BadPost(Object o) { super("str"); this. o = o; } public String toString() { // superconstructor will boom here, because o is not initialized! return super.toString() + ", obj = " + o.toString(); } public static void main(String[] args) { new BadSuper("test 1"); new BadPost(new Object()); } } It shows that actually, subfields have to be inilialized before the supreclass! Meantime, java requirement "saves" us from writing specializing the class by specializing what the super constructor argument is, public class MyKryo extends Kryo { class MyClassResolver extends DefaultClassResolver { public Registration register(Registration registration) { System.out.println(MyKryo.this.getDepth()); return super.register(registration); } } MyKryo() { // cannot instantiate MyClassResolver in super super(new MyClassResolver(), new MapReferenceResolver()); } } Try to make it compilable. It is always pain. Especially, when you cannot assign the argument later. Initialization order is not important for initialization in general. I could understand that you should not use super methods before initializing super. But, the requirement for super to be the first statement is different. It only saves you from the code that does useful things simply. I do not see how this adds safety. Actually, safety is degraded because we need to use ugly workarounds. Doing post-initialization, outside the constructors also degrades safety (otherwise, why do we need constructors?) and defeats the java final safety reenforcer. To conclude Reading not initialized is a bug. Initialization order is not important from the computer science point of view. Doing initalization or computations in different order is not a bug. Reenforcing read-access to not initialized is good but compilers fail to detect all such bugs Making super the first does not solve the problem as it "Prevents" shooting into right things but not into the foot It requires to invent workarounds, where, because of complexity of analysis, it is easier to shoot into the foot doing post-initialization outside the constructors degrades safety (otherwise, why do we need constructors?) and that degrade safety by defeating final access modifier When there was java forum alive, java bigots attecked me for these thoughts. Particularly, they dislaked that fields can be initialized in parallel, saying that natural development ensures correctness. When I replied that you could use an advanced engineering to create a human right away, without "developing" any ape first, and it still be an ape, they stopped to listen me. Cos modern technology cannot afford it. Ok, Take something simpler. How do you produce a Renault? Should you construct an Automobile first? No, you start by producing a Renault and, once completed, you'll see that this is an automobile. So, the requirement to produce fields in "natural order" is unnatural. In case of alarmclock or armchair, which are still chair and clock, you may need first develop the base (clock and chair) and then add extra. So, I can have examples where superfields must be initialized first and, oppositely, when they need to be initialized later. The order does not exist in advance. So, the compiler cannot be aware of the proper order. Only programmer/constructor knows is. Compiler should not take more responsibility and enforce the wrong order onto programmer. Saying that I cannot initialize some fields because I did not ininialized the others is like "you cannot initialize the thing because it is not initialized". This is a kind of argument we have. So, to conclude once more, the feature that "protects" me from doing things in simple and right way in order to enforce something that does not add noticeably to the bug elimination at that is a strongly negative thing and it pisses me off, altogether with the all the arguments to support it I've seen so far. It is "a conceptual question about software development" Should there be the requirement to call super() first or not. I do not know. If you do or have an idea, you have place to answer. I think that I have provided enough arguments against this feature. Lets appreciate the ones who benefit form it. Let it just be something more than simple abstract and stupid "write your own language" or "protection" kind of argument. Why do we need it in the language that I am going to develop?

    Read the article

  • Do we still have a case against the goto statement? [closed]

    - by FredOverflow
    Possible Duplicate: Is it ever worthwhile using goto? In a recent article, Andrew Koenig writes: When asked why goto statements are harmful, most programmers will say something like "because they make programs hard to understand." Press harder, and you may well hear something like "I don't really know, but that's what I was taught." For that reason, I'd like to summarize Dijkstra's arguments. He then shows two program fragments, one without a goto and and one with a goto: if (n < 0) n = 0; Assuming that n is a variable of a built-in numeric type, we know that after this code, n is nonnegative. Suppose we rewrite this fragment: if (n >= 0) goto nonneg; n = 0; nonneg: ; In theory, this rewrite should have the same effect as the original. However, rewriting has changed something important: It has opened the possibility of transferring control to nonneg from anywhere else in the program. I emphasized the part that I don't agree with. Modern languages like C++ do not allow goto to transfer control arbitrarily. Here are two examples: You cannot jump to a label that is defined in a different function. You cannot jump over a variable initialization. Now consider composing your code of tiny functions that adhere to the single responsibility principle: int clamp_to_zero(int n) { if (n >= 0) goto n_is_not_negative: n = 0; n_is_not_negative: return n; } The classic argument against the goto statement is that control could have transferred from anywhere inside your program to the label n_is_not_negative, but this simply is not (and was never) true in C++. If you try it, you will get a compiler error, because labels are scoped. The rest of the program doesn't even see the name n_is_not_negative, so it's just not possible to jump there. This is a static guarantee! Now, I'm not saying that this version is better then the one without the goto, but to make the latter as expressive as the first one, we would at least have to insert a comment, or even better yet, an assertion: int clamp_to_zero(int n) { if (n < 0) n = 0; // n is not negative at this point assert(n >= 0); return n; } Note that you basically get the assertion for free in the goto version, because the condition n >= 0 is already written in line 1, and n = 0; satisfies the condition trivially. But that's just a random observation. It seems to me that "don't use gotos!" is one of those dogmas like "don't use multiple returns!" that stem from a time where the real problem were functions of hundreds or even thousand of lines of code. So, do we still have a case against the goto statement, other than that it is not particularly useful? I haven't written a goto in at least a decade, but it's not like I was running away in terror whenever I encountered one. 1 Ideally, I would like to see a strong and valid argument against gotos that still holds when you adhere to established programming principles for clean code like the SRP. "You can jump anywhere" is not (and has never been) a valid argument in C++, and somehow I don't like teaching stuff that is not true. 1: Also, I have never been able to resurrect even a single velociraptor, no matter how many gotos I tried :(

    Read the article

< Previous Page | 68 69 70 71 72 73 74 75 76 77 78 79  | Next Page >