Search Results

Search found 2240 results on 90 pages for 'assert redirected to'.

Page 12/90 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • convincing C# compiler that execution will stop after a member returns

    - by Sarah Vessels
    I don't think this is currently possible or if it's even a good idea, but it's something I was thinking about just now. I use MSTest for unit testing my C# project. In one of my tests, I do the following: MyClass instance; try { instance = getValue(); } catch (MyException ex) { Assert.Fail("Caught MyException"); } instance.doStuff(); // Use of unassigned local variable 'instance' To make this code compile, I have to assign a value to instance either at its declaration or in the catch block. However, Assert.Fail will never, to the best of my knowledge, allow execution to proceed past it, hence instance will never be used without a value. Why is it then that I must assign a value to it? If I change the Assert.Fail to something like throw ex, the code compiles fine, I assume because it knows that exception will disallow execution to proceed to a point where instance would be used uninitialized. So is it a case of runtime versus compile-time knowledge about where execution will be allowed to proceed? Would it ever be reasonable for C# to have some way of saying that a member, in this case Assert.Fail, will never allow execution after it returns? Maybe that could be in the form of a method attribute. Would this be useful or an unnecessary complexity for the compiler?

    Read the article

  • Windows 7 dsound.dll load from dll crash

    - by Jonas Byström
    I'm getting a crash when loading dsound.dll from another DLL in Windows 7. The following code crashes: #include <Windows.h> #include <mmreg.h> #include <dsound.h> #include <assert.h> HRESULT (WINAPI *pDirectSoundEnumerateA)(LPDSENUMCALLBACKA pDSEnumCallback, LPVOID pContext); HMODULE hDsound; BOOL CALLBACK DSEnum(LPGUID a, LPCSTR b, LPCSTR c, LPVOID d) { return TRUE; } void CrashTest() { HRESULT hr; hDsound = LoadLibraryA("dsound.dll"); assert(hDsound); *(void**)&pDirectSoundEnumerateA = (void*)GetProcAddress(hDsound, "DirectSoundEnumerateA"); assert(pDirectSoundEnumerateA); hr = pDirectSoundEnumerateA(DSEnum, NULL); assert(!FAILED(hr)); } BOOL APIENTRY DllMain(HANDLE hModule,DWORD ul_reason_for_call,LPVOID lpReserved) { if (ul_reason_for_call == DLL_PROCESS_ATTACH) { DisableThreadLibraryCalls(hModule); CrashTest(); } } with this error code: Unhandled exception at ... in ...: 0xC0000005: Access violation reading location 0x00000044. (it's always 0x44 for some reason). It works on Windows XP or when loading directly from the .exe (not from a separate DLL). Help!?! :)

    Read the article

  • Why Can I Change Struct's int[] Property from Method Without Specifying "ref"?

    - by AMissico
    From a method, I can pass a struct which contains an array of integers, and change the values in the array. I am not sure I understand fully why I can do this. Can someone please explain why I can change the values stored in the int[]? private void DoIt(){ SearchInfo a = new SearchInfo(); a.Index = 1; a.Map = new int[] { 1 }; SearchInfo b = new SearchInfo(); b.Index = 1; b.Map = new int[] { 1 }; ModifyA(a); ModifyB(ref b); Debug.Assert(a.Index == 1); Debug.Assert(a.Map[0] == 1, "why did this change?"); Debug.Assert(b.Index == 99); Debug.Assert(b.Map[0] == 99); } void ModifyA(SearchInfo a) { a.Index = 99; a.Map[0] = 99; } void ModifyB(ref SearchInfo b) { b.Index = 99; b.Map[0] = 99; } struct SearchInfo { public int[] Map; public int Index; }

    Read the article

  • Managing logs/warnings in Python extensions

    - by Dimitri Tcaciuc
    TL;DR version: What do you use for configurable (and preferably captured) logging inside your C++ bits in a Python project? Details follow. Say you have a a few compiled .so modules that may need to do some error checking and warn user of (partially) incorrect data. Currently I'm having a pretty simplistic setup where I'm using logging framework from Python code and log4cxx library from C/C++. log4cxx log level is defined in a file (log4cxx.properties) and is currently fixed and I'm thinking how to make it more flexible. Couple of choices that I see: One way to control it would be to have a module-wide configuration call. # foo/__init__.py import sys from _foo import import bar, baz, configure_log configure_log(sys.stdout, WARNING) # tests/test_foo.py def test_foo(): # Maybe a custom context to change the logfile for # the module and restore it at the end. with CaptureLog(foo) as log: assert foo.bar() == 5 assert log.read() == "124.24 - foo - INFO - Bar returning 5" Have every compiled function that does logging accept optional log parameters. # foo.c int bar(PyObject* x, PyObject* logfile, PyObject* loglevel) { LoggerPtr logger = default_logger("foo"); if (logfile != Py_None) logger = file_logger(logfile, loglevel); ... } # tests/test_foo.py def test_foo(): with TemporaryFile() as logfile: assert foo.bar(logfile=logfile, loglevel=DEBUG) == 5 assert logfile.read() == "124.24 - foo - INFO - Bar returning 5" Some other way? Second one seems to be somewhat cleaner, but it requires function signature alteration (or using kwargs and parsing them). First one is.. probably somewhat awkward but sets up entire module in one go and removes logic from each individual function. What are your thoughts on this? I'm all ears to alternative solutions as well. Thanks,

    Read the article

  • Problem when copying array of different types using Arrays.copyOf

    - by Shervin
    I am trying to create a method that pretty much takes anything as a parameter, and returns a concatenated string representation of the value with some delimiter. public static String getConcatenated(char delim, Object ...names) { String[] stringArray = Arrays.copyOf(names, names.length, String[].class); //Exception here return getConcatenated(delim, stringArray); } And the actual method public static String getConcatenated(char delim, String ... names) { if(names == null || names.length == 0) return ""; StringBuilder sb = new StringBuilder(); for(int i = 0; i < names.length; i++) { String n = names[i]; if(n != null) { sb.append(n.trim()); sb.append(delim); } } //Remove the last delim return sb.substring(0, sb.length()-1).toString(); } And I have the following JUnit test: final String two = RedpillLinproUtils.getConcatenated(' ', "Shervin", "Asgari"); Assert.assertEquals("Result", "Shervin Asgari", two); //OK final String three = RedpillLinproUtils.getConcatenated(';', "Shervin", "Asgari"); Assert.assertEquals("Result", "Shervin;Asgari", three); //OK final String four = RedpillLinproUtils.getConcatenated(';', "Shervin", null, "Asgari", null); Assert.assertEquals("Result", "Shervin;Asgari", four); //OK final String five = RedpillLinproUtils.getConcatenated('/', 1, 2, null, 3, 4); Assert.assertEquals("Result", "1/2/3/4", five); //FAIL However, the test fails on the last part with the exception: java.lang.ArrayStoreException at java.lang.System.arraycopy(Native Method) at java.util.Arrays.copyOf(Arrays.java:2763) Can someone spot the error?

    Read the article

  • iPhone SpeakHere example produces different number of samples

    - by pion
    I am looking at the SpeakHere example and added the following: // Overriding the output audio route UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker; AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride); assert(status == noErr); // Changing the default output route. The new output route remains in effect unless you change the audio session category. This option is available starting in iPhone OS 3.1. UInt32 doChangeDefaultRoute = 1; status = AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof(doChangeDefaultRoute), &doChangeDefaultRoute); assert(status == noErr); // Enable Bluetooth. See audioRouteOverride & doChangeDefaultRoute above // http://developer.apple.com/iphone/library/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/Cookbook/Cookbook.html#//apple_ref/doc/uid/TP40007875-CH6-SW2 UInt32 allowBluetoothInput = 1; status = AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryEnableBluetoothInput, sizeof(allowBluetoothInput), &allowBluetoothInput); assert(status == noErr); Also, void AQRecorder::handleInputBufferCallback(void *aqData, ... ... if (inNumPackets > 0) { NSLog(@"Number of samples = %d", inBuffer->mAudioDataByteSize/2); // print out the number of sample status = AudioFileWritePackets(aqr->mAudioFile, FALSE, inBuffer->mAudioDataByteSize, inPacketDesc, aqr->mCurrentPacket, &inNumPackets, inBuffer->mAudioData); assert(status == noErr); aqr->mCurrentPacket += inNumPackets; } ... Notice the "NSLog(@"Number of samples = %d", inBuffer-mAudioDataByteSize/2); // print out the number of sample" statement above. I am using iPhone SDK 3.1.3. I got the following results The number of samples is around 44,100 on Simulator The number of samples is around 22,000 on iPhone The number of samples is around 4,000 on iPhone using Jawbone Bluetooth I am new on this. Why did itproduce different number of samples? Thanks in advance for your help.

    Read the article

  • Entity Framework: Auto-updating foreign key when setting a new object reference

    - by Adrian Grigore
    Hi, I am porting an existing application from Linq to SQL to Entity Framework 4 (default code generation). One difference I noticed between the two is that a foreign key property are not updated when resetting the object reference. Now I need to decide how to deal with this. For example supposing you have two entity types, Company and Employee. One Company has many Employees. In Linq To SQL, setting the company also sets the company id: var company=new Company(ID=1); var employee=new Employee(); Debug.Assert(employee.CompanyID==0); employee.Company=company; Debug.Assert(employee.CompanyID==1); //Works fine! In Entity Framework (and without using any code template customization) this does not work: var company=new Company(ID=1); var employee=new Employee(); Debug.Assert(employee.CompanyID==0); employee.Company=company; Debug.Assert(employee.CompanyID==1); //Throws, since CompanyID was not updated! How can I make EF behave the same way as LinqToSQL? I had a look at the default code generation T4 template, but I could not figure out how to make the necessary changes.

    Read the article

  • XPath _relative_ to given element in HTMLUnit/Groovy?

    - by Misha Koshelev
    Dear All: I would like to evaluate an XPath expression relative to a given element. I have been reading here: http://www.w3schools.com/xpath/default.asp And it seems like one of the syntaxes below should work (esp no leading slash or descendant:) However, none seem to work in HTMLUnit. Any help much appreciated (oh this is a groovy script btw). Thank you! http://htmlunit.sourceforge.net/ http://groovy.codehaus.org/ Misha #!/usr/bin/env groovy import com.gargoylesoftware.htmlunit.WebClient def html=""" <html><head><title>Test</title></head> <body> <div class='levelone'> <div class='leveltwo'> <div class='levelthree' /> </div> <div class='leveltwo'> <div class='levelthree' /> <div class='levelthree' /> </div> </div> </body> </html> """ def f=new File('/tmp/test.html') if (f.exists()) { f.delete() } def fos=new FileOutputStream(f) fos<<html def webClient=new WebClient() def page=webClient.getPage('file:///tmp/test.html') def element=page.getByXPath("//div[@class='levelone']") assert element.size()==1 element=page.getByXPath("div[@class='levelone']") assert element.size()==0 element=page.getByXPath("/div[@class='levelone']") assert element.size()==0 element=page.getByXPath("descendant:div[@class='levelone']") // this gives namespace error assert element.size()==0 Thank you!!!

    Read the article

  • problem with kCFSocketReadCallBack

    - by zp26
    Hello. I have a problem with my program. I created a socket with "kCFSocketReadCallBack. My intention was to call the "acceptCallback" only when it receives a string to the socket. Instead my program does not just accept the connection always goes into "startReceive" stop doing so and sometimes crash the program. Can anybody help? Thanks readSocket = CFSocketCreateWithNative( NULL, fd, kCFSocketReadCallBack, AcceptCallback, &context ); static void AcceptCallback(CFSocketRef s, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) // Called by CFSocket when someone connects to our listening socket. // This implementation just bounces the request up to Objective-C. { ServerVistaController * obj; #pragma unused(address) // assert(address == NULL); assert(data != NULL); obj = (ServerVistaController *) info; assert(obj != nil); #pragma unused(s) assert(s == obj->listeningSocket); if (type & kCFSocketAcceptCallBack){ [obj acceptConnection:*(int *)data]; } if (type & kCFSocketAcceptCallBack){ [obj startReceive:*(int *)data]; } } -(void)startReceive:(int)fd { CFReadStreamRef readStream = NULL; CFIndex bytes; UInt8 buffer[MAXLENGTH]; CFStreamCreatePairWithSocket( kCFAllocatorDefault, fd, &readStream, NULL); if(!readStream){ close(fd); [self updateLabel:@"No readStream"]; } CFReadStreamOpen(readStream); [self updateLabel:@"OpenStream"]; bytes = CFReadStreamRead( readStream, buffer, sizeof(buffer)); if (bytes < 0) { [self updateLabel:(NSString*)buffer]; close(fd); } CFReadStreamClose(readStream); }

    Read the article

  • Factorial function - design and test.

    - by lukas
    I'm trying to nail down some interview questions, so I stared with a simple one. Design the factorial function. This function is a leaf (no dependencies - easly testable), so I made it static inside the helper class. public static class MathHelper { public static int Factorial(int n) { Debug.Assert(n >= 0); if (n < 0) { throw new ArgumentException("n cannot be lower that 0"); } Debug.Assert(n <= 12); if (n > 12) { throw new OverflowException("Overflow occurs above 12 factorial"); } //by definition if (n == 0) { return 1; } int factorialOfN = 1; for (int i = 1; i <= n; ++i) { //checked //{ factorialOfN *= i; //} } return factorialOfN; } } Testing: [TestMethod] [ExpectedException(typeof(OverflowException))] public void Overflow() { int temp = FactorialHelper.MathHelper.Factorial(40); } [TestMethod] public void ZeroTest() { int factorialOfZero = FactorialHelper.MathHelper.Factorial(0); Assert.AreEqual(1, factorialOfZero); } [TestMethod] public void FactorialOf5() { int factOf5 = FactorialHelper.MathHelper.Factorial(5); Assert.AreEqual(120,factOf5); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void NegativeTest() { int factOfMinus5 = FactorialHelper.MathHelper.Factorial(-5); } I have a few questions: Is it correct? (I hope so ;) ) Does it throw right exceptions? Should I use checked context or this trick ( n 12 ) is ok? Is it better to use uint istead of checking for negative values? Future improving: Overload for long, decimal, BigInteger or maybe generic method? Thank you

    Read the article

  • Replacing symbol from object file at compile time. For example swapping out main

    - by Anthony Sottile
    Here's the use case: I have a .cpp file which has functions implemented in it. For sake of example say it has the following: [main.cpp] #include <iostream> int foo(int); int foo(int a) { return a * a; } int main() { for (int i = 0; i < 5; i += 1) { std::cout << foo(i) << std::endl; } return 0; } I want to perform some amount of automated testing on the function foo in this file but would need to replace out the main() function to do my testing. Preferably I'd like to have a separate file like this that I could link in over top of that one: [mymain.cpp] #include <iostream> #include <cassert> extern int foo(int); int main() { assert(foo(1) == 1); assert(foo(2) == 4); assert(foo(0) == 0); assert(foo(-2) == 4); return 0; } I'd like (if at all possible) to avoid changing the original .cpp file in order to do this -- though this would be my approach if this is not possible: do a replace for "(\s)main\s*\(" == "\1__oldmain\(" compile as usual. The environment I am targeting is a linux environment with g++.

    Read the article

  • Creating a Simple C# Wrapper to clean up code

    - by Tangopop
    I have this code: public void Contacts(string domainToBeTested, string[] browserList, string timeOut, int numberOfBrowsers) { verificationErrors = new StringBuilder(); for (int i = 0; i < numberOfBrowsers; i++) { ISelenium selenium = new DefaultSelenium("LMTS10", 4444, browserList[i], domainToBeTested); try { selenium.Start(); selenium.Open(domainToBeTested); selenium.Click("link=Email"); Assert.IsTrue(selenium.IsElementPresent("//div[@id='tabs-2']/p/a/strong")); selenium.Click("link=Address"); Assert.IsTrue(selenium.IsElementPresent("//div[@id='tabs-3']/p/strong")); selenium.Click("link=Telephone"); Assert.IsTrue(selenium.IsElementPresent("//div[@id='tabs-1']/ul/li/strong")); } catch (AssertionException e) { verificationErrors.AppendLine(browserList[i] + " :: " + e.Message); } finally { selenium.Stop(); } } Assert.AreEqual("", verificationErrors.ToString(), verificationErrors.ToString()); } My problem is i would like to make it so that i can use the code surrounding the 'try' many many times in the rest of the code. I think it has something to do with wrappers, but i can't get a simple answer for this from the web. So in simple terms the only piece of this code which changes is the bit between the try {} the rest is standard code that i have currently used over 100 times and is turning out to be a pain to maintain. Hope this is clear, many thanks.

    Read the article

  • Mocking the Unmockable: Using Microsoft Moles with Gallio

    - by Thomas Weller
    Usual opensource mocking frameworks (like e.g. Moq or Rhino.Mocks) can mock only interfaces and virtual methods. In contrary to that, Microsoft’s Moles framework can ‘mock’ virtually anything, in that it uses runtime instrumentation to inject callbacks in the method MSIL bodies of the moled methods. Therefore, it is possible to detour any .NET method, including non-virtual/static methods in sealed types. This can be extremely helpful when dealing e.g. with code that calls into the .NET framework, some third-party or legacy stuff etc… Some useful collected resources (links to website, documentation material and some videos) can be found in my toolbox on Delicious under this link: http://delicious.com/thomasweller/toolbox+moles A Gallio extension for Moles Originally, Moles is a part of Microsoft’s Pex framework and thus integrates best with Visual Studio Unit Tests (MSTest). However, the Moles sample download contains some additional assemblies to also support other unit test frameworks. They provide a Moled attribute to ease the usage of mole types with the respective framework (there are extensions for NUnit, xUnit.net and MbUnit v2 included with the samples). As there is no such extension for the Gallio platform, I did the few required lines myself – the resulting Gallio.Moles.dll is included with the sample download. With this little assembly in place, it is possible to use Moles with Gallio like that: [Test, Moled] public void SomeTest() {     ... What you can do with it Moles can be very helpful, if you need to ‘mock’ something other than a virtual or interface-implementing method. This might be the case when dealing with some third-party component, legacy code, or if you want to ‘mock’ the .NET framework itself. Generally, you need to announce each moled type that you want to use in a test with the MoledType attribute on assembly level. For example: [assembly: MoledType(typeof(System.IO.File))] Below are some typical use cases for Moles. For a more detailed overview (incl. naming conventions and an instruction on how to create the required moles assemblies), please refer to the reference material above.  Detouring the .NET framework Imagine that you want to test a method similar to the one below, which internally calls some framework method:   public void ReadFileContent(string fileName) {     this.FileContent = System.IO.File.ReadAllText(fileName); } Using a mole, you would replace the call to the File.ReadAllText(string) method with a runtime delegate like so: [Test, Moled] [Description("This 'mocks' the System.IO.File class with a custom delegate.")] public void ReadFileContentWithMoles() {     // arrange ('mock' the FileSystem with a delegate)     System.IO.Moles.MFile.ReadAllTextString = (fname => fname == FileName ? FileContent : "WrongFileName");       // act     var testTarget = new TestTarget.TestTarget();     testTarget.ReadFileContent(FileName);       // assert     Assert.AreEqual(FileContent, testTarget.FileContent); } Detouring static methods and/or classes A static method like the below… public static string StaticMethod(int x, int y) {     return string.Format("{0}{1}", x, y); } … can be ‘mocked’ with the following: [Test, Moled] public void StaticMethodWithMoles() {     MStaticClass.StaticMethodInt32Int32 = ((x, y) => "uups");       var result = StaticClass.StaticMethod(1, 2);       Assert.AreEqual("uups", result); } Detouring constructors You can do this delegate thing even with a class’ constructor. The syntax for this is not all  too intuitive, because you have to setup the internal state of the mole, but generally it works like a charm. For example, to replace this c’tor… public class ClassWithCtor {     public int Value { get; private set; }       public ClassWithCtor(int someValue)     {         this.Value = someValue;     } } … you would do the following: [Test, Moled] public void ConstructorTestWithMoles() {     MClassWithCtor.ConstructorInt32 =            ((@class, @value) => new MClassWithCtor(@class) {ValueGet = () => 99});       var classWithCtor = new ClassWithCtor(3);       Assert.AreEqual(99, classWithCtor.Value); } Detouring abstract base classes You can also use this approach to ‘mock’ abstract base classes of a class that you call in your test. Assumed that you have something like that: public abstract class AbstractBaseClass {     public virtual string SaySomething()     {         return "Hello from base.";     } }      public class ChildClass : AbstractBaseClass {     public override string SaySomething()     {         return string.Format(             "Hello from child. Base says: '{0}'",             base.SaySomething());     } } Then you would set up the child’s underlying base class like this: [Test, Moled] public void AbstractBaseClassTestWithMoles() {     ChildClass child = new ChildClass();     new MAbstractBaseClass(child)         {                 SaySomething = () => "Leave me alone!"         }         .InstanceBehavior = MoleBehaviors.Fallthrough;       var hello = child.SaySomething();       Assert.AreEqual("Hello from child. Base says: 'Leave me alone!'", hello); } Setting the moles behavior to a value of  MoleBehaviors.Fallthrough causes the ‘original’ method to be called if a respective delegate is not provided explicitly – here it causes the ChildClass’ override of the SaySomething() method to be called. There are some more possible scenarios, where the Moles framework could be of much help (e.g. it’s also possible to detour interface implementations like IEnumerable<T> and such…). One other possibility that comes to my mind (because I’m currently dealing with that), is to replace calls from repository classes to the ADO.NET Entity Framework O/R mapper with delegates to isolate the repository classes from the underlying database, which otherwise would not be possible… Usage Since Moles relies on runtime instrumentation, mole types must be run under the Pex profiler. This only works from inside Visual Studio if you write your tests with MSTest (Visual Studio Unit Test). While other unit test frameworks generally can be used with Moles, they require the respective tests to be run via command line, executed through the moles.runner.exe tool. A typical test execution would be similar to this: moles.runner.exe <mytests.dll> /runner:<myframework.console.exe> /args:/<myargs> So, the moled test can be run through tools like NCover or a scripting tool like MSBuild (which makes them easy to run in a Continuous Integration environment), but they are somewhat unhandy to run in the usual TDD workflow (which I described in some detail here). To make this a bit more fluent, I wrote a ReSharper live template to generate the respective command line for the test (it is also included in the sample download – moled_cmd.xml). - This is just a quick-and-dirty ‘solution’. Maybe it makes sense to write an extra Gallio adapter plugin (similar to the many others that are already provided) and include it with the Gallio download package, if  there’s sufficient demand for it. As of now, the only way to run tests with the Moles framework from within Visual Studio is by using them with MSTest. From the command line, anything with a managed console runner can be used (provided that the appropriate extension is in place)… A typical Gallio/Moles command line (as generated by the mentioned R#-template) looks like that: "%ProgramFiles%\Microsoft Moles\bin\moles.runner.exe" /runner:"%ProgramFiles%\Gallio\bin\Gallio.Echo.exe" "Gallio.Moles.Demo.dll" /args:/r:IsolatedAppDomain /args:/filter:"ExactType:TestFixture and Member:ReadFileContentWithMoles" -- Note: When using the command line with Echo (Gallio’s console runner), be sure to always include the IsolatedAppDomain option, otherwise the tests won’t use the instrumentation callbacks! -- License issues As I already said, the free mocking frameworks can mock only interfaces and virtual methods. if you want to mock other things, you need the Typemock Isolator tool for that, which comes with license costs (Although these ‘costs’ are ridiculously low compared to the value that such a tool can bring to a software project, spending money often is a considerable gateway hurdle in real life...).  The Moles framework also is not totally free, but comes with the same license conditions as the (closely related) Pex framework: It is free for academic/non-commercial use only, to use it in a ‘real’ software project requires an MSDN Subscription (from VS2010pro on). The demo solution The sample solution (VS 2008) can be downloaded from here. It contains the Gallio.Moles.dll which provides the here described Moled attribute, the above mentioned R#-template (moled_cmd.xml) and a test fixture containing the above described use case scenarios. To run it, you need the Gallio framework (download) and Microsoft Moles (download) being installed in the default locations. Happy testing…

    Read the article

  • [C++] A minimalistic smart array (container) class template

    - by legends2k
    I've written a (array) container class template (lets call it smart array) for using it in the BREW platform (which doesn't allow many C++ constructs like STD library, exceptions, etc. It has a very minimal C++ runtime support); while writing this my friend said that something like this already exists in Boost called MultiArray, I tried it but the ARM compiler (RVCT) cries with 100s of errors. I've not seen Boost.MultiArray's source, I've just started learning template only lately; template meta programming interests me a lot, although am not sure if this is strictly one, which can be categorised thus. So I want all my fellow C++ aficionados to review it ~ point out flaws, potential bugs, suggestions, optimisations, etc.; somthing like "you've not written your own Big Three which might lead to...". Possibly any criticism that'll help me improve this class and thereby my C++ skills. smart_array.h #include <vector> using std::vector; template <typename T, size_t N> class smart_array { vector < smart_array<T, N - 1> > vec; public: explicit smart_array(vector <size_t> &dimensions) { assert(N == dimensions.size()); vector <size_t>::iterator it = ++dimensions.begin(); vector <size_t> dimensions_remaining(it, dimensions.end()); smart_array <T, N - 1> temp_smart_array(dimensions_remaining); vec.assign(dimensions[0], temp_smart_array); } explicit smart_array(size_t dimension_1 = 1, ...) { static_assert(N > 0, "Error: smart_array expects 1 or more dimension(s)"); assert(dimension_1 > 1); va_list dim_list; vector <size_t> dimensions_remaining(N - 1); va_start(dim_list, dimension_1); for(size_t i = 0; i < N - 1; ++i) { size_t dimension_n = va_arg(dim_list, size_t); assert(dimension_n > 0); dimensions_remaining[i] = dimension_n; } va_end(dim_list); smart_array <T, N - 1> temp_smart_array(dimensions_remaining); vec.assign(dimension_1, temp_smart_array); } smart_array<T, N - 1>& operator[](size_t index) { assert(index < vec.size() && index >= 0); return vec[index]; } size_t length() const { return vec.size(); } }; template<typename T> class smart_array<T, 1> { vector <T> vec; public: explicit smart_array(vector <size_t> &dimension) : vec(dimension[0]) { assert(dimension[0] > 0); } explicit smart_array(size_t dimension_1 = 1) : vec(dimension_1) { assert(dimension_1 > 0); } T& operator[](size_t index) { assert(index < vec.size() && index >= 0); return vec[index]; } size_t length() { return vec.size(); } }; Sample Usage: #include <iostream> using std::cout; using std::endl; int main() { // testing 1 dimension smart_array <int, 1> x(3); x[0] = 0, x[1] = 1, x[2] = 2; cout << "x.length(): " << x.length() << endl; // testing 2 dimensions smart_array <float, 2> y(2, 3); y[0][0] = y[0][1] = y[0][2] = 0; y[1][0] = y[1][1] = y[1][2] = 1; cout << "y.length(): " << y.length() << endl; cout << "y[0].length(): " << y[0].length() << endl; // testing 3 dimensions smart_array <char, 3> z(2, 4, 5); cout << "z.length(): " << z.length() << endl; cout << "z[0].length(): " << z[0].length() << endl; cout << "z[0][0].length(): " << z[0][0].length() << endl; z[0][0][4] = 'c'; cout << z[0][0][4] << endl; // testing 4 dimensions smart_array <bool, 4> r(2, 3, 4, 5); cout << "z.length(): " << r.length() << endl; cout << "z[0].length(): " << r[0].length() << endl; cout << "z[0][0].length(): " << r[0][0].length() << endl; cout << "z[0][0][0].length(): " << r[0][0][0].length() << endl; // testing copy constructor smart_array <float, 2> copy_y(y); cout << "copy_y.length(): " << copy_y.length() << endl; cout << "copy_x[0].length(): " << copy_y[0].length() << endl; cout << copy_y[0][0] << "\t" << copy_y[1][0] << "\t" << copy_y[0][1] << "\t" << copy_y[1][1] << "\t" << copy_y[0][2] << "\t" << copy_y[1][2] << endl; return 0; }

    Read the article

  • A minimalistic smart array (container) class template

    - by legends2k
    I've written a (array) container class template (lets call it smart array) for using it in the BREW platform (which doesn't allow many C++ constructs like STD library, exceptions, etc. It has a very minimal C++ runtime support); while writing this my friend said that something like this already exists in Boost called MultiArray, I tried it but the ARM compiler (RVCT) cries with 100s of errors. I've not seen Boost.MultiArray's source, I've started learning templates only lately; template meta programming interests me a lot, although am not sure if this is strictly one that can be categorized thus. So I want all my fellow C++ aficionados to review it ~ point out flaws, potential bugs, suggestions, optimizations, etc.; something like "you've not written your own Big Three which might lead to...". Possibly any criticism that will help me improve this class and thereby my C++ skills. Edit: I've used std::vector since it's easily understood, later it will be replaced by a custom written vector class template made to work in the BREW platform. Also C++0x related syntax like static_assert will also be removed in the final code. smart_array.h #include <vector> #include <cassert> #include <cstdarg> using std::vector; template <typename T, size_t N> class smart_array { vector < smart_array<T, N - 1> > vec; public: explicit smart_array(vector <size_t> &dimensions) { assert(N == dimensions.size()); vector <size_t>::iterator it = ++dimensions.begin(); vector <size_t> dimensions_remaining(it, dimensions.end()); smart_array <T, N - 1> temp_smart_array(dimensions_remaining); vec.assign(dimensions[0], temp_smart_array); } explicit smart_array(size_t dimension_1 = 1, ...) { static_assert(N > 0, "Error: smart_array expects 1 or more dimension(s)"); assert(dimension_1 > 1); va_list dim_list; vector <size_t> dimensions_remaining(N - 1); va_start(dim_list, dimension_1); for(size_t i = 0; i < N - 1; ++i) { size_t dimension_n = va_arg(dim_list, size_t); assert(dimension_n > 0); dimensions_remaining[i] = dimension_n; } va_end(dim_list); smart_array <T, N - 1> temp_smart_array(dimensions_remaining); vec.assign(dimension_1, temp_smart_array); } smart_array<T, N - 1>& operator[](size_t index) { assert(index < vec.size() && index >= 0); return vec[index]; } size_t length() const { return vec.size(); } }; template<typename T> class smart_array<T, 1> { vector <T> vec; public: explicit smart_array(vector <size_t> &dimension) : vec(dimension[0]) { assert(dimension[0] > 0); } explicit smart_array(size_t dimension_1 = 1) : vec(dimension_1) { assert(dimension_1 > 0); } T& operator[](size_t index) { assert(index < vec.size() && index >= 0); return vec[index]; } size_t length() { return vec.size(); } }; Sample Usage: #include "smart_array.h" #include <iostream> using std::cout; using std::endl; int main() { // testing 1 dimension smart_array <int, 1> x(3); x[0] = 0, x[1] = 1, x[2] = 2; cout << "x.length(): " << x.length() << endl; // testing 2 dimensions smart_array <float, 2> y(2, 3); y[0][0] = y[0][1] = y[0][2] = 0; y[1][0] = y[1][1] = y[1][2] = 1; cout << "y.length(): " << y.length() << endl; cout << "y[0].length(): " << y[0].length() << endl; // testing 3 dimensions smart_array <char, 3> z(2, 4, 5); cout << "z.length(): " << z.length() << endl; cout << "z[0].length(): " << z[0].length() << endl; cout << "z[0][0].length(): " << z[0][0].length() << endl; z[0][0][4] = 'c'; cout << z[0][0][4] << endl; // testing 4 dimensions smart_array <bool, 4> r(2, 3, 4, 5); cout << "z.length(): " << r.length() << endl; cout << "z[0].length(): " << r[0].length() << endl; cout << "z[0][0].length(): " << r[0][0].length() << endl; cout << "z[0][0][0].length(): " << r[0][0][0].length() << endl; // testing copy constructor smart_array <float, 2> copy_y(y); cout << "copy_y.length(): " << copy_y.length() << endl; cout << "copy_x[0].length(): " << copy_y[0].length() << endl; cout << copy_y[0][0] << "\t" << copy_y[1][0] << "\t" << copy_y[0][1] << "\t" << copy_y[1][1] << "\t" << copy_y[0][2] << "\t" << copy_y[1][2] << endl; return 0; }

    Read the article

  • An Xml Serializable PropertyBag Dictionary Class for .NET

    - by Rick Strahl
    I don't know about you but I frequently need property bags in my applications to store and possibly cache arbitrary data. Dictionary<T,V> works well for this although I always seem to be hunting for a more specific generic type that provides a string key based dictionary. There's string dictionary, but it only works with strings. There's Hashset<T> but it uses the actual values as keys. In most key value pair situations for me string is key value to work off. Dictionary<T,V> works well enough, but there are some issues with serialization of dictionaries in .NET. The .NET framework doesn't do well serializing IDictionary objects out of the box. The XmlSerializer doesn't support serialization of IDictionary via it's default serialization, and while the DataContractSerializer does support IDictionary serialization it produces some pretty atrocious XML. What doesn't work? First off Dictionary serialization with the Xml Serializer doesn't work so the following fails: [TestMethod] public void DictionaryXmlSerializerTest() { var bag = new Dictionary<string, object>(); bag.Add("key", "Value"); bag.Add("Key2", 100.10M); bag.Add("Key3", Guid.NewGuid()); bag.Add("Key4", DateTime.Now); bag.Add("Key5", true); bag.Add("Key7", new byte[3] { 42, 45, 66 }); TestContext.WriteLine(this.ToXml(bag)); } public string ToXml(object obj) { if (obj == null) return null; StringWriter sw = new StringWriter(); XmlSerializer ser = new XmlSerializer(obj.GetType()); ser.Serialize(sw, obj); return sw.ToString(); } The error you get with this is: System.NotSupportedException: The type System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] is not supported because it implements IDictionary. Got it! BTW, the same is true with binary serialization. Running the same code above against the DataContractSerializer does work: [TestMethod] public void DictionaryDataContextSerializerTest() { var bag = new Dictionary<string, object>(); bag.Add("key", "Value"); bag.Add("Key2", 100.10M); bag.Add("Key3", Guid.NewGuid()); bag.Add("Key4", DateTime.Now); bag.Add("Key5", true); bag.Add("Key7", new byte[3] { 42, 45, 66 }); TestContext.WriteLine(this.ToXmlDcs(bag)); } public string ToXmlDcs(object value, bool throwExceptions = false) { var ser = new DataContractSerializer(value.GetType(), null, int.MaxValue, true, false, null); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, value); return Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length); } This DOES work but produces some pretty heinous XML (formatted with line breaks and indentation here): <ArrayOfKeyValueOfstringanyType xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <KeyValueOfstringanyType> <Key>key</Key> <Value i:type="a:string" xmlns:a="http://www.w3.org/2001/XMLSchema">Value</Value> </KeyValueOfstringanyType> <KeyValueOfstringanyType> <Key>Key2</Key> <Value i:type="a:decimal" xmlns:a="http://www.w3.org/2001/XMLSchema">100.10</Value> </KeyValueOfstringanyType> <KeyValueOfstringanyType> <Key>Key3</Key> <Value i:type="a:guid" xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/">2cd46d2a-a636-4af4-979b-e834d39b6d37</Value> </KeyValueOfstringanyType> <KeyValueOfstringanyType> <Key>Key4</Key> <Value i:type="a:dateTime" xmlns:a="http://www.w3.org/2001/XMLSchema">2011-09-19T17:17:05.4406999-07:00</Value> </KeyValueOfstringanyType> <KeyValueOfstringanyType> <Key>Key5</Key> <Value i:type="a:boolean" xmlns:a="http://www.w3.org/2001/XMLSchema">true</Value> </KeyValueOfstringanyType> <KeyValueOfstringanyType> <Key>Key7</Key> <Value i:type="a:base64Binary" xmlns:a="http://www.w3.org/2001/XMLSchema">Ki1C</Value> </KeyValueOfstringanyType> </ArrayOfKeyValueOfstringanyType> Ouch! That seriously hurts the eye! :-) Worse though it's extremely verbose with all those repetitive namespace declarations. It's good to know that it works in a pinch, but for a human readable/editable solution or something lightweight to store in a database it's not quite ideal. Why should I care? As a little background, in one of my applications I have a need for a flexible property bag that is used on a free form database field on an otherwise static entity. Basically what I have is a standard database record to which arbitrary properties can be added in an XML based string field. I intend to expose those arbitrary properties as a collection from field data stored in XML. The concept is pretty simple: When loading write the data to the collection, when the data is saved serialize the data into an XML string and store it into the database. When reading the data pick up the XML and if the collection on the entity is accessed automatically deserialize the XML into the Dictionary. (I'll talk more about this in another post). While the DataContext Serializer would work, it's verbosity is problematic both for size of the generated XML strings and the fact that users can manually edit this XML based property data in an advanced mode. A clean(er) layout certainly would be preferable and more user friendly. Custom XMLSerialization with a PropertyBag Class So… after a bunch of experimentation with different serialization formats I decided to create a custom PropertyBag class that provides for a serializable Dictionary. It's basically a custom Dictionary<TType,TValue> implementation with the keys always set as string keys. The result are PropertyBag<TValue> and PropertyBag (which defaults to the object type for values). The PropertyBag<TType> and PropertyBag classes provide these features: Subclassed from Dictionary<T,V> Implements IXmlSerializable with a cleanish XML format ToXml() and FromXml() methods to export and import to and from XML strings Static CreateFromXml() method to create an instance It's simple enough as it's merely a Dictionary<string,object> subclass but that supports serialization to a - what I think at least - cleaner XML format. The class is super simple to use: [TestMethod] public void PropertyBagTwoWayObjectSerializationTest() { var bag = new PropertyBag(); bag.Add("key", "Value"); bag.Add("Key2", 100.10M); bag.Add("Key3", Guid.NewGuid()); bag.Add("Key4", DateTime.Now); bag.Add("Key5", true); bag.Add("Key7", new byte[3] { 42,45,66 } ); bag.Add("Key8", null); bag.Add("Key9", new ComplexObject() { Name = "Rick", Entered = DateTime.Now, Count = 10 }); string xml = bag.ToXml(); TestContext.WriteLine(bag.ToXml()); bag.Clear(); bag.FromXml(xml); Assert.IsTrue(bag["key"] as string == "Value"); Assert.IsInstanceOfType( bag["Key3"], typeof(Guid)); Assert.IsNull(bag["Key8"]); //Assert.IsNull(bag["Key10"]); Assert.IsInstanceOfType(bag["Key9"], typeof(ComplexObject)); } This uses the PropertyBag class which uses a PropertyBag<string,object> - which means it returns untyped values of type object. I suspect for me this will be the most common scenario as I'd want to store arbitrary values in the PropertyBag rather than one specific type. The same code with a strongly typed PropertyBag<decimal> looks like this: [TestMethod] public void PropertyBagTwoWayValueTypeSerializationTest() { var bag = new PropertyBag<decimal>(); bag.Add("key", 10M); bag.Add("Key1", 100.10M); bag.Add("Key2", 200.10M); bag.Add("Key3", 300.10M); string xml = bag.ToXml(); TestContext.WriteLine(bag.ToXml()); bag.Clear(); bag.FromXml(xml); Assert.IsTrue(bag.Get("Key1") == 100.10M); Assert.IsTrue(bag.Get("Key3") == 300.10M); } and produces typed results of type decimal. The types can be either value or reference types the combination of which actually proved to be a little more tricky than anticipated due to null and specific string value checks required - getting the generic typing right required use of default(T) and Convert.ChangeType() to trick the compiler into playing nice. Of course the whole raison d'etre for this class is the XML serialization. You can see in the code above that we're doing a .ToXml() and .FromXml() to serialize to and from string. The XML produced for the first example looks like this: <?xml version="1.0" encoding="utf-8"?> <properties> <item> <key>key</key> <value>Value</value> </item> <item> <key>Key2</key> <value type="decimal">100.10</value> </item> <item> <key>Key3</key> <value type="___System.Guid"> <guid>f7a92032-0c6d-4e9d-9950-b15ff7cd207d</guid> </value> </item> <item> <key>Key4</key> <value type="datetime">2011-09-26T17:45:58.5789578-10:00</value> </item> <item> <key>Key5</key> <value type="boolean">true</value> </item> <item> <key>Key7</key> <value type="base64Binary">Ki1C</value> </item> <item> <key>Key8</key> <value type="nil" /> </item> <item> <key>Key9</key> <value type="___Westwind.Tools.Tests.PropertyBagTest+ComplexObject"> <ComplexObject> <Name>Rick</Name> <Entered>2011-09-26T17:45:58.5789578-10:00</Entered> <Count>10</Count> </ComplexObject> </value> </item> </properties>   The format is a bit cleaner than the DataContractSerializer. Each item is serialized into <key> <value> pairs. If the value is a string no type information is written. Since string tends to be the most common type this saves space and serialization processing. All other types are attributed. Simple types are mapped to XML types so things like decimal, datetime, boolean and base64Binary are encoded using their Xml type values. All other types are embedded with a hokey format that describes the .NET type preceded by a three underscores and then are encoded using the XmlSerializer. You can see this best above in the ComplexObject encoding. For custom types this isn't pretty either, but it's more concise than the DCS and it works as long as you're serializing back and forth between .NET clients at least. The XML generated from the second example that uses PropertyBag<decimal> looks like this: <?xml version="1.0" encoding="utf-8"?> <properties> <item> <key>key</key> <value type="decimal">10</value> </item> <item> <key>Key1</key> <value type="decimal">100.10</value> </item> <item> <key>Key2</key> <value type="decimal">200.10</value> </item> <item> <key>Key3</key> <value type="decimal">300.10</value> </item> </properties>   How does it work As I mentioned there's nothing fancy about this solution - it's little more than a subclass of Dictionary<T,V> that implements custom Xml Serialization and a couple of helper methods that facilitate getting the XML in and out of the class more easily. But it's proven very handy for a number of projects for me where dynamic data storage is required. Here's the code: /// <summary> /// Creates a serializable string/object dictionary that is XML serializable /// Encodes keys as element names and values as simple values with a type /// attribute that contains an XML type name. Complex names encode the type /// name with type='___namespace.classname' format followed by a standard xml /// serialized format. The latter serialization can be slow so it's not recommended /// to pass complex types if performance is critical. /// </summary> [XmlRoot("properties")] public class PropertyBag : PropertyBag<object> { /// <summary> /// Creates an instance of a propertybag from an Xml string /// </summary> /// <param name="xml">Serialize</param> /// <returns></returns> public static PropertyBag CreateFromXml(string xml) { var bag = new PropertyBag(); bag.FromXml(xml); return bag; } } /// <summary> /// Creates a serializable string for generic types that is XML serializable. /// /// Encodes keys as element names and values as simple values with a type /// attribute that contains an XML type name. Complex names encode the type /// name with type='___namespace.classname' format followed by a standard xml /// serialized format. The latter serialization can be slow so it's not recommended /// to pass complex types if performance is critical. /// </summary> /// <typeparam name="TValue">Must be a reference type. For value types use type object</typeparam> [XmlRoot("properties")] public class PropertyBag<TValue> : Dictionary<string, TValue>, IXmlSerializable { /// <summary> /// Not implemented - this means no schema information is passed /// so this won't work with ASMX/WCF services. /// </summary> /// <returns></returns> public System.Xml.Schema.XmlSchema GetSchema() { return null; } /// <summary> /// Serializes the dictionary to XML. Keys are /// serialized to element names and values as /// element values. An xml type attribute is embedded /// for each serialized element - a .NET type /// element is embedded for each complex type and /// prefixed with three underscores. /// </summary> /// <param name="writer"></param> public void WriteXml(System.Xml.XmlWriter writer) { foreach (string key in this.Keys) { TValue value = this[key]; Type type = null; if (value != null) type = value.GetType(); writer.WriteStartElement("item"); writer.WriteStartElement("key"); writer.WriteString(key as string); writer.WriteEndElement(); writer.WriteStartElement("value"); string xmlType = XmlUtils.MapTypeToXmlType(type); bool isCustom = false; // Type information attribute if not string if (value == null) { writer.WriteAttributeString("type", "nil"); } else if (!string.IsNullOrEmpty(xmlType)) { if (xmlType != "string") { writer.WriteStartAttribute("type"); writer.WriteString(xmlType); writer.WriteEndAttribute(); } } else { isCustom = true; xmlType = "___" + value.GetType().FullName; writer.WriteStartAttribute("type"); writer.WriteString(xmlType); writer.WriteEndAttribute(); } // Actual deserialization if (!isCustom) { if (value != null) writer.WriteValue(value); } else { XmlSerializer ser = new XmlSerializer(value.GetType()); ser.Serialize(writer, value); } writer.WriteEndElement(); // value writer.WriteEndElement(); // item } } /// <summary> /// Reads the custom serialized format /// </summary> /// <param name="reader"></param> public void ReadXml(System.Xml.XmlReader reader) { this.Clear(); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "key") { string xmlType = null; string name = reader.ReadElementContentAsString(); // item element reader.ReadToNextSibling("value"); if (reader.MoveToNextAttribute()) xmlType = reader.Value; reader.MoveToContent(); TValue value; if (xmlType == "nil") value = default(TValue); // null else if (string.IsNullOrEmpty(xmlType)) { // value is a string or object and we can assign TValue to value string strval = reader.ReadElementContentAsString(); value = (TValue) Convert.ChangeType(strval, typeof(TValue)); } else if (xmlType.StartsWith("___")) { while (reader.Read() && reader.NodeType != XmlNodeType.Element) { } Type type = ReflectionUtils.GetTypeFromName(xmlType.Substring(3)); //value = reader.ReadElementContentAs(type,null); XmlSerializer ser = new XmlSerializer(type); value = (TValue)ser.Deserialize(reader); } else value = (TValue)reader.ReadElementContentAs(XmlUtils.MapXmlTypeToType(xmlType), null); this.Add(name, value); } } } /// <summary> /// Serializes this dictionary to an XML string /// </summary> /// <returns>XML String or Null if it fails</returns> public string ToXml() { string xml = null; SerializationUtils.SerializeObject(this, out xml); return xml; } /// <summary> /// Deserializes from an XML string /// </summary> /// <param name="xml"></param> /// <returns>true or false</returns> public bool FromXml(string xml) { this.Clear(); // if xml string is empty we return an empty dictionary if (string.IsNullOrEmpty(xml)) return true; var result = SerializationUtils.DeSerializeObject(xml, this.GetType()) as PropertyBag<TValue>; if (result != null) { foreach (var item in result) { this.Add(item.Key, item.Value); } } else // null is a failure return false; return true; } /// <summary> /// Creates an instance of a propertybag from an Xml string /// </summary> /// <param name="xml"></param> /// <returns></returns> public static PropertyBag<TValue> CreateFromXml(string xml) { var bag = new PropertyBag<TValue>(); bag.FromXml(xml); return bag; } } } The code uses a couple of small helper classes SerializationUtils and XmlUtils for mapping Xml types to and from .NET, both of which are from the WestWind,Utilities project (which is the same project where PropertyBag lives) from the West Wind Web Toolkit. The code implements ReadXml and WriteXml for the IXmlSerializable implementation using old school XmlReaders and XmlWriters (because it's pretty simple stuff - no need for XLinq here). Then there are two helper methods .ToXml() and .FromXml() that basically allow your code to easily convert between XML and a PropertyBag object. In my code that's what I use to actually to persist to and from the entity XML property during .Load() and .Save() operations. It's sweet to be able to have a string key dictionary and then be able to turn around with 1 line of code to persist the whole thing to XML and back. Hopefully some of you will find this class as useful as I've found it. It's a simple solution to a common requirement in my applications and I've used the hell out of it in the  short time since I created it. Resources You can find the complete code for the two classes plus the helpers in the Subversion repository for Westwind.Utilities. You can grab the source files from there or download the whole project. You can also grab the full Westwind.Utilities assembly from NuGet and add it to your project if that's easier for you. PropertyBag Source Code SerializationUtils and XmlUtils Westwind.Utilities Assembly on NuGet (add from Visual Studio) © Rick Strahl, West Wind Technologies, 2005-2011Posted in .NET  CSharp   Tweet (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • varnish3, mod_geoip with apache2 using mod_rewrite and mod_rpaf

    - by mursalat
    I am maintaining a website with 3 different versions of the site, with 3 different languages, handles with a single system written in php, which takes in environment variables based on the domain name that is being accessed. These are the three sites: myshop.com : english international version myshop.eu : european version of site myshop.ru : russian version of the site when myshop.com is accessed from russia it is to be redirected to myshop.ru, and any country from europe accesses myshop.com, is redirected to myshop.eu, and international visitors stay at myshop.com, although they can go to the country specific site. All these redirections for the country is done using GeoIP apache2 mod in order to determine the country code, which is used in a RewriteCondition to state a RewriteRule, there are some exceptions of IPs that do not do the rewrite for, basically the IPs of the developer's PCs. The site has been doing just fine, until we decided to setup varnish to give the site a boost, it really did give it a great boost, but the country specific rewrites has become buggy. What started to happen is that a russian visitor can go to myshop.com and won't be redirected, until he clicks a random link (perhaps a link not cached by varnish yet) and the user is redirected to their specific country. For that i setup mod_rpaf, and for exceptions to the rewrite rule (for the developer's ip), i used this RewriteCond %{HTTP:X-FORWARDED-FOR} !^43\.43\.43\.43, and i restarted varnish and apache2, it worked for a while, then it messed up again. And whole day i have been doing changes however i have little no clue as to what's going on, sometimes it works, and sometimes it doesn't, and sometimes it half works, etc... As for geoip, i used a php to check the $_SERVER variable, and here is the general idea of the output [HTTP_X_FORWARDED_FOR] => 43.43.43.44 [HTTP_X_VARNISH] => 1705675599 [SERVER_ADDR] => 127.0.0.1 [SERVER_PORT] => 80 [REMOTE_ADDR] => 43.43.43.44 [GEOIP_ADDR] => 43.43.43.44 [GEOIP_CONTINENT_CODE] => EU [GEOIP_COUNTRY_CODE] => FR [GEOIP_COUNTRY_NAME] => France Now, thanks to the "random" redirects, i hardly have a clue as to what is going on, so can you guys please give me some ideas as to what tools to use to debug this? I have tried to see the redirect logs, but they really dont show much, and varnishlog isn't helping much either - although i must admit i am no professional at varnish. I believe the problem is with varnish trying to cache the url, and thus apache redirects are not being done properly, however visits the site first has a redirect, and based on that other users are served the content, depending on from where the user was when the cache was last updated, is it correct? if so, how can i solve the problem? Also, i have the option of using geoip redirects on varnish3 instead of using apache2 to do the redirects, is that what the best practice is? Any suggestion as to debugging this or to fix this would be helpful! thnx!

    Read the article

  • Network drives don't get mapped and desktop redirection stops working when domain user becomes a member of the Local Administrator group on their PC

    - by Kim Jong-Un
    We have a Small Business Server 2003 domain controller with Windows 7 workstations joined to the domain. I noticed recently that, if I make a user a local administrator on his computer, his redirected desktop and mapped network drives do not connect at login (error on login that network drives inaccessible and desktop is blank). However, it is still possible for this user to browse to his home directory where his redirected folders are located- so he still has access to that location. Does anyone have any theories as to what is going on here?

    Read the article

  • Can I include the path and query string in an IIS "Error Pages" redirect?

    - by Dylan Beattie
    I'm setting up a custom 403.4 handler so that non-SSL requests to my site are redirected to a different URL - and what I'd like to do is to include the script path and query string in the redirect, so that a user who requests http://www.site.com/foo?bar=1 will be redirected to https://www.site.com/foo?bar=1 I know something similar is possible when configuring a top-level site redirect, using the $S, $Q, %v tokens referred to in this IIS reference page - but this syntax doesn't seem to work when configuring a custom error redirect.

    Read the article

  • ASP.NET MVC unit test controller with HttpContext

    - by user299592
    I am trying to write a unit test for my one controller to verify if a view was returned properly, but this controller has a basecontroller that accesses the HttpContext.Current.Session. Everytime I create a new instance of my controller is calls the basecontroller constructor and the test fails with a null pointer exception on the HttpContext.Current.Session. Here is the code: public class BaseController : Controller { protected BaseController() { ViewData["UserID"] = HttpContext.Current.Session["UserID"]; } } public class IndexController : BaseController { public ActionResult Index() { return View("Index.aspx"); } } [TestMethod] public void Retrieve_IndexTest() { // Arrange const string expectedViewName = "Index"; IndexController controller = new IndexController(); // Act var result = controller.Index() as ViewResult; // Assert Assert.IsNotNull(result, "Should have returned a ViewResult"); Assert.AreEqual(expectedViewName, result.ViewName, "View name should have been {0}", expectedViewName); } Any ideas on how to mock the Session that is accessed in the base controller so the test in the descendant controller will run?

    Read the article

  • 'Design By Contract' in C#

    - by IAmCodeMonkey
    I wanted to try a little design by contract in my latest C# application and wanted to have syntax akin to: public string Foo() { set { Assert.IsNotNull(value); Assert.IsTrue(value.Contains("bar")); _foo = value; } } I know I can get static methods like this from a unit test framework, but I wanted to know if something like this was already built-in to the language or if there was already some kind of framework floating around. I can write my own Assert functions, just don't want to reinvent the wheel.

    Read the article

  • How do I enumerate a list of interfaces that are directly defined on an inheriting class/interface?

    - by Jordan
    Given the following C# class: public class Foo : IEnumerable<int> { // implementation of Foo and all its inherited interfaces } I want a method like the following that doesn't fail on the assertions: public void SomeMethod() { // This doesn't work Type[] interfaces = typeof(Foo).GetInterfaces(); Debug.Assert(interfaces != null); Debug.Assert(interfaces.Length == 1); Debug.Assert(interfaces[0] == typeof(IEnumerable<int>)); } Can someone help by fixing this method so the assertions don't fail? Calling typeof(Foo).GetInterfaces() doesn't work because it returns the entire interface hierarchy (i.e. interfaces variable contains IEnumerable<int> and IEnumerable), not just the top level.

    Read the article

  • Resolving the metadata token of a generic type parameter

    - by 280Z28
    Is there any way the .NET 4.0 (or earlier) reflection API to resolve a generic type parameter? See the two lines after my ArgumentException comment for my current attempt. [TestMethod] public void TestGenericParameterTokenResolution() { Type genericParameter = typeof(List<>).GetGenericArguments()[0]; Assert.IsTrue(genericParameter.IsGenericParameter); int metadataToken = genericParameter.MetadataToken; // make sure the metadata token is a GenericParam Assert.AreEqual(metadataToken & 0xFF000000, 0x2A000000); Module module = typeof(List<>).Module; // the following both throw an ArgumentException. Type resolvedParameter = module.ResolveType(metadataToken); resolvedParameter = (Type)module.ResolveMember(metadataToken); Assert.AreSame(genericParameter, resolvedParameter); }

    Read the article

  • redirectToAction results in null model

    - by Maslow
    I have 2 actions on a controller: public class CalculatorsController : Controller { // // GET: /Calculators/ public ActionResult Index() { return RedirectToAction("Accounting"); } public ActionResult Accounting() { var combatants = Models.Persistence.InMemoryCombatantPersistence.GetCombatants(); Debug.Assert(combatants != null); var bvm = new BalanceViewModel(combatants); Debug.Assert(bvm!=null); Debug.Assert(bvm.Combatants != null); return View(bvm); } } When the Index method is called, I get a null model coming out. When the Accounting method is called directly via it's url, I get a hydrated model.

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >