Search Results

Search found 25123 results on 1005 pages for 'domain model'.

Page 58/1005 | < Previous Page | 54 55 56 57 58 59 60 61 62 63 64 65  | Next Page >

  • Grails - how to save a domain object inside a Service ?

    - by w-
    I have a service and inside one of the functions i'm creating a domain object and trying to save it. when it gets to the save part, i get the error No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here What do i need to do in order to save a domain object inside of a service. everything on the internet makes it look like this should just work....

    Read the article

  • Under which circumstances can a *local* user account access a remote SQL Server with a trusted connection?

    - by Heinzi
    One of our customers has the following configuration: On the domain controller, there's an SQL Server. On his PC (WinXP), he logs on with LocalPC\LocalUser. In Windows Explorer, he opens DomainController\SomeShare and authenticates as Domain\Administrator. He starts our application, which opens a trusted connection (Windows authentication) to the SQL Server. It works. In SSMS, the connection shows up with the user Domain\Administrator. Firstly, I was surprised that this even works. (My first suspicion was that there is a user with the same name and password in the domain, but there is no user LocalUser in the domain.) Then we tried to reproduce the same behaviour on his new PC, but failed: On his new PC (Win7), he logs on with OtherLocalPC\OtherLocalUser. In Windows Explorer, he opens DomainController\SomeShare and authenticates as Domain\Administrator. He starts our application, which opens a trusted connection (Windows authentication) to the SQL Server. It fails with the error message Login failed for user ''. The user is not associated with a trusted SQL Server connection. Hence my question: Under which conditions can a non-domain user access a remote SQL Server using Windows Authentication with different credentials? Apparently, it's possible (it works on his old PC), but why? And how can I reproduce it?

    Read the article

  • How to output JSON from within Django and call it with jQuery from a cross domain?

    - by Emre Sevinç
    For a bookmarklet project I'm trying to get JSON data using jQuery from my server (which is naturally on a different domain) running a Django powered system. According to jQuery docs: "As of jQuery 1.2, you can load JSON data located on another domain if you specify a JSONP callback, which can be done like so: "myurl?callback=?". jQuery automatically replaces the ? with the correct method name to call, calling your specified callback." And for example I can test it successfully in my Firebug console using the following snippet: $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any& format=json&jsoncallback=?", function(data){ alert(data.title); }); It prints the returned data in an alert window, e.g. 'Recent uploads tagged cat'. However when I try the similar code with my server I don't get anything at all: $.getJSON("http://mydjango.yafz.org/randomTest?jsoncallback=?", function(data){ alert(data.title); }); There are no alert windows and the Firebug status bar says "Transferring data from mydjango.yafz.org..." and keeps on waiting. On the server side I have this: def randomTest(request): somelist = ['title', 'This is a constant result'] encoded = json.dumps(somelist) response = HttpResponse(encoded, mimetype = "application/json") return response I also tried this without any success: def randomTest(request): if request.is_ajax() == True: req = {} req ['title'] = 'This is a constant result.' response = json.dumps(req) return HttpResponse(response, mimetype = "application/json") So to cut a long story short: what is the suggested method of returning a piece of data from within a Django view and retrieve it using jQuery in a cross domain fashion? What are my mistakes above?

    Read the article

  • What is New in ASP.NET 4.0 Code Access Security

    - by Xiaohong
    ASP.NET Code Access Security (CAS) is a feature that helps protect server applications on hosting multiple Web sites, ASP.NET lets you assign a configurable trust level that corresponds to a predefined set of permissions. ASP.NET has predefined ASP.NET Trust Levels and Policy Files that you can assign to applications, you also can assign custom trust level and policy files. Most web hosting companies run ASP.NET applications in Medium Trust to prevent that one website affect or harm another site etc. As .NET Framework's Code Access Security model has evolved, ASP.NET 4.0 Code Access Security also has introduced several changes and improvements. The main change in ASP.NET 4.0 CAS In ASP.NET v4.0 partial trust applications, application domain can have a default partial trust permission set as opposed to being full-trust, the permission set name is defined in the <trust /> new attribute permissionSetName that is used to initialize the application domain . By default, the PermissionSetName attribute value is "ASP.Net" which is the name of the permission set you can find in all predefined partial trust configuration files. <trust level="Something" permissionSetName="ASP.Net" /> This is ASP.NET 4.0 new CAS model. For compatibility ASP.NET 4.0 also support legacy CAS model where application domain still has full trust permission set. You can specify new legacyCasModel attribute on the <trust /> element to indicate whether the legacy CAS model is enabled. By default legacyCasModel is false which means that new 4.0 CAS model is the default. <trust level="Something" legacyCasModel="true|false" /> In .Net FX 4.0 Config directory, there are two set of predefined partial trust config files for each new CAS model and legacy CAS model, trust config files with name legacy.XYZ.config are for legacy CAS model: New CAS model: Legacy CAS model: web_hightrust.config legacy.web_hightrust.config web_mediumtrust.config legacy.web_mediumtrust.config web_lowtrust.config legacy.web_lowtrust.config web_minimaltrust.config legacy.web_minimaltrust.config   The figure below shows in ASP.NET 4.0 new CAS model what permission set to grant to code for partial trust application using predefined partial trust levels and policy files:    There also some benefits that comes with the new CAS model: You can lock down a machine by making all managed code no-execute by default (e.g. setting the MyComputer zone to have no managed execution code permissions), it should still be possible to configure ASP.NET web applications to run as either full-trust or partial trust. UNC share doesn’t require full trust with CASPOL at machine-level CAS policy. Side effect that comes with the new CAS model: processRequestInApplicationTrust attribute is deprecated  in new CAS model since application domain always has partial trust permission set in new CAS model.   In ASP.NET 4.0 legacy CAS model or ASP.NET 2.0 CAS model, even though you assign partial trust level to a application but the application domain still has full trust permission set. The figure below shows in ASP.NET 4.0 legacy CAS model (or ASP.NET 2.0 CAS model) what permission set to grant to code for partial trust application using predefined partial trust levels and policy files:     What $AppDirUrl$, $CodeGen$, $Gac$ represents: $AppDirUrl$ The application's virtual root directory. This allows permissions to be applied to code that is located in the application's bin directory. For example, if a virtual directory is mapped to C:\YourWebApp, then $AppDirUrl$ would equate to C:\YourWebApp. $CodeGen$ The directory that contains dynamically generated assemblies (for example, the result of .aspx page compiles). This can be configured on a per application basis and defaults to %windir%\Microsoft.NET\Framework\{version}\Temporary ASP.NET Files. $CodeGen$ allows permissions to be applied to dynamically generated assemblies. $Gac$ Any assembly that is installed in the computer's global assembly cache (GAC). This allows permissions to be granted to strong named assemblies loaded from the GAC by the Web application.   The new customization of CAS Policy in ASP.NET 4.0 new CAS model 1. Define which named permission set in partial trust configuration files By default the permission set that will be assigned at application domain initialization time is the named "ASP.Net" permission set found in all predefined partial trust configuration files. However ASP.NET 4.0 allows you set PermissionSetName attribute to define which named permission set in a partial trust configuration file should be the one used to initialize an application domain. Example: add "ASP.Net_2" named permission set in partial trust configuration file: <PermissionSet class="NamedPermissionSet" version="1" Name="ASP.Net_2"> <IPermission class="FileIOPermission" version="1" Read="$AppDir$" PathDiscovery="$AppDir$" /> <IPermission class="ReflectionPermission" version="1" Flags ="RestrictedMemberAccess" /> <IPermission class="SecurityPermission " version="1" Flags ="Execution, ControlThread, ControlPrincipal, RemotingConfiguration" /></PermissionSet> Then you can use "ASP.Net_2" named permission set for the application domain permission set: <trust level="Something" legacyCasModel="false" permissionSetName="ASP.Net_2" /> 2. Define a custom set of Full Trust Assemblies for an application By using the new fullTrustAssemblies element to configure a set of Full Trust Assemblies for an application, you can modify set of partial trust assemblies to full trust at the machine, site or application level. The configuration definition is shown below: <fullTrustAssemblies> <add assemblyName="MyAssembly" version="1.1.2.3" publicKey="hex_char_representation_of_key_blob" /></fullTrustAssemblies> 3. Define <CodeGroup /> policy in partial trust configuration files ASP.NET 4.0 new CAS model will retain the ability for developers to optionally define <CodeGroup />with membership conditions and assigned permission sets. The specific restriction in ASP.NET 4.0 new CAS model though will be that the results of evaluating custom policies can only result in one of two outcomes: either an assembly is granted full trust, or an assembly is granted the partial trust permission set currently associated with the running application domain. It will not be possible to use custom policies to create additional custom partial trust permission sets. When parsing the partial trust configuration file: Any assemblies that match to code groups associated with "PermissionSet='FullTrust'" will run at full trust. Any assemblies that match to code groups associated with "PermissionSet='Nothing'" will result in a PolicyError being thrown from the CLR. This is acceptable since it provides administrators with a way to do a blanket-deny of managed code followed by selectively defining policy in a <CodeGroup /> that re-adds assemblies that would be allowed to run. Any assemblies that match to code groups associated with other permissions sets will be interpreted to mean the assembly should run at the permission set of the appdomain. This means that even though syntactically a developer could define additional "flavors" of partial trust in an ASP.NET partial trust configuration file, those "flavors" will always be ignored. Example: defines full trust in <CodeGroup /> for my strong named assemblies in partial trust config files: <CodeGroup class="FirstMatchCodeGroup" version="1" PermissionSetName="Nothing"> <IMembershipCondition    class="AllMembershipCondition"    version="1" /> <CodeGroup    class="UnionCodeGroup"    version="1"    PermissionSetName="FullTrust"    Name="My_Strong_Name"    Description="This code group grants code signed full trust. "> <IMembershipCondition      class="StrongNameMembershipCondition" version="1"       PublicKeyBlob="hex_char_representation_of_key_blob" /> </CodeGroup> <CodeGroup   class="UnionCodeGroup" version="1" PermissionSetName="ASP.Net">   <IMembershipCondition class="UrlMembershipCondition" version="1" Url="$AppDirUrl$/*" /> </CodeGroup> <CodeGroup class="UnionCodeGroup" version="1" PermissionSetName="ASP.Net">   <IMembershipCondition class="UrlMembershipCondition" version="1" Url="$CodeGen$/*"   /> </CodeGroup></CodeGroup>   4. Customize CAS policy at runtime in ASP.NET 4.0 new CAS model ASP.NET 4.0 new CAS model allows to customize CAS policy at runtime by using custom HostSecurityPolicyResolver that overrides the ASP.NET code access security policy. Example: use custom host security policy resolver to resolve partial trust web application bin folder MyTrustedAssembly.dll to full trust at runtime: You can create a custom host security policy resolver and compile it to assembly MyCustomResolver.dll with strong name enabled and deploy in GAC: public class MyCustomResolver : HostSecurityPolicyResolver{ public override HostSecurityPolicyResults ResolvePolicy(Evidence evidence) { IEnumerator hostEvidence = evidence.GetHostEnumerator(); while (hostEvidence.MoveNext()) { object hostEvidenceObject = hostEvidence.Current; if (hostEvidenceObject is System.Security.Policy.Url) { string assemblyName = hostEvidenceObject.ToString(); if (assemblyName.Contains(“MyTrustedAssembly.dll”) return HostSecurityPolicyResult.FullTrust; } } //default fall-through return HostSecurityPolicyResult.DefaultPolicy; }} Because ASP.NET accesses the custom HostSecurityPolicyResolver during application domain initialization, and a custom policy resolver requires full trust, you also can add a custom policy resolver in <fullTrustAssemblies /> , or deploy in the GAC. You also need configure a custom HostSecurityPolicyResolver instance by adding the HostSecurityPolicyResolverType attribute in the <trust /> element: <trust level="Something" legacyCasModel="false" hostSecurityPolicyResolverType="MyCustomResolver, MyCustomResolver" permissionSetName="ASP.Net" />   Note: If an assembly policy define in <CodeGroup/> and also in hostSecurityPolicyResolverType, hostSecurityPolicyResolverType will win. If an assembly added in <fullTrustAssemblies/> then the assembly has full trust no matter what policy in <CodeGroup/> or in hostSecurityPolicyResolverType.   Other changes in ASP.NET 4.0 CAS Use the new transparency model introduced in .Net Framework 4.0 Change in dynamically compiled code generated assemblies by ASP.NET: In new CAS model they will be marked as security transparent level2 to use Framework 4.0 security transparent rule that means partial trust code is treated as completely Transparent and it is more strict enforcement. In legacy CAS model they will be marked as security transparent level1 to use Framework 2.0 security transparent rule for compatibility. Most of ASP.NET products runtime assemblies are also changed to be marked as security transparent level2 to switch to SecurityTransparent code by default unless SecurityCritical or SecuritySafeCritical attribute specified. You also can look at Security Changes in the .NET Framework 4 for more information about these security attributes. Support conditional APTCA If an assembly is marked with the Conditional APTCA attribute to allow partially trusted callers, and if you want to make the assembly both visible and accessible to partial-trust code in your web application, you must add a reference to the assembly in the partialTrustVisibleAssemblies section: <partialTrustVisibleAssemblies> <add assemblyName="MyAssembly" publicKey="hex_char_representation_of_key_blob" />/partialTrustVisibleAssemblies>   Most of ASP.NET products runtime assemblies are also changed to be marked as conditional APTCA to prevent use of ASP.NET APIs in partial trust environments such as Winforms or WPF UI controls hosted in Internet Explorer.   Differences between ASP.NET new CAS model and legacy CAS model: Here list some differences between ASP.NET new CAS model and legacy CAS model ASP.NET 4.0 legacy CAS model  : Asp.net partial trust appdomains have full trust permission Multiple different permission sets in a single appdomain are allowed in ASP.NET partial trust configuration files Code groups Machine CAS policy is honored processRequestInApplicationTrust attribute is still honored    New configuration setting for legacy model: <trust level="Something" legacyCASModel="true" ></trust><partialTrustVisibleAssemblies> <add assemblyName="MyAssembly" publicKey="hex_char_representation_of_key_blob" /></partialTrustVisibleAssemblies>   ASP.NET 4.0 new CAS model: ASP.NET will now run in homogeneous application domains. Only full trust or the app-domain's partial trust grant set, are allowable permission sets. It is no longer possible to define arbitrary permission sets that get assigned to different assemblies. If an application currently depends on fine-tuning the partial trust permission set using the ASP.NET partial trust configuration file, this will no longer be possible. processRequestInApplicationTrust attribute is deprecated Dynamically compiled assemblies output by ASP.NET build providers will be updated to explicitly mark assemblies as transparent. ASP.NET partial trust grant sets will be independent from any enterprise, machine, or user CAS policy levels. A simplified model for locking down web servers that only allows trusted managed web applications to run. Machine policy used to always grant full-trust to managed code (based on membership conditions) can instead be configured using the new ASP.NET 4.0 full-trust assembly configuration section. The full-trust assembly configuration section requires explicitly listing each assembly as opposed to using membership conditions. Alternatively, the membership condition(s) used in machine policy can instead be re-defined in a <CodeGroup /> within ASP.NET's partial trust configuration file to grant full-trust.   New configuration setting for new model: <trust level="Something" legacyCASModel="false" permissionSetName="ASP.Net" hostSecurityPolicyResolverType=".NET type string" ></trust><fullTrustAssemblies> <add assemblyName=”MyAssembly” version=”1.0.0.0” publicKey="hex_char_representation_of_key_blob" /></fullTrustAssemblies><partialTrustVisibleAssemblies> <add assemblyName="MyAssembly" publicKey="hex_char_representation_of_key_blob" /></partialTrustVisibleAssemblies>     Hope this post is helpful to better understand the ASP.Net 4.0 CAS. Xiaohong Tang ASP.NET QA Team

    Read the article

  • ASP.NET MVC 3 Hosting :: How to Deploy Web Apps Using ASP.NET MVC 3, Razor and EF Code First - Part I

    - by mbridge
    First, you can download the source code from http://efmvc.codeplex.com. The following frameworks will be used for this step by step tutorial. 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; } }    Define Domain Model Let’s create domain model for our simple web application Category Class 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 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.                 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. Category.cshtml @model MyFinance.Domain.Category <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.Description) </div> <div class="editor-field"> @Html.EditorFor(model => model.Description) @Html.ValidationMessageFor(model => model.Description) </div> 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"; } Tomorrow, we will cotinue the second part of this article. :)

    Read the article

  • ASP.NET MVC2 Model Validation Fails with Non-US Date Format

    - by 81bronco
    I have a small MVC2 app that displays in two cultures: en-US and es-MX. One portion contains a user input for a date that is pre-populated with the current date in the Model. When using en-US, the date field is displayed as MM/dd/yyyy and can be changed using the same format without causing any validation errors. When using es-MX, the date field is displayed as dd/MM/yyyy, but when the date is edited in this format, the server-side validation fails with the message: The value '17/05/1991' is not valid for The Date. One of the first things that jumps out at me about that message is that it is not localized. Both the message itself (which I do not think I can control) and the Display Name of the field (which I can control and is localized in my code). Should be displaying in a localized format. I have tried stepping through the code to see exactly where the validation is failing, but it seems to be happening inside some of the compiled MVC or DataAnnotations code that I cannot see. Application details: IIS6, ASP.NET 3.5 (C#), MVC 2 RTM Sample Model Code: public class TestVieModel{ [LocalizedDisplayNameDisplayName("TheDateDisplayName", NameResourceType=typeof(Resources.Model.TestViewModel))] [Required(ErrorMessageResourceName="TheDateValidationMessageRequired", ErrorMessageResourceType=typeof(Resources.Model.TestViewModel))] [DataType(DataType.Date)] public DateTime TheDate { get; set; } } Sample Controller Action Code: [HttpPost] [ValidateAntiForgeryToken] public ActionResult Save(TestViewModel model) { if(ModelState.IsValid) { // <--- Always is false when using es-MX and a date foramtted as dd/MM/yyyy. // Do other stuff return this.View("Complete", model); } // Validation failed, redisplay the form. return this.View("Enter", model); } Sample View Code: <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<HispanicSweeps.Web.Model.LosMets.EnterViewModel>" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Test</title> </head> <body> <% using (Html.BeginForm()) {%> <%= Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <div class="editor-label"> <%= Html.LabelFor(model => model.DateOfBirth) %> </div> <div class="editor-field"> <%= Html.EditorFor(model => model.DateOfBirth) %> <%= Html.ValidationMessageFor(model => model.DateOfBirth) %> </div> <p><input type="submit" value="Save" /></p> </fieldset> <% } %> </body> </html>

    Read the article

  • Can I use the character ñ in a sub-domain?

    - by nute
    We are launching our website in Spanish and are probably going to call it espanol.mydomain.com Since the real spelling is español, ideally we would allow people to type español.mydomain.com. Is that something that is possible today? Can we use this character in domains and sub-domains?

    Read the article

  • Windows Cluster issue

    - by George2
    Hello everyone, For Windows Server 2008 failover cluster, I find it is dependent on Windows domain (in other words, Windows domain is pre-requisite of installing Windows Server 2008 fail over cluster). I am not sure why it is dependent on Windows domain? What features of Windows domain will Windows Server 2008 failover cluster utilize? thanks in advance, George

    Read the article

  • Why can't I change the domain when connecting to network shares in Windows 8?

    - by Nathan Osman
    I have a computer running Windows 8.1 Pro. I also have Ubuntu 12.04.3 Server running within Hyper-V on the same machine. The Ubuntu server has Samba installed. Both the host and guest OS are connected to the workgroup WORKGROUP. When I open up "Network" in Windows 8.1 and attempt to connect to the server (both by name and IP address), I receive the following prompt: Entering the correct username and password for an account on the server fails. /etc/samba/smb.conf has the following share definitions set: [homes] comment = Home Directories browseable = no

    Read the article

  • Windows SteadyState - system's security log is full

    - by Matt
    Quick version: New computer, attached to Windows domain, with SteadyState w/ Disk Protection turned on, cannot log on as domain user because Windows states 'system security log is full' Troubleshooting performed: disabled all 'restrictions' listed in SteadyState, cleared system security log, changed security log settings to overwrite entries when it becomes full, restarted computer to commit changes, verified changes were commited - still cannot log on as domain user, changed Documents and Settings folder to another partition, still cannot log on as domain user Let me know if you need a more detailed description of any steps performed. I appreciate any help you can give me.

    Read the article

  • Two different sites, same IP, same top-level domain, on IIS 7.5 -- one works and the other displays HTTP 404 error

    - by user717236
    I'm running a Windows 2008 R2 box with IIS 7.5 as the web server. On IIS, I have two websites: mysubsite1.mysite.com and mysubsite2.mysite.com. There is only one IP on the server and both sites share this IP. Here is how I have the bindings configured: mysubsite1.mysite.com works fine. However, mysubsite2.mysite.com gives me the following error: Not Found HTTP Error 404. The requested resource is not found. Now, if I change the Host name field for mysubsite1.mysite.com to blank and restart the web server, both sites work! The question is why is the host name field for the first site causing an HTTP 404 error for the second site when both sites' Host name fields are filled? I would appreciate any insight. Thank you.

    Read the article

  • How do I maintain coherency between model and view-model in MVVM pattern?

    - by Mike Garrett
    Problem Statement I'm writing a very basic WPF application to alter the contents of a configuration file. The data format is an XML file with a schema. I want to use it as a learning project for MVVM, so I have duly divided the code into Model: C# classes auto-generated from xsd.exe View-Model: View-friendly representation of the Model. View: Xaml and empty code behind I understand how the View-Model can make View-binding a breeze. However, doesn't that leave the View-Model <- Model semantics very awkward? Xsd.exe generates C# classes with arrays for multiple XML elements. However, at the V-VM level you need Observable Collections. Questions: Does this really mean I have to keep two completely different collection types representing the same data in coherence? What are the best practices for maintaining coherence between the Model and the View-Model?

    Read the article

  • ASP.NET MVC 2 AJAX dilemma: Lose Models concept or create unmanageable JavaScript

    - by Slightly Frustrated
    Hi, Ok, let's assume we are working with ASP.NET MVC 2 (latest and greatest preview) and we want to create AJAX user interface with jQuery. So what are our real options here? Option 1 - Pass Json from the Controller to the view, and then the view submits Json back to the controller. This means (in the order given): User opens some View (let's say - /Invoices/January) which has to visualize a list of data (e.g. <IEnumerable<X.Y.Z.Models.Invoice>>) Controller retrieves the Model from the repository (assuming we are using repository pattern). Controller creates a new instance of a class which we will serialize to Json. The reasaon we do this, is because the model may not be serializable (circular reference ftl) Controller populates the soon-to-be-serialized class with data Controller serializes the class to Json and passes it the view. User does some change and submits the 'form' The View submits back Json to the controller The Controller now must 'manually' validate the input, because the Json passed does not bind to a Model See, if our View is communicating to the controller via Json, we lose the Model validation, which IMHO is incredible disadvantage. In this case, forget about data annotations and stuff. Option 2 - Ok, the alternative of the first approach is to pass the Models to the Views, which is the default behavior in the template when you start a new project. We pass a strong typed model to the view The view renders the appropriate html and javascript, sticking to the model property names. This is important! The user submits the form. If we stick to the model names, when we .serialize() the form and submit it to the controller it will map to a model. There is no Json mapping. The submitted form directly binds to a strongly typed model, hence, we can use the model validation. E.g. we keep the business logic where it should be. Problem with this approach is, if we refactor some of the Models (change property names, types, etc), the javascript we wrote would become invalid. We will have to manually refactor the scripting and hope we don't miss something. There is no way you can test it either. Ok, the question is - how to write an AJAX front end, which keeps the business logic validation in the model (e.g. controller passes and receives a Model type), but in the same time doesn't screw up the javascript and html when we refactor the model?

    Read the article

  • asp.net mvc model binding

    - by mctayl
    Hi there Iam using asp.net mvc to do model binding, when I pass a model to a view, I am able to see the model data displayed in the form inside a label, <%= Html.Label(Model.title) % <%= Html.Label(Model.description) % however, I am not able to do the same using <%= Html.TextArea(Model.description)% is there a syntax difference between displaying in a label as oppsed tp a textbox

    Read the article

  • How can I VPN into a domain and act as if it is local?

    - by Duall
    I've looked and looked and the internet seems to have finally failed me, there's no information on my specific issue. I have two locations, and one server (sbs 2008); I need them to act like one physical LAN. I know it's possible, I just know how to set it up, or anything about VPNs, etc. So, just to clarify a bit more: 1 Small Business Server 2008 ~30 Computers with varying systems from Windows XP to 7 2 Physical Locations I use redirected folders, but since that would consume a lot of bandwith over VPN, I have a machine over there that can be the workhorse for storage. Users need to access e-mail and shared databases from this server (or possibly some form of DFS with aforementioned workhorse) from the other building. Is there a nice tutorial (or I nice person that wants to write it) online that can explain how to set up computers from an external network to act like they were in the LAN?

    Read the article

  • How to show ModelState.AddModelError when the Model is Empty in MVC4

    - by kk1076
    I am displaying a shopping cart. I need to check for empty values in Shopping cart and display a message like "The Shopping Cart is empty". When I use ModelState.AddModelError in myAction, it throws an exception as there is null reference in Model. How to display the ErrorMessage. My Action public ActionResult Index() { string id = Request.QueryString["UserID"]; IList<CartModel> objshop = new List<CartModel>(); objshop = GetCartDetails(id); if (objshop.Count > 0) { return View(objshop.ToList()); } else { ModelState.AddModelError("", "Your Shopping Cart is empty!"); } return View(); } My View @{ @Html.ValidationSummary(true) } <th > @Html.DisplayNameFor(model => model.ProductName) </th> <th > @Html.DisplayNameFor(model => model.Quantity) </th> <th > @Html.DisplayNameFor(model => model.Rate) </th> <th > @Html.DisplayNameFor(model => model.Price) </th> @foreach (var item in Model) { <td> @Html.DisplayFor(modelItem => item.ProductName)</td> <td> @Html.DisplayFor(modelItem => item.Quantity)</td> <td> @Html.DisplayFor(modelItem => item.Rate) </td> <td> @Html.DisplayFor(modelItem => item.Price) </td> } Any suggestions.

    Read the article

  • Connecting to a subdomain severs the connection to the domain itself. What's going on?

    - by TheAgent
    Hi all. We have a website on a third-party server (server leased and shared with other websites) and the server provides access to our SQL Server database through a subdomain in the form of mssql.DomainName.com. I was told to use SQL Management Studio Express to connect to this subdomain in order to manage the database. After a few tries and getting many "Timeout" messages, I finally manage to connect to the server; everything's fine. But now I can't connect to DomainName.com anymore. Trying to browse DomainName.com using Firefox, it tries to "lookup" DomainName.com address and fails, telling me "the server was not found". I have to disconnect Management Studio from the server and wait a couple of hour for DomainName.com to become available again, and after that, trying to reconnect to the SQL Server again repeats the scenario. While I can't browse DomainName.com directly, I can use a proxy to connect to it, meaning that the problem is somehow related to a DNS my computer tries to ask to translate the name to the corresponding IP. Anyone seen anything like this before? Any ideas? Thanks in advance.

    Read the article

  • Django populate select field based on model query

    - by Mike
    I have the following model class DNS(models.Model): domain = models.ForeignKey(Domain) host_start = models.CharField(max_length=150, blank=True, null=True) type = models.SmallIntegerField(max_length=1, default=0, choices=DNS_CHOICE) value = models.SmallIntegerField(max_length=3, default=0, blank=True, null=True) ip = models.IPAddressField(blank=True, null=True) host_end = models.ForeignKey("DNS", blank=True, null=True) other_end = HostnameField(max_length=150, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) sticky = models.BooleanField(default=0) other = models.BooleanField(default=0) When I try to init a form with just foreignkeys on host_end.. it always shows all entries in the DNS table domain = Domain.objects.get(id=request.GET['domain'], user=request.user, active=1) form = DNSFormCNAME(initial={'ip': settings.MAIN_IP, 'type': request.GET['type'], 'host_end': DNS.objects.filter(domain=domain)}) I just want the zones that match that domain.. not all domains.

    Read the article

  • ASP.NET MVC 2 Model object validation

    - by Jimmy
    Hey guys, I'm trying to validate a model object outside of the context of ModelState within a controller, I currently have a parser that creates model objects from an excel file and I want to be able to report how many entries were added to the database and how many failed, is there a way to validate a model object on its data annotations outside of model binding? I'm looking for something similar to the rails model method of model.valid? or a way for me to implement that myself. My current solution is just manually checking if a few key fields are present but this duplicates requirements between my model class and its metadata, there has to be a better way to hook into the model validation checking that is done by mvc 2. Thanks

    Read the article

  • Dns.GetHostEntry is not giving me a good IP to pass to IPEndPoint function in my domain

    - by Beach Miles
    My c# code from my asynchronous socket client to get the address of my socket server. string testServerIP = "192.168.0.1"; IPHostEntry ipHostInfo = Dns.GetHostEntry(testServerIP); //time server address IPAddress ipAddress = ipHostInfo.AddressList[0]; IPEndPoint remoteEP = new IPEndPoint(ipAddress, port); I get the following error message from the above code. CheckServerReconnect:Cant connect to 192.168.0.1 The requested name is valid and was found in the database, but it does not have the correct associated data being resolved for

    Read the article

  • Inter Quake Model IQM render Directx9

    - by Andrew_0
    I'm trying to render an Inter Quake Model(http://lee.fov120.com/iqm/) in DirectX9 that I exported from blender. I want to display animations which IQM supports and my model format does not. The model is a cylinder. It loads fine in the iqm sdk opengl viewer but when i try to render it in directx9 using for example(this is just to render the vertices): IDirect3DDevice9 * device; HRESULT hr = S_OK; for(int i = 0; i < nummeshes; i++) { iqmmesh &m = meshes[0]; hr = device->DrawIndexedPrimitiveUP(D3DPT_TRIANGLELIST, 0, 3*m.num_triangles, m.num_triangles ,&tris[m.first_triangle] ,D3DFMT_INDEX32 ,inposition ,sizeof(unsigned int)); } It renders like this: Incorrect The light grey bit that looks like two triangles in the middle is what is rendered(ignore the other stuff). Whereas it is meant to look like this(using a custom importer which I designed which matches what is displayed in blender): Correct Anyone have any suggestions on what might be going wrong?

    Read the article

  • Wordpress Multisite- How to restrict a non-wordpress page only to one domain

    - by yibe
    I am running three blogs from a wordpress multisite. Currently, I am developing a separate, non wordpress application. I want to link this application with blog1. I put the application in the subfoler of my root directory (The Wordpress multisite is installed in the root). I linked the application in the menu of blog1. So far so good. But, it is possible to access the application from all the three blogs. I want the application to be accessible only from blog1-domain/my-app/ but when I tried blog2-domain/my-app, it just opened normally. Generally, the application is accessible from all the three domains followed by /my-app. I don't think it is proper to go this way. Then, what can I do to restrict my app to be accessible only from a my blog1-domain/my-app ? Or am I not using a good blog structure?. I am open to all kind of suggestions. Thank you for your help.

    Read the article

< Previous Page | 54 55 56 57 58 59 60 61 62 63 64 65  | Next Page >