Search Results

Search found 724 results on 29 pages for 'constants'.

Page 16/29 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • What is causing this behavior with the movement of Pong Ball in 2D? [closed]

    - by thegermanpole
    //edit after running it through the debugger it turned out i had the display function set to x,x...TIL how to use a debugger I've been trying to teach myself C++ SDL with the lazyfoo tutorial and seem to have run into a roadblock. The code below is the movement function of my Dot class, which controls the ball. The ball seems to ignore yvel and moves with xvel to the bottom right. The code should be pretty readable, the rest of the relevant facts are: All variables are names Constants are in caps dotrad is the radius of my dot yvel and xvel are set to 5 in the constructor The dot is created at x and y equal to 100 When I comment out the x movement block it doesn't move, but if i comment out the y movement block, it keeps on going down to the right. void Dot::move() { if(((y+yvel+dotrad) <= SCREEN_HEIGHT) && (0 <= (y-dotrad+yvel))) { y+=yvel; } else { yvel = -1*yvel; } if(((x+xvel+dotrad) <= SCREEN_WIDTH) && (0 <= (x-dotrad+xvel))) { x +=xvel; } else { xvel = -1*xvel; } }

    Read the article

  • Classes as a compilation unit

    - by Yannbane
    If "compilation unit" is unclear, please refer to this. However, what I mean by it will be clear from the context. Edit: my language allows for multiple inheritance, unlike Java. I've started designing+developing my own programming language for educational, recreational, and potentially useful purposes. At first, I've decided to base it off Java. This implied that I would have all the code be written inside classes, and that code compiles to classes, which are loaded by the VM. However, I've excluded features such as interfaces and abstract classes, because I found no need for them. They seemed to be enforcing a paradigm, and I'd like my language not to do that. I wanted to keep the classes as the compilation unit though, because it seemed convenient to implement, familiar, and I just liked the idea. Then I noticed that I'm basically left with a glorified module system, where classes could be used either as "namespaces", providing constants and functions using the static directive, or as templates for objects that need to be instantiated ("actual" purpose of classes in other languages). Now I'm left wondering: what are the benefits of having classes as compilation units? (Also, any general commentary on my design would be much appreciated.)

    Read the article

  • python2.7 help() modules returnd error

    - by GerberaH
    # python Python 2.7.3 (default, Aug 1 2012, 05:14:39) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> help() Welcome to Python 2.7! This is the online help utility. If this is your first time using Python, you should definitely check out the tutorial on the Internet at http://docs.python.org/tutorial/. Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python modules. To quit this help utility and return to the interpreter, just type "quit". To get a list of available modules, keywords, or topics, type "modules", "keywords", or "topics". Each module also comes with a one-line summary of what it does; to list the modules whose summaries contain a given word such as "spam", type "modules spam". help> modules Please wait a moment while I gather a list of all available modules... /usr/lib/python2.7/dist-packages/gobject/constants.py:24: Warning: g_boxed_type_register_static: assertion `g_type_from_name (name) == 0' failed import gobject._gobject /usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning: g_boxed_type_register_static: assertion `g_type_from_name (name) == 0' failed from gtk import _gtk ** (python:6240): CRITICAL **: pyg_register_boxed: assertion `boxed_type != 0' failed /usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning: cannot register existing type `GdkDevice' from gtk import _gtk /usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning: g_type_get_qdata: assertion `node != NULL' failed from gtk import _gtk Speicherzugriffsfehler (Speicherabzug geschrieben)

    Read the article

  • Is there a better way to organize my module tests that avoids an explosion of new source files?

    - by luser droog
    I've got a neat (so I thought) way of having each of my modules produce a unit-test executable if compiled with the -DTESTMODULE flag. This flag guards a main() function that can access all static data and functions in the module, without #including a C file. From the README: -- Modules -- The various modules were written and tested separately before being coupled together to achieve the necessary basic functionality. Each module retains its unit-test, its main() function, guarded by #ifdef TESTMODULE. `make test` will compile and execute all the unit tests, producing copious output, but importantly exitting with an appropriate success or failure code, so the `make test` command will fail if any of the tests fail. Module TOC __________ test obj src header structures CONSTANTS ---- --- --- --- -------------------- m m.o m.c m.h mfile mtab TABSZ s s.o s.c s.h stack STACKSEGSZ v v.o v.c v.h saverec_ f.o f.c f.h file ob ob.o ob.c ob.h object ar ar.o ar.c ar.h array st st.o st.c st.h string di di.o di.c di.h dichead dictionary nm nm.o nm.c nm.h name gc gc.o gc.c gc.h garbage collector itp itp.c itp.h context osunix.o osunix.c osunix.h unix-dependent functions It's compile by a tricky bit of makefile, m:m.c ob.h ob.o err.o $(CORE) itp.o $(OP) cc $(CFLAGS) -DTESTMODULE $(LDLIBS) -o $@ $< err.o ob.o s.o ar.o st.o v.o di.o gc.o nm.o itp.o $(OP) f.o where the module is compiled with its own C file plus every other object file except itself. But it's creating difficulties for the kindly programmer who offered to write the Autotools files for me. So the obvious way to make it "less weird" would be to bust-out all the main functions into separate source files. But, but ... Do I gotta?

    Read the article

  • handle null values for string when implementing IXmlSerializable interface

    - by user208081
    I have the following class that implements IXmlSerializable. When implementing WriteXml(), I need to handle the case where the string members of this class may be null values. What is the best way of handling this? Currently, I am using the default constructor in which all the string properties are initialized to empty string values. This way, when WriteXml() is called, the string will not be null. One other way I could do this is check using String.IsNullOrEmpty before writing each string in xml. Any suggestions on how I can improve this code? using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; using System.Globalization; namespace TCS.Common.InformationObjects { public sealed class FaxSender : IXmlSerializable { #region Public Constants private const string DEFAULT_CLASS_NAME = "FaxSender"; #endregion Public Constants #region Public Properties public string Name { get; set; } public string Organization { get; set; } public string PhoneNumber { get; set; } public string FaxNumber { get; set; } public string EmailAddress { get; set; } #endregion Public Properties #region Public Methods #region Constructors public FaxSender() { Name = String.Empty; Organization = String.Empty; PhoneNumber = String.Empty; FaxNumber = String.Empty; EmailAddress = String.Empty; } public FaxSender(string name, string organization, string phoneNumber, string faxNumber, string emailAddress) { Name = name; Organization = organization; PhoneNumber = phoneNumber; FaxNumber = faxNumber; EmailAddress = emailAddress; } #endregion Constructors #region IXmlSerializable Members public System.Xml.Schema.XmlSchema GetSchema() { throw new NotImplementedException(); } public void ReadXml(System.Xml.XmlReader reader) { throw new NotImplementedException(); } public void WriteXml(System.Xml.XmlWriter xmlWriter) { try { // <sender> xmlWriter.WriteStartElement("sender"); // Write the name of the sender as an element. xmlWriter.WriteElementString("name", this.Name.ToString(CultureInfo.CurrentCulture)); // Write the organization of the sender as an element. xmlWriter.WriteElementString("organization", this.Organization.ToString(CultureInfo.CurrentCulture)); // Write the phone number of the sender as an element. xmlWriter.WriteElementString("phone_number", this.PhoneNumber.ToString(CultureInfo.CurrentCulture)); // Write the fax number of the sender as an element. xmlWriter.WriteElementString("fax_number", this.FaxNumber.ToString(CultureInfo.CurrentCulture)); // Write the email address of the sender as an element. xmlWriter.WriteElementString("email_address", this.EmailAddress.ToString(CultureInfo.CurrentCulture)); // </sender> xmlWriter.WriteEndElement(); } catch { // Rethrow any exceptions. throw; } } #endregion IXmlSerializable Members #endregion Public Methods } }

    Read the article

  • How to make condition inside getView of Custom BaseAdapter

    - by user1501150
    I want to make a Custom ListView with Custom BaseAdapter, where the the status=1,I want to show a CheckBox, and else I want to show a textView.. My given condition is: if (NewtheStatus == 1) { alreadyOrderText .setVisibility(TextView.GONE); } else{ checkBox.setVisibility(CheckBox.GONE); } But Some times I obtain some row that has neither checkBox nor TextView. The Code of my Custom BaseAdapter is given below . private class MyCustomAdapter extends BaseAdapter { private static final int TYPE_ITEM = 0; private static final int TYPE_ITEM_WITH_HEADER = 1; // private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1; private ArrayList<WatchListAllEntity> mData = new ArrayList(); private LayoutInflater mInflater; private ArrayList<WatchListAllEntity> items = new ArrayList<WatchListAllEntity>(); public MyCustomAdapter(Context context, ArrayList<WatchListAllEntity> items) { mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public void addItem(WatchListAllEntity watchListAllEntity) { // TODO Auto-generated method stub items.add(watchListAllEntity); } public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; final int position1 = position; if (v == null) { LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.listitempict, null); } watchListAllEntity = new WatchListAllEntity(); watchListAllEntity = items.get(position); Log.i("position: iteamsLength ", position + ", " + items.size()); if (watchListAllEntity != null) { ImageView itemImage = (ImageView) v .findViewById(R.id.imageviewproduct); if (watchListAllEntity.get_thumbnail_image_url1() != null) { Drawable image = ImageOperations(watchListAllEntity .get_thumbnail_image_url1().replace(" ", "%20"), "image.jpg"); // itemImage.setImageResource(R.drawable.icon); if (image != null) { itemImage.setImageDrawable(image); itemImage.setAdjustViewBounds(true); } else { itemImage.setImageResource(R.drawable.iconnamecard); } Log.i("status_ja , status", watchListAllEntity.get_status_ja() + " ," + watchListAllEntity.getStatus()); int NewtheStatus = Integer.parseInt(watchListAllEntity .getStatus()); CheckBox checkBox = (CheckBox) v .findViewById(R.id.checkboxproduct); TextView alreadyOrderText = (TextView) v .findViewById(R.id.alreadyordertext); if (NewtheStatus == 1) { alreadyOrderText .setVisibility(TextView.GONE); } else{ checkBox.setVisibility(CheckBox.GONE); } Log.i("Loading ProccardId: ", watchListAllEntity.get_proc_card_id() + ""); checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { WatchListAllEntity watchListAllEntity2 = items .get(position1); Log.i("Position: ", position1 + ""); // TODO Auto-generated method stub if (isChecked) { Constants.orderList.add(watchListAllEntity2 .get_proc_card_id()); Log.i("Proc Card Id Add: ", watchListAllEntity2 .get_proc_card_id() + ""); } else { Constants.orderList.remove(watchListAllEntity2 .get_proc_card_id()); Log.i("Proc Card Id Remove: ", watchListAllEntity2.get_proc_card_id() + ""); } } }); } } return v; } private Drawable ImageOperations(String url, String saveFilename) { try { InputStream is = (InputStream) this.fetch(url); Drawable d = Drawable.createFromStream(is, "src"); return d; } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } } public Object fetch(String address) throws MalformedURLException, IOException { URL url = new URL(address); Object content = url.getContent(); return content; } public int getCount() { // TODO Auto-generated method stub int sizef=items.size(); Log.i("Size", sizef+""); return items.size(); } public Object getItem(int position) { // TODO Auto-generated method stub return items.get(position); } public long getItemId(int position) { // TODO Auto-generated method stub return position; } }

    Read the article

  • Improve heavy work in a loop in multithreading

    - by xjaphx
    I have a little problem with my data processing. public void ParseDetails() { for (int i = 0; i < mListAppInfo.Count; ++i) { ParseOneDetail(i); } } For 300 records, it usually takes around 13-15 minutes. I've tried to improve by using Parallel.For() but it always stop at some point. public void ParseDetails() { Parallel.For(0, mListAppInfo.Count, i => ParseOneDetail(i)); } In method ParseOneDetail(int index), I set an output log for tracking the record id which is under processing. Always hang at some point, I don't know why.. ParseOneDetail(): 89 ... ParseOneDetail(): 90 ... ParseOneDetail(): 243 ... ParseOneDetail(): 92 ... ParseOneDetail(): 244 ... ParseOneDetail(): 93 ... ParseOneDetail(): 245 ... ParseOneDetail(): 247 ... ParseOneDetail(): 94 ... ParseOneDetail(): 248 ... ParseOneDetail(): 95 ... ParseOneDetail(): 99 ... ParseOneDetail(): 249 ... ParseOneDetail(): 100 ... _ <hang at this point> Appreciate your help and suggestions to improve this. Thank you! Edit 1: update for method: private void ParseOneDetail(int index) { Console.WriteLine("ParseOneDetail(): " + index + " ... "); ApplicationInfo appInfo = mListAppInfo[index]; var htmlWeb = new HtmlWeb(); var document = htmlWeb.Load(appInfo.AppAnnieURL); // get first one only HtmlNode nodeStoreURL = document.DocumentNode.SelectSingleNode(Constants.XPATH_FIRST); appInfo.StoreURL = nodeStoreURL.Attributes[Constants.HREF].Value; } Edit 2: This is the error output after a while running as Enigmativity suggest, ParseOneDetail(): 234 ... ParseOneDetail(): 87 ... ParseOneDetail(): 235 ... ParseOneDetail(): 236 ... ParseOneDetail(): 88 ... ParseOneDetail(): 238 ... ParseOneDetail(): 89 ... ParseOneDetail(): 90 ... ParseOneDetail(): 239 ... ParseOneDetail(): 92 ... Unhandled Exception: System.AggregateException: One or more errors occurred. --- > System.Net.WebException: The operation has timed out at System.Net.HttpWebRequest.GetResponse() at HtmlAgilityPack.HtmlWeb.Get(Uri uri, String method, String path, HtmlDocum ent doc, IWebProxy proxy, ICredentials creds) in D:\Source\htmlagilitypack.new\T runk\HtmlAgilityPack\HtmlWeb.cs:line 1355 at HtmlAgilityPack.HtmlWeb.LoadUrl(Uri uri, String method, WebProxy proxy, Ne tworkCredential creds) in D:\Source\htmlagilitypack.new\Trunk\HtmlAgilityPack\Ht mlWeb.cs:line 1479 at HtmlAgilityPack.HtmlWeb.Load(String url, String method) in D:\Source\htmla gilitypack.new\Trunk\HtmlAgilityPack\HtmlWeb.cs:line 1103 at HtmlAgilityPack.HtmlWeb.Load(String url) in D:\Source\htmlagilitypack.new\ Trunk\HtmlAgilityPack\HtmlWeb.cs:line 1061 at SimpleChartParser.AppAnnieParser.ParseOneDetail(ApplicationInfo appInfo) i n c:\users\nhn60\documents\visual studio 2010\Projects\FunToolPack\SimpleChartPa rser\AppAnnieParser.cs:line 90 at SimpleChartParser.AppAnnieParser.<ParseDetails>b__0(ApplicationInfo ai) in c:\users\nhn60\documents\visual studio 2010\Projects\FunToolPack\SimpleChartPar ser\AppAnnieParser.cs:line 80 at System.Threading.Tasks.Parallel.<>c__DisplayClass21`2.<ForEachWorker>b__17 (Int32 i) at System.Threading.Tasks.Parallel.<>c__DisplayClassf`1.<ForWorker>b__c() at System.Threading.Tasks.Task.InnerInvoke() at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask) at System.Threading.Tasks.Task.<>c__DisplayClass7.<ExecuteSelfReplicating>b__ 6(Object ) --- End of inner exception stack trace --- at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceled Exceptions) at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationTo ken cancellationToken) at System.Threading.Tasks.Parallel.ForWorker[TLocal](Int32 fromInclusive, Int 32 toExclusive, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWit hState, Func`4 bodyWithLocal, Func`1 localInit, Action`1 localFinally) at System.Threading.Tasks.Parallel.ForEachWorker[TSource,TLocal](TSource[] ar ray, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Act ion`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithEveryt hing, Func`1 localInit, Action`1 localFinally) at System.Threading.Tasks.Parallel.ForEachWorker[TSource,TLocal](IEnumerable` 1 source, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState , Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithE verything, Func`1 localInit, Action`1 localFinally) at System.Threading.Tasks.Parallel.ForEach[TSource](IEnumerable`1 source, Act ion`1 body) at SimpleChartParser.AppAnnieParser.ParseDetails() in c:\users\nhn60\document s\visual studio 2010\Projects\FunToolPack\SimpleChartParser\AppAnnieParser.cs:li ne 80 at SimpleChartParser.Program.Main(String[] args) in c:\users\nhn60\documents\ visual studio 2010\Projects\FunToolPack\SimpleChartParser\Program.cs:line 15

    Read the article

  • MVC multi page form losing session

    - by Bryan
    I have a multi-page form that's used to collect leads. There are multiple versions of the same form that we call campaigns. Some campaigns are 3 page forms, others are 2 pages, some are 1 page. They all share the same lead model and campaign controller, etc. There is 1 action for controlling the flow of the campaigns, and a separate action for submitting all the lead information into the database. I cannot reproduce this locally, and there are checks in place to ensure users can't skip pages. Session mode is InProc. This runs after every POST action which stores the values in session: protected override void OnActionExecuted(ActionExecutedContext filterContext) { base.OnActionExecuted(filterContext); if (this.Request.RequestType == System.Net.WebRequestMethods.Http.Post && this._Lead != null) ParentStore.Lead = this._Lead; } This is the Lead property within the controller: private Lead _Lead; /// <summary> /// Gets the session stored Lead model. /// </summary> /// <value>The Lead model stored in session.</value> protected Lead Lead { get { if (this._Lead == null) this._Lead = ParentStore.Lead; return this._Lead; } } ParentStore class: public static class ParentStore { internal static Lead Lead { get { return SessionStore.Get<Lead>(Constants.Session.Lead, new Lead()); } set { SessionStore.Set(Constants.Session.Lead, value); } } Campaign POST action: [HttpPost] public virtual ActionResult Campaign(Lead lead, string campaign, int page) { if (this.Session.IsNewSession) return RedirectToAction("Campaign", new { campaign = campaign, page = 0 }); if (ModelState.IsValid == false) return View(GetCampaignView(campaign, page), this.Lead); TrackLead(this.Lead, campaign, page, LeadType.Shared); return RedirectToAction("Campaign", new { campaign = campaign, page = ++page }); } The problem is occuring between the above action, and before the following Submit action executes: [HttpPost] public virtual ActionResult Submit(Lead lead, string campaign, int page) { if (this.Session.IsNewSession || this.Lead.Submitted || !this.LeadExists) return RedirectToAction("Campaign", new { campaign = campaign, page = 0 }); lead.AddCustomQuestions(); MergeLead(campaign, lead, this.AdditionalQuestionsType, false); if (ModelState.IsValid == false) return View(GetCampaignView(campaign, page), this.Lead); var sharedLead = this.Lead.ToSharedLead(Request.Form.ToQueryString(false)); //Error occurs here and sends me an email with whatever values are in the form collection. EAUtility.ProcessLeadProxy.SubmitSharedLead(sharedLead); this.Lead.Submitted = true; VisitorTracker.DisplayConfirmationPixel = true; TrackLead(this.Lead, campaign, page, LeadType.Shared); return RedirectToAction(this.ConfirmationView); } Every visitor to our site gets a unique GUID visitorID. But when these error occurs there is a different visitorID between the Campaign POST and the Submit POST. Because we track each form submission via the TrackLead() method during campaign and submit actions I can see session is being lost between calls, despite the OnActionExecuted firing after every POST and storing the form in session. So when there are errors, we get half the form under one visitorID and the remainder of the form under a different visitorID. Luckily we use a third party service which sends an API call every time a form value changes which uses it's own ID. These IDs are consistent between the first half of the form, and the remainder of the form, and the only way I can save the leads from the lost session issues. I should also note that this works fine 99% of the time. EDIT: I've modified my code to explicitly store my lead object in TempData and used the TempData.Keep() method to persist the object between subsequent requests. I've only deployed this behavior to 1 of my 3 sites but so far so good. I had also tried storing my lead objects in Session directly in the controller action i.e., Session.Add("lead", this._Lead); which uses HTTPSessionStateBase, attempting to circumvent the wrapper class, instead of HttpContext.Current.Session which uses HTTPSessionState. This modification made no difference on the issue, as expected.

    Read the article

  • Using Dynamic Proxies to centralize JPA code

    - by Daziplqa
    Hi All, Actually, This is not a question but really I need your opinions in a matter... I put his post here because I know you always active, so please don't consider this a bad question and share me your opinions. I've used Java dynamic proxies to Centralize The code of JPA that I used in a standalone mode, and Here's the dynamic proxy code: package com.forat.service; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import com.forat.service.exceptions.DAOException; /** * Example of usage : * <pre> * OnlineFromService onfromService = * (OnlineFromService) DAOProxy.newInstance(new OnlineFormServiceImpl()); * try { * Student s = new Student(); * s.setName("Mohammed"); * s.setNationalNumber("123456"); * onfromService.addStudent(s); * }catch (Exception ex) { * System.out.println(ex.getMessage()); * } *</pre> * @author mohammed hewedy * */ public class DAOProxy implements InvocationHandler{ private Object object; private Logger logger = Logger.getLogger(this.getClass().getSimpleName()); private DAOProxy(Object object) { this.object = object; } public static Object newInstance(Object object) { return Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), new DAOProxy(object)); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { EntityManagerFactory emf = null; EntityManager em = null; EntityTransaction et = null; Object result = null; try { emf = Persistence.createEntityManagerFactory(Constants.UNIT_NAME); em = emf.createEntityManager();; Method entityManagerSetter = object.getClass(). getDeclaredMethod(Constants.ENTITY_MANAGER_SETTER_METHOD, EntityManager.class); entityManagerSetter.invoke(object, em); et = em.getTransaction(); et.begin(); result = method.invoke(object, args); et.commit(); return result; }catch (Exception ex) { et.rollback(); Throwable cause = ex.getCause(); logger.log(Level.SEVERE, cause.getMessage()); if (cause instanceof DAOException) throw new DAOException(cause.getMessage(), cause); else throw new RuntimeException(cause.getMessage(), cause); }finally { em.close(); emf.close(); } } } And here's the link that contains more info (http://m-hewedy.blogspot.com/2010/04/using-dynamic-proxies-to-centralize-jpa.html) (plz don't consider this as adds, as I can copy and past the entire topic here if you want that) So, Please give me your opinions. Thanks.

    Read the article

  • Testing Entity Framework applications, pt. 3: NDbUnit

    - by Thomas Weller
    This is the third of a three part series that deals with the issue of faking test data in the context of a legacy app that was built with Microsoft's Entity Framework (EF) on top of an MS SQL Server database – a scenario that can be found very often. Please read the first part for a description of the sample application, a discussion of some general aspects of unit testing in a database context, and of some more specific aspects of the here discussed EF/MSSQL combination. Lately, I wondered how you would ‘mock’ the data layer of a legacy application, when this data layer is made up of an MS Entity Framework (EF) model in combination with a MS SQL Server database. Originally, this question came up in the context of how you could enable higher-level integration tests (automated UI tests, to be exact) for a legacy application that uses this EF/MSSQL combo as its data store mechanism – a not so uncommon scenario. The question sparked my interest, and I decided to dive into it somewhat deeper. What I've found out is, in short, that it's not very easy and straightforward to do it – but it can be done. The two strategies that are best suited to fit the bill involve using either the (commercial) Typemock Isolator tool or the (free) NDbUnit framework. The use of Typemock was discussed in the previous post, this post now will present the NDbUnit approach... NDbUnit is an Apache 2.0-licensed open-source project, and like so many other Nxxx tools and frameworks, it is basically a C#/.NET port of the corresponding Java version (DbUnit namely). In short, it helps you in flexibly managing the state of a database in that it lets you easily perform basic operations (like e.g. Insert, Delete, Refresh, DeleteAll)  against your database and, most notably, lets you feed it with data from external xml files. Let's have a look at how things can be done with the help of this framework. Preparing the test data Compared to Typemock, using NDbUnit implies a totally different approach to meet our testing needs.  So the here described testing scenario requires an instance of an SQL Server database in operation, and it also means that the Entity Framework model that sits on top of this database is completely unaffected. First things first: For its interactions with the database, NDbUnit relies on a .NET Dataset xsd file. See Step 1 of their Quick Start Guide for a description of how to create one. With this prerequisite in place then, the test fixture's setup code could look something like this: [TestFixture, TestsOn(typeof(PersonRepository))] [Metadata("NDbUnit Quickstart URL",           "http://code.google.com/p/ndbunit/wiki/QuickStartGuide")] [Description("Uses the NDbUnit library to provide test data to a local database.")] public class PersonRepositoryFixture {     #region Constants     private const string XmlSchema = @"..\..\TestData\School.xsd";     #endregion // Constants     #region Fields     private SchoolEntities _schoolContext;     private PersonRepository _personRepository;     private INDbUnitTest _database;     #endregion // Fields     #region Setup/TearDown     [FixtureSetUp]     public void FixtureSetUp()     {         var connectionString = ConfigurationManager.ConnectionStrings["School_Test"].ConnectionString;         _database = new SqlDbUnitTest(connectionString);         _database.ReadXmlSchema(XmlSchema);         var entityConnectionStringBuilder = new EntityConnectionStringBuilder         {             Metadata = "res://*/School.csdl|res://*/School.ssdl|res://*/School.msl",             Provider = "System.Data.SqlClient",             ProviderConnectionString = connectionString         };         _schoolContext = new SchoolEntities(entityConnectionStringBuilder.ConnectionString);         _personRepository = new PersonRepository(this._schoolContext);     }     [FixtureTearDown]     public void FixtureTearDown()     {         _database.PerformDbOperation(DbOperationFlag.DeleteAll);         _schoolContext.Dispose();     }     ...  As you can see, there is slightly more fixture setup code involved if your tests are using NDbUnit to provide the test data: Because we're dealing with a physical database instance here, we first need to pick up the test-specific connection string from the test assemblies' App.config, then initialize an NDbUnit helper object with this connection along with the provided xsd file, and also set up the SchoolEntities and the PersonRepository instances accordingly. The _database field (an instance of the INdUnitTest interface) will be our single access point to the underlying database: We use it to perform all the required operations against the data store. To have a flexible mechanism to easily insert data into the database, we can write a helper method like this: private void InsertTestData(params string[] dataFileNames) {     _database.PerformDbOperation(DbOperationFlag.DeleteAll);     if (dataFileNames == null)     {         return;     }     try     {         foreach (string fileName in dataFileNames)         {             if (!File.Exists(fileName))             {                 throw new FileNotFoundException(Path.GetFullPath(fileName));             }             _database.ReadXml(fileName);             _database.PerformDbOperation(DbOperationFlag.InsertIdentity);         }     }     catch     {         _database.PerformDbOperation(DbOperationFlag.DeleteAll);         throw;     } } This lets us easily insert test data from xml files, in any number and in a  controlled order (which is important because we eventually must fulfill referential constraints, or we must account for some other stuff that imposes a specific ordering on data insertion). Again, as with Typemock, I won't go into API details here. - Unfortunately, there isn't too much documentation for NDbUnit anyway, other than the already mentioned Quick Start Guide (and the source code itself, of course) - a not so uncommon problem with smaller Open Source Projects. Last not least, we need to provide the required test data in xml form. A snippet for data from the People table might look like this, for example: <?xml version="1.0" encoding="utf-8" ?> <School xmlns="http://tempuri.org/School.xsd">   <Person>     <PersonID>1</PersonID>     <LastName>Abercrombie</LastName>     <FirstName>Kim</FirstName>     <HireDate>1995-03-11T00:00:00</HireDate>   </Person>   <Person>     <PersonID>2</PersonID>     <LastName>Barzdukas</LastName>     <FirstName>Gytis</FirstName>     <EnrollmentDate>2005-09-01T00:00:00</EnrollmentDate>   </Person>   <Person>     ... You can also have data from various tables in one single xml file, if that's appropriate for you (but beware of the already mentioned ordering issues). It's true that your test assembly may end up with dozens of such xml files, each containing quite a big amount of text data. But because the files are of very low complexity, and with the help of a little bit of Copy/Paste and Excel magic, this appears to be well manageable. Executing some basic tests Here are some of the possible tests that can be written with the above preparations in place: private const string People = @"..\..\TestData\School.People.xml"; ... [Test, MultipleAsserts, TestsOn("PersonRepository.GetNameList")] public void GetNameList_ListOrdering_ReturnsTheExpectedFullNames() {     InsertTestData(People);     List<string> names =         _personRepository.GetNameList(NameOrdering.List);     Assert.Count(34, names);     Assert.AreEqual("Abercrombie, Kim", names.First());     Assert.AreEqual("Zheng, Roger", names.Last()); } [Test, MultipleAsserts, TestsOn("PersonRepository.GetNameList")] [DependsOn("RemovePerson_CalledOnce_DecreasesCountByOne")] public void GetNameList_NormalOrdering_ReturnsTheExpectedFullNames() {     InsertTestData(People);     List<string> names =         _personRepository.GetNameList(NameOrdering.Normal);     Assert.Count(34, names);     Assert.AreEqual("Alexandra Walker", names.First());     Assert.AreEqual("Yan Li", names.Last()); } [Test, TestsOn("PersonRepository.AddPerson")] public void AddPerson_CalledOnce_IncreasesCountByOne() {     InsertTestData(People);     int count = _personRepository.Count;     _personRepository.AddPerson(new Person { FirstName = "Thomas", LastName = "Weller" });     Assert.AreEqual(count + 1, _personRepository.Count); } [Test, TestsOn("PersonRepository.RemovePerson")] public void RemovePerson_CalledOnce_DecreasesCountByOne() {     InsertTestData(People);     int count = _personRepository.Count;     _personRepository.RemovePerson(new Person { PersonID = 33 });     Assert.AreEqual(count - 1, _personRepository.Count); } Not much difference here compared to the corresponding Typemock versions, except that we had to do a bit more preparational work (and also it was harder to get the required knowledge). But this picture changes quite dramatically if we look at some more demanding test cases: Ok, and what if things are becoming somewhat more complex? Tests like the above ones represent the 'easy' scenarios. They may account for the biggest portion of real-world use cases of the application, and they are important to make sure that it is generally sound. But usually, all these nasty little bugs originate from the more complex parts of our code, or they occur when something goes wrong. So, for a testing strategy to be of real practical use, it is especially important to see how easy or difficult it is to mimick a scenario which represents a more complex or exceptional case. The following test, for example, deals with the case that there is some sort of invalid input from the caller: [Test, MultipleAsserts, TestsOn("PersonRepository.GetCourseMembers")] [Row(null, typeof(ArgumentNullException))] [Row("", typeof(ArgumentException))] [Row("NotExistingCourse", typeof(ArgumentException))] public void GetCourseMembers_WithGivenVariousInvalidValues_Throws(string courseTitle, Type expectedInnerExceptionType) {     var exception = Assert.Throws<RepositoryException>(() =>                                 _personRepository.GetCourseMembers(courseTitle));     Assert.IsInstanceOfType(expectedInnerExceptionType, exception.InnerException); } Apparently, this test doesn't need an 'Arrange' part at all (see here for the same test with the Typemock tool). It acts just like any other client code, and all the required business logic comes from the database itself. This doesn't always necessarily mean that there is less complexity, but only that the complexity happens in a different part of your test resources (in the xml files namely, where you sometimes have to spend a lot of effort for carefully preparing the required test data). Another example, which relies on an underlying 1-n relationship, might be this: [Test, MultipleAsserts, TestsOn("PersonRepository.GetCourseMembers")] public void GetCourseMembers_WhenGivenAnExistingCourse_ReturnsListOfStudents() {     InsertTestData(People, Course, Department, StudentGrade);     List<Person> persons = _personRepository.GetCourseMembers("Macroeconomics");     Assert.Count(4, persons);     Assert.ForAll(         persons,         @p => new[] { 10, 11, 12, 14 }.Contains(@p.PersonID),         "Person has none of the expected IDs."); } If you compare this test to its corresponding Typemock version, you immediately see that the test itself is much simpler, easier to read, and thus much more intention-revealing. The complexity here lies hidden behind the call to the InsertTestData() helper method and the content of the used xml files with the test data. And also note that you might have to provide additional data which are not even directly relevant to your test, but are required only to fulfill some integrity needs of the underlying database. Conclusion The first thing to notice when comparing the NDbUnit approach to its Typemock counterpart obviously deals with performance: Of course, NDbUnit is much slower than Typemock. Technically,  it doesn't even make sense to compare the two tools. But practically, it may well play a role and could or could not be an issue, depending on how much tests you have of this kind, how often you run them, and what role they play in your development cycle. Also, because the dataset from the required xsd file must fully match the database schema (even in parts that otherwise wouldn't be relevant to you), it can be quite cumbersome to be in a team where different people are working with the database in parallel. My personal experience is – as already said in the first part – that Typemock gives you a better development experience in a 'dynamic' scenario (when you're working in some kind of TDD-style, you're oftentimes executing the tests from your dev box, and your database schema changes frequently), whereas the NDbUnit approach is a good and solid solution in more 'static' development scenarios (when you need to execute the tests less frequently or only on a separate build server, and/or the underlying database schema can be kept relatively stable), for example some variations of higher-level integration or User-Acceptance tests. But in any case, opening Entity Framework based applications for testing requires a fair amount of resources, planning, and preparational work – it's definitely not the kind of stuff that you would call 'easy to test'. Hopefully, future versions of EF will take testing concerns into account. Otherwise, I don't see too much of a future for the framework in the long run, even though it's quite popular at the moment... The sample solution A sample solution (VS 2010) with the code from this article series is available via my Bitbucket account from here (Bitbucket is a hosting site for Mercurial repositories. The repositories may also be accessed with the Git and Subversion SCMs - consult the documentation for details. In addition, it is possible to download the solution simply as a zipped archive – via the 'get source' button on the very right.). The solution contains some more tests against the PersonRepository class, which are not shown here. Also, it contains database scripts to create and fill the School sample database. To compile and run, the solution expects the Gallio/MbUnit framework to be installed (which is free and can be downloaded from here), the NDbUnit framework (which is also free and can be downloaded from here), and the Typemock Isolator tool (a fully functional 30day-trial is available here). Moreover, you will need an instance of the Microsoft SQL Server DBMS, and you will have to adapt the connection strings in the test projects App.config files accordingly.

    Read the article

  • Installing flex on Mac Parallels

    - by Ali Syed
    Hello folks, I am trying to install Flex 3 on my Windows 7 Virtual machine (parallels desktop) on my Mac Pro. The problem seems to be some sort of conflict between the copy of Flex 3 Builder installed on Mac OS X. The installer tries to install Flex in x:/Program Files/Adobe/Flex Builder 3/ but since Parallels Desktop connects all directories, there resides the Flex Builder 3 installation of MAC. I get this error Log: !SESSION 2010-04-22 16:09:23.031 ----------------------------------------------- eclipse.buildId=unknown java.version=1.5.0_11 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=de_DE Framework arguments: -application org.eclipse.update.core.standaloneUpdate -command install -from file:\C:\Program Files\Adobe\Flex Builder 3 Windose\com.adobe.flexbuilder.update.site/ -featureId com.adobe.flexbuilder.feature.standalone -version 3.0.214193 Command-line arguments: -application org.eclipse.update.core.standaloneUpdate -command install -from file:\C:\Program Files\Adobe\Flex Builder 3 Windose\com.adobe.flexbuilder.update.site/ -featureId com.adobe.flexbuilder.feature.standalone -version 3.0.214193 !ENTRY org.eclipse.update.core 4 0 2010-04-22 16:09:29.187 !MESSAGE Cannot install featurecom.adobe.flexbuilder.feature.standalone 3.0.214193

    Read the article

  • Convert Environment.OSVersion to NTDDI version format

    - by David Brown
    In sdkddkver.h of the Windows Platform SDK, there are various OS versions defined as NTDDI_*. For example, Windows XP and its service packs are defined as: #define NTDDI_WINXP 0x05010000 #define NTDDI_WINXPSP1 0x05010100 #define NTDDI_WINXPSP2 0x05010200 #define NTDDI_WINXPSP3 0x05010300 #define NTDDI_WINXPSP4 0x05010400 There are also masks which, along with the OSVER, SPVER, and SUBVER macros, allow you to pull the respective parts out of the NTDDI version. #define OSVERSION_MASK 0xFFFF0000 #define SPVERSION_MASK 0x0000FF00 #define SUBVERSION_MASK 0x000000FF I have all of these defined as constants in C# and what I'd like to do now is convert the data returned by Environment.OSVersion to a value corresponding to one of the NTDDI versions in sdkddkver.h. I could make a massive switch statement, but that's not really as future-proof as I'd like it to be. I would need to update the conversion method every time a new OS or service pack is released. I have a feeling this could be done with the help of some bitwise operators, but I'll be honest and say that those aren't my strong point. I appreciate any help!

    Read the article

  • Windows "known folders": is there any one of them which is reliably read/write for all users on all

    - by Stabledog
    SHGetKnownFolderPath() and its cohorts accept one of the constants defined here (http://msdn.microsoft.com/en-us/library/dd378457%28v=VS.85%29.aspx ), returning the path to a directory. I'm looking for one of these folders which is reliably writable by all users (including LocalSystem) on XP, Vista, and Windows 7... but I think I'm striking out. It appears that, in fact, there is no single location on the hard drive anymore where you can put a file and be assured that all users can write to it on all these OS versions, without fiddling the permissions first. Is this true?

    Read the article

  • A better way of converting Codepage-1251 in RTF to Unicode

    - by blue painted
    I am trying to parse RTF (via MSEDIT) in various languages, all in Delphi 2010, in order to produce HTML in unicode. Taking Russian/Cyrillic as my starting point I find that the overall document codepage is 1252 (Western) but the Russian parts of the text are identified by the charset of the font (RUSSIAN_CHARSET 204). So far I am: 1) Use AnsiString (or RawByteString) when parsing the RTF 2) Determine the CodePage by a lookup from the font charset (see http://msdn.microsoft.com/en-us/library/cc194829.aspx) 3) Translating using a lookup table in my code: (This table generated from http://msdn.microsoft.com/en-gb/goglobal/cc305144.aspx) - I'm going to need one table per supported codepage! There MUST be a better way than this? Preferably something supplied by the OS and so less brittle than tables of constants.

    Read the article

  • Configuring asp.net web applications. Best practices

    - by Andrew Florko
    Hello everybody, There is a lot of configurable information for a web-site: UI messages Number of records used in pagination & other UI parameters Cache duration for web-pages & timeouts Route maps & site structure ... There are many approaches to store all this information also: AppSettings (web.config) Custom sections (web.config) External xml/text files referred from web.config Internal static class(es) of constants Database table(s) ... What approaches do you usually choose for your tasks & what approaches do you find unsuitable? Thank you in advance!

    Read the article

  • Looking for calculator source code, BSD-licensed

    - by Horace Ho
    I have an urgent project which need many functions of a calculator (plus a few in-house business rule formulas). As I won't have time to re-invent the wheel so I am looking for source code directly. Requirements: BSD licensed (GPL won't help) in c/c++ programming language 32-bit CPU minimum dependency on platform API/data structure best with both RPN and prefix notation supported emulator/simulator code also acceptable (if not impossible to add custom formula) with following functions (from wikipedia) Scientific notation for calculating large numbers floating point arithmetic logarithmic functions, using both base 10 and base e trigonometry functions (some including hyperbolic trigonometry) exponents and roots beyond the square root quick access to constants such as pi and e plus hexadecimal, binary, and octal calculations, including basic Boolean math fractions optional statistics and probability calculations complex numbers programmability equation solving

    Read the article

  • Good freeware COM/ActiveX Type Library Explorer?

    - by Tomalak
    I used to have a dated, but valuable solution to display COM/ActiveX control- and type-library contents (ProgIDs, method names and signatures, enumerations, constants, interfaces/coclasses, etc.) of all such libraries registered on my system. It provided an Explorer-like overview of everything that was available to ActiveX development/scripting and served as an automatic API documentation tool since official docs for most COM/ActiveX libraries are either missing completely or fragmentary at best. My recent move to a 64bit Windows rendered the program I had unusable, due to internal dependencies on the 32bit VB6 runtime (comctl32.ocx) that is no longer supported on 64bit Windows. Does anyone know an alternative that still works?

    Read the article

  • Compile-time lookup array creation for ANSI-C?

    - by multiproximus
    A previous programmer preferred to generate large lookup tables (arrays of constants) to save runtime CPU cycles rather than calculating values on the fly. He did this by creating custom Visual C++ projects that were unique for each individual lookup table... which generate array files that are then #included into a completely separate ANSI-C micro-controller (Renesas) project. This approach is fine for his original calculation assumptions, but has become tedious when the input parameters need to be modified, requiring me to recompile all of the Visual C++ projects and re-import those files into the ANSI-C project. What I would like to do is port the Visual C++ source directly into the ANSI-C microcontroller project and let the compiler create the array tables. So, my question is: Can ANSI-C compilers compute and generate lookup arrays during compile time? And if so, how should I go about it? Thanks in advance for your help!

    Read the article

  • How to get roles with JSR 196 authentification in GlassFish?

    - by deamon
    I want to use a custom authentication module conforming to JSR 196 in GlassFish 3. The interface javax.security.auth.message.ServerAuth has the method: AuthStatus validateRequest( MessageInfo messageInfo, javax.security.auth.Subject clientSubject, javax.security.auth.Subject serviceSubject ) AuthStatus can be one of several constants like FAILURE or SUCCESS. The question is: How can I get the roles from a "role datebase" with JSR 196? Example: The server receives a request with a SSO token (CAS token for example), checks whether the token is valid, populates the remote user object with roles fetches from a database via JDBC or from REST service via http. Is the role fetching in the scope of JSR 196? How could that be implemented? Do I have to use JSR 196 together with JSR 115 to use custom authentication and a custom role source?

    Read the article

  • Problem with #ifndef and #pragma once

    - by Xaver
    I want write the program with next struct stdafx.h - contains some #define defenitions of program constants and #include of headers wich uses in all project. frmMain.h - contatins code of Form1 also can Show form2 and uses some code from BckHeadr.h and some functions call that headers included in stdafx.h. frmIniPrgs.h - contatins code of Form2 and uses some code from BckHeadr.h and some functions call that headers included in stdafx.h. BckHeadr.h - contatins some definitions of functions and some functions call that headers included in stdafx.h. I know what i must use #ifndef or #pragma once directives. But i can not decided this problem. I included in stdafx.h: frmIniPrgs.H, BckHeadr.h, frmMain.h. And use #ifndef in all modules. I uset it like this: #ifndef MYMODULE_H #define MYMODULE_H //module code #endif

    Read the article

  • Visual Studio 2010 automation

    - by JoelFan
    I am trying to run the following code (which I got from here ) Public Sub WriteToMyNewPane() Dim win As Window = _ DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput) Dim ow As OutputWindow = win.Object Dim owPane As OutputWindowPane Dim cnt As Integer = ow.OutputWindowPanes.Count owPane = ow.OutputWindowPanes.Add("My New Output Pane") owPane.Activate() owPane.OutputString("My text1" & vbCrLf) owPane.OutputString("My text2" & vbCrLf) owPane.OutputString("My text3" & vbCrLf) End Sub Instead of running it as a Macro, I want to run it as an independent console application that connects to a currently running instance of Visual Studio 2010. I'm having a hard time figuring out how to set the value of DTE. I think I may need to call GetActiveObject, but I'm not sure how. Any pointers?

    Read the article

  • Best practices for organizing .NET P/Invoke code to Win32 APIs

    - by Paul Sasik
    I am refactoring a large and complicated code base in .NET that makes heavy use of P/Invoke to Win32 APIs. The structure of the project is not the greatest and I am finding DllImport statements all over the place, very often duplicated for the same function, and also declared in a variety of ways: The import directives and methods are sometimes declared as public, sometimes private, sometimes as static and sometimes as instance methods. My worry is that refactoring may have unintended consequences but this might be unavoidable. Are there documented best practices I can follow that can help me out? My instict is to organize a static/shared Win32 P/Invoke API class that lists all of these methods and associated constants in one file... (The code base is made up of over 20 projects with a lot of windows message passing and cross-thread calls. It's also a VB.NET project upgraded from VB6 if that makes a difference.)

    Read the article

  • Visual Studio does not flag unterminated string constant in VB.Net

    - by JoelFan
    I noticed that if I leave off the terminating double quote for a string constant in Visual Studio 2010, there is no error or even a warning, i.e. Dim foo as String = "hi However, the continuous integration tool we are using flags an error: error BC30648: String constants must end with a double quote. What's going on here? Is there some language rule in VB.NET that makes a terminating double quote optional "sometimes"? Is there some setting in Visual Studio that will make it flag this as an error?

    Read the article

  • Proving that a function f(n) belongs to a Big-Theta(g(n))

    - by PLS
    Its a exercise that ask to indicate the class Big-Theta(g(n)) the functions belongs to and to prove the assertion. In this case f(n) = (n^2+1)^10 By definition f(n) E Big-Theta(g(n)) <= c1*g(n) < f(n) < c2*g(n), where c1 and c2 are two constants. I know that for this specific f(n) the Big-Theta is g(n^20) but I don't know who to prove it properly. I guess I need to manipulate this inequality but I don't know how

    Read the article

  • Debugging dynamic sql + dynamic tables in MS SQL Server 2008.

    - by Hamish Grubijan
    Hi, I have a messy stored procedure which uses dynamic sql. I can debug it in runtime by adding print @sql; where @sql; is the string containing the dynamic SQL, right before I call execute (@sql);. Now, the multi-page stored procedure also creates dynamic tables and uses them in a query. I want to print those tables to the console right before I do an execute, so that I know exactly what the query is trying to do. However, the SQL Server 08 does not like that. When I try: print #temp_table; and try to compile the S.P. I get this error: The name "#temp_table" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted. Please help.

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >