Search Results

Search found 51 results on 3 pages for 'creditcard'.

Page 1/3 | 1 2 3  | Next Page >

  • Best practices to store CreditCard information into DataBase

    - by Garis Suero
    In my country the online payments are not an old thing, the first time i saw a web application taking payments directly to a local bank account was last year. So, Im a newbie coding web payment system. My question is, what are the best practices to store creditcard information into the database... I have many ideas: encrypting the creditcard, database security restriction, etc. What have you done?

    Read the article

  • Google adwords API - credit card safety question

    - by user5650
    Google is asking me to fax credit card xerox in order to activate adwords API in MCC. 1) Are there alternatives to this - is there a 3rd party provider who will give me this service without me sending them the credit card info? 2) How secure is it to send my credit card fax via some online fax service? 3) Do you think they will reject the application if I hide my CVV number in the fax? Any other thoughts appreciated.

    Read the article

  • Google adwords API - credit card safety question

    - by anon
    Hi, Google is asking me to fax credit card xerox in order to activate adwords API in MCC. This really sucks imo... they could have had prepaid option. In any case, my questions: 1) Are there alternatives to this - is there a 3rd party provider who will give me this service without me sending them the credit card info? 2) How secure is it to send my credit card fax via some online fax service? 3) Do you think they will reject the application if I hide my CVV number in the fax? Any other thoughts appreciated :) thanks

    Read the article

  • What I need to know if I want credit card payments in an ecommerce website

    - by Andriane
    I live in Costa Rica (central america). I want to build an ecommerce website with credit card payments, I know Asp.NET and SQL Server 2008. I know paypal and the express checkout solution, but many people (and clients) here doesnt like it or dont use it. Paypal and Authorize.Net dont support countries of Latin America, so if you can tell me one company who can or what can I do to setup my shopping cart, im studing right now security and how to implement SSL certificates and encrypt sensible data and PCI compliance in some way. I need this for my own framework in ASP.NET and provide ecommerce solutions here in my country.

    Read the article

  • Best tools to build an auction website

    - by Daniel Loureiro
    Can I get your feedback on the best tools to build an auction website with the following features: The site takes a commission (like 5%) on each transaction Each user can assign a rating (like 4.5 stars) to his completed transaction, and comment on the seller's profile. Accept payments in paypal and credit card I've been looking into Joomla! and JomSocial but they haven't convinced me much so far. I have some programming experience in C, Python and Java. If no CMS tools are of use I'd appreaciate if you could tell the best route to take in programming to get the auction site done.

    Read the article

  • Automated Post-billing Service/Solution

    - by geoffreak
    I'm trying to find a solution or service that will allow for my company to automatically take a customer's credit card information via the web to keep on file and bill against based on how much they have used the services we provide. We need a service that will also handle the payment processing as well. Note that this is not recurring billing. The bill at the end of each month won't be the same. Presently, we are having to take a customer's credit card information over the phone and manually input it into Quickbooks, but this just doesn't work for scalability. We will still be manually invoicing the customers, but we need automated credit card acceptance and storage without the liabilities involved with storing it on our own server. Solutions that integrate with Wordpress would be a plus.

    Read the article

  • Looking for a modern payment processor which accepts adult sites

    - by JakeRow123
    I love how easy authorize.net is to use, but they don't accept adult sites. I am lanching an adult site soon but I can't find any good credit card processors I can use. Most sites use CCbill or Epoch but they are both terrible since the customer is redirected to their external site which also has an ancient 1990's look. It's not like authorize.net's API that you can query and get the result back as to whether the payment went through or not. This makes authorize.net blend seamlessly with the product. But since adult sites are against their TOS and also paypals, what is a good alternative? I am looking for one that won't redirect the user from my site, is big enough to be reliable and trustworthy and has fairly low rates. Any help is appreciated!

    Read the article

  • Using paypal to process credit cards in Sweden through an API [on hold]

    - by Mastikator
    I'm looking for a Paypal API that lets me process credit cards to make payments without being redirected to a paypal site and without enforcing consumers to use their paypal account. And it needs to work in Sweden. The ones I've looked at (dodirectpayment, expresscheckout, paypalpro gateway) and none of them have let me process credit cards in Sweden via an API that doesn't force the user to visit the paypal login site. I have a form on my webpage that the user types their credit card number, ccv2, expiration, name, address, etc. I need an API that works in Sweden that simply processes the request, and it has to be without the step of being redirected into a paypal website. The ones that I have found only worked in a select few countries, is there an international solution? I've already spent over 12 work hours just looking for an API that meets my requirements.

    Read the article

  • What payment processors fullfill this requirements and what are their pluses and minuses? [on hold]

    - by Sharen Eayrs
    Accept credit card Allow me to automatically credit a customers' account. We're not selling e-book. We're selling a credit to our account. So it's important that customers do not get credited twice. Easy to program and integrate with our sites. Have affiliate programs. Transfer money to bank accounts quickly Accept merchants from many countries No monthly fee is a plus. I am thinking of using 2co.com avangate.com clickbank.com Some people reccomend https://stripe.com/us/features (is it easy to implement) http://www.paymentwall.com/ There are so many payment processor I am very confused. Can anyone tell me pluses and minuses of those ones. or perhaps others. What would be the plus and minuses of those 3 that you know off

    Read the article

  • Inheritance Mapping Strategies with Entity Framework Code First CTP5: Part 3 – Table per Concrete Type (TPC) and Choosing Strategy Guidelines

    - by mortezam
    This is the third (and last) post in a series that explains different approaches to map an inheritance hierarchy with EF Code First. I've described these strategies in previous posts: Part 1 – Table per Hierarchy (TPH) Part 2 – Table per Type (TPT)In today’s blog post I am going to discuss Table per Concrete Type (TPC) which completes the inheritance mapping strategies supported by EF Code First. At the end of this post I will provide some guidelines to choose an inheritance strategy mainly based on what we've learned in this series. TPC and Entity Framework in the Past Table per Concrete type is somehow the simplest approach suggested, yet using TPC with EF is one of those concepts that has not been covered very well so far and I've seen in some resources that it was even discouraged. The reason for that is just because Entity Data Model Designer in VS2010 doesn't support TPC (even though the EF runtime does). That basically means if you are following EF's Database-First or Model-First approaches then configuring TPC requires manually writing XML in the EDMX file which is not considered to be a fun practice. Well, no more. You'll see that with Code First, creating TPC is perfectly possible with fluent API just like other strategies and you don't need to avoid TPC due to the lack of designer support as you would probably do in other EF approaches. Table per Concrete Type (TPC)In Table per Concrete type (aka Table per Concrete class) we use exactly one table for each (nonabstract) class. All properties of a class, including inherited properties, can be mapped to columns of this table, as shown in the following figure: As you can see, the SQL schema is not aware of the inheritance; effectively, we’ve mapped two unrelated tables to a more expressive class structure. If the base class was concrete, then an additional table would be needed to hold instances of that class. I have to emphasize that there is no relationship between the database tables, except for the fact that they share some similar columns. TPC Implementation in Code First Just like the TPT implementation, we need to specify a separate table for each of the subclasses. We also need to tell Code First that we want all of the inherited properties to be mapped as part of this table. In CTP5, there is a new helper method on EntityMappingConfiguration class called MapInheritedProperties that exactly does this for us. Here is the complete object model as well as the fluent API to create a TPC mapping: public abstract class BillingDetail {     public int BillingDetailId { get; set; }     public string Owner { get; set; }     public string Number { get; set; } }          public class BankAccount : BillingDetail {     public string BankName { get; set; }     public string Swift { get; set; } }          public class CreditCard : BillingDetail {     public int CardType { get; set; }     public string ExpiryMonth { get; set; }     public string ExpiryYear { get; set; } }      public class InheritanceMappingContext : DbContext {     public DbSet<BillingDetail> BillingDetails { get; set; }              protected override void OnModelCreating(ModelBuilder modelBuilder)     {         modelBuilder.Entity<BankAccount>().Map(m =>         {             m.MapInheritedProperties();             m.ToTable("BankAccounts");         });         modelBuilder.Entity<CreditCard>().Map(m =>         {             m.MapInheritedProperties();             m.ToTable("CreditCards");         });                 } } The Importance of EntityMappingConfiguration ClassAs a side note, it worth mentioning that EntityMappingConfiguration class turns out to be a key type for inheritance mapping in Code First. Here is an snapshot of this class: namespace System.Data.Entity.ModelConfiguration.Configuration.Mapping {     public class EntityMappingConfiguration<TEntityType> where TEntityType : class     {         public ValueConditionConfiguration Requires(string discriminator);         public void ToTable(string tableName);         public void MapInheritedProperties();     } } As you have seen so far, we used its Requires method to customize TPH. We also used its ToTable method to create a TPT and now we are using its MapInheritedProperties along with ToTable method to create our TPC mapping. TPC Configuration is Not Done Yet!We are not quite done with our TPC configuration and there is more into this story even though the fluent API we saw perfectly created a TPC mapping for us in the database. To see why, let's start working with our object model. For example, the following code creates two new objects of BankAccount and CreditCard types and tries to add them to the database: using (var context = new InheritanceMappingContext()) {     BankAccount bankAccount = new BankAccount();     CreditCard creditCard = new CreditCard() { CardType = 1 };                      context.BillingDetails.Add(bankAccount);     context.BillingDetails.Add(creditCard);     context.SaveChanges(); } Running this code throws an InvalidOperationException with this message: The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: AcceptChanges cannot continue because the object's key values conflict with another object in the ObjectStateManager. Make sure that the key values are unique before calling AcceptChanges. The reason we got this exception is because DbContext.SaveChanges() internally invokes SaveChanges method of its internal ObjectContext. ObjectContext's SaveChanges method on its turn by default calls AcceptAllChanges after it has performed the database modifications. AcceptAllChanges method merely iterates over all entries in ObjectStateManager and invokes AcceptChanges on each of them. Since the entities are in Added state, AcceptChanges method replaces their temporary EntityKey with a regular EntityKey based on the primary key values (i.e. BillingDetailId) that come back from the database and that's where the problem occurs since both the entities have been assigned the same value for their primary key by the database (i.e. on both BillingDetailId = 1) and the problem is that ObjectStateManager cannot track objects of the same type (i.e. BillingDetail) with the same EntityKey value hence it throws. If you take a closer look at the TPC's SQL schema above, you'll see why the database generated the same values for the primary keys: the BillingDetailId column in both BankAccounts and CreditCards table has been marked as identity. How to Solve The Identity Problem in TPC As you saw, using SQL Server’s int identity columns doesn't work very well together with TPC since there will be duplicate entity keys when inserting in subclasses tables with all having the same identity seed. Therefore, to solve this, either a spread seed (where each table has its own initial seed value) will be needed, or a mechanism other than SQL Server’s int identity should be used. Some other RDBMSes have other mechanisms allowing a sequence (identity) to be shared by multiple tables, and something similar can be achieved with GUID keys in SQL Server. While using GUID keys, or int identity keys with different starting seeds will solve the problem but yet another solution would be to completely switch off identity on the primary key property. As a result, we need to take the responsibility of providing unique keys when inserting records to the database. We will go with this solution since it works regardless of which database engine is used. Switching Off Identity in Code First We can switch off identity simply by placing DatabaseGenerated attribute on the primary key property and pass DatabaseGenerationOption.None to its constructor. DatabaseGenerated attribute is a new data annotation which has been added to System.ComponentModel.DataAnnotations namespace in CTP5: public abstract class BillingDetail {     [DatabaseGenerated(DatabaseGenerationOption.None)]     public int BillingDetailId { get; set; }     public string Owner { get; set; }     public string Number { get; set; } } As always, we can achieve the same result by using fluent API, if you prefer that: modelBuilder.Entity<BillingDetail>()             .Property(p => p.BillingDetailId)             .HasDatabaseGenerationOption(DatabaseGenerationOption.None); Working With The Object Model Our TPC mapping is ready and we can try adding new records to the database. But, like I said, now we need to take care of providing unique keys when creating new objects: using (var context = new InheritanceMappingContext()) {     BankAccount bankAccount = new BankAccount()      {          BillingDetailId = 1                          };     CreditCard creditCard = new CreditCard()      {          BillingDetailId = 2,         CardType = 1     };                      context.BillingDetails.Add(bankAccount);     context.BillingDetails.Add(creditCard);     context.SaveChanges(); } Polymorphic Associations with TPC is Problematic The main problem with this approach is that it doesn’t support Polymorphic Associations very well. After all, in the database, associations are represented as foreign key relationships and in TPC, the subclasses are all mapped to different tables so a polymorphic association to their base class (abstract BillingDetail in our example) cannot be represented as a simple foreign key relationship. For example, consider the the domain model we introduced here where User has a polymorphic association with BillingDetail. This would be problematic in our TPC Schema, because if User has a many-to-one relationship with BillingDetail, the Users table would need a single foreign key column, which would have to refer both concrete subclass tables. This isn’t possible with regular foreign key constraints. Schema Evolution with TPC is Complex A further conceptual problem with this mapping strategy is that several different columns, of different tables, share exactly the same semantics. This makes schema evolution more complex. For example, a change to a base class property results in changes to multiple columns. It also makes it much more difficult to implement database integrity constraints that apply to all subclasses. Generated SQLLet's examine SQL output for polymorphic queries in TPC mapping. For example, consider this polymorphic query for all BillingDetails and the resulting SQL statements that being executed in the database: var query = from b in context.BillingDetails select b; Just like the SQL query generated by TPT mapping, the CASE statements that you see in the beginning of the query is merely to ensure columns that are irrelevant for a particular row have NULL values in the returning flattened table. (e.g. BankName for a row that represents a CreditCard type). TPC's SQL Queries are Union Based As you can see in the above screenshot, the first SELECT uses a FROM-clause subquery (which is selected with a red rectangle) to retrieve all instances of BillingDetails from all concrete class tables. The tables are combined with a UNION operator, and a literal (in this case, 0 and 1) is inserted into the intermediate result; (look at the lines highlighted in yellow.) EF reads this to instantiate the correct class given the data from a particular row. A union requires that the queries that are combined, project over the same columns; hence, EF has to pad and fill up nonexistent columns with NULL. This query will really perform well since here we can let the database optimizer find the best execution plan to combine rows from several tables. There is also no Joins involved so it has a better performance than the SQL queries generated by TPT where a Join is required between the base and subclasses tables. Choosing Strategy GuidelinesBefore we get into this discussion, I want to emphasize that there is no one single "best strategy fits all scenarios" exists. As you saw, each of the approaches have their own advantages and drawbacks. Here are some rules of thumb to identify the best strategy in a particular scenario: If you don’t require polymorphic associations or queries, lean toward TPC—in other words, if you never or rarely query for BillingDetails and you have no class that has an association to BillingDetail base class. I recommend TPC (only) for the top level of your class hierarchy, where polymorphism isn’t usually required, and when modification of the base class in the future is unlikely. If you do require polymorphic associations or queries, and subclasses declare relatively few properties (particularly if the main difference between subclasses is in their behavior), lean toward TPH. Your goal is to minimize the number of nullable columns and to convince yourself (and your DBA) that a denormalized schema won’t create problems in the long run. If you do require polymorphic associations or queries, and subclasses declare many properties (subclasses differ mainly by the data they hold), lean toward TPT. Or, depending on the width and depth of your inheritance hierarchy and the possible cost of joins versus unions, use TPC. By default, choose TPH only for simple problems. For more complex cases (or when you’re overruled by a data modeler insisting on the importance of nullability constraints and normalization), you should consider the TPT strategy. But at that point, ask yourself whether it may not be better to remodel inheritance as delegation in the object model (delegation is a way of making composition as powerful for reuse as inheritance). Complex inheritance is often best avoided for all sorts of reasons unrelated to persistence or ORM. EF acts as a buffer between the domain and relational models, but that doesn’t mean you can ignore persistence concerns when designing your classes. SummaryIn this series, we focused on one of the main structural aspect of the object/relational paradigm mismatch which is inheritance and discussed how EF solve this problem as an ORM solution. We learned about the three well-known inheritance mapping strategies and their implementations in EF Code First. Hopefully it gives you a better insight about the mapping of inheritance hierarchies as well as choosing the best strategy for your particular scenario. Happy New Year and Happy Code-Firsting! References ADO.NET team blog Java Persistence with Hibernate book a { color: #5A99FF; } a:visited { color: #5A99FF; } .title { padding-bottom: 5px; font-family: Segoe UI; font-size: 11pt; font-weight: bold; padding-top: 15px; } .code, .typeName { font-family: consolas; } .typeName { color: #2b91af; } .padTop5 { padding-top: 5px; } .padTop10 { padding-top: 10px; } .exception { background-color: #f0f0f0; font-style: italic; padding-bottom: 5px; padding-left: 5px; padding-top: 5px; padding-right: 5px; }

    Read the article

  • how to access generated groupname for asp radiobutton

    - by rap-uvic
    Hi, I need to access radiobutton groupname in my jquery. However, groupname that's rendered for an asp radiobutton is kind of different. Example: <asp:RadioButton runat="server" GroupName="payment" ID="creditcard" Checked="true" value="creditcard" /> will generate: <input type="radio" checked="checked" value="creditcard" name="ctl00$ContentPlaceHolder1$payment" id="ctl00_ContentPlaceHolder1_creditcard"> I can't work with <%=creditcard.GroupName% in jquery. Is there a way I can get the generated groupname or name for it?

    Read the article

  • Inheritance Mapping Strategies with Entity Framework Code First CTP5 Part 1: Table per Hierarchy (TPH)

    - by mortezam
    A simple strategy for mapping classes to database tables might be “one table for every entity persistent class.” This approach sounds simple enough and, indeed, works well until we encounter inheritance. Inheritance is such a visible structural mismatch between the object-oriented and relational worlds because object-oriented systems model both “is a” and “has a” relationships. SQL-based models provide only "has a" relationships between entities; SQL database management systems don’t support type inheritance—and even when it’s available, it’s usually proprietary or incomplete. There are three different approaches to representing an inheritance hierarchy: Table per Hierarchy (TPH): Enable polymorphism by denormalizing the SQL schema, and utilize a type discriminator column that holds type information. Table per Type (TPT): Represent "is a" (inheritance) relationships as "has a" (foreign key) relationships. Table per Concrete class (TPC): Discard polymorphism and inheritance relationships completely from the SQL schema.I will explain each of these strategies in a series of posts and this one is dedicated to TPH. In this series we'll deeply dig into each of these strategies and will learn about "why" to choose them as well as "how" to implement them. Hopefully it will give you a better idea about which strategy to choose in a particular scenario. Inheritance Mapping with Entity Framework Code FirstAll of the inheritance mapping strategies that we discuss in this series will be implemented by EF Code First CTP5. The CTP5 build of the new EF Code First library has been released by ADO.NET team earlier this month. EF Code-First enables a pretty powerful code-centric development workflow for working with data. I’m a big fan of the EF Code First approach, and I’m pretty excited about a lot of productivity and power that it brings. When it comes to inheritance mapping, not only Code First fully supports all the strategies but also gives you ultimate flexibility to work with domain models that involves inheritance. The fluent API for inheritance mapping in CTP5 has been improved a lot and now it's more intuitive and concise in compare to CTP4. A Note For Those Who Follow Other Entity Framework ApproachesIf you are following EF's "Database First" or "Model First" approaches, I still recommend to read this series since although the implementation is Code First specific but the explanations around each of the strategies is perfectly applied to all approaches be it Code First or others. A Note For Those Who are New to Entity Framework and Code-FirstIf you choose to learn EF you've chosen well. If you choose to learn EF with Code First you've done even better. To get started, you can find a great walkthrough by Scott Guthrie here and another one by ADO.NET team here. In this post, I assume you already setup your machine to do Code First development and also that you are familiar with Code First fundamentals and basic concepts. You might also want to check out my other posts on EF Code First like Complex Types and Shared Primary Key Associations. A Top Down Development ScenarioThese posts take a top-down approach; it assumes that you’re starting with a domain model and trying to derive a new SQL schema. Therefore, we start with an existing domain model, implement it in C# and then let Code First create the database schema for us. However, the mapping strategies described are just as relevant if you’re working bottom up, starting with existing database tables. I’ll show some tricks along the way that help you dealing with nonperfect table layouts. Let’s start with the mapping of entity inheritance. -- The Domain ModelIn our domain model, we have a BillingDetail base class which is abstract (note the italic font on the UML class diagram below). We do allow various billing types and represent them as subclasses of BillingDetail class. As for now, we support CreditCard and BankAccount: Implement the Object Model with Code First As always, we start with the POCO classes. Note that in our DbContext, I only define one DbSet for the base class which is BillingDetail. Code First will find the other classes in the hierarchy based on Reachability Convention. public abstract class BillingDetail  {     public int BillingDetailId { get; set; }     public string Owner { get; set; }             public string Number { get; set; } } public class BankAccount : BillingDetail {     public string BankName { get; set; }     public string Swift { get; set; } } public class CreditCard : BillingDetail {     public int CardType { get; set; }                     public string ExpiryMonth { get; set; }     public string ExpiryYear { get; set; } } public class InheritanceMappingContext : DbContext {     public DbSet<BillingDetail> BillingDetails { get; set; } } This object model is all that is needed to enable inheritance with Code First. If you put this in your application you would be able to immediately start working with the database and do CRUD operations. Before going into details about how EF Code First maps this object model to the database, we need to learn about one of the core concepts of inheritance mapping: polymorphic and non-polymorphic queries. Polymorphic Queries LINQ to Entities and EntitySQL, as object-oriented query languages, both support polymorphic queries—that is, queries for instances of a class and all instances of its subclasses, respectively. For example, consider the following query: IQueryable<BillingDetail> linqQuery = from b in context.BillingDetails select b; List<BillingDetail> billingDetails = linqQuery.ToList(); Or the same query in EntitySQL: string eSqlQuery = @"SELECT VAlUE b FROM BillingDetails AS b"; ObjectQuery<BillingDetail> objectQuery = ((IObjectContextAdapter)context).ObjectContext                                                                          .CreateQuery<BillingDetail>(eSqlQuery); List<BillingDetail> billingDetails = objectQuery.ToList(); linqQuery and eSqlQuery are both polymorphic and return a list of objects of the type BillingDetail, which is an abstract class but the actual concrete objects in the list are of the subtypes of BillingDetail: CreditCard and BankAccount. Non-polymorphic QueriesAll LINQ to Entities and EntitySQL queries are polymorphic which return not only instances of the specific entity class to which it refers, but all subclasses of that class as well. On the other hand, Non-polymorphic queries are queries whose polymorphism is restricted and only returns instances of a particular subclass. In LINQ to Entities, this can be specified by using OfType<T>() Method. For example, the following query returns only instances of BankAccount: IQueryable<BankAccount> query = from b in context.BillingDetails.OfType<BankAccount>() select b; EntitySQL has OFTYPE operator that does the same thing: string eSqlQuery = @"SELECT VAlUE b FROM OFTYPE(BillingDetails, Model.BankAccount) AS b"; In fact, the above query with OFTYPE operator is a short form of the following query expression that uses TREAT and IS OF operators: string eSqlQuery = @"SELECT VAlUE TREAT(b as Model.BankAccount)                       FROM BillingDetails AS b                       WHERE b IS OF(Model.BankAccount)"; (Note that in the above query, Model.BankAccount is the fully qualified name for BankAccount class. You need to change "Model" with your own namespace name.) Table per Class Hierarchy (TPH)An entire class hierarchy can be mapped to a single table. This table includes columns for all properties of all classes in the hierarchy. The concrete subclass represented by a particular row is identified by the value of a type discriminator column. You don’t have to do anything special in Code First to enable TPH. It's the default inheritance mapping strategy: This mapping strategy is a winner in terms of both performance and simplicity. It’s the best-performing way to represent polymorphism—both polymorphic and nonpolymorphic queries perform well—and it’s even easy to implement by hand. Ad-hoc reporting is possible without complex joins or unions. Schema evolution is straightforward. Discriminator Column As you can see in the DB schema above, Code First has to add a special column to distinguish between persistent classes: the discriminator. This isn’t a property of the persistent class in our object model; it’s used internally by EF Code First. By default, the column name is "Discriminator", and its type is string. The values defaults to the persistent class names —in this case, “BankAccount” or “CreditCard”. EF Code First automatically sets and retrieves the discriminator values. TPH Requires Properties in SubClasses to be Nullable in the Database TPH has one major problem: Columns for properties declared by subclasses will be nullable in the database. For example, Code First created an (INT, NULL) column to map CardType property in CreditCard class. However, in a typical mapping scenario, Code First always creates an (INT, NOT NULL) column in the database for an int property in persistent class. But in this case, since BankAccount instance won’t have a CardType property, the CardType field must be NULL for that row so Code First creates an (INT, NULL) instead. If your subclasses each define several non-nullable properties, the loss of NOT NULL constraints may be a serious problem from the point of view of data integrity. TPH Violates the Third Normal FormAnother important issue is normalization. We’ve created functional dependencies between nonkey columns, violating the third normal form. Basically, the value of Discriminator column determines the corresponding values of the columns that belong to the subclasses (e.g. BankName) but Discriminator is not part of the primary key for the table. As always, denormalization for performance can be misleading, because it sacrifices long-term stability, maintainability, and the integrity of data for immediate gains that may be also achieved by proper optimization of the SQL execution plans (in other words, ask your DBA). Generated SQL QueryLet's take a look at the SQL statements that EF Code First sends to the database when we write queries in LINQ to Entities or EntitySQL. For example, the polymorphic query for BillingDetails that you saw, generates the following SQL statement: SELECT  [Extent1].[Discriminator] AS [Discriminator],  [Extent1].[BillingDetailId] AS [BillingDetailId],  [Extent1].[Owner] AS [Owner],  [Extent1].[Number] AS [Number],  [Extent1].[BankName] AS [BankName],  [Extent1].[Swift] AS [Swift],  [Extent1].[CardType] AS [CardType],  [Extent1].[ExpiryMonth] AS [ExpiryMonth],  [Extent1].[ExpiryYear] AS [ExpiryYear] FROM [dbo].[BillingDetails] AS [Extent1] WHERE [Extent1].[Discriminator] IN ('BankAccount','CreditCard') Or the non-polymorphic query for the BankAccount subclass generates this SQL statement: SELECT  [Extent1].[BillingDetailId] AS [BillingDetailId],  [Extent1].[Owner] AS [Owner],  [Extent1].[Number] AS [Number],  [Extent1].[BankName] AS [BankName],  [Extent1].[Swift] AS [Swift] FROM [dbo].[BillingDetails] AS [Extent1] WHERE [Extent1].[Discriminator] = 'BankAccount' Note how Code First adds a restriction on the discriminator column and also how it only selects those columns that belong to BankAccount entity. Change Discriminator Column Data Type and Values With Fluent API Sometimes, especially in legacy schemas, you need to override the conventions for the discriminator column so that Code First can work with the schema. The following fluent API code will change the discriminator column name to "BillingDetailType" and the values to "BA" and "CC" for BankAccount and CreditCard respectively: protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder) {     modelBuilder.Entity<BillingDetail>()                 .Map<BankAccount>(m => m.Requires("BillingDetailType").HasValue("BA"))                 .Map<CreditCard>(m => m.Requires("BillingDetailType").HasValue("CC")); } Also, changing the data type of discriminator column is interesting. In the above code, we passed strings to HasValue method but this method has been defined to accepts a type of object: public void HasValue(object value); Therefore, if for example we pass a value of type int to it then Code First not only use our desired values (i.e. 1 & 2) in the discriminator column but also changes the column type to be (INT, NOT NULL): modelBuilder.Entity<BillingDetail>()             .Map<BankAccount>(m => m.Requires("BillingDetailType").HasValue(1))             .Map<CreditCard>(m => m.Requires("BillingDetailType").HasValue(2)); SummaryIn this post we learned about Table per Hierarchy as the default mapping strategy in Code First. The disadvantages of the TPH strategy may be too serious for your design—after all, denormalized schemas can become a major burden in the long run. Your DBA may not like it at all. In the next post, we will learn about Table per Type (TPT) strategy that doesn’t expose you to this problem. References ADO.NET team blog Java Persistence with Hibernate book a { text-decoration: none; } a:visited { color: Blue; } .title { padding-bottom: 5px; font-family: Segoe UI; font-size: 11pt; font-weight: bold; padding-top: 15px; } .code, .typeName { font-family: consolas; } .typeName { color: #2b91af; } .padTop5 { padding-top: 5px; } .padTop10 { padding-top: 10px; } p.MsoNormal { margin-top: 0in; margin-right: 0in; margin-bottom: 10.0pt; margin-left: 0in; line-height: 115%; font-size: 11.0pt; font-family: "Calibri" , "sans-serif"; }

    Read the article

  • New Validation Attributes in ASP.NET MVC 3 Future

    - by imran_ku07
         Introduction:             Validating user inputs is an very important step in collecting information from users because it helps you to prevent errors during processing data. Incomplete or improperly formatted user inputs will create lot of problems for your application. Fortunately, ASP.NET MVC 3 makes it very easy to validate most common input validations. ASP.NET MVC 3 includes Required, StringLength, Range, RegularExpression, Compare and Remote validation attributes for common input validation scenarios. These validation attributes validates most of your user inputs but still validation for Email, File Extension, Credit Card, URL, etc are missing. Fortunately, some of these validation attributes are available in ASP.NET MVC 3 Future. In this article, I will show you how to leverage Email, Url, CreditCard and FileExtensions validation attributes(which are available in ASP.NET MVC 3 Future) in ASP.NET MVC 3 application.       Description:             First of all you need to download ASP.NET MVC 3 RTM Source Code from here. Then extract all files in a folder. Then open MvcFutures project from mvc3-rtm-sources\mvc3\src\MvcFutures folder. Build the project. In case, if you get compile time error(s) then simply remove the reference of System.Web.WebPages and System.Web.Mvc assemblies and add the reference of System.Web.WebPages and System.Web.Mvc 3 assemblies again but from the .NET tab and then build the project again, it will create a Microsoft.Web.Mvc assembly inside mvc3-rtm-sources\mvc3\src\MvcFutures\obj\Debug folder. Now we can use Microsoft.Web.Mvc assembly inside our application.             Create a new ASP.NET MVC 3 application. For demonstration purpose, I will create a dummy model UserInformation. So create a new class file UserInformation.cs inside Model folder and add the following code,   public class UserInformation { [Required] public string Name { get; set; } [Required] [EmailAddress] public string Email { get; set; } [Required] [Url] public string Website { get; set; } [Required] [CreditCard] public string CreditCard { get; set; } [Required] [FileExtensions(Extensions = "jpg,jpeg")] public string Image { get; set; } }             Inside UserInformation class, I am using Email, Url, CreditCard and FileExtensions validation attributes which are defined in Microsoft.Web.Mvc assembly. By default FileExtensionsAttribute allows png, jpg, jpeg and gif extensions. You can override this by using Extensions property of FileExtensionsAttribute class.             Then just open(or create) HomeController.cs file and add the following code,   public class HomeController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(UserInformation u) { return View(); } }             Next just open(or create) Index view for Home controller and add the following code,  @model NewValidationAttributesinASPNETMVC3Future.Model.UserInformation @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Index</h2> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>UserInformation</legend> <div class="editor-label"> @Html.LabelFor(model => model.Name) </div> <div class="editor-field"> @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> <div class="editor-label"> @Html.LabelFor(model => model.Email) </div> <div class="editor-field"> @Html.EditorFor(model => model.Email) @Html.ValidationMessageFor(model => model.Email) </div> <div class="editor-label"> @Html.LabelFor(model => model.Website) </div> <div class="editor-field"> @Html.EditorFor(model => model.Website) @Html.ValidationMessageFor(model => model.Website) </div> <div class="editor-label"> @Html.LabelFor(model => model.CreditCard) </div> <div class="editor-field"> @Html.EditorFor(model => model.CreditCard) @Html.ValidationMessageFor(model => model.CreditCard) </div> <div class="editor-label"> @Html.LabelFor(model => model.Image) </div> <div class="editor-field"> @Html.EditorFor(model => model.Image) @Html.ValidationMessageFor(model => model.Image) </div> <p> <input type="submit" value="Save" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div>             Now just run your application. You will find that both client side and server side validation for the above validation attributes works smoothly.                      Summary:             Email, URL, Credit Card and File Extension input validations are very common. In this article, I showed you how you can validate these input validations into your application. I explained this with an example. I am also attaching a sample application which also includes Microsoft.Web.Mvc.dll. So you can add a reference of Microsoft.Web.Mvc assembly directly instead of doing any manual work. Hope you will enjoy this article too.   SyntaxHighlighter.all()

    Read the article

  • RegEx for Dynamic URL Goals settings in Google Analytics

    - by gaaustralia
    Hi, I have tried to work this regex to set up a goal in GA for 2 days, but I cannot get my head around it... The url format is like this: /purchase.php?cDd=1&transaction_id=xxxxxxx&verify=xxxxxxxxxxxxxxxx=&method=creditcard&type=purchase transaction_id= is populated with a sept of numbers verify= is populated by a string of numbers, letters in both caps and lower case Basically I would like to only match URLs which finish by "&method=creditcard&type=purchase" I have tried to just put &method=creditcard&type=purchase but it does retrieve other URLs too Would anyone has any ideas

    Read the article

  • Inheritance Mapping Strategies with Entity Framework Code First CTP5: Part 2 – Table per Type (TPT)

    - by mortezam
    In the previous blog post you saw that there are three different approaches to representing an inheritance hierarchy and I explained Table per Hierarchy (TPH) as the default mapping strategy in EF Code First. We argued that the disadvantages of TPH may be too serious for our design since it results in denormalized schemas that can become a major burden in the long run. In today’s blog post we are going to learn about Table per Type (TPT) as another inheritance mapping strategy and we'll see that TPT doesn’t expose us to this problem. Table per Type (TPT)Table per Type is about representing inheritance relationships as relational foreign key associations. Every class/subclass that declares persistent properties—including abstract classes—has its own table. The table for subclasses contains columns only for each noninherited property (each property declared by the subclass itself) along with a primary key that is also a foreign key of the base class table. This approach is shown in the following figure: For example, if an instance of the CreditCard subclass is made persistent, the values of properties declared by the BillingDetail base class are persisted to a new row of the BillingDetails table. Only the values of properties declared by the subclass (i.e. CreditCard) are persisted to a new row of the CreditCards table. The two rows are linked together by their shared primary key value. Later, the subclass instance may be retrieved from the database by joining the subclass table with the base class table. TPT Advantages The primary advantage of this strategy is that the SQL schema is normalized. In addition, schema evolution is straightforward (modifying the base class or adding a new subclass is just a matter of modify/add one table). Integrity constraint definition are also straightforward (note how CardType in CreditCards table is now a non-nullable column). Another much more important advantage is the ability to handle polymorphic associations (a polymorphic association is an association to a base class, hence to all classes in the hierarchy with dynamic resolution of the concrete class at runtime). A polymorphic association to a particular subclass may be represented as a foreign key referencing the table of that particular subclass. Implement TPT in EF Code First We can create a TPT mapping simply by placing Table attribute on the subclasses to specify the mapped table name (Table attribute is a new data annotation and has been added to System.ComponentModel.DataAnnotations namespace in CTP5): public abstract class BillingDetail {     public int BillingDetailId { get; set; }     public string Owner { get; set; }     public string Number { get; set; } } [Table("BankAccounts")] public class BankAccount : BillingDetail {     public string BankName { get; set; }     public string Swift { get; set; } } [Table("CreditCards")] public class CreditCard : BillingDetail {     public int CardType { get; set; }     public string ExpiryMonth { get; set; }     public string ExpiryYear { get; set; } } public class InheritanceMappingContext : DbContext {     public DbSet<BillingDetail> BillingDetails { get; set; } } If you prefer fluent API, then you can create a TPT mapping by using ToTable() method: protected override void OnModelCreating(ModelBuilder modelBuilder) {     modelBuilder.Entity<BankAccount>().ToTable("BankAccounts");     modelBuilder.Entity<CreditCard>().ToTable("CreditCards"); } Generated SQL For QueriesLet’s take an example of a simple non-polymorphic query that returns a list of all the BankAccounts: var query = from b in context.BillingDetails.OfType<BankAccount>() select b; Executing this query (by invoking ToList() method) results in the following SQL statements being sent to the database (on the bottom, you can also see the result of executing the generated query in SQL Server Management Studio): Now, let’s take an example of a very simple polymorphic query that requests all the BillingDetails which includes both BankAccount and CreditCard types: projects some properties out of the base class BillingDetail, without querying for anything from any of the subclasses: var query = from b in context.BillingDetails             select new { b.BillingDetailId, b.Number, b.Owner }; -- var query = from b in context.BillingDetails select b; This LINQ query seems even more simple than the previous one but the resulting SQL query is not as simple as you might expect: -- As you can see, EF Code First relies on an INNER JOIN to detect the existence (or absence) of rows in the subclass tables CreditCards and BankAccounts so it can determine the concrete subclass for a particular row of the BillingDetails table. Also the SQL CASE statements that you see in the beginning of the query is just to ensure columns that are irrelevant for a particular row have NULL values in the returning flattened table. (e.g. BankName for a row that represents a CreditCard type) TPT ConsiderationsEven though this mapping strategy is deceptively simple, the experience shows that performance can be unacceptable for complex class hierarchies because queries always require a join across many tables. In addition, this mapping strategy is more difficult to implement by hand— even ad-hoc reporting is more complex. This is an important consideration if you plan to use handwritten SQL in your application (For ad hoc reporting, database views provide a way to offset the complexity of the TPT strategy. A view may be used to transform the table-per-type model into the much simpler table-per-hierarchy model.) SummaryIn this post we learned about Table per Type as the second inheritance mapping in our series. So far, the strategies we’ve discussed require extra consideration with regard to the SQL schema (e.g. in TPT, foreign keys are needed). This situation changes with the Table per Concrete Type (TPC) that we will discuss in the next post. References ADO.NET team blog Java Persistence with Hibernate book a { text-decoration: none; } a:visited { color: Blue; } .title { padding-bottom: 5px; font-family: Segoe UI; font-size: 11pt; font-weight: bold; padding-top: 15px; } .code, .typeName { font-family: consolas; } .typeName { color: #2b91af; } .padTop5 { padding-top: 5px; } .padTop10 { padding-top: 10px; } p.MsoNormal { margin-top: 0in; margin-right: 0in; margin-bottom: 10.0pt; margin-left: 0in; line-height: 115%; font-size: 11.0pt; font-family: "Calibri" , "sans-serif"; }

    Read the article

  • Enum.HasFlag method in C# 4.0

    - by Jalpesh P. Vadgama
    Enums in dot net programming is a great facility and we all used it to increase code readability. In earlier version of .NET framework we don’t have any method anything that will check whether a value is assigned to it or not. In C# 4.0 we have new static method called HasFlag which will check that particular value is assigned or not. Let’s take an example for that. First I have created a enum called PaymentType which could have two values Credit Card or Debit Card. Just like following. public enum PaymentType { DebitCard=1, CreditCard=2 } Now We are going to assigned one of the value to this enum instance and then with the help of HasFlag method we are going to check whether particular value is assigned to enum or not like following. protected void Page_Load(object sender, EventArgs e) { PaymentType paymentType = PaymentType.CreditCard; if (paymentType.HasFlag(PaymentType.DebitCard)) { Response.Write("Process Debit Card"); } if (paymentType.HasFlag(PaymentType.CreditCard)) { Response.Write("Process Credit Card"); } } Now Let’s check out in browser as following. As expected it will print process Credit Card as we have assigned that value to enum. That’s it It’s so simple and cool. Stay tuned for more.. Happy Programming.. Technorati Tags: Enum,C#4.0,ASP.NET 4.0

    Read the article

  • JPA Cascade delete.

    - by Win Man
    Hi, I am new to JPA/Hibernate. Currently using EJB3, Hibernate/JPA. I have an inheritacnce structure as follows.. @Entity @DiscriminatorColumn(name = "form_type") @Inheritance(strategy = InheritanceType.JOINED) @GenericGenerator(name = "FORMS_SEQ", strategy = "sequence-identity", parameters = @Parameter(name = "sequence", value = "FORMS_SEQ")) @Table(name = "Forms") public abstract class Form{ //code for Form } @Entity @Table(name = "CREDIT_CARDS") @PrimaryKeyJoinColumn(name="CREDIT_CARD_ID") public class CreditCardForm extends Form { //Code for CreditCards. } When I add a row with save the rows are properly inserted into the parent and the child table. However when I try to delete I get an error - 10:19:35,465 ERROR [TxPolicy] javax.ejb.EJBTransactionRolledbackException: Removing a detached instance com.data.entities.form.financial.CreditCard#159? I am using a simple for loop to determine the inheritance type - CreditCard or DebitCard and then calling entityManager.remove(entity). What am I doing wrong? Code for delete.. for(Form content: contents){ if(content.getType()==Type.CREDIT_CARD){ creditCardService.delete((CreditCard)content); } Thanks. WM

    Read the article

  • How to get ID of EditorFor with nested viewmodels in asp.net mvc 2

    - by Luke
    So I have two nested view models, CreditCard - BillAddress. I have a view, "EditBilling", that has EditorFor(CreditCard). The CreditCard EditorTemplate has EditorFor(BillAddress), and the BillAddress EditorTemplate has EditorFor(BillState). The end result is a select list with id "CreditCard_BillAddress_BillState". I need to reference this in javascript, thus need to know the ID. In other situations, with non-nested ViewModels, I have used the following code: $('#<%= ViewData.ModelMetadata.PropertyName %>_BillState') The problem here is that the ModelMetadata.PropertyName property is only aware of the current property, not the parent(s). So I end up with the following: $('#BillAddress_BillState') How does one go about getting the client ID of nested strongly typed helpers? Thanks in advance.

    Read the article

  • Effective Data Validation

    - by John Conde
    What's an effective way to handle data validation, say, from a form submission? Originally I had a bunch of if statements that checked each value and collected invalid values in an array for later retrieval (and listing). // Store errors here $errors = array(); // Hypothetical check if a string is alphanumeric if (!preg_match('/^[a-z\d]+$/i', $fieldvalue)) { $errors[$fieldname] = 'Please only use letters and numbers for your street address'; } // etc... What I did next was create a class that handles various data validation scenarios and store the results in an internal array. After data validation was complete I would check to see if any errors occurred and handle accordingly: class Validation { private $errorList = array(); public function isAlphaNumeric($string, $field, $msg = '') { if (!preg_match('/^[a-z\d]+$/i', $string)) { $this->errorList[$field] = $msg; } } // more methods here public function creditCard($cardNumber, $field, $msg = '') { // Validate credit card number } // more methods here public function hasErrors() { return count($this->errorList); } } /* Client code */ $validate = new Validation(); $validate->isAlphaNumeric($fieldvalue1, $fieldname1, 'Please only use letters and numbers for your street address'); $validate->creditCard($fieldvalue2, $fieldname2, 'Please enter a valid credit card number'); if ($validate->hasErrors()) { // Handle as appropriate } Naturally it didn't take long before this class became bloated with the virtually unlimited types of data to be validated. What I'm doing now is using decorators to separate the different types of data into their own classes and call them only when needed leaving generic validations (i.e. isAlphaNumeric()) in the base class: class Validation { private $errorList = array(); public function isAlphaNumeric($string, $field, $msg = '') { if (!preg_match('/^[a-z\d]+$/i', $string)) { $this->errorList[$field] = $msg; } } // more generic methods here public function setError($field, $msg = '') { $this->errorList[$field] = $msg; } public function hasErrors() { return count($this->errorList); } } class ValidationCreditCard { protected $validate; public function __construct(Validation $validate) { $this->validate = $validate; } public function creditCard($cardNumber, $field, $msg = '') { // Do validation // ... // if there is an error $this->validate->setError($field, $msg); } // more methods here } /* Client code */ $validate = new Validation(); $validate->isAlphaNumeric($fieldvalue, $fieldname, 'Please only use letters and numbers for your street address'); $validateCC = new ValidationCreditCard($validate); $validateCC->creditCard($fieldvalue2, $fieldname2, 'Please enter a valid credit card number'); if ($validate->hasErrors()) { // Handle as appropriate } Am I on the right track? Or did I just complicate data validation more then I needed to?

    Read the article

  • SQL SERVER – Solution – Challenge – Puzzle – Usage of FAST Hint

    - by pinaldave
    Earlier I had posted quick puzzle and I had received wonderful response to the same from Brad Schulz. Today we will go over the solution. The puzzle was posted here: SQL SERVER – Challenge – Puzzle – Usage of FAST Hint The question was in what condition the hint FAST will be useful. In the response to this puzzle blog post here is what SQL Server Expert Brad Schulz has pointed me to his blog post where he explain how FAST hint can be useful. I strongly recommend to read his blog post over here. With the permission of the Brad, I am reproducing following queries here. He has come up with example where FAST hint improves the performance. USE AdventureWorks GO DECLARE @DesiredDateAtMidnight DATETIME = '20010709' DECLARE @NextDateAtMidnight DATETIME = DATEADD(DAY,1,@DesiredDateAtMidnight) -- Query without FAST SELECT OrderID=h.SalesOrderID ,h.OrderDate ,h.TerritoryID ,TerritoryName=t.Name ,c.CardType ,c.CardNumber ,CardExpire=RIGHT(STR(100+ExpMonth),2)+'/'+STR(ExpYear,4) ,h.TotalDue FROM Sales.SalesOrderHeader h LEFT JOIN Sales.SalesTerritory t ON h.TerritoryID=t.TerritoryID LEFT JOIN Sales.CreditCard c ON h.CreditCardID=c.CreditCardID WHERE OrderDate>=@DesiredDateAtMidnight AND OrderDate<@NextDateAtMidnight ORDER BY h.SalesOrderID; -- Query with FAST(10) SELECT OrderID=h.SalesOrderID ,h.OrderDate ,h.TerritoryID ,TerritoryName=t.Name ,c.CardType ,c.CardNumber ,CardExpire=RIGHT(STR(100+ExpMonth),2)+'/'+STR(ExpYear,4) ,h.TotalDue FROM Sales.SalesOrderHeader h LEFT JOIN Sales.SalesTerritory t ON h.TerritoryID=t.TerritoryID LEFT JOIN Sales.CreditCard c ON h.CreditCardID=c.CreditCardID WHERE OrderDate>=@DesiredDateAtMidnight AND OrderDate<@NextDateAtMidnight ORDER BY h.SalesOrderID OPTION(FAST 10) Now when you check the execution plan for the same, you will find following visible difference. You will find query with FAST returns results with much lower cost. Thank you Brad for excellent post and teaching us something. I request all of you to read original blog post written by Brad for much more information. Reference: Pinal Dave (http://blog.sqlauthority.com) Filed under: Pinal Dave, Readers Contribution, Readers Question, SQL, SQL Authority, SQL Puzzle, SQL Query, SQL Scripts, SQL Server, SQL Tips and Tricks, T SQL, Technology

    Read the article

  • Questioning the motivation for dependency injection: Why is creating an object graph hard?

    - by oberlies
    Dependency injection frameworks like Google Guice give the following motivation for their usage (source): To construct an object, you first build its dependencies. But to build each dependency, you need its dependencies, and so on. So when you build an object, you really need to build an object graph. Building object graphs by hand is labour intensive (...) and makes testing difficult. But I don't buy this argument: Even without dependency injection, I can write classes which are both easy to instantiate and convenient to test. E.g. the example from the Guice motivation page could be rewritten in the following way: class BillingService { private final CreditCardProcessor processor; private final TransactionLog transactionLog; // constructor for tests, taking all collaborators as parameters BillingService(CreditCardProcessor processor, TransactionLog transactionLog) { this.processor = processor; this.transactionLog = transactionLog; } // constructor for production, calling the (productive) constructors of the collaborators public BillingService() { this(new PaypalCreditCardProcessor(), new DatabaseTransactionLog()); } public Receipt chargeOrder(PizzaOrder order, CreditCard creditCard) { ... } } So dependency injection may really be an advantage in advanced use cases, but I don't need it for easy construction and testability, do I?

    Read the article

  • Questioning one of the arguments for dependency injection: Why is creating an object graph hard?

    - by oberlies
    Dependency injection frameworks like Google Guice give the following motivation for their usage (source): To construct an object, you first build its dependencies. But to build each dependency, you need its dependencies, and so on. So when you build an object, you really need to build an object graph. Building object graphs by hand is labour intensive (...) and makes testing difficult. But I don't buy this argument: Even without dependency injection, I can write classes which are both easy to instantiate and convenient to test. E.g. the example from the Guice motivation page could be rewritten in the following way: class BillingService { private final CreditCardProcessor processor; private final TransactionLog transactionLog; // constructor for tests, taking all collaborators as parameters BillingService(CreditCardProcessor processor, TransactionLog transactionLog) { this.processor = processor; this.transactionLog = transactionLog; } // constructor for production, calling the (productive) constructors of the collaborators public BillingService() { this(new PaypalCreditCardProcessor(), new DatabaseTransactionLog()); } public Receipt chargeOrder(PizzaOrder order, CreditCard creditCard) { ... } } So there may be other arguments for dependency injection (which are out of scope for this question!), but easy creation of testable object graphs is not one of them, is it?

    Read the article

  • Picker view wont rotate- iPhone

    - by lotuseater
    hi, I am making a booking page. I have included 3 pickers in it. I have included all the delegates required for the pickers to work but it wont rotate. I have enabled user interaction and multitouch in the nib file. Here is my code. Please help me. :( @interface ChooseContactsFrom : UIViewController { IBOutlet UIPickerView *statePickup; IBOutlet UIPickerView *paymentMethodPickup; IBOutlet UIDatePicker *expiryDatePickup; IBOutlet UIView *statePickupView; IBOutlet UIView *paymentMethodPickupView; IBOutlet UIView *expiryDatePickupView; } (void)viewDidLoad { self.title = @"Choose Contacts"; //Fill in the states name/ stateArray = [[NSArray alloc]initWithObjects:@"",nil]; paymentModeArray = [[NSArray alloc] initWithObjects:@"Credit Card", @"Cash",@"Account",@"Voucher",@"Debit Card", nil]; paymentMethodPickup.frame = CGRectMake(0.0, 44.0, paymentMethodPickup.frame.size.width, paymentMethodPickup.frame.size.height); paymentMethodPickup.userInteractionEnabled = YES; paymentMethodPickup.multipleTouchEnabled = YES; paymentMethodPickupView.frame = CGRectMake(0.0, 210.0, paymentMethodPickupView.frame.size.width, paymentMethodPickupView.frame.size.height); statePickup.frame = CGRectMake(0.0, 44.0,statePickup.frame.size.width, statePickup.frame.size.height); statePickupView.frame = CGRectMake(0.0, 210.0, statePickupView.frame.size.width, statePickupView.frame.size.height); stateArray = [[NSArray alloc] initWithObjects:@"state1", @"state2", @"state3", @"state4", @"state5", @"state6", @"state7", @"state8", @"state9", @"state10", nil]; expiryDatePickup.frame = CGRectMake(0.0, 44.0, expiryDatePickup.frame.size.width, expiryDatePickup.frame.size.height); expiryDatePickupView.frame = CGRectMake(0.0, 210.0, expiryDatePickupView.frame.size.width, expiryDatePickupView.frame.size.height); [super viewDidLoad]; } -(IBAction)back:(id)sender { [self dismissModalViewControllerAnimated:YES]; } pragma mark pickerView delegates (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView { return 1; } (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component { if( thePickerView == statePickup) { return [stateArray count]; } else if(thePickerView == paymentMethodPickup) { return [paymentModeArray count]; } else { return 0; } } (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { if(thePickerView == statePickup) { return [stateArray objectAtIndex:row]; } else if(thePickerView == paymentMethodPickup) { return [paymentModeArray objectAtIndex:row]; } else { return @" "; } } (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{ return 50; } (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component { return 250; } (void)pickerView:(UIPickerView *)thepickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { if(thepickerView == statePickup) { state.text=[stateArray objectAtIndex:row]; } if(thepickerView == paymentMethodPickup) { payment.text=[paymentModeArray objectAtIndex:row]; } } (void)ClearSubviews { //[firstName resignFirstResponder]; // [lastName resignFirstResponder]; // [email resignFirstResponder]; // [address1 resignFirstResponder]; // [address2 resignFirstResponder]; // [city resignFirstResponder]; // //[state resignFirstResponder]; // [payment resignFirstResponder]; // [creditCard resignFirstResponder]; // [expirydate removeFromSuperview]; // [statePickup removeFromSuperview]; // [paymentMethodPickup removeFromSuperview]; } (BOOL)textFieldShouldBeginEditing:(UITextField *)textField { // [self showPicker:textField]; //[self setViewMovedUp]; if(textField == firstName || textField == lastName || textField == email || textField == address1 || textField == address2 ||textField == city) { [self ClearSubviews]; //pickerToolbar.hidden = TRUE; return YES; } else if(textField == payment) { [self ClearSubviews]; [self setViewMovedUp]; [payment setText:[paymentModeArray objectAtIndex:0]]; [self.view insertSubview:paymentMethodPickupView aboveSubview:self.view]; return NO; } else if(textField == state) { [self ClearSubviews]; [self setViewMovedUp]; [state setText:[stateArray objectAtIndex:0]]; [self.view insertSubview:statePickupView aboveSubview:self.view]; return NO; } else if(textField == expirydate) { [self setViewMovedUp]; expiryDatePickup.date = [NSDate date]; NSDate *date1 = [NSDate date]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateStyle:NSDateFormatterMediumStyle]; NSString *strDate=[dateFormatter stringFromDate:date1]; NSString *str=[[NSString alloc] initWithString: strDate]; [expirydate setText:str]; [self.view insertSubview:expiryDatePickupView aboveSubview:self.view]; return NO; } else if(textField == creditCard) { [self ClearSubviews]; [self setViewMovedUp]; return YES; } else { [self ClearSubviews]; return YES; } } -(BOOL)textFieldShouldEndEditing:(UITextField *)textField { return YES; } (void)textFieldDidEndEditing:(UITextField *)textField { if(textField == creditCard) { [self moveDown]; } } (BOOL)textFieldShouldReturn:(UITextField *)textField { [firstName resignFirstResponder]; [lastName resignFirstResponder]; [email resignFirstResponder]; [address1 resignFirstResponder]; [address2 resignFirstResponder]; [city resignFirstResponder]; [creditCard resignFirstResponder]; return YES; } -(IBAction)textFieldDoneEditing:(id)sender { [sender resignFirstResponder]; } ////////----------------------------------------------------------------------- pragma mark move screen (void)setViewMovedUp { [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.3]; // Make changes to the view's frame inside the animation block. They will be animated instead // of taking place immediately. CGRect rect = [self.view frame]; // If moving up, not only decrease the origin but increase the height so the view // covers the entire screen behind the keyboard. rect.origin.y -= 50.0f; rect.size.height -= 80.0f; [self.view setFrame:rect]; [UIView commitAnimations]; } -(void)moveDown { [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.3]; // Make changes to the view's frame inside the animation block. They will be animated instead // of taking place immediately. CGRect rect = [self.view frame]; rect.origin.y += 50.0f; rect.size.height += 80.0f; [self.view setFrame:rect]; // [UIView setBackgroundColor:[UIColor darkGrayColor]]; [UIView commitAnimations]; } pragma mark Method to show pickers -(void)showPicker:(UITextField *)textField { if(textField == expirydate) { expiryDatePickup .date = [NSDate date]; NSDate *date1 = [NSDate date]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateStyle:NSDateFormatterMediumStyle]; NSString *strDate=[dateFormatter stringFromDate:date1]; NSString *str=[[NSString alloc] initWithString: strDate]; [expirydate setText:str]; [self.view insertSubview:expiryDatePickup aboveSubview:self.view]; } else if(textField == payment) { [payment setText:[paymentModeArray objectAtIndex:0]]; [self.view insertSubview:paymentMethodPickupView aboveSubview:self.view]; } else if(textField == state) { [state setText:[stateArray objectAtIndex:0]]; [self.view insertSubview:statePickupView aboveSubview:self.view]; } } (IBAction)datePickerChanged:(id)sender { NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateStyle:NSDateFormatterMediumStyle]; NSDate *date=expiryDatePickup.date; formattedDateString1 = [dateFormatter stringFromDate:date]; [expirydate setText:formattedDateString1]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit; components = [gregorian components:unitFlags fromDate:date]; [gregorian release]; } pragma mark done and cancel methods -(IBAction) btnCancelExpiryDate:(id)sender { [self moveDown]; [expirydate setText:@" "]; [expiryDatePickupView removeFromSuperview]; } -(IBAction) btnDoneExpiryDate:(id)sender { [self moveDown]; [expiryDatePickupView removeFromSuperview]; expiryDatePickup .date = [NSDate date]; } -(IBAction)cancelPaymentType:(id)sender { [self moveDown]; [payment setText:@" "]; [paymentMethodPickupView removeFromSuperview]; } -(IBAction)donePaymentType:(id)sender { [self moveDown]; [paymentMethodPickupView removeFromSuperview]; } -(IBAction)doneState:(id)sender { [self moveDown]; [statePickupView removeFromSuperview]; } (IBAction)cancelState:(id)sender; { [self moveDown]; [state setText:@" "]; [statePickupView removeFromSuperview]; }

    Read the article

1 2 3  | Next Page >