Daily Archives

Articles indexed Thursday January 6 2011

Page 14/36 | < Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >

  • Database with 5 Tables with Insert and Select

    - by kirbby
    hi guys, my problem is that i have 5 tables and need inserts and selects. what i did is for every table a class and there i wrote the SQL Statements like this public class Contact private static String IDCont = "id_contact"; private static String NameCont = "name_contact"; private static String StreetCont = "street_contact"; private static String Street2Cont = "street2_contact"; private static String Street3Cont = "street3_contact"; private static String ZipCont = "zip_contact"; private static String CityCont = "city_contact"; private static String CountryCont = "country_contact"; private static String Iso2Cont = "iso2_contact"; private static String PhoneCont = "phone_contact"; private static String Phone2Cont = "phone2_contact"; private static String FaxCont = "fax_contact"; private static String MailCont = "mail_contact"; private static String Mail2Cont = "mail2_contact"; private static String InternetCont = "internet_contact"; private static String DrivemapCont = "drivemap_contact"; private static String PictureCont = "picture_contact"; private static String LatitudeCont = "latitude_contact"; private static String LongitudeCont = "longitude_contact"; public static final String TABLE_NAME = "contact"; public static final String SQL_CREATE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(" + IDCont + "INTEGER not NULL," + NameCont + " TEXT not NULL," + StreetCont + " TEXT," + Street2Cont + " TEXT," + Street3Cont + " TEXT," + ZipCont + " TEXT," + CityCont + " TEXT," + CountryCont + " TEXT," + Iso2Cont + " TEXT," + PhoneCont + " TEXT," + Phone2Cont + " TEXT," + FaxCont + " TEXT," + MailCont + " TEXT," + Mail2Cont + " TEXT," + InternetCont + " TEXT," + //website of the contact DrivemapCont + " TEXT," + //a link to a drivemap to the contact PictureCont + " TEXT," + //a photo of the contact building (contact is not a person) LatitudeCont + " TEXT," + LongitudeCont + " TEXT," + "primary key(id_contact)" + "foreign key(iso2)"; and my insert looks like this public boolean SQL_INSERT_CONTACT(int IDContIns, String NameContIns, String StreetContIns, String Street2ContIns, String Street3ContIns, String ZipContIns, String CityContIns, String CountryContIns, String Iso2ContIns, String PhoneContIns, String Phone2ContIns, String FaxContIns, String MailContIns, String Mail2ContIns, String InternetContIns, String DrivemapContIns, String PictureContIns, String LatitudeContIns, String LongitudeContIns) { try{ db.execSQL("INSERT INTO " + "contact" + "(" + IDCont + ", " + NameCont + ", " + StreetCont + ", " + Street2Cont + ", " + Street3Cont + ", " + ZipCont + ", " + CityCont + ", " + CountryCont + ", " + Iso2Cont + ", " + PhoneCont + ", " + Phone2Cont + ", " + FaxCont + ", " + MailCont + ", " + Mail2Cont + ", " + InternetCont + ", " + DrivemapCont + ", " + PictureCont + ", " + LatitudeCont + ", " + LongitudeCont + ") " + "VALUES (" + IDContIns + ", " + NameContIns +", " + StreetContIns + ", " + Street2ContIns + ", " + Street3ContIns + ", " + ZipContIns + ", " + CityContIns + ", " + CountryContIns + ", " + Iso2ContIns + ", " + PhoneContIns + ", " + Phone2ContIns + ", " + FaxContIns + ", " + MailContIns + ", " + Mail2ContIns + ", " + InternetContIns + ", " + DrivemapContIns + ", " + PictureContIns + ", " + LatitudeContIns + ", " + LongitudeContIns +")"); return true; } catch (SQLException e) { return false; } } i have a DBAdapter class there i created the database public class DBAdapter { public static final String DB_NAME = "mol.db"; private static final int DB_VERSION = 1; private static final String TAG = "DBAdapter"; //to log private final Context context; private SQLiteDatabase db; public DBAdapter(Context context) { this.context = context; OpenHelper openHelper = new OpenHelper(this.context); this.db = openHelper.getWritableDatabase(); } public static class OpenHelper extends SQLiteOpenHelper { public OpenHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL(Contact.SQL_CREATE); db.execSQL(Country.SQL_CREATE); db.execSQL(Picture.SQL_CREATE); db.execSQL(Product.SQL_CREATE); db.execSQL(Project.SQL_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL(Contact.SQL_DROP); db.execSQL(Country.SQL_DROP); db.execSQL(Picture.SQL_DROP); db.execSQL(Product.SQL_DROP); db.execSQL(Project.SQL_DROP); onCreate(db); } i found so many different things and tried them but i didn't get anything to work... i need to know how can i access the database in my activity and how i can get the insert to work and is there sth wrong in my code? thanks for your help thats how i tried to get it into my activity public class MainTabActivity extends TabActivity { private Context context; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.maintabactivity); TabHost mTabHost = getTabHost(); Intent intent1 = new Intent().setClass(this,MapOfLight.class); //Intent intent2 = new Intent().setClass(this,Test.class); //Testactivity //Intent intent2 = new Intent().setClass(this,DetailView.class); //DetailView Intent intent2 = new Intent().setClass(this,ObjectList.class); //ObjectList //Intent intent2 = new Intent().setClass(this,Gallery.class); //Gallery Intent intent3 = new Intent().setClass(this,ContactDetail.class); mTabHost.addTab(mTabHost.newTabSpec("tab_mol").setIndicator(this.getText(R.string.mol), getResources().getDrawable(R.drawable.ic_tab_mol)).setContent(intent1)); mTabHost.addTab(mTabHost.newTabSpec("tab_highlights").setIndicator(this.getText(R.string.highlights),getResources().getDrawable(R.drawable.ic_tab_highlights)).setContent(intent2)); mTabHost.addTab(mTabHost.newTabSpec("tab_contacts").setIndicator(this.getText(R.string.contact),getResources().getDrawable(R.drawable.ic_tab_contact)).setContent(intent3)); mTabHost.setCurrentTab(1); SQLiteDatabase db; DBAdapter dh = null; OpenHelper openHelper = new OpenHelper(this.context); dh = new DBAdapter(this); db = openHelper.getWritableDatabase(); dh.SQL_INSERT_COUNTRY("AT", "Austria", "AUT"); } } i tried it with my country table because it has only 3 columns public class Country { private static String Iso2Count = "iso2_country"; private static String NameCount = "name_country"; private static String FlagCount = "flag_image_url_country"; public static final String TABLE_NAME = "country"; public static final String SQL_CREATE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(" + Iso2Count + " TEXT not NULL," + NameCount + " TEXT not NULL," + FlagCount + " TEXT not NULL," + "primary key(iso2_country)"; public boolean SQL_INSERT_COUNTRY(String Iso2CountIns, String NameCountIns, String FlagCountIns) { try{ db.execSQL("INSERT INTO " + "country" + "(" + Iso2Count + ", " + NameCount + ", " + FlagCount + ") " + "VALUES ( " + Iso2CountIns + ", " + NameCountIns +", " + FlagCountIns + " )"); return true; } catch (SQLException e) { return false; } } another question is it better to put the insert and select from each table into a separate class, so i have 1 class for each table or put them all into the DBAdapter class?

    Read the article

  • How to change the position of the Horizontal line dynamically ?

    - by Hari
    I am making asp.net website. In that there is a link button (named Landline number).Below that there are three textboxes. And after that there is one horizontal line. Now at a first time only link button and horizontal will be visible, and textboxes which is bellowed to link button will not be visible. Now if user will click on the link button then textboxes which is bellowed to link button will be visible. Then horizontal line which is at the first time bellowed to the link button should be adjust to its location and should go after textboxes. And if user clicks to link button again then textboxes should be visible false. And horizontal line should be displayed its original position that is bellowed to the link button. Of course I am able to do with visibility of textboxes but I can not understand how to change the position of the horizontal line dynamically?

    Read the article

  • Define Javascript slider hit/rollover area

    - by Rob
    Hey, Im having an issue defining the hit area for a javascript sliding element. See example: http://www.warface.co.uk/clients/warface.co.uk/ Please slide over the grey box on the right side to reveal the button, although this works I would only like for the slider to only be triggered by rolling over the red block. CSS .slidingtwitter { /* -- This is the hit area -- */ background: #ccc; width:255px; height:55px; overflow: hidden; top:50%; right: 0px; /* -- This is the sliding start point -- */ position: fixed; font-family: Gotham, Sans-Serif; z-index: 50; } .slidingtwitter.right { right:0px; } .slidingtwitter .caption { /* -- This is the sliding area -- */ background: #fff; position: absolute; width:260px; height:55px; right: -205px; /* -- This is the sliding start point -- */ } .slidingtwitter a { color: #484848; font-size: 20px; text-transform: uppercase; } .slidingtwitter a:hover { color: black; } .slidingtwitter .smaller { font-size: 12px; font-family: Gotham Medium; } .twitterblock { background: #f35555 url("styles/images/button_twitter.png") no-repeat 14px 15px ; width:35px; height:35px; padding:10px; float:left; display:block; } .slidingtwitter .followme { background: url("styles/images/button_arrowheadthin.jpg")no-repeat right 0; height:35px; display:block; float:left; line-height:14px; width:140px; margin:10px 0px 0px 14px; padding-top:6px; padding-right: 40px; } JS $('.slidingtwitter').hover(function(){ $(".slide", this).stop().animate({right:'0px'},{queue:false,duration:400}); //Position on rollover },function() { $(".slide", this).stop().animate({right:'-205px'},{queue:false,duration:400}); //Position on rollout }); Any suggestions would be much appreciated.

    Read the article

  • Wizard form in Struts

    - by Kuntal Basu
    I am creating a wizard in Struts. It cotains 4 steps. For Each step I have separate ActionClass say:- Step1Action.java Step2Action.java Step3Action.java Step4Action.java and in each class there are 2 methods input() and process(). input() method is for showing the page in input mode process() method is will be use for processing the submitted data (if validation is ok) I am carrying all data upto the last step in a session. And saving all of them in database in the last step Similaly 4 action tags in struts.xml like :- <action name="step1" class="com.mycomp.myapp.action.Step1Action1" method="input"> <result name="success" type="redirectAction">step2</result> <result name="input">/view/step1.jsp</result> </action> <action name="step2" class="com.mycomp.myapp.action.Step1Action2" method="input"> <result name="success" type="redirectAction">step3</result> <result name="input">/view/step2.jsp</result> </action> But I think I am going wrong. Please Tell me How will I handle This case?

    Read the article

  • Keeping track of dirty blocks on a block device

    - by mikeY
    I'm looking for a way to keep track of what blocks on a block device are modified after a point in time. How I eventually want to use this for is to keep two 2TB disks in sync, one which only comes online (connected through USB) once a month. Without knowing what blocks have been modified, I have to go through the whole 2TB every time. I'm using a recent GNU/Linux OS and have C and Python experience. I'm hoping to avoid writing kernel level code as I don't have any experience in that area whatsoever. My current theory is that there should be some hooks somewhere where my code can get called when a disk flush is performed. Any ideas?

    Read the article

  • "dynamic" keyword and JSON data

    - by Peter Perhác
    An action method in my ASP.NET MVC2 application returns a JsonResult object and in my unit test I would like to check that the returned JSON object indeed contains the expected values. I tried this: 1. dynamic json = ((JsonResult)myActionResult).Data; 2. Assert.AreEqual(JsonMessagesHelper.ErrorLevel.ERROR.ToString(), json.ErrorLevel); But I get a RuntimeBinderException "'object' does not contain a definition for 'ErrorLevel'". However, when I place a breakpoint on line 2 and inspect the json dynamic variable (see picture below), it obviously does contain the ErrorLevel string and it has the expected value, so if the runtime binder wasn't playing funny the test would pass. What am I not getting? What am I doing wrong and how can I fix this? How can I make the assertion pass?

    Read the article

  • How to increase query speed without using full-text search?

    - by andre matos
    This is my simple query; By searching selectnothing I'm sure I'll have no hits. SELECT nome_t FROM myTable WHERE nome_t ILIKE '%selectnothing%'; This is the EXPLAIN ANALYZE VERBOSE Seq Scan on myTable (cost=0.00..15259.04 rows=37 width=29) (actual time=2153.061..2153.061 rows=0 loops=1) Output: nome_t Filter: (nome_t ~~* '%selectnothing%'::text) Total runtime: 2153.116 ms myTable has around 350k rows and the table definition is something like: CREATE TABLE myTable ( nome_t text NOT NULL, ) I have an index on nome_t as stated below: CREATE INDEX idx_m_nome_t ON myTable USING btree (nome_t); Although this is clearly a good candidate for Fulltext search I would like to rule that option out for now. This query is meant to be run from a web application and currently it's taking around 2 seconds which is obviously too much; Is there anything I can do, like using other index methods, to improve the speed of this query?

    Read the article

  • Receive data in same order as that of NSOperationQueue

    - by Nishit
    Hi, I have an NSOperationQueue, in which I keep on adding NSOperation objects that hit server and brings data. Is there a way to store the received data in the order in which they were fired? For example, suppose the A, B and C objects are added in NSOperationQueue in the order ABC. Now each of the three A, B and C will bring data in their corresponding threads. I want to store the results in the same order in an array so that the contents of array becomes "Result A", "Result B" and "Result C". Please provide a solution or a direction towards the right answer for this problems. Thanks Guys Basically, I want to design an autosuggest component which brings data from server (same as in google app), and I thought NSOperationQueue to be the best method to implement this. Currently I set the maxConcurrentOperationCount to 1, but I want to set it to more than 1, as data comes from the server very slowly. Please point out the right dolution or direction towards this question. Thanks

    Read the article

  • How do I change the on-screen keyboard for a PasswordBox

    - by McKay
    I have a box that I want to take a password of only numbers (like an ATM-card PIN), how is the best way to do that? Requirements: Password (with the hidden numbers) Typing digits as the default (only?) keyboard What I've tried: I thought that InputScopes would be the way to go, but I can't set the input scope on a password box. I even tried putting the password InputScope on a normal TextBox, but that didn't mask the appearance of the characters in the text box. Suggestions?

    Read the article

  • const member functions can call const member functions only?

    - by Abhi
    Hi all. Do const member functions call only const member functions? class Transmitter{ const static string msg; mutable int size; public: void xmit() const{ size = compute(); cout<<msg; } private: int compute() const{return 5;} }; string const Transmitter::msg = "beep"; int main(){ Transmitter t; t.xmit(); return EXIT_SUCCESS; } If i dont make compute() a const, then the compiler complains. Is it because since a const member function is not allowed to modify members, it wont allow any calls to non-consts since it would mean that the const member function would be 'indirectly' modifying the data members?

    Read the article

  • Tools for Automated Source Code Editing

    - by Steve
    I'm working on a research project to automatically modify code to include advanced mathematical concepts (like adding random effects into a loop or encapsulating an existing function with a new function that adds in a more advanced physical model). My question to the community is: are there are any good tools for manipulating source code directly? I want to do things like Swap out functions Add variable declarations wherever they are required Determine if a function is multiplied by anything Determine what functions are called on a line of code See what parameters are passed to a function and replace them with alternatives Introduce new function calls on certain lines of code Wherever possible just leaving the rest of the code untouched and write out the results I never want to actually compile the code I only want to understand what symbols are used, replace and add in a syntactically correct way, and be able to declare variables at the right position. I've been using a minimal flex/bison approach with some success but I do not feel the it is robust. I hate to take on writing a full language parser just to add some new info to the end of a line or the top of a function. It seems like this is almost what is going to be required but it also seems like there should be some tools out there to do these types of manipulations already. The code to be changed is in a variety of languages, but I'm particularly interested in FORTRAN. Any thoughts?

    Read the article

  • Editing/Updating one of the results in a search query.

    - by eggman20
    Hi guys. I'm creating a page that searches for an item and then be able to edit/update it. I was able to do it when it returns just one result but when it gives me multiple results I could only edit the very last item. Below is my code: ....... $dj =$_POST[djnum]; $sql= "SELECT * From dj WHERE datajack LIKE '$dj%'"; $result = mysql_query($sql); //more code in here// while ($info =mysql_fetch_array($result)) { // display the result echo "<form action=\"dj_update.php\" method=\"POST\"><input type=\"hidden\" name=\"djnumber\" value=\"".$info['datajack']."\">"; echo "<tr><td>DJ ".$info['datajack']."</td>"; echo "<td>".$info['building']."&nbsp;</td>"; echo "<td>Rm ".$info['room']."&nbsp;</td>"; echo "<td>".$info['switch']."&nbsp;</td>"; echo "<td>".$info['port']."&nbsp;</td>"; echo "<td>".$info['notes']."&nbsp;</td>"; echo "<td style=\"text-align:center;\"><input type=\"Submit\" value=\"Edit\" ></td></tr>"; } // more code here // Then this is the screen shot of the result: The idea is the user should be able to click on "Edit" and be able to edit/update that particular item. But when I click any of the Edit button I could only edit the last item. What am I missing here? Is there an easier way to do this? Thanks guys and Happy new year!

    Read the article

  • Grails remoteLink handling error codes

    - by soybie
    I'm on grails 1.3.6 and I see the following behavior. <g:javascript library="prototype" /> ... <g:remoteLink action="punch" id="${personInstance.id}" update="damage_${personInstance.id}" on401="alert('foo!');"> generates: <a on401="alert('foo!');" onclick="new Ajax.Updater('damage_5','/blah/person/punch/5',{asynchronous:true,evalScripts:true});return false;" href="/blah/person/punch/5"></a> "on401" isn't a supported event attribute for an anchor tag, so is this a bug in grails?

    Read the article

  • Developing web apps using ASP.NET MVC 3, Razor and EF Code First - Part 1

    - by shiju
    In this post, I will demonstrate web application development using ASP. NET MVC 3, Razor and EF code First. This post will also cover Dependency Injection using Unity 2.0 and generic Repository and Unit of Work for EF Code First. The following frameworks will be used for this step by step tutorial. ASP.NET MVC 3 EF Code First CTP 5 Unity 2.0 Define Domain Model Let’s create domain model for our simple web application Category class public class Category {     public int CategoryId { get; set; }     [Required(ErrorMessage = "Name Required")]     [StringLength(25, ErrorMessage = "Must be less than 25 characters")]     public string Name { get; set;}     public string Description { get; set; }     public virtual ICollection<Expense> Expenses { get; set; } }   Expense class public class Expense {             public int ExpenseId { get; set; }            public string  Transaction { get; set; }     public DateTime Date { get; set; }     public double Amount { get; set; }     public int CategoryId { get; set; }     public virtual Category Category { get; set; } } We have two domain entities - Category and Expense. A single category contains a list of expense transactions and every expense transaction should have a Category. In this post, we will be focusing on CRUD operations for the entity Category and will be working on the Expense entity with a View Model object in the later post. And the source code for this application will be refactored over time. The above entities are very simple POCO (Plain Old CLR Object) classes and the entity Category is decorated with validation attributes in the System.ComponentModel.DataAnnotations namespace. Now we want to use these entities for defining model objects for the Entity Framework 4. Using the Code First approach of Entity Framework, we can first define the entities by simply writing POCO classes without any coupling with any API or database library. This approach lets you focus on domain model which will enable Domain-Driven Development for applications. EF code first support is currently enabled with a separate API that is runs on top of the Entity Framework 4. EF Code First is reached CTP 5 when I am writing this article. Creating Context Class for Entity Framework We have created our domain model and let’s create a class in order to working with Entity Framework Code First. For this, you have to download EF Code First CTP 5 and add reference to the assembly EntitFramework.dll. You can also use NuGet to download add reference to EEF Code First.    public class MyFinanceContext : DbContext {     public MyFinanceContext() : base("MyFinance") { }     public DbSet<Category> Categories { get; set; }     public DbSet<Expense> Expenses { get; set; }         }   The above class MyFinanceContext is derived from DbContext that can connect your model classes to a database. The MyFinanceContext class is mapping our Category and Expense class into database tables Categories and Expenses using DbSet<TEntity> where TEntity is any POCO class. When we are running the application at first time, it will automatically create the database. EF code-first look for a connection string in web.config or app.config that has the same name as the dbcontext class. If it is not find any connection string with the convention, it will automatically create database in local SQL Express database by default and the name of the database will be same name as the dbcontext class. You can also define the name of database in constructor of the the dbcontext class. Unlike NHibernate, we don’t have to use any XML based mapping files or Fluent interface for mapping between our model and database. The model classes of Code First are working on the basis of conventions and we can also use a fluent API to refine our model. The convention for primary key is ‘Id’ or ‘<class name>Id’.  If primary key properties are detected with type ‘int’, ‘long’ or ‘short’, they will automatically registered as identity columns in the database by default. Primary key detection is not case sensitive. We can define our model classes with validation attributes in the System.ComponentModel.DataAnnotations namespace and it automatically enforces validation rules when a model object is updated or saved. Generic Repository for EF Code First We have created model classes and dbcontext class. Now we have to create generic repository pattern for data persistence with EF code first. If you don’t know about the repository pattern, checkout Martin Fowler’s article on Repository Let’s create a generic repository to working with DbContext and DbSet generics. public interface IRepository<T> where T : class     {         void Add(T entity);         void Delete(T entity);         T GetById(long Id);         IEnumerable<T> All();     }   RepositoryBasse – Generic Repository class public abstract class RepositoryBase<T> where T : class { private MyFinanceContext database; private readonly IDbSet<T> dbset; protected RepositoryBase(IDatabaseFactory databaseFactory) {     DatabaseFactory = databaseFactory;     dbset = Database.Set<T>(); }   protected IDatabaseFactory DatabaseFactory {     get; private set; }   protected MyFinanceContext Database {     get { return database ?? (database = DatabaseFactory.Get()); } } public virtual void Add(T entity) {     dbset.Add(entity);            }        public virtual void Delete(T entity) {     dbset.Remove(entity); }   public virtual T GetById(long id) {     return dbset.Find(id); }   public virtual IEnumerable<T> All() {     return dbset.ToList(); } }   DatabaseFactory class public class DatabaseFactory : Disposable, IDatabaseFactory {     private MyFinanceContext database;     public MyFinanceContext Get()     {         return database ?? (database = new MyFinanceContext());     }     protected override void DisposeCore()     {         if (database != null)             database.Dispose();     } } Unit of Work If you are new to Unit of Work pattern, checkout Fowler’s article on Unit of Work . According to Martin Fowler, the Unit of Work pattern "maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems." Let’s create a class for handling Unit of Work   public interface IUnitOfWork {     void Commit(); }   UniOfWork class public class UnitOfWork : IUnitOfWork {     private readonly IDatabaseFactory databaseFactory;     private MyFinanceContext dataContext;       public UnitOfWork(IDatabaseFactory databaseFactory)     {         this.databaseFactory = databaseFactory;     }       protected MyFinanceContext DataContext     {         get { return dataContext ?? (dataContext = databaseFactory.Get()); }     }       public void Commit()     {         DataContext.Commit();     } }   The Commit method of the UnitOfWork will call the commit method of MyFinanceContext class and it will execute the SaveChanges method of DbContext class.   Repository class for Category In this post, we will be focusing on the persistence against Category entity and will working on other entities in later post. Let’s create a repository for handling CRUD operations for Category using derive from a generic Repository RepositoryBase<T>.   public class CategoryRepository: RepositoryBase<Category>, ICategoryRepository     {     public CategoryRepository(IDatabaseFactory databaseFactory)         : base(databaseFactory)         {         }                } public interface ICategoryRepository : IRepository<Category> { } If we need additional methods than generic repository for the Category, we can define in the CategoryRepository. Dependency Injection using Unity 2.0 If you are new to Inversion of Control/ Dependency Injection or Unity, please have a look on my articles at http://weblogs.asp.net/shijuvarghese/archive/tags/IoC/default.aspx. I want to create a custom lifetime manager for Unity to store container in the current HttpContext.   public class HttpContextLifetimeManager<T> : LifetimeManager, IDisposable {     public override object GetValue()     {         return HttpContext.Current.Items[typeof(T).AssemblyQualifiedName];     }     public override void RemoveValue()     {         HttpContext.Current.Items.Remove(typeof(T).AssemblyQualifiedName);     }     public override void SetValue(object newValue)     {         HttpContext.Current.Items[typeof(T).AssemblyQualifiedName] = newValue;     }     public void Dispose()     {         RemoveValue();     } }   Let’s create controller factory for Unity in the ASP.NET MVC 3 application. public class UnityControllerFactory : DefaultControllerFactory { IUnityContainer container; public UnityControllerFactory(IUnityContainer container) {     this.container = container; } protected override IController GetControllerInstance(RequestContext reqContext, Type controllerType) {     IController controller;     if (controllerType == null)         throw new HttpException(                 404, String.Format(                     "The controller for path '{0}' could not be found" +     "or it does not implement IController.",                 reqContext.HttpContext.Request.Path));       if (!typeof(IController).IsAssignableFrom(controllerType))         throw new ArgumentException(                 string.Format(                     "Type requested is not a controller: {0}",                     controllerType.Name),                     "controllerType");     try     {         controller= container.Resolve(controllerType) as IController;     }     catch (Exception ex)     {         throw new InvalidOperationException(String.Format(                                 "Error resolving controller {0}",                                 controllerType.Name), ex);     }     return controller; }   }   Configure contract and concrete types in Unity Let’s configure our contract and concrete types in Unity for resolving our dependencies.   private void ConfigureUnity() {     //Create UnityContainer               IUnityContainer container = new UnityContainer()                 .RegisterType<IDatabaseFactory, DatabaseFactory>(new HttpContextLifetimeManager<IDatabaseFactory>())     .RegisterType<IUnitOfWork, UnitOfWork>(new HttpContextLifetimeManager<IUnitOfWork>())     .RegisterType<ICategoryRepository, CategoryRepository>(new HttpContextLifetimeManager<ICategoryRepository>());                 //Set container for Controller Factory                ControllerBuilder.Current.SetControllerFactory(             new UnityControllerFactory(container)); }   In the above ConfigureUnity method, we are registering our types onto Unity container with custom lifetime manager HttpContextLifetimeManager. Let’s call ConfigureUnity method in the Global.asax.cs for set controller factory for Unity and configuring the types with Unity.   protected void Application_Start() {     AreaRegistration.RegisterAllAreas();     RegisterGlobalFilters(GlobalFilters.Filters);     RegisterRoutes(RouteTable.Routes);     ConfigureUnity(); }   Developing web application using ASP.NET MVC 3 We have created our domain model for our web application and also have created repositories and configured dependencies with Unity container. Now we have to create controller classes and views for doing CRUD operations against the Category entity. Let’s create controller class for Category Category Controller   public class CategoryController : Controller {     private readonly ICategoryRepository categoryRepository;     private readonly IUnitOfWork unitOfWork;           public CategoryController(ICategoryRepository categoryRepository, IUnitOfWork unitOfWork)     {         this.categoryRepository = categoryRepository;         this.unitOfWork = unitOfWork;     }       public ActionResult Index()     {         var categories = categoryRepository.All();         return View(categories);     }     [HttpGet]     public ActionResult Edit(int id)     {         var category = categoryRepository.GetById(id);         return View(category);     }       [HttpPost]     public ActionResult Edit(int id, FormCollection collection)     {         var category = categoryRepository.GetById(id);         if (TryUpdateModel(category))         {             unitOfWork.Commit();             return RedirectToAction("Index");         }         else return View(category);                 }       [HttpGet]     public ActionResult Create()     {         var category = new Category();         return View(category);     }           [HttpPost]     public ActionResult Create(Category category)     {         if (!ModelState.IsValid)         {             return View("Create", category);         }                     categoryRepository.Add(category);         unitOfWork.Commit();         return RedirectToAction("Index");     }       [HttpPost]     public ActionResult Delete(int  id)     {         var category = categoryRepository.GetById(id);         categoryRepository.Delete(category);         unitOfWork.Commit();         var categories = categoryRepository.All();         return PartialView("CategoryList", categories);       }        }   Creating Views in Razor Now we are going to create views in Razor for our ASP.NET MVC 3 application.  Let’s create a partial view CategoryList.cshtml for listing category information and providing link for Edit and Delete operations. CategoryList.cshtml @using MyFinance.Helpers; @using MyFinance.Domain; @model IEnumerable<Category>      <table>         <tr>         <th>Actions</th>         <th>Name</th>          <th>Description</th>         </tr>     @foreach (var item in Model) {             <tr>             <td>                 @Html.ActionLink("Edit", "Edit",new { id = item.CategoryId })                 @Ajax.ActionLink("Delete", "Delete", new { id = item.CategoryId }, new AjaxOptions { Confirm = "Delete Expense?", HttpMethod = "Post", UpdateTargetId = "divCategoryList" })                           </td>             <td>                 @item.Name             </td>             <td>                 @item.Description             </td>         </tr>          }       </table>     <p>         @Html.ActionLink("Create New", "Create")     </p> The delete link is providing Ajax functionality using the Ajax.ActionLink. This will call an Ajax request for Delete action method in the CategoryCotroller class. In the Delete action method, it will return Partial View CategoryList after deleting the record. We are using CategoryList view for the Ajax functionality and also for Index view using for displaying list of category information. Let’s create Index view using partial view CategoryList  Index.chtml @model IEnumerable<MyFinance.Domain.Category> @{     ViewBag.Title = "Index"; }    <h2>Category List</h2>    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>    <div id="divCategoryList">               @Html.Partial("CategoryList", Model) </div>   We can call the partial views using Html.Partial helper method. Now we are going to create View pages for insert and update functionality for the Category. Both view pages are sharing common user interface for entering the category information. So I want to create an EditorTemplate for the Category information. We have to create the EditorTemplate with the same name of entity object so that we can refer it on view pages using @Html.EditorFor(model => model) . So let’s create template with name Category. Let’s create view page for insert Category information   @model MyFinance.Domain.Category   @{     ViewBag.Title = "Save"; }   <h2>Create</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>Category</legend>                @Html.EditorFor(model => model)               <p>             <input type="submit" value="Create" />         </p>     </fieldset> }   <div>     @Html.ActionLink("Back to List", "Index") </div> ViewStart file In Razor views, we can add a file named _viewstart.cshtml in the views directory  and this will be shared among the all views with in the Views directory. The below code in the _viewstart.cshtml, sets the Layout page for every Views in the Views folder.      @{     Layout = "~/Views/Shared/_Layout.cshtml"; }   Source Code You can download the source code from http://efmvc.codeplex.com/ . The source will be refactored on over time.   Summary In this post, we have created a simple web application using ASP.NET MVC 3 and EF Code First. We have discussed on technologies and practices such as ASP.NET MVC 3, Razor, EF Code First, Unity 2, generic Repository and Unit of Work. In my later posts, I will modify the application and will be discussed on more things. Stay tuned to my blog  for more posts on step by step application building.

    Read the article

  • How to ship a server internationally?

    - by devians
    I have a fileserver that will need to be shipped internationally soon. I'm looking on advice for packing and recommendations on methods/companies. Should it be shipped whole, or in parts? How to pack it, precautions to take. Any way you slice it, it's going to be very heavy. Will this cause problems? Whats the best way to protect it from shock? It would be pointless for it to arrive with broken hdd's. If you've done this before, your hindsight would be invaluable.

    Read the article

  • SSL connection error for only one site (of many) on server

    - by Matt Lacey
    I have a server running many websites, each with SSL. One of the sites is now refusing connections over SSL. This was previously working and I'm looking for assistance in determining what has been changed. Here's the situation: http://site1.com/ - works https://site1.com/ - works http://site2.com/ - works https://site2.com/ - Doesn't work (but did previously) Both sites are on the same server (Win Server 2003 SP2 - IIS6) Both sites use certificates from the same authority and are both valid (according to IIS). As far as I can tell, both sites have certificates configured identically in IIS. (Checked by a manual/visual check of properties, side by side) Through use of OpenSSL I can see that there's a "ssl handshake failure" when trying to connect to site2 using https. What could be the cause of this? How can I investigate further? Without SSL connections being available to this site, users are unable to log in or register. :( disclaimer: I'm not a server admin and not responsible for the box. Yes, there are wider issues here but I need to get this working again first.

    Read the article

  • Win 7 Explorer backup and long paths

    - by user53299
    I use Explorer to do backups because Win 7's backup program asks me to take backups previously done and to put them back in the drive. I am opposed to that idea since I believe backups should remain in storage. With Explorer backups (burn and burn to disc) I have encountered the "destination path too long" error message and it shows the name of a folder "Debug" three times. I have hundreds of folders named "Debug" thanks to Visual Studio. At this moment I'm too angry at Microsoft to write a program to determine my 3 longest paths. (Aside: This is all after coincidentally reading two articles about path junctions earlier this evening which already made me kind of unhappy.) Please, is there an easy way to continue to make backups with Explorer? Edit: I should add that renaming paths wrecks Visual Studio projects so I really need to isolate the small number of problem paths or find a cleaner solution.

    Read the article

  • why won't php 5.3.3 compile libphp5.so on redhat ent

    - by spatel
    I'm trying to upgrade to php 5.3.3 from php 5.2.13. However, the apache module, libphp5.so will not be compiled. Below is a output I got along with the configure options I used. The configure statement is a reduced version of what I normally use. ========== './configure' '--disable-debug' '--disable-rpath' '--with-apxs2=/usr/local/apache2/bin/apxs' ... ** ** ** Warning: inter-library dependencies are not known to be supported. ** ** ** All declared inter-library dependencies are being dropped. ** ** ** Warning: libtool could not satisfy all declared inter-library ** ** ** dependencies of module libphp5. Therefore, libtool will create ** ** ** a static module, that should work as long as the dlopening ** ** ** application is linked with the -dlopen flag. copying selected object files to avoid basename conflicts... Generating phar.php Generating phar.phar PEAR package PHP_Archive not installed: generated phar will require PHP's phar extension be enabled. clicommand.inc pharcommand.inc directorytreeiterator.inc directorygraphiterator.inc invertedregexiterator.inc phar.inc Build complete. Don't forget to run 'make test'. ============= php 5.2.13 recompiles just fine so something is up with 5.3.3. Any help would be greatly appreciated!!

    Read the article

  • Dummy/default page for apache

    - by Ency
    I'm trying to set up default page for my apache2, for following cases: User is accessing http://IP_Address instead of hostname Requested protocol (HTTP/HTTPS) is not available (eg. only http*s*://domain.com exists) Currently I've got something like that <VirtualHost eserver:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/local/ <Directory /> Options FollowSymLinks AllowOverride None </Directory> </VirtualHost> I think, it works well, i'm trying to do similar thing for HTTPS, but it does not work. <VirtualHost eserver:443> SSLCertificateKeyFile /etc/apache2/ssl/dummy.key SSLCertificateFile /etc/apache2/ssl/dummy.crt SSLProtocol all SSLCipherSuite HIGH:MEDIUM ErrorLog /var/log/apache2/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn ServerSignature Off </VirtualHost> My default is places in sites-enabled as a first one 000-default I do not care about not certificate validity during accessing default page, my goal is not show different HTTPS page if user one of points is applied

    Read the article

  • W3 Total Cache or WP Super Cache?

    - by javipas
    I'm just preparing the setup of a new VPS where I will migrate a WordPress blog with a good traffic (currently, around 40k pageviews a day), and I was thinking about the caching strategy. I've found different ideas and recommendations, but from previous experiences I will setup a Nginx+PHP-FPM+MySQL (LEMP) system on a Linode VPS. I've read also about setting Nginx as a reverse proxy with Apache, and even using Varnish too, but I don't know if all of this can benefit the speed/performance of the blog (that's the only thing that will be installed on the VPS). The question now is... would you recommend W3 Total Cache or WP Super Cache? I've used W3 on some blogs, but I haven't noticed great benefits and don't need all its options, so I think I could give the veteran WP Super Cache a try. Besides, some users have complained about W3 complex configuration and lack of performance (even consumig more CPU) on some cases.

    Read the article

  • P2V Server 2008R2 with vmware converter 4.3.0 No source volumes

    - by Peter
    I'm trying to P2V a Windows Server 2008R2 to vmware vsphere 4.1 using Vmware vCenter Converter standalone 4.3. Source Box Windows Server 2008R2 24GB ram Dual Quad-Cores 1 Raid 5 drive 680 GB 3 GB "Recovery" partition 40 GB OS partition 637 GB Data partion When we try and convert using the stand alone converter and the built in vCenter converter there are no source volumes listed. Has anyone dealt with this before?

    Read the article

  • Subdomains and address bar

    - by Priednis
    I have a fairly noob question about how subdomains work. As I understand at first the DNS server specifies that a request for certain subdomain.domain.com has to go to the IP address of domain.com, and the webserver at domain.com further processes the request and displays the needed subdomain page. It is not entirely clear to me how (for example Apache) server does it. As I understand there can be entries in vhosts.conf file which specify folders that contain the subdomain data. Something like: <VirtualHost *> ServerName www.domain.com DocumentRoot /home/httpd/htdocs/ </VirtualHost> <VirtualHost *> ServerName subdomain.domain.com DocumentRoot /home/httpd/htdocs/subdomain/ </VirtualHost> and there also can be redirect entries in .htaccess files like rewritecond %{http_host} ^subdomain.domain.com [nc] rewriterule ^(.*)$ http://www.domain.com/subdomain/ [r=301,nc] however in this case the user gets directed to the directory which contains the subdomain data but the user gets "out" of the subdomain. I would like to know - how, when going to subdomain.domain.com the subdomain.domain.com, beginning of address remains visible in the address bar of the explorer? Can it be done by an alternate entry in .htaccess file? If a VirtualHost entry is specified in the vhosts.conf file, does it mean, that a new user account has to be specified for access to this directory?

    Read the article

  • Exchange 2003 Internet Mail Size Limits

    - by scampbell
    I have unsuccessfully tried to increase per user incoming mail size settings by editing their user account settings on our Exchange server, but large incoming mail from external domains is still blocked using the default global settings. After reading here: http://support.microsoft.com/default.aspx?scid=kb;en-us;322679 I see that All Internet e-mail messages use the global setting for limits on sending and on receiving. The message categorizer evaluates the sender's sending limit and the recipient's receiving limit. In example 2 earlier, a user with a user mailbox limit of 3 MB could receive messages from another user with a 3-MB sending limit. Because Internet users use the global setting, they can send only a 2-MB message. Which to me is madness! Surely if I want to allow a user to receive mail up to a certain size then I should be able to set it as such? Is there a specific way of getting round this? Would setting the global defaults high and setting a lower, say 10MB, limit on the SMTP connector do the trick? Thanks.

    Read the article

  • Moving a "All-in-one" PC when turned on/off.

    - by Purak
    I have an "all-in-one" pc. I know that moving a pc when it is switched on is harmful to the hardware components. What I would like to know is if the same applies to "all-in-one" pc's and if the same applies to regularly moving it from one side of the room to the other when it is turned off! The reason for the question is that I work on one desk during the day, and in the evening move it to the couch so I can do other stuff while watching TV or something. I always turn it off before the move, but somebody told me that I can be damaging the machine by doing so. Can anybody shed some light on this? Many thanks

    Read the article

  • Solaris 10: Identify a PID and the CPU it's running on

    - by Marcus
    I have multiple instances of a database running on a Solaris system. I'd like to prove that each database process is being handled by a different CPU. Essentially, I want to be able to do something like a ps -ef | grep <process_name> to get the PIDs and then run another command (if required) to identify the CPU... Is prstat able to do this? I'm making an assumption that as each database instance is started each one uses a different CPU. I'm not sure if I'm understanding this correctly... The reason I want to do this is because Sun hardware has slow CPU's, but lots of them. Therefore, to get the best performance out of it, I need to try and spread the load among CPU's... Thanks

    Read the article

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