I'm trying to figure out the best way to represent some data. It basically follows the form Manufacturer.Product.Attribute = Value. Something like:
Acme.*.MinimumPrice = 100
Acme.ProductA.MinimumPrice = 50
Acme.ProductB.MinimumPrice = 60
Acme.ProductC.DefaultColor = Blue
So the minimum price across all Acme products is 100 except in the case of product A and B. I want to store this data in C# and have some function where GetValue("Acme.ProductC.MinimumPrice") returns 100 but GetValue("Acme.ProductA.MinimumPrice") return 50.
I'm not sure how to best represent the data. Is there a clean way to code this in C#?
By best I mean more time tested, easier to implement and easier for the users to work with. I do not want my licensing crap to interfere with their work.
I was thinking of launching a WCF service that check with my license DB if it's a valid license and if it is, send a True.
If the returned response is False, then shut down the program after telling them to fix their license.
Do you think this is a good way to handle it?
I have a legacy HTTP server where I need to send an XML file over HTTP request (POST) using Java (not browser) and the server will respond with another XML in its HTTP response. It is similar to Web Service but there's no WSDL and I have to follow the existing XML structure to construct my XML to be sent.
I have done a research and found an example that matches my requirement here. The example uses HttpClient from Apache Commons. (There are also other examples I found but they use java.net networking package (like URLConnection) which is tedious so I don't want to use them).
But it's also my requirement to use Spring and JMS.
I know from Spring's reference that it's possible to combine HttpClient, JMS and Spring. My question is, how?
Note that it's NOT in my requirement to use HttpClient. If you have a better suggestion, I'm welcome.
Appreciate it.
For your reference, here's the XML-over-HTTP example I've been talking about:
/*
* $Header:
* $Revision$
* $Date$
* ====================================================================
*
* Copyright 2002-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
import java.io.File;
import java.io.FileInputStream;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
/**
*
* This is a sample application that demonstrates
* how to use the Jakarta HttpClient API.
*
* This application sends an XML document
* to a remote web server using HTTP POST
*
* @author Sean C. Sullivan
* @author Ortwin Glück
* @author Oleg Kalnichevski
*/
public class PostXML {
/**
*
* Usage:
* java PostXML http://mywebserver:80/ c:\foo.xml
*
* @param args command line arguments
* Argument 0 is a URL to a web server
* Argument 1 is a local filename
*
*/
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println(
"Usage: java -classpath <classpath> [-Dorg.apache.commons."+
"logging.simplelog.defaultlog=<loglevel>]" +
" PostXML <url> <filename>]");
System.out.println("<classpath> - must contain the "+
"commons-httpclient.jar and commons-logging.jar");
System.out.println("<loglevel> - one of error, "+
"warn, info, debug, trace");
System.out.println("<url> - the URL to post the file to");
System.out.println("<filename> - file to post to the URL");
System.out.println();
System.exit(1);
}
// Get target URL
String strURL = args[0];
// Get file to be posted
String strXMLFilename = args[1];
File input = new File(strXMLFilename);
// Prepare HTTP post
PostMethod post = new PostMethod(strURL);
// Request content will be retrieved directly
// from the input stream
// Per default, the request content needs to be buffered
// in order to determine its length.
// Request body buffering can be avoided when
// content length is explicitly specified
post.setRequestEntity(new InputStreamRequestEntity(
new FileInputStream(input), input.length()));
// Specify content type and encoding
// If content encoding is not explicitly specified
// ISO-8859-1 is assumed
post.setRequestHeader(
"Content-type", "text/xml; charset=ISO-8859-1");
// Get HTTP client
HttpClient httpclient = new HttpClient();
// Execute request
try {
int result = httpclient.executeMethod(post);
// Display status code
System.out.println("Response status code: " + result);
// Display response
System.out.println("Response body: ");
System.out.println(post.getResponseBodyAsString());
} finally {
// Release current connection to the connection pool
// once you are done
post.releaseConnection();
}
}
}
I have recently tried sharpening my rails skills with this tool:
http://github.com/edgecase/ruby_koans
but I am having trouble passing some tests. Also I am not sure if I'm doing some things correctly since the objective is just to pass the test, there are a lot of ways in passing it and I may be doing something that isn't up to standards.
Is there a way to confirm if I'm doing things right?
a specific example:
in about_nil,
def test_nil_is_an_object
assert_equal __, nil.is_a?(Object), "Unlike NULL in other languages"
end
so is it telling me to check if that second clause is equal to an object(so i can say nil is an object) or just put assert_equal true, nil.is_a?(Object) because the statement is true?
and the next test:
def test_you_dont_get_null_pointer_errors_when_calling_methods_on_nil
# What happens when you call a method that doesn't exist. The
# following begin/rescue/end code block captures the exception and
# make some assertions about it.
begin
nil.some_method_nil_doesnt_know_about
rescue Exception => ex
# What exception has been caught?
assert_equal __, ex.class
# What message was attached to the exception?
# (HINT: replace __ with part of the error message.)
assert_match(/__/, ex.message)
end
end
Im guessing I should put a "No method error" string in the assert_match, but what about the assert_equal?
I'm coding a function in jquery that executes if ctrl+R is pressed but I can't seem to find out what the left and right ctrl keycodes are....can someone please help?
I built an inventory database where ISBN numbers are the primary keys for the items. This worked great for a while as the items were books. Now I want to add non-books. some of the non-books have EANs or ISSNs, some do not.
It's in PostgreSQL with django apps for the frontend and JSON api, plus a few supporting python command-line tools for management. the items in question are mostly books and artist prints, some of which are self-published.
What is nice about using ISBNs as primary keys is that in on top of relational integrity, you get lots of handy utilities for validating ISBNs, automatically looking up missing or additional information on the book items, etcetera, many of which I've taken advantage. some such tools are off-the-shelf (PyISBN, PyAWS etc) and some are hand-rolled -- I tried to keep all of these parts nice and decoupled, but you know how things can get.
I couldn't find anything online about 'private ISBNs' or 'self-assigned ISBNs' but that's the sort of thing I was interested in doing. I doubt that's what I'll settle on, since there is already an apparent run on ISBN numbers.
should I retool everything for EAN numbers, or migrate off ISBNs as primary keys in general? if anyone has any experience with working with these systems, I'd love to hear about it, your advice is most welcome.
Hi,
in my app i need to open a website with the corresponding TLD for that country. Lets say google.com, google.de, etc...
But i don't know which country codes the're specifically using in NSLocale's dict. Can i assume that the lowercase version of NSLocaleCountryCode can be appended as TLD?
Regards, Erik
I am using Sql Server 2005
This is a part of my database diagram. I want to perform deletion on my database which will start from tblDomain up tp tblSubTopics.
Consider that each table has IsDeleted column which has to be marked true if request was made to delete data. But that data shoud remain their physically.
Tables which will have IsDeleted Column are
tblDomain
tblSubject
tblTopic
tblSubTopic
Now I want, if a user marks one domain as deleted then all the refrence field should also get marked as deleted. i.e.
1 domain is related to 5 subjects, those 5 subjects are related to 25 topics, those 25 topics are related to 500 subtopics and so on.
Then how should i mark all these fileds as Deleted. ?
Need help on this.
I'm just wondering why this error occurred. Below is the script concerned.
SELECT loc.ID
,loc.LocCode
,loc.LocName
,st.StateName
,reg.RegionName
,ctry.CountryName
,ISNULL(CONVERT(DATE, loc.UpdatedDate), CONVERT(DATE,loc.CreatedDate)) AS [ModifiedDate]
,stf.Name AS [ModifiedBy]
FROM Spkr_Country AS ctry WITH (NOLOCK)
INNER JOIN Spkr_Location AS loc WITH (NOLOCK) ON ctry.ID = loc.CountryID
INNER JOIN Spkr_State AS st WITH (NOLOCK) ON loc.StateID = st.ID
INNER JOIN Spkr_Region AS reg WITH (NOLOCK) ON loc.RegionID = reg.ID
INNER JOIN Staff AS stf ON ISNULL(loc.UpdatedBy, loc.CreatedBy) = stf.StaffId
WHERE (loc.IsActive = 1)
AND (
(@LocCode = '')
OR (
@LocCode <> ''
AND loc.LocCode LIKE @LocCode + '%'
)
)
AND (
(@RegionID < 1)
OR (
@RegionID > 0
AND loc.RegionID = @RegionID
)
)
AND (
(@StateID < 1)
OR (
@StateID > 0
AND loc.StateID = @StateID
)
)
AND (
(@CountryID < 1)
OR (
@CountryID > 0
AND loc.CountryID = @CountryID
)
)
The error probably occurred here INNER JOIN Staff AS stf ON ISNULL(loc.UpdatedBy, loc.CreatedBy) = stf.StaffId The requirement that I wanted is that if the loc.UpdatedBy is null, it will use the loc.CreatedBy column. However, when I used this, it generated the error mentioned.
In the database, the loc.CreatedBy is not null while the loc.UpdatedBy is nullable.
I checked it by running the script but it's working fine.
How do I do with it? What's wrong with my code? Please help.
I'm having some a little trouble understanding how to handle the database end of a program I'm making. I'm using an ORM in Kohana, but am hoping that a generalized understanding of how to solve this issue will lead me to an answer with the ORM.
I'm writing a program for users to manage their stock research information. My tables are basically like so:
CREATE TABLE tags(
id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
tags VARCHAR(30),
UNIQUE(tags)
)
ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE stock_tags(
id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
tag_id INT NOT NULL,
stock_id INT NOT NULL,
FOREIGN KEY (tag_id) REFERENCES tags(id),
FOREIGN KEY(stock_id) REFERENCES stocks(id) ON DELETE CASCADE
)
ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE notes(
id INT AUTO_INCREMENT NOT NULL,
stock_id INT NOT NULL,
notes TEXT NOT NULL,
FOREIGN KEY (stock_id) REFERENCES stocks(id) ON DELETE CASCADE,
PRIMARY KEY(id)
)
ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE links(
id INT AUTO_INCREMENT NOT NULL,
stock_id INT NOT NULL,
links VARCHAR(2083) NOT NULL,
FOREIGN KEY (stock_id) REFERENCES stocks(id) ON DELETE CASCADE,
PRIMARY KEY(id)
)
ENGINE=INNODB DEFAULT CHARSET=utf8;
How would I get all the attributes of a single stock, including its links, notes, and tags? Do I have to add links, notes, and tags columns to the stocks table and then how do you call it? I know this differs using an ORM and I'd assume that I can use join tables in SQL.
Thanks for any help, this will really help me understand the issue a lot better.
Okay I have two tables. They both have keys. I have another table that references both keys. How can I make a constraint when I add into that third if either of the keys don't exist in the first two tables it won't insert that tuple into the third table. I am inserting in phpMyAdmin. Thanks.
I'm using freerdp together with xmonad and it has been giving me a lot of trouble.
The super key (or "windows key") is my mod key in xmonad and it has been interfering with my freerdp usage rather annoyingly. Whenever I switched workspaces (or did anything else in xmonad involving the super key), windows (controlled by the freerdp instance in focus) registered a keypress as well. This event combined with the loss of focus got the super key stuck in windows indefinitely: the press of the keys d and r would first show my desktop, then open the run dialog (as if I was pressing the windows key constantly).
I've tried several versions of freerdp, but all exhibited this annoying behavior. So I resorted to patching freerdp myself to just ignore the left super key on my keyboard. I love free software for a lot of reasons (especially the ability to alter things like this myself), however I still find it annoying to patch and rebuild freerdp on all version (and dependency) changes.
How do you deal with situations like this? Is there even a "right way" to resolve this issue?
...apart from the obvious looping through the list and a dirty great case statement!
I've turned over a few Linq queries in my head but nothing seems to get anywhere close.
Here's the an example DTO if it helps:
class ClientCompany
{
public string Title { get; private set; }
public string Forenames { get; private set; }
public string Surname { get; private set; }
public string EmailAddress { get; private set; }
public string TelephoneNumber { get; private set; }
public string AlternativeTelephoneNumber { get; private set; }
public string Address1 { get; private set; }
public string Address2 { get; private set; }
public string TownOrDistrict { get; private set; }
public string CountyOrState { get; private set; }
public string PostCode { get; private set; }
}
We have no control over the fact that we're getting the data in as KV pairs, I'm afraid.
Hi,
I have this table:
id
feed_id
...
Let's say that I have 500 rows and I want to select 3 entries for each feed_id? And 50 as total limit.
How to write this SQL?
To keep myself interested, I try to put little Easter Eggs in my projects (mostly to amuse myself). I've seen some websites where you can type a series of letters "aswzaswz" and you get a "secret function" - how would I achieve this in C#?
I've assigned a "secret function" in the past by using modifier keys
bool showFunThing = (Control.ModifierKeys & Keys.Control) == Keys.Control;
but wanted to get a bit more secretive (without the modifier keys) I just wanted the form to detect a certain word typed without any input ... I've built a method that I think should do it:
private StringBuilder _pressedKeys = new StringBuilder();
protected override void OnKeyDown(KeyEventArgs e)
{
const string kWord = "fun";
char letter = (char)e.KeyValue;
if (!char.IsLetterOrDigit(letter))
{ return; }
_pressedKeys.Append(letter);
if (_pressedKeys.Length == kWord.Length)
{
if (_pressedKeys.ToString().ToLower() == kWord)
{
MessageBox.Show("Fun");
_pressedKeys.Clear();
}
}
base.OnKeyDown(e);
}
Now I need to wire it up but I can't figure out how I'm supposed to raise the event in the form designer ... I've tried this:
this.KeyDown +=new System.Windows.Forms.KeyEventHandler(OnKeyDown);
and a couple of variations on this but I'm missing something because it won't fire (or compile). It tells me that the OnKeyDown method is expecting a certain signature but I've got other methods like this where I haven't specified arguments.
I fear that I may have got myself confused so I am turning to SO for help ... anyone?
I am writing a recursive function to print out the differences between 2 multildimensional php arrays. The purpose of this code is to see the difference between jpeg headers to deteremine how adobe bridge cs3 is saving rating information within the jpg file.
When I am single-stepping through the code using my eclipse - zend debugger ide, it appears that even though the initial if statement is false (ie both values are arrays), the subsequent elseif statements are never executed. The function is attached below.
function array_diff_multi($array1,$array2,$level){
$keys = array_keys($array1);
foreach($keys as $key)
{
$value1 = $array1[$key];
if(array_key_exists($key,$array2) ){
$value2 = $array2[$key];
// Check if they are both arrays, if so recursion is needed
if (is_array($value1) && is_array($value2)){
array_diff_multi($value1,$value2,$level . "[ " . $key . " ]");
}
// the values aren't both arrays *** THE CODE IN THE ELSEIF BELOW IS NOT EXECUTED ***
elseif(is_array($value1) != is_array($value2)){
print "" . $level . $key ."=" . $value1 . "as array, compared to ". $value2 ."";
}
// the values don't match
elseif($value1 != $value2){
print "" . $level . $key ."=" . $value1 ." != " . $value2 ."";
}
else;
}
else{
print "" . $level. $key . "does not exist in array2";
}
}
}
How can I get some part of string that I need?
accountid=xxxxxx type=prem servertime=1256876305 addtime=1185548735 validuntil=1265012019 username=noob directstart=1 protectfiles=0 rsantihack=1 plustrafficmode=1 mirrors= jsconfig=1 [email protected] lots=0 fpoints=6076 ppoints=149 curfiles=38 curspace=3100655714 bodkb=60000000 premkbleft=25000000 ppointrate=116
I want data after email= but up to live.com.?
As a software engineer/programmer myself, I love the possibility to download the code and learn from it. However building software is what brings food to my table. I have doubts regarding the type of license I should use for my own personal projects or when picking up one project to learn from.
There are already many questions about licenses on Stackoverflow, but I would like to make this one much more specific. If your main profession and way of living is building software:
which type of license do you find more useful for you?
And I mean, the license that can benefit you most as a professional because it gives you more freedom to reuse the experience you gain.
GPL is a great license to build communities because it forces you to give back your work. However I like BSD licenses because of their extra freedom. I know that if the code I am exploring is BSD licensed, I might be able to expand not only my skills, but also my programmer toolbox. Whenever I am working for a company, I might recall that something similar was done in another project and I will be able to copy or imitate certain part of the code.
I know that there are religious wars regarding GPL vs BSD and it is not my intention to start one. Probably many companies already take snipsets from GPL projects anyway. I just want to insist in the factor of professional enrichment. I do not intend to discriminate any license. I said I prefer BSD licenses but I also use Linux because the user base is bigger and also the market demand.
Something quite odd is happening with y types and I quite dont understand if this is justified or not. I would tend to think not.
This code works fine :
type DictionarySingleton private () =
static let mutable instance = Dictionary<string*obj, obj>()
static member Instance = instance
let memoize (f:'a -> 'b) =
fun (x:'a) ->
let key = f.ToString(), (x :> obj)
if (DictionarySingleton.Instance).ContainsKey(key)
then let r = (DictionarySingleton.Instance).[key]
r :?> 'b
else
let res = f x
(DictionarySingleton.Instance).[key] <- (res :> obj)
res
And this ones complains
type DictionarySingleton private () =
static let mutable instance = Dictionary<string*obj, _>()
static member Instance = instance
let memoize (f:'a -> 'b) =
fun (x:'a) ->
let key = f.ToString(), (x :> obj)
if (DictionarySingleton.Instance).ContainsKey(key)
then let r = (DictionarySingleton.Instance).[key]
r :?> 'b
else
let res = f x
(DictionarySingleton.Instance).[key] <- (res :> obj)
res
The difference is only the underscore in the dictionary definition.
The infered types are the same, but the dynamic cast from r to type 'b exhibits an error.
'this runtime coercition ... runtime type tests are not allowed on some types, etc..'
Am I missing something or is it a rough edge ?
when I am editing a cell and press enter the next row is automatically selected, I want to stay with the current row... I want to happen nothing except the EndEdit.
I have this:
private void dtgProductos_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
dtgProductos[e.ColumnIndex, e.RowIndex].Selected = true; //this line is not working
var index = dtgProductos.SelectedRows[0].Cells.IndexOf(dtgProductos.SelectedRows[0].Cells[e.ColumnIndex]);
switch (index)
{
case 2:
{
dtgProductos.SelectedRows[0].Cells[4].Selected = true;
dtgProductos.BeginEdit(true);
}
break;
case 4:
{
dtgProductos.SelectedRows[0].Cells[5].Selected = true;
dtgProductos.BeginEdit(true);
}
break;
case 5:
{
btnAddProduct.Focus();
}
break;
default:
break;
}
}
so when I edit a row that is not the last one I get this error:
Operation is not valid because it results in a reentrant call to the SetCurrentCellAddressCore function.
Taking an example that is provided on the Fluent nHibernate website, I need to extend it slightly:
I need to add a 'Quantity' column to the StoreProduct table. How would I map this using nHibernate?
An example mapping is provided for the given scenario above, but I'm not sure how I would get the Quantity column to map:
public class StoreMap : ClassMap<Store>
{
public StoreMap()
{
Id(x => x.Id);
Map(x => x.Name);
HasMany(x => x.Employee)
.Inverse()
.Cascade.All();
HasManyToMany(x => x.Products)
.Cascade.All()
.Table("StoreProduct");
}
}