Thursday, March 31, 2011

Using ninject/autofac for a given scenario

I have some providers, say -

<Providers>
    <Provider Type="Providers.IM"  Name="Im"/>
    <Provider Type="Providers.Web" Name="Web"/>
    ...
</Provider>

Each of these providers can give me a session :

<Sessions>
    <Session Name="GoogleIM" Provider="Im"  URL="..." />
    <Session Name="YahooIM"  Provider="Im"  URL="..." />
    <Session Name="YahooWeb" Provider="Web" URL="..." />
    ...
</Session>

Currently, I instantiate "named" sessions by looking at the provider, instantiating the type, and injecting the URL (manually).

I could use a session factory, which would probably have to understand the url and return a proper session.

Is there a way to handle this more elegantly/simply with ninject/autofac?

From stackoverflow

Algorithm to find an optimum number of rummy-style sets?

I'm developing a card game that uses rummy-style sets of three cards. From a random selection of cards, I need the algorithm to pick out which cards would get me the highest number of sets.

By "rummy-style sets of three" I mean:

  • All three cards have the same value, like three Jacks. OR
  • All three cards are of the same suit and sequential in order, like a 7, 8, 9 all of diamonds.

For example, given the cards: 6D, 7D, 7C, 7H, 8D, 8C, 9C, 10H
I could form the set: {7D, 7C, 7H}, but that would be the only set I would get out of it, and it would not be optimum.
The optimum sets in this case are: { {6D, 7D, 8D}, {7C, 8C, 9C} }

I have tried brute force (permute through all the given cards, see what matches in order in that permutation), but that proved too slow. The problem feels like it has similarities to other solved problems, and that's why I ask here.

From stackoverflow
  • My intuitive approach would be to start by discovering all the possible sets, by examining each card and searching for what can make a set with that card (i.e. consecutive things and same-value-things.) Once you've got all the possible sets, which should be a pretty quick operation unless you have a really large amount of cards, then you can make a map of which sets preclude the inclusion of other sets (they use the same cards.) At that point, even permuting all the legal combinations of sets (for each of the sets that i don't have; try adding it if i can legally use it in my current set of sets; repeat) should be fast enough to serve.

  • Hi,

    if you have N cards (N = 8), you can enumerate through all the distinct triples in the set in time N * (N - 1) * (N - 2) (with N = 8 you get 336). This is pretty fast. Check which ones of the triples are "rummy-style" sets, and store them in a table as integer triples (the integer denote the sequence numbers of the cards).

    That's the first step. The second step is now to do combinatorial optimization and calculate the optimal choice. The simple way to do this is to use backtracking search. You run an index ('i') over the set of triples you have found. First you try to include the 'i'th triple in the solution, and then continue from index i+1 recursively; then you backtrack and decide that the 'i'th triple is not in the solution, and continue from i+1 recursively. There are many optimizations to this, but for the small sets it's going to work pretty fine.

    Here how it works with your example:

    Cards: 6D, 7D, 7C, 7H, 8D, 8C, 9C, 10H

    Let's enumerate all the possible triples:

    Cards        Index triple
    6D 7D 8D     <0, 1, 4>
    7D 7C 7H     <1, 2, 3>
    7C 8C 9C     <2, 5, 6>
    

    The full backtracking search goes like this:

    Decide on <0, 1, 4>:
      <0, 1, 4> INCLUDED:
         <1, 2, 3> CLASHES with <0, 1, 4>
         Decide on <2, 5, 6>:
           <2, 5, 6> INCLUDED:
              Solution with 2 sets (* BEST SOLUTION)
           <2, 5, 6> EXCLUDED:
              Solution with 1 sets
      <0, 1, 4> EXCLUDED:
         Decide on <1, 2, 3>:
            <1, 2, 3> INCLUDED:
               <2, 5, 6> CLASHES with <1, 2, 3>
               Solution with 1 sets
            <1, 2, 3> EXCLUDED:
               Decide on <2, 5, 6>:
                 <2, 5, 6> INCLUDED:
                    Solution with 1 set
                 <2, 5, 6> EXCLUDED:
                    Solution with 0 sets
    

    Then you pick the solution with most sets (marked with asterisk).

    This is pretty simple to implement. Try it!

    PeteVasi : Thanks, I'll give it a shot. :)
  • To find all possible valid triples, you could do 2 steps:

    1. sort cards first ascending by number, then by suit, as you did
       in your example and look what triples you can get
    2. now sort a second time, but first by suit and then by number 
       and look what triples you can get
    
    In step 1) you can just look sequencially for 3 same numbers => O(n)
    In step 2) the same, but now looking for 3 sequential numbers of the same suit. => O(n)
    

    Merging the two results gives you all possible triples. If I'm not wrong, at this point you reached the NP-hard problem of maximum set packing, as you want to get the maximum subset of non-overlapping triples. As the number of cards is limited and not so high you could use for example the backtracking algorithm that antti.huima mentioned for solving this problem.

    PeteVasi : Looks like a good way to pull out all of the sets, I'll try it out, thanks.

Display logging output in Cocoa

What is the best way to display constantly updated logging output using Cocoa Components? The output is line-based and generated by the application. Appending lines should be fast, and the view should automatically scroll to the bottom. All in all, it should work and look like basic standard out in a terminal.

My code is written in Python, using the PyObjC bridge. I'm looking for approaches/examples I can adapt, Objective-C code is welcome.

From stackoverflow
  • It seems that there are two options: (1) use an NSTableView and (2) use an NSTextView. Console.app appears to use an NSTableView but an NSTextView is probably less code.

    For (1), I would write an NSTableDataSource that returns the appropriate line (either from memory or from disk) for tableView_objectValueForTableColumn_rowIndex_ and the total number of log lines for numberOfRowsInTableView_. Set this data source as the dataSource for an NSTableView. You may need to call tableView.reloadData() to redisplay the data when a new log line comes in. Assuming the table view is embedded in an NSScrollView (the default if you create the table view in Interface Builder), you can scroll to the bottom with this method from the Apple Scroll View Programming Guide (easily translated to Python)

    - (void)scrollToBottom:sender;
    {
        NSPoint newScrollOrigin;
    
        // assume that the scrollview is an existing variable
        if ([[scrollview documentView] isFlipped]) {
            newScrollOrigin=NSMakePoint(0.0,NSMaxY([[scrollview documentView] frame])
                                           -NSHeight([[scrollview contentView] bounds]));
        } else {
            newScrollOrigin=NSMakePoint(0.0,0.0);
        }
    
        [[scrollview documentView] scrollPoint:newScrollOrigin];
    
    }
    

    Obviously, this code assumes that you've got an IBOutlet to the scroll view.

    For (2), you can add a line to the end of the text view with textView.textStorage().appendString_(new_log + '\n') (assuming there isn't already a newline on the end). You can force the enclosing scroll view to scroll to the end (indirectoy) by calling textView.setSelectedRange_(NSMakeRange(textView.textStorage().length(),0))

What are some of the strategy to handle unhandled exception in asp.net mvc applications?

I would like to know some of the strategy/practice you deal with to handle unhandled exceptions in ASP.NET MVC.

In short I want to avoid the yellow screen whenever any error happens and show a error consistent error message to the visitor.

I mean do you write a controller for this which shows the appropriate error page or you go some other way like writing an httpmodule and trapping the error at a global level.

Any inputs in this direction is appreciated.

From stackoverflow
  • Try the HandleError attribute.

  • Don't use the exception handling article that you linked to. It's an old article where they didn't have the HandleError attribute added in the framework. Use the HandleError attribute. It was added in preview 4.

    rajesh pillai : I'll check this. Thanks for the input.
  • Using the HandleError attribute is the way to go. Here is a small sample which I use to handle Ajax calls from JQuery, ExtJs, and others.

    On your controller

    public class DataController : Controller
    {    
        [HandleError(ExceptionType = typeof(ArgumentException), View = "ErrorAjax")]
        public void Foo(string x, string y)
        {    
            if (String.IsNullorEmpty(x))
                throw new ArgumentException("String cannot be empty!");
    
                // Call your layers or whatever here
                AnotherCall();
        }
    }
    

    Then on your view (ErrorAjax). Notice it's strongly typed (HandleErrorInfo)

    <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<HandleErrorInfo>" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Sorry Dude!</title>
    </head>
    <body>
        <div>
            <!-- be creative here-->
            Sorry, an error occurred while processing your request.
            Action = <%= ViewData.Model.ActionName %>
            Controller = <%= ViewData.Model.ControllerName %>
            Message = <%= ViewData.Model.Exception.Message %>
    
        </div>
    </body>
    </html>
    

    A couple of gotchas

    1. Check your web.config and make sure customErrors mode="On"
    2. For starters, create the View under the Shared folder
    Simon_Weaver : 3. also make sure your error page doesn't return any errors. For one must use HandlerErrorInfo as its model - as shown above, but there are of course other possible sources for errors.

In Javascript, how can i perform a global replace on string with a variable inside '/' and '/g'?

Hi to all.

I want to perform a global replace of string using String.replace in Javascript.

In the documentation i read that i can do this with /g, i.e. for example;

var mystring = mystring.replace(/test/g, mystring);

and this will replace all occurrences inside mystring. No quotes for the expression.

But if i have a variable to find, how can i do this without quotes??

I've tried something like this:

var stringToFind = "test";

//first try

mystring = mystring.replace('/' + stringToFind + '/g', mystring);

//second try, not much sense at all

mystring = mystring.replace(/stringToFind/g, mystring);

but they don't work. Any ideas?

From stackoverflow
  • var mystring = "hello world test world";
    var find = "world";
    var regex = new RegExp(find, "g");
    alert(mystring.replace(regex, "yay")); // alerts "hello yay test yay"
    
    Ropstah : This one helped me!
    KClough : It also helped me!
    Nicky Hajal : Same here, thanks!
  • Try:

    var stringToFind = "test";
    mystring = mystring.replace(new RegExp(stringToFind, "g"), mystring);
    
    KooiInc : I suppose the last' mystring' in the replace is not what you meant?
  • Thats a regular expression, not a string. Use the constructor for a RegExp object to dynamically create a regex.

    var r = new RegExp(stringToFind, 'g');
    mystring.replace(r, 'some replacement text');
    
  • If you want variables interpolated, you need to use the RegExp object

    https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Regular_Expressions

    Example:

    var str = "This is my name";
    var replace = "i";
    var re = new RegExp(replace, 'g')    
    
    str = str.replace(re, 'p');
    alert(str);
    
  • For regex, new RegExp(stringtofind, 'g');. BUT. If ‘find’ contains characters that are special in regex, they will have their regexy meaning. So if you tried to replace the '.' in 'abc.def' with 'x', you'd get 'xxxxxxx' — whoops.

    If all you want is a simple string replacement, there is no need for regular expressions! Here is the plain string replace idiom:

    mystring= mystring.split(stringtofind).join(replacementstring);
    
    Thomas : +1 always good to see people thinking beyond the literal answer to the question.
  • Can you use prototype.js? If so you could use String.gsub, like

    var myStr = "a day in a life of a thing";
     var replace = "a";
     var resultString = myStr.gsub(replace, "g");
     // resultString will be "g day in g life of g thing"
    

    It will also take regular expressions. To me this is one of the more elegant ways to solve it. prototypejs gsub documentation

  • String.prototype.replaceAll = function (replaceThis, withThis) {
       var re = new RegExp(RegExp.quote(replaceThis),"g"); 
       return this.replace(re, withThis);
    };
    
    
    RegExp.quote = function(str) {
         return str.replace(/([.?*+^$[\]\\(){}-])/g, "\\$1");
    };
    
    var aa = "qwerr.erer".replaceAll(".","A");
    alert(aa);
    

    silmiar post

  • Thanks to all, i've got the point! Before i didn't know how to manage regex in javascript..

    Yes i use the prototype framework, and before posting this question i've searched into the prototype String documentation, but found nothing, i'm so dumb :|

How would I use LINQ2XML in this scenario?

I have my LINQ2XML query working half way to my goal:

var XMLDoc = XDocument.Load("WeatherData.xml");

var maximums = from tempvalue in 
                   XMLDoc.Descendants("temperature").Elements("value")
               where tempvalue.Parent.Attribute("type").Value == "maximum"
               select (string)tempvalue;

var minimums = from tempvalue in 
                   XMLDoc.Descendants("temperature").Elements("value")
               where tempvalue.Parent.Attribute("type").Value == "minimum"
               select (string)tempvalue;

List<string> MaxTemps = maximums.ToList();
List<string> MinTemps = minimums.ToList();

However, I'm having trouble with getting the time information from the XML document, because I have to match the layout-key information(see the XML comments), and I'm wondering what would be the best solution in LINQ to join this time data with my existing queries:

(By the way, this XML data comes from a web service)

<?xml version="1.0" encoding="utf-8"?>
<dwml>
  <data>
    <time-layout>
      <!--        Maximums Key         -->
      <layout-key>k-p24h-n7-1</layout-key>
      <start-valid-time>2009-02-09T07:00:00-05:00</start-valid-time>
      <end-valid-time>2009-02-09T19:00:00-05:00</end-valid-time>
      <start-valid-time>2009-02-10T07:00:00-05:00</start-valid-time>
      <end-valid-time>2009-02-10T19:00:00-05:00</end-valid-time>
      <start-valid-time>2009-02-11T07:00:00-05:00</start-valid-time>
      <end-valid-time>2009-02-11T19:00:00-05:00</end-valid-time>
      <start-valid-time>2009-02-12T07:00:00-05:00</start-valid-time>
      <end-valid-time>2009-02-12T19:00:00-05:00</end-valid-time>
      <start-valid-time>2009-02-13T07:00:00-05:00</start-valid-time>
      <end-valid-time>2009-02-13T19:00:00-05:00</end-valid-time>
      <start-valid-time>2009-02-14T07:00:00-05:00</start-valid-time>
      <end-valid-time>2009-02-14T19:00:00-05:00</end-valid-time>
      <start-valid-time>2009-02-15T07:00:00-05:00</start-valid-time>
      <end-valid-time>2009-02-15T19:00:00-05:00</end-valid-time>
    </time-layout>
    <time-layout>
      <!--        Minimums Key         -->
      <layout-key>k-p24h-n7-2</layout-key>
      <start-valid-time>2009-02-08T19:00:00-05:00</start-valid-time>
      <end-valid-time>2009-02-09T08:00:00-05:00</end-valid-time>
      <start-valid-time>2009-02-09T19:00:00-05:00</start-valid-time>
      <end-valid-time>2009-02-10T08:00:00-05:00</end-valid-time>
      <start-valid-time>2009-02-10T19:00:00-05:00</start-valid-time>
      <end-valid-time>2009-02-11T08:00:00-05:00</end-valid-time>
      <start-valid-time>2009-02-11T19:00:00-05:00</start-valid-time>
      <end-valid-time>2009-02-12T08:00:00-05:00</end-valid-time>
      <start-valid-time>2009-02-12T19:00:00-05:00</start-valid-time>
      <end-valid-time>2009-02-13T08:00:00-05:00</end-valid-time>
      <start-valid-time>2009-02-13T19:00:00-05:00</start-valid-time>
      <end-valid-time>2009-02-14T08:00:00-05:00</end-valid-time>
      <start-valid-time>2009-02-14T19:00:00-05:00</start-valid-time>
      <end-valid-time>2009-02-15T08:00:00-05:00</end-valid-time>
    </time-layout>
    <parameters>
      <!--                                     1st Key   -->
      <temperature type="maximum" time-layout="k-p24h-n7-1">
        <value>44</value>
        <value>57</value>
        <value>55</value>
        <value>40</value>
        <value>39</value>
        <value>34</value>
        <value>33</value>
      </temperature>
      <!--                                     2nd Key   -->
      <temperature type="minimum" time-layout="k-p24h-n7-2">
        <value>24</value>
        <value>38</value>
        <value>46</value>
        <value>35</value>
        <value>25</value>
        <value>27</value>
        <value>23</value>
      </temperature>
    </parameters>
  </data>
</dwml>
From stackoverflow
  • I would start out by breaking this down into smaller pieces. First, I would massage the time layouts into a more workable form, grouped by the layout key, with the valid start time and valid end time associated with each other:

    var timeLayouts =
        from tempvalue in XMLDoc.Descendants("time-layout")
        let tempStartTimes = tempvalue.Elements("start-valid-time").
                Select((x, i) => new { Index = i, ValidDateTime = (DateTime)x })
        let tempEndTimes = tempvalue.Elements("end-valid-time").
                Select((x, i) => new { Index = i, ValidDateTime = (DateTime)x })
        select new
        {
            LayoutKey = tempvalue.Element("layout-key").Value,
            ValidTimeRanges =
                from s in tempStartTimes
                from e in tempEndTimes
                where s.Index == e.Index
                select new 
                { 
                    Index = s.Index, 
                    ValidStartDateTime = s.ValidDateTime, 
                    ValidEndDateTime = e.ValidDateTime 
                }
        };
    

    Then, I would massage the parameters in much the same way:

    var parameters =
        from tempvalue in XMLDoc.Descendants("temperature")
        select new
        {
            TemperatureType = (string) tempvalue.Attribute("type"),
            TimeLayout = (string) tempvalue.Attribute("time-layout"),
            Temperatures = tempvalue.Elements("value").Select((x, i) =>
                new { Index = i, Temperature = (int)x })
        };
    

    From there, it's not so hard to get your maximums and minimums:

    var maximums =
        from p in parameters
        where p.TemperatureType == "maximum"
        from tl in timeLayouts
        where tl.LayoutKey == p.TimeLayout
        from tr in tl.ValidTimeRanges
        from t in p.Temperatures
        where tr.Index == t.Index
        select new { tr.ValidStartDateTime, tr.ValidEndDateTime, 
            t.Temperature };
    
    var minimums =
        from p in parameters
        where p.TemperatureType == "minimum"
        from tl in timeLayouts
        where tl.LayoutKey == p.TimeLayout
        from tr in tl.ValidTimeRanges
        from t in p.Temperatures
        where tr.Index == t.Index
        select new { tr.ValidStartDateTime, tr.ValidEndDateTime, 
            t.Temperature };
    

    You could go some other ways with this, if you wanted to simplify some of the representations (you could flatten out the layouts and parameters into something more "tabular", for example), it would just require a few tweaks.

    M4dRefluX : Thank you so much! I've been pulling my hair out trying to figure this out, reading books, code examples, etc. and nothing was suitable to my scenario. Your timeLayouts query will serve me well for pretty much the entire SOAP service.
    casperOne : @M4dRefluX: No problem. If you have any questions about the specifics, feel free to ask.

How do I set up one time password authentication?

I have a home network which I access remotely quite a bit. But I'm worried about security. While I do have strong passwords, I'm worried that someone will acquire my password and use it to gain access.

I heard about "one time passwords" and even got to use them at my university. We'd just press a button on a device (or run an application on a phone) and get a generated password that would work for the next minute or so.

  • How can I set something like that up?
  • Are there systems that are easy to use and set up?
  • Has anyone played around with an SDK of one of these systems?
  • Where can I get a starter kit from?

EDIT: I'm running a mixed Linux and Windows network, and I'm vaguely hoping to use this for authenticating on both operating systems. (No, there's no domain controller, but I can set one up using Samba, I suppose.)

From stackoverflow
  • One approach could be as follows:-

    U'll need to make a program which will generate a password which will only be accepted by ur home system for a specific time-frame.

    For ex. When you run the program the output will valid be for a specific time duration and will be accepted by your home security system as the system will also generate the same output while matching the hash, the trick is to get the same hash at both the places.

    I guess this will need more brainstorming!!!!

  • On Linux it's called S/Key: here

    Not a button gizmo but you seed it and print off a list of one-time passwords to carry around with you. To make it work with a mixed env you'd need to get it working on your Windows box then get the Linux box to auth from that or (easier) get it working on Linux then link it to Samba so Windows can auth off it.

    Google is your friend.

  • As an addendum to renegadeMind's post one way to do this would be to have a program on both ends that generates a sequence of random numbers. A property of Pseudo-random number generators (PRNGs) is that if you start them with the same seed, they will continue to generate the same sequence of random numbers. So depending on your experience (or availability of technology) you could set your network up to generate a new password every x minutes. Then you could carry around a piece of software that would run on a phone or other embedded hardware that calculates what step in the sequence the PRNG is up to and then list the current password for you.

    Having said that the security of your system would be limited to the seed you choose and the time you choose that each key is valid for.

    In addition to this there is probably a software solution that will do this for you. IMHO it's better to take the existing implementation then reinventing the wheel.

    Edit: Wikipedia has a good article here. The part on specific OTP technologies will probably be the most relevant.

    Good luck though!

    wiki article on PRNG

    renegadeMind : yep, thats one way of doing it!
  • S/Key is fine for a low-cost OTP implementation. If you're really worried about it, though, then worry also about your sessions being hijacked after they're initiated. In which case you might consider an SSH tunnel to encrypt your traffic. SSH also lends itself better to tunneling other applications through it once you set up your access. Finally, it you don't have an easy way to carry around an SSH client with you (or don't trust other people's SSH clients), there are a few web-based SSH clients that you could offer from your own server -- so it's under your control but available from any browser.

  • The first thing you need to decide is what authentication protocol will be your standard. I recommend Radius, especially for two-factor authentication in the enterprise. Radius is supported by all the major VPN & networking providers as well as all the major 2FA providers.

    Then, consider the services you want to protect. For linux, this usually means PAM. Luckily, adding 2FA to linux via pam is pretty painless: http://www.wikidsystems.com/support/wikid-support-center/how-to/pam-radius-how-to/. For windows services, you will want to route them through ISA or the VPN.

    You can configure all your radius requests to go through AD using the MS radius plugin IAS/NPS. http://www.networkworld.com/news/2010/050710-two-factor-authentication-through-windows-server.html?source=nww_rss

    Finally, when choosing your 2FA solution, just make sure they support radius.

    As for SDKs, that is a per-vendor situation. Here's a link to ours: http://www.wikidsystems.com/downloads/network-clients

    hth, nick

Get the user's identity with no authentication

I have an ASP.NET app that writes files to a NETAPP. It's finicky, and the only way we could get it to work was to set <identity impersonate="true"/> and remove the <authentication.../> tag in web.config. This allows the app to write to the NETAPP (with the appropriate monkeying of permissions behind the scenes), but now my app can't tell who is actually using it. Is there another way to get the user's ID without forcing them to log in? This is an internal app, so it would only be run from workstations with a logged in user. Any ideas?

Edit: I'm not an IIS expert, but I believe the app was set up to run under a certain privileged account to get it to work. I'm also looking for alternate ways to set this up if there is no way to get the user's ID.

From stackoverflow
    • Set authentication to 'Windows' in your web.config
    • Turn off 'Anonymous access' for the web site in IIS
    • Turn on 'Integrated Windows Authentication' for the website in IIS
    • Leave the identity impersonation turned on in your web.config

    I believe that will do what you need.

  • One possibility is for me to move the writing portion to a web service, so that the service can get all the necessary permissions without affecting how my app functions. It's a lot of work, though, so I'm hoping for a simpler answer.

  • If you have Integrated Windows Authentication then

    string username = HttpContext.Current.Request["LOGON_USER"];
    

    Edit based on comments; Maybe the solution you actually want it so disable impersonation for the entire application and only impersonate the required bits that need to be impersonated.

    See this page for some additional details on how to accomplish this.

    http://www.west-wind.com/WebLog/posts/1572.aspx

    gfrizzle : The problem is that I have to turn off Windows Authentication to get it to write to the NETAPP, so this won't work.
    Bob : See my updated answer. Maybe you should use a solution like the link offers for writing to NETAPP

Where should I set compiler options like {$STRINGCHECKS OFF}?

If I place it in the .dpr or any other unit will it be considered globally?

From stackoverflow
  • I dont think so. IIRC the rule is that anything in the dpr or unit is local to that file. If you put it into the project options (under conditionals) then it is global. Many writers put such stuff into a text file and then do a {$I MyConditionals.txt} at the top of each unit.

  • Some compiler directives have different scope than others. Some affect the entire application, some only the unit they're put in, and some only the code around which they're placed. For example,

    {$WARNINGS OFF}  // Turn off warning messages from compiler
    procedure SomeProcedureThatHasAnAsmBlock;
    begin
      asm
        // Some assembler code that generates warnings, but
        // that you know is actually right. These warnings
        // are usually like "expression always evaluates to false"
        // or something like that.
      end;
    end;
    {$WARNINGS ON}   // Turn warnings back on for other code
    

    Since {$STRINGCHECKS} is undocumented (at least in the version of the D2009 help file I have), it's hard to know what it's scope is. Barry Kelly of CodeGear is here sometimes, and he works on the compiler itself; maybe he'll wander by and be able to help.

  • IIRC you can turn it off globally in the Project Options window.

  • Project -> Options -> Delphi Compiler -> Code generation, set "String format checking" OFF.

How to roll back a previous version of a TFS project?

Duplicate

how to Rollback using TFS


Somehow I checked in a version of a web project that deleted an entire folder (with subfolders and asp.net files). I want those files back, I can sacrifice the latest check-in because I can easily replicate it again.

How do I tell the TF server to roll back to the version just before the current one?

Thank you.

From stackoverflow

Custom django widget - decompress() arg not populated.

As an exercise I am trying to create a custom django widget for a 24 hour clock. The widget will is a MultiWidget - a select box for each field.

I am trying to follow docs online (kinda sparse) and looking at the Pro Django book, but I can't seem to figure it out. Am I on the right track? I can save my data from the form, but when I prepopulate the form, the form doesn't have the previous values.

It seems the issue is that the decompress() methods 'value' argument is always empty, so I have nothing to interpret.

from django.forms import widgets

import datetime

class MilitaryTimeWidget(widgets.MultiWidget):
    """
    A widget that displays 24 hours time selection.
    """
    def __init__(self, attrs=None):
        hours = [ (i, "%02d" %(i)) for i in range(0, 24) ]
        minutes = [ (i, "%02d" %(i)) for i in range(0, 60) ]
        _widgets = (
            widgets.Select(attrs=attrs, choices=hours), 
            widgets.Select(attrs=attrs, choices=minutes),
            )
        super(MilitaryTimeWidget, self).__init__(_widgets, attrs)

    def decompress(self, value):
        print "******** %s" %value
        if value:
            return [int(value.hour), int(value.minute)]
        return [None, None]

    def value_from_datadict(self, data, files, name):
        hour = data.get("%s_0" %name, None)
        minute = data.get("%s_1" %name, None)
        if hour and minute:
            hour = int(hour)
            minute = int(minute)
            return datetime.time(hour=hour, minute=minute)
        return None

In my form, I am calling the widget like:

arrival_time = forms.TimeField(label="Arrival Time", required=False, widget=MilitaryTimeWidget())
From stackoverflow
  • I can't reproduce the problem:

    >>> class MyForm(forms.Form):
    ...     t = forms.TimeField(widget=MilitaryTimeWidget())
    ...
    >>> print MyForm(data={'t_0': '13', 't_1': '34'})
    ******** 13:34:00
    <tr><th><label for="id_t_0">T:</label></th><td><select name="t_0" id="id_t_0">
    <option value="0">00</option>
    [...]
    <option value="13" selected="selected">13</option>
    [...]
    <option value="23">23</option>
    </select><select name="t_1" id="id_t_1">
    <option value="0">00</option>
    [...]
    <option value="34" selected="selected">34</option>
    [...]
    <option value="59">59</option>
    </select></td></tr>
    

    Check that your request.POST is correct.

    As a sidenote, are you sure this widget gives good usability? Four mouse clicks and possible scrolling of the minutes combobox...

    ashchristopher : I think my problem is that I am not trying to populate the form using the POST data but instead trying to populate using one of my models. Since I am missing the arrival_time_0 and arrival_time_1 (the names given to each select widget) in the data I pass in, it isnt being populated.
    ashchristopher : It seems rather heavy-handed and non-pythonic to purposfully split that data in my view before passing into the form. Thoughts?
  • Note this line in the docstring for MultiWidget:

    You'll probably want to use this class with MultiValueField.

    That's the root of your problem. You might be able to get the single-widget-only approach working (Marty says it's possible in Pro Django, but I've never tried it, and I think it's likely to be more work), but in that case your widget shouldn't be a subclass of MultiWidget.

    What you need to do (if you want to follow the MultiWidget/MultiValueField path) is:

    • remove your value_from_datadict method
    • define a subclass of MultiValueField with a definition of the compress() method which does the task you're currently doing in value_from_datadict() (transforming a list of numbers into a datetime.time object)
    • set your Widget as the default one for your custom form Field (using the widget class attribute)
    • either create a custom model Field which returns your custom form Field from its formfield() method, or use your custom form field manually as a field override in a ModelForm.

    Then everything will Just Work.

    akaihola : Looks like django.forms.fields.SplitDateTimeField and django.forms.widgets.SplitDateTimeWidget are good models to base on.

Is it possible to develop for sharepoint using continuous integration techniques?

We are gearing up for some pretty serious Sharepoint(MOSS 2007) development including custom web parts, lists, master pages and layouts etc etc and etc.

We are evaluating version control and it seems that the discussion has not got much deeper than that. I am keen that we can easily deploy from the source control to our test and production servers with as little human contact as possible, and preferably entirely automatically after every check in.

I have not worked using CI before and so am feeling a bit ignorant as to what is possible with Sharepoint, and what is too complex to be sensible.

I fear if we head off down a too 'easy' path then we will come to regret it pretty swiftly when we have to spend half a day setting up each environment after we release some new functionality.

I have not even started to address in my head what happens when there is actual content in the lists added by users and how that will affect what we do on the development side.

Links to blogs/documentation are welcomed. Personal experiences VERY welcome.

From stackoverflow
  • The closest I have experience is on a project that used STSDEV to build solutions for release. Custom build actions allowed us to remove the sharepoint solution from the target server, install the new solutions and reset the required application pools.

    Took a while to build, but it worked well. We did not release to test using this process, but it may be possible.

    Here is an example of a targets file. Unfortunately, it is a bit complex.

    <?xml version="1.0" encoding="utf-8" ?>
    <Project DefaultTargets="DebugBuild" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    
      <PropertyGroup>
        <PackageName>MyFeatures.wsp</PackageName>
        <PackageFile>MyFeatures.wsp</PackageFile>
        <TargetUrl>http://intranet</TargetUrl>
        <ProjectDeploymentFilesFolder>DeploymentFiles</ProjectDeploymentFilesFolder>
        <ProjectRootFilesFolder>$(ProjectDir)\RootFiles</ProjectRootFilesFolder>
        <WssRootFilesFolder>$(ProgramFiles)\Common Files\Microsoft Shared\web server extensions\12</WssRootFilesFolder>
        <ReleaseFolder>$(SolutionDir)Deployment</ReleaseFolder>
        <MAKECAB>"C:\Windows\System32\makecab.exe"</MAKECAB>
        <STSADM>"$(ProgramFiles)\Common Files\Microsoft Shared\web server extensions\12\bin\stsadm.exe"</STSADM>
        <STSDEV>"$(SolutionDir)..\Tools\STSDev\stsdev.exe"</STSDEV>
        <GACUTIL>"C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\gacutil.exe"</GACUTIL>
        <IISAPP>cscript c:\windows\system32\iisapp.vbs</IISAPP>    
        <WARMUPSITE>"$(SolutionDir)..\Tools\WarmUpServer\AsyncWarmup.bat" "$(SolutionDir)..\Tools\WarmUpServer\"</WARMUPSITE>
        <TIMERJOBSRESTART>net stop SPTimerV3 &amp; net start SPTimerV3</TIMERJOBSRESTART>
      </PropertyGroup>
    
      <ItemGroup>
        <WSSSourceFiles Include="$(ProjectDir)\RootFiles\**\*.*" />
      </ItemGroup>  
    
    <Target Name="DebugBuild">
      <Message Text="Refreshing Deployment Files..." Importance="high" />
      <Exec Command="$(STSDEV) /refresh $(TargetName) $(ProjectDir)" ContinueOnError="true" />
      <Message Text="Deleting Solution Package File..." Importance="high" />
      <Delete Files="$(ProjectDeploymentFilesFolder)\$(PackageFile)" ContinueOnError="true" />
      <Message Text="Building Solution Package (Debug Version)" Importance="high" />
      <Exec Command="$(MAKECAB) /F $(ProjectDir)\$(ProjectDeploymentFilesFolder)\SolutionPackage.ddf /D CabinetNameTemplate=$(PackageFile)" ContinueOnError="false" />
      <Message Text="" Importance="high" />
      <Message Text="Copying WSP file to CAB" Importance="high" />
      <Delete Files="$(ProjectDeploymentFilesFolder)\$(PackageFile).cab" ContinueOnError="true" />
      <Copy SourceFiles="$(ProjectDeploymentFilesFolder)\$(PackageFile)" DestinationFiles="$(ProjectDeploymentFilesFolder)\$(PackageFile).cab" SkipUnchangedFiles="false" />
      <Message Text="Copying WSP file to release folder: $(ReleaseFolder) from $(ProjectDeploymentFilesFolder)\$(PackageFile)" Importance="high" />
      <Exec Command="attrib -r &quot;$(ReleaseFolder)\$(PackageFile)&quot;" ContinueOnError="true"></Exec>
      <Delete Files="$(ReleaseFolder)\$(PackageFile)" ContinueOnError="true" />
      <Copy SourceFiles="$(ProjectDeploymentFilesFolder)\$(PackageFile)" DestinationFolder="$(ReleaseFolder)" SkipUnchangedFiles="false" />
      <Message Text="" Importance="high" />
    </Target>
    
    <Target Name="DebugInstall" DependsOnTargets="DebugBuild">
      <Message Text="Installing Solution..." Importance="high" />
      <Exec Command="$(STSADM) -o addsolution -filename $(ProjectDeploymentFilesFolder)\$(PackageFile)" ContinueOnError="true" />
      <Exec Command="$(STSADM) -o execadmsvcjobs" />
      <Message Text="" Importance="high" />
    </Target>
    
    <Target Name="DebugDeploy" DependsOnTargets="DebugInstall">
      <Message Text="Deploying Solution..." Importance="high" />
      <Exec Command="$(STSADM) -o deploysolution -name $(PackageName) -immediate -allowgacdeployment -url http://intranet" />
      <Exec Command="$(STSADM) -o execadmsvcjobs" />
      <Copy SourceFiles="$(TargetDir)$(TargetName).pdb" DestinationFolder="C:\WINDOWS\assembly\GAC_MSIL\MyFeatures\1.0.0.0__ce271be627d58c77" SkipUnchangedFiles="" />
      <Message Text="$(TargetDir)$(TargetName).pdb copied to GAC for debugging." Importance="high" />
      <Message Text="" Importance="high" />
    </Target>
    
    <Target Name="DebugDeployForce" DependsOnTargets="DebugInstall">
      <Message Text="Deploying Solution..." Importance="high" />
      <Exec Command="$(STSADM) -o deploysolution -name $(PackageName) -immediate -allowgacdeployment -url http://intranet -force" />
      <Exec Command="$(STSADM) -o execadmsvcjobs" />
      <Copy SourceFiles="$(TargetDir)$(TargetName).pdb" DestinationFolder="C:\WINDOWS\assembly\GAC_MSIL\MyFeatures\1.0.0.0__ce271be627d58c77" SkipUnchangedFiles="" />
      <Message Text="$(TargetDir)$(TargetName).pdb copied to GAC for debugging." Importance="high" />
      <Message Text="" Importance="high" />
    </Target>
    
    <Target Name="DebugRedeploy" >
      <Message Text="" Importance="high" />
      <Message Text="Starting sequence of Retract/Delete/Build/Install/Deploy" Importance="high" />
      <CallTarget Targets="DebugRetract" />
      <CallTarget Targets="DebugDelete" />
      <CallTarget Targets="DebugBuild" />
      <CallTarget Targets="DebugInstall" />
      <CallTarget Targets="DebugDeployForce" />
      <Message Text="" Importance="high" />
    </Target>      
    
      <Target Name="DebugRetract" >
      <Message Text="Retracting Solution" />
      <Exec Command="$(STSADM) -o retractsolution -name $(PackageName) -immediate -url http://intranet" ContinueOnError="true" />
      <Exec Command="$(STSADM) -o execadmsvcjobs" />
      <Message Text="" Importance="high" />
    </Target>
    
    <Target Name="DebugDelete" DependsOnTargets="DebugRetract">
      <Message Text="Deleting Solution Package from Farm Solution Package Store" />
      <Exec Command="$(STSADM) -o deletesolution -name $(PackageName)" ContinueOnError="true" />
      <Exec Command="$(STSADM) -o execadmsvcjobs" />
      <Message Text="" Importance="high" />
    </Target>
    
       </Project>
    
  • Look at Powershell ... unfortunately this is one of the major gripes with SharePoint is a lack of a good development and deployment process. Everything should be packaged into solutions and deployed via powershell, powershell can also manage any clean up of information. To version simply deploy the solutions as an upgrade and use Powershell to update in your apps as appropriate (if you update your version number). It is a lot of extra work but works well enough. In a recent upgrade I had to version two web parts and then used powershell to loop through all ~1,500 my sites removing the old web parts and adding back in the new ones.

    As you go you should start to develop a strong Powershell library to perform powerful updating tasks.

  • The only was to work with SharePoint with some kind of continous integration is when you are working with features and solution packages (wsp).

    You just have to somehow get to package your wsp with all the necessary files/DLLs and configuration and then deploy it. Once it's deployed, you can create a batch script to automatically reactivate all features.

    Please be aware that all file that has been customized (unghosted) will NOT be updated. You must make sure to make a reset to site definition (by code it's "SPFile.RevertContentStream").

    Good luck!

Set Programatically a Windows Service Log on to Local System Account with Desktop interact.

Hello Everyone :)

I have a Windows service built which is being installed by .NET 2.0's installutil /i command.

It installs the service as with the following Account and Password:

NT AUTHORITY\LocalService

running my service with

net start

brings a Error 5: Access Denied Message.

To remove it I've had to open up services.msc and from the Properties give the service

Logon As -> Local System Account -> Allow Service to interact with desktop.

Can I put this whole "clicky" business into code which is either:

Native .NET C# code

OR

WMI or some other Batch script.

I'll be using a batch script anyways so either is fine :)

Thanks for the help!

From stackoverflow
  • Figured out an Answer, thanks very much to the following Webpage to which I give full credit.

    link text

    Here's the Solution I have, just change your service name as needed. Throw it in a C# Console App and run it :)

    static void Main(string[] args)
    {
        string serviceName = "SERVICE_NAME_HERE"; 
        string objPath = string.Format("Win32_Service.Name='{0}'", serviceName);
        using (ManagementObject service = new ManagementObject(new ManagementPath(objPath)))
        {
            object[] wmiParams = new object[11];
            wmiParams[6] = "LocalSystem";
            wmiParams[7] = "";
            service.InvokeMethod("Change", wmiParams);
        }
    }
    

    }

    Phil : You forgot the "Desktop interact" part. Just add wmiParams[5] = true;

Eval stacktrace with formatting

I want to take an EventLog entry which has a stack trace in its Message and bind it to a GridView. If I use Eval("Message") and put it in a label or a < p >, it displays, but the stack trace is smashed together.

If I Eval it in a TextBox, it keeps its formatting.

Is there a way to evaluate this stacktrace value to some sort of literal-type control and preserve formatting?

I've tried Server.HtmlEncode(Eval("Message")) without success.

From stackoverflow
  • It sounds like you need to convert the newlines to HTML linebreaks. Try something like this:

    String htmlMessage = e.Message.Replace("\n", "<br/>");
    
    Macho Matt : It doesn't solve all of the indenting that was in place, but I know where to go from here. Thanks!

Custom (IDictionary) XML Serialization for SOAP/asmx/WebMethods?

Using ASP.NET WebServices, by default you can't pass any IDictionary objects, because xml serialization for IDictionaries isn't supported. I have found various ways to serialized dictionaries (http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx, http://blogs.msdn.com/psheill/archive/2005/04/09/406823.aspx, http://www.mattberther.com/2004/06/14/serializing-an-idictionary-object/) but, I can't find any way to hook this into the Asp.NET web methods.

Is there a way to hook it up so that I can use IDictionaries with WebMethods?

From stackoverflow
  • depends on how you are calling these methods, we use the .net 2.0 method with "web references" and you will notice that the WSDL generated class is a partial, we create a (web reference name).cs file and have something like:

    
    public partial class WebReferenceName : System.Web.Services.Protocols.SoapHttpClientProtocol 
    {
        // Overload the WSDL generated method that only takes a simple array
        public ReturnType MethodName(List  collection)
        {
         // redirect the call to the wsdl generated method with the appropriate parameters
         return this.MethodName(collection.ToArray());
        }
    }
    

    Overloading will allow you to call the method name with either type of collection

    At the web service side you can convert from a simple collection back to a more powerful collection, most likely with the use of that more powerful collections ctor. One of the ctors will probably consume a simple collection.

  • The question is - where do you want to pass the dictionary? If you simply want to teach your service how to serialize a dictionary, then implement the IXmlSerializable interface on your dictionary class, and serialize it however you like.

    The problem will be on the client. How should a Java client deserialize what you sent? For that matter, how would a .NET client know how to do that? There's no good way when using the old ASMX web services to have the client do something special. It's one of many reasons that WCF was invented.

BlackBerry - Add items to a ListField

Can someone please give me a simple example on how to add three rows to a ListField so that the list shows something like this?

Item 1

Item 2

Item 3

I just want to show a list in which the user can select one of the items and the program would do something depending on the item selected.

I've search all over the internet but it seems impossible to find a simple example on how to do this (most examples I found are incomplete) and the blackberry documentation is terrible.

Thanks!

From stackoverflow
  • You probably want to look at using an ObjectListField. Handling the select action is done throught the containing Screen object, I've done this below using a MenuItem, I'm not really sure how to set a default select listener, you may have to detect key and trackwheel events.

    Some example code for you: (not tested!)

    MainScreen screen = new MainScreen();
    screen.setTitle("my test");
    
    final ObjectListField list = new ObjectLIstField();
    String[] items = new String[] { "Item 1", "Item 2", "Item 3" };
    list.set(items);
    
    screen.addMenuItem(new MenuItem("Select", 100, 1) {
        public void run() {
            int selectedIndex = list.getSelectedIndex();
            String item = (String)list.get(selectedIndex);
            // Do someting with item
        });
    screen.add(list);
    
  • Thanks Rory! It does work for adding the list items. I was able to display the three lines the way I wanted.

    Now, like you said, I have the challenge of how to handle the select action. I'll investigate on how to detect key and trackwheel events. My idea is to open a new screen depending on which item was selected.

    Any ideas on how to do this will be very much appreciated.

    Thanks!

  • You can detect the click on each list item by overriding

    protected boolean navigationClick(int status, int time)

    Then you just need to work out what to do in response to the click. The way I did this was by using an anonymous class, set for each list item. Let me know if you need more detail.

  • I am interested in more detail.

    Thanks.

  • You can override the navigationClick method like this:

    ObjectListField list = new ObjectListField()
    {
        protected boolean navigationClick(int status, int time)
        {
         // Your implementation here.
        }
    };
    
  • Hi, Can anyone tell me how to get all selected items from a list with checkboxes?

    Please help

  • Hey, I was wondering how could I add more than one string per line. i.e. I want to display a Name and details, similar format to how you can view contacts.

    thanks!

  • Hey Mike, try to implement a paint function and use drawtext.

How to block (or unblock) the ASP.NET error logger Elmah?

Some one configured my server in a way that intentionally or inadvertently blocks ELMAH. I wish I know what that was. My current server admin can't figure out what's blocking it either.

Clues have so far

  • Error message is "This type of page is not served...it has been explicitly forbidden"

  • Ordinary .ashx handlers work just fine. (HelloWorld.ashx works)

  • I'm running in Full Trust.

  • I'm on Win 2000, IIS 5

  • Machine config doesn't have any references to ELMAH (neither does my web.config)

  • The ELMAH_Error table exists, but has no entries.

  • My application with ELMAH works fine on my machine (i.e. shows the error log).

  • I updated the Handler section to change the name to Elmha.ashx, instead of elmah.axd.

From stackoverflow
  • This was happening on server I didn't have access to the windows application error log. After getting that, it was obvious that elmah and blowery were not playing well together (headers already sent errors).

Entity Framework: Singletonish ObjectContext - Good, Bad, or Overthinking?

The idea is to create a class that exposes a context but handles the storage of it in a web application.

Currently this is what I have:

public class EntityContext
{

    private static String MAIN_CONTEXT_KEY = "MainContext";
    private static TISQLEntities _context;

    public static void RemoveContext()
    {
        if (
            HttpContext.Current != null 
            && 
            HttpContext.Current.Items[MAIN_CONTEXT_KEY] != null
           )
        {
            ((TISQLEntities)HttpContext.Current.Items[MAIN_CONTEXT_KEY]).Dispose();
            HttpContext.Current.Items[MAIN_CONTEXT_KEY] = null;
        }

        if (_context != null)
        {
            _context.Dispose();
            _context = null;
        }
    }

    public static TISQLEntities Context
    {
        get
        {
            if (HttpContext.Current == null)
            {
                if (_context == null)
                {
                    _context = new TISQLEntities();
                }

                return _context;
            }

            if (HttpContext.Current.Items[MAIN_CONTEXT_KEY] == null)
            {
                HttpContext.Current.Items[MAIN_CONTEXT_KEY] = new TISQLEntities();
            }

            return (TISQLEntities)HttpContext.Current.Items[MAIN_CONTEXT_KEY];
        }
    }
}

And then in the Global.asax file:

protected void Application_EndRequest(object sender, EventArgs e)
{
    EntityContext.RemoveContext();
}

The idea is that if this is being run with a web application, the context is created on first need (and saved to the current HttpContext) and torn down whenever the request is over.

If this is a UnitTest situation it is against created on first need and removed in the TestCleanup (Not as important in this post but just wanted to clarify the _context object).

Now the idea behind this is in the least to not have to do this:

using(TISQLEntities context = new TISQLEntities())
{
  ....
}

Everytime I want to query. I realize this may be me being lazy, but I just think that it's easier and cleaner to have:

EntityContext.Context.User.Select(...)

And avoids "using" which I try to avoid for most cases. On top of that, I'm not creating 9001 contexts per postback.

Now what I am curious about is that am I over thinking this? Should I just keep creating a context for every method that needs one? Say on a post back I have to:

  • Get the user from an ID
  • Get a site from an id
  • Add the Site to the User (user.Site = foundSite)
  • Save the user

That could entail at least 3 contexts. Is entity framework smart enough that it's ok to just keep creating contexts whenever?

From stackoverflow
  • You are implementing the equivalent of NHibernate's session per request pattern which is a good construct in NHibernate. While I can't say 100% for sure that it's applicable to EF it most likely is. Further expanding on other session management patterns is the Session per Business Conversation which allows NHibernate to extend holding a session over the duration of a HttpSession by disconnecting and reconnecting the session as opposed to destroying and creating. If the EF allows a similar ability as opposed to keeping a static open connection you could look at how I implemented that pattern using AOP on my blog through my profile.

    Programmin Tool : I didn't know this was a pattern exactly, but yes I have worked with nHibernate before and was trying to do the same with EF. That's basically what I'm trying to accomplish.
    Chris Marisic : Yes there are a few session management patterns. The most common correct pattern is session per request, session per business conversation is very new, the antipatterns for session management are session per application and session per call (no management, create and destroy the session everytime)
  • If you are trying to implement something like NHibernate does with its Session, I think its a good idea to have this kind of pattern. I know for sure that in LinqToSql the context object implementation is more like an entrypoint class thats acts as a facade. I would like to think LinqToEntities is similar. You could have a factory implementation to get a datacontext to your model where you can recycle the datacontext. If you go the singleton way consider bottleneck ,availability and responsibility of the singleton object.

  • Check out this blog entry that provides some more details about creating a singleton for the Entity Framework context and why this wouldn't work in ASP.NET and comes up with a solution that does something similar as you suggest.

ORACLE: UPDATE using two tables, Concatenation

I have two tables involved in this query I need to create, and I'm not exactly sure how to join these two tables in order to update.

I have a ITEM and CONSUMER_ITEMS table. The ITEM table has a distinct code for each item and a UPC code. I need to concatenate a string with the ITEM.UPC_CODE to CONSUMER_ITEMS.NEW_ITEM_CODE where CONSUMER_ITEMS.ITEM_CODE = (Specific list of ITEM.ITEM_CODES)

How would I go about updating the CONSUMER_ITEMS.NEW_ITEM_CODE Field?

It would essentially be equal to 'string' || ITEM.UPC but how do I reference the CONSUMER_ITEMS.ITEM_CODE to be equal to the specific ITEM_CODE in the list of ITEM_CODES to be updated.

From stackoverflow
  • Sounds like you want:

    UPDATE consumer_items ci
    SET    new_item_code = (SELECT 'string' || item.upc_code
                            FROM   item
                            WHERE  item.item_code = ci.item_code
                           )
    WHERE  ci.item_code IN ('a','b','c');
    

    Alternatively, assuming there is a foreign key relationship between the tables and that consumer_items has a primary key, this should work:

    UPDATE (SELECT ci.id, ci.new_item_code, item.upc_code
            FROM   consumer_items ci
                   JOIN item ON item.item_code = ci.item_code
            WHERE  ci.item_code IN ('a','b','c')
           ) v
    SET v.new_item_code = 'string' || v.upc_code
    

    EDIT: Added WHERE clauses

    jlrolin : Basically, my item.item_code = ('SET OF VALUES') that would reference item_codes in CONSUMER_ITEMS
    Tony Andrews : Do you mean like I have now added above?
    jlrolin : Oddly enough, it won;t let me modify a view, and the first statement brings about multiple values in a subquery errors
    Tony Andrews : So ITEM_CODE isn't unique in ITEMS table then? I had assumed it must be.
  • Right, that looks great but the item.item_code = ci.item_code doesn't work because:

    SELECT distinct i.code, i.upc FROM item i, consumer_items ci WHERE i.ccode = '123132' AND i.scode = 'ACTIVE' AND i.upc IS NOT NULL AND ci.item_code = i.code AND i.code IN (SELECT DISTINCT tr.item_code FROM t_r tr WHERE tr.category = 'RRE') AND ci.NEW_ITEM_CODE IS NULL

    This is the distinct list of CODES and UPC associated with those codes that much be used to update the CONSUMER_ITEMS.

    new_item_code = (SELECT 'string' || item.upc_code FROM item WHERE item.item_code = (SELECT distinct i.code, i.upc FROM item i, consumer_items ci WHERE i.ccode = '123132' AND i.scode = 'ACTIVE' AND i.upc IS NOT NULL AND ci.item_code = i.code AND i.code IN (SELECT DISTINCT tr.item_code FROM t_r tr WHERE tr.category = 'RRE') AND ci.NEW_ITEM_CODE IS NULL));

    doesn't seem to work

    Tony Andrews : Sorry, but I didn't understand any of that! Perhaps we need to see some sample data?
    jlrolin : see above for better explanation.
  • The list of i.ITEM_CODE, i.UPC is this:

    014940  070182132137
    018266  929245021085
    018268  729245021108
    018418  029245022815
    018419  129245022822
    018420  229245022839
    018421  529245022846
    018422  929245022853
    

    The first column is ITEM CODES, Second Column is UPCs. This is on the ITEMS table.

    The CONSUMER_ITEMS table essentially has a CONSUMER_ITEMS.ITEM_CODE as well. That's the LINK, but it also has a field called CONSUMER_ITEMS.NEW_ITEM_CODE. We want to fill the NEW_ITEM_CODE with the UPC from the corresponding ITEM_CODE in the list above with a concatentation of 'string' || UPC CODE FROM ABOVE.

    How we generate that list is:

    SELECT distinct i.code, i.upc
    FROM item i, consumer_items ci 
    WHERE i.ccode = '123434' 
    AND i.scode = 'ACTIVE' 
    AND i.upc IS NOT NULL 
    AND ci.item_code = i.code 
    AND i.code IN 
    (SELECT DISTINCT tr.item_code 
     FROM tr_table tr 
     WHERE tr.category = 'RRE') 
    AND ci.NEW_ITEM_CODE IS NULL
    

    This generates the ITEM_CODE, UPC list above. I need to update the CONSUMER_ITEMS that MATCH those codes above. Specifically, I need to update their NEW_ITEM_CODE fields, which are null, with the corresponding UPC concatenated with a STRING.

  • Any thoughts?

  • /*+ BYPASS_UJVC */

    use this hint if you are getting the following oracle error- ORA-01779: cannot modify a column which maps to a non key-preserved table